Menu
Markdown and reStructuredText
GitHub supports several lightweight markup languages for documentation;the most popular ones (generally, not just at GitHub) are Markdownand reStructuredText. Markdown is sometimes considered easier touse, and is often preferred when the purpose is simply to generate HTML.On the other hand, reStructuredText is more extensible and powerful,with native support (not just embedded HTML) for tables, as well asthings like automatic generation of tables of contents.
Highlights current line in Atom. Contribute to richrace/highlight-line development by creating an account on GitHub. RSyntaxTextArea is a syntax highlighting, code folding text component for Java Swing. It extends JTextComponent so it integrates completely with the standard javax.swing.text package. It is fast and efficient, and can be used in any application that needs to edit or view source code.
Unless you are embedding text into a programming language (especiallyPython doc comments, for which purpose reStructuredText was originallydeveloped) you will probably choose to use Markdown for a small document(like this Gist once was). But as you add more sections and features, you maydecide that you want the power of reStructuredText. To avoid having toconvert all of your Markdown formatting when that happens, use this Gistas a guide to the markup syntax common to Markdown and reStructuredText.
By using only the common subset shared by these two lightweight markuplanguages (largely from Setext, which inspired both of them) for yourdocuments, you can eliminate the need for conversion. Even if you alsouse features that are specific to one or the other, using the commonsubset wherever possible allows for painless cut & paste between them.
Another advantage of restricting yourself to the common subset describedhere is that the resulting source is more likely to be parsed the same wayby different Markdown processors, which may handle some details likeindentation slightly differently.
If you have already used Markdown-specific syntax, or you just don'twant to limit yourself to the (admittedly very limited) intersection offunctionality in the subset, you can use Pandoc to convert Markdowninto reStructuredText - the online converter at<http://johnmacfarlane.net/pandoc/try> is handy if you don't happen tohave Haskell installed. (In fact, you may find the extended Markdownsupported by Pandoc adds enough functionality that you don't need to usereStructuredText at all - at least, once you get Haskell and Pandocinstalled.)
The Common Denominator
The basics of text formatting are common to both, a blank line (it maycontain spaces or tabs, but nothing else) is used to separate paragraphsand everything within a paragraph 'flows' and is wrapped to the displaywidth. Be sure to avoid initial indentation (either of an entireparagraph or just the first line) for normal text, as indentation issignificant to both Markdown and reStructuredText, but in differentways.
When writing text, you should try to wrap source lines to 72characters - but only when initially entering them - avoid re-wrappingtext when you edit it later, to limit the number of 'insignificantchanges' in your version control system (you are using one, right?!).Feel free to use two spaces after the period at the end of a sentence(or not) if that is useful for your text editor - I'm looking at you,Emacs - since multiple spaces are treated the same as a single space.Similarly, multiple blank lines are treated just like one blank line;you may want to use multiple blank lines at the end of a section.
Font Faces - Emphasis and Examples
Within paragraphs, inline markup provides basic formatting to addemphasis to particular words or phrases, most commonly by making themitalic or bold (depending on the font, italics are often renderedwith an oblique face instead). In technical writing,
monospacedtext
may be used to highlight program or function names, or for veryshort snippets of code.As with many types of formatting, Markdown provides multiple ways ofspecifying font faces, one of which is also used by reStructuredText:italics are marked with one asterisk (
*
) and bold face with two. Theremust be whitespace or other punctuation before the leading asterisks,and after the trailing ones; furthermore there must be no space betweenthe asterisks and the text being emphasized. Although Markdown supportsnesting bold and italic, reStructuredText does not (this is one of therare cases where Markdown is more powerful, as there is no way torepresent bold italics in reStructuredText).Monospaced text is marked with two backquotes '``' instead of asterisks;no bold or italic is possible within it (asterisks just representthemselves), although in some contexts, code syntax highlighting may beapplied. Note that in monospaced text, multiple spaces are notcollapsed, but are preserved; however, flow and wrapping do occur, andany number of spaces may be replaced by a line break. Markdown allowsmonospaced text within bold or italic sections, but not vice versa -reStructuredText allows neither. In summary, the common inline markupis the following:
Mark italic text with one asterisk, bold text with two.For
monospaced text
, use two 'backquotes' instead.(Markdown allows a single backquote to indicate monospaced text, howeverdouble backquotes ar better, since they allow for embedded backquotesand are required for reStructuredText.)
Escaping Markup
Sometimes you may want to use markup characters just as themselves,without any special interpretation. Within double backquotes used to markmonospaced text (or in code blocks as described below), markup charactersare not treated specially, but in other contexts, you must precede markupcharacters with a backslash () to escape them (this applies to thebackslash character as well):
*This* is not italic - My Pictures is a Windows folder
While reStructuredText will treat a backslash before any non-whitespacecharacter as an escape, Markdown only treats backslash as an escape whenit precedes one of the following characters:
- backslash
- ` backtick
- * asterisk
- _ underscore
- {} curly braces
- [] square brackets
- () parentheses
- # hash mark
- + plus sign
- - minus sign (hyphen)
- . dot
- ! exclamation mark
For compatibility, only use backslash before one of these characters, andbe sure to escape any backslashes that you want to appear in the output.
Code or Console Example Blocks
If you have example code or console text that you want to appear withall line breaks and relative indentation preserved, in a monospaced textblock, there is no common format for Markdown and reStructuredText, butyou can combine the formatting for both of them by ending one paragraphwith a double colon
::
(for reStructuredText) and indenting the nextone by four or more spaces (for Markdown) to make it appear inmonospaced font without flow or word-wrapping:A normal paragraph ending with
::
will flow and be word-wrapped:(We cheat a little bit here, Markdown does not interpret thedouble-colon, but displays it as-is, whereas reStructuredText displaysjust a single colon, but this is not too noticeable or annoying, as longas you remember to use the double colon in your source.)
Line Blocks and Hard Line Breaks
You may want to preserve line breaks in text blocks but don't want themin monospaced text; common cases are verse (poetry or lyrics), streetaddresses, and unadorned lists without bullets or numbering. Markdownand reStructuredText use completely different syntax for this, but youcan combine the markup for both reStructuredText line blocks andMarkdown hard line breaks by starting each line with a vertical bar (
|
)and a space and ending it with two spaces. For line breaks in thesource you don't want to preserve, omit the two spaces before the linebreak and start the next line with one to three spaces instead. Put ablank line before the start and after the end of every line block.Line blocks were added to reStructuredText in Docutils version 0.3.5and there are some reStructuredText formatters that do not supportthem; notably the GitHub README markup does not display them correctly.
These line blocks can also contain inline markup (which in a codeexample block might be displayed literally), but keep any markup withineach line, since emphasis starting on one line and ending on anotherapplies to vertical bars between them, which appear in Markdown output:
tori naki uo no
-- Matsuo BashÅ, The Narrow Road to Oku (Oku no Hosomichi),Tokyo, 1996, p. 23 (Translation: Donald Keene)
Birds are weeping and the eyes
(Again, we cheat a bit, since the Markdown output includes the verticalbars; but at least they make it very clear when you end a line withoutthe required two spaces, something that is quite easy to do as there isusually no visual indication of whether they are there or not.)
Block Quotations
When quoting long blocks of text from another writer, it is common(especially in the context of e-mail) to set it off from the main textby indenting it, possibly adding a vertical quotation line along theleft margin. Markdown and reStructuredText use different syntax forthis, but you can combine their markup for block quotes by starting thefirst line of a quotation with one space and a right angle bracket(
>
), indenting all the remaining lines by one space as well (do notadd angle brackets to them).Note that in reStructuredText, a block quotation cannot directly followa code example block - if it does it will be treated as part of theexample. A normal paragraph or an 'empty comment' (a line with only twoperiods (
..
) and blank lines before and after it) must separatethem.Every block quotation must have a blank line before and after it; theycan use the same inline markup as ordinary paragraphs. Nestedquotations are possible by following a block quotation with another thatstarts with two spaces and two right angle brackets; this allows up tothree levels of quotation (a fourth level is not possible since Markdowntreats four leading spaces as a code example). While two right anglebrackets can be adjacent, three adjacent right angle brackets are adoctest block (a special kind of code example block) in reStructuredTextand must have spaces between them to prevent that interpretation:
> A block quotation will wrap and flow, and can have inline
markup
just like a regular paragraph. It will be indented onthe left (and possibly the right) margins, and may have a verticalquotation line on the left.>> With two spaces and two right angle brackets, a following blockquotation will be doubly indented, and will have a second verticalquotation line along the left if quotation lines are generated.
> >> A third level of quotation is the maximum level possible.
(The cheat here is that the reStructuredText output includes the rightangle bracket(s) on the first line in addition to the indentation; thisis not ideal, but is generally acceptable when used for a quotation, andnot just indented text.)
Titles and Section headers
Both Markdown and reStructuredText allow you to structure your documentby adding header titles for sections and subsections. While they eachsupport a large number of levels of headers in different ways, thecommon subset only has two levels: titles, formed by underlining thetext with , and subtitles, formed by underlining with
--
. Theunderlining must be on the very next line, and be at leastas long as the (sub)title:Note that a blank line after the underlining is optional, but a blankline before the (sub)title is required.
Bulleted and Enumerated Lists
In addition to (sub)section headers, both Markdown and reStructuredTextsupport itemized lists; these can be numbered (enumerated) or unnumbered(bulleted) and the two types of lists can be nested within themselvesand each other. List items are lines starting (possibly after spacesfor indentation) with a bullet symbol (
*
, -
, or +
) for bulletedlists, or a number and a period (1.
) for enumerated lists; in bothcases followed by one or more spaces and then the item text. AlthoughreStructuredText supports other symbols for bulleted lists andparentheses instead of period for enumerated lists, as well as #
inplace of the number for auto-enumeration, Markdown only supports thesubset described above.The spaces after the symbol or number determine the indentation neededfor additional item text on continuation lines or following paragraphs,as well as the symbols or numbers for sub-lists. Symbol or number indentationof all items at any nesting level must be the same (even for longenumerated lists with two-digit numbers) but the indentation of the textof different items need not be the same.
If a list item contains multiple paragraphs (separated by blank lines)or sub-lists, the indentation of the item text must be at least fourspaces more than the item symbol or number; this usually requires extraspaces between the number and period (or symbol) and the item text.
A blank line is required before the first item and after the last itemin every top-level list, but is optional between items. A blank lineis also required by reStructuredText before the first item of asub-list; omitting it sometimes appears to work, but only because thesub-list is indented more than the item text. This extra indentationmay cause the item text to be treated as part of a definition list anddisplayed in bold; in other cases, it causes the sub-list to bewrapped within a block quote, causing both the left and right marginsto move inwards and creating a double-indent effect.
A sub-list without a preceding blank line can also work if there is noitem text preceding the sub-list; but this generates odd-lookingoutput that is confusing to human readers, with the first bullet ornumber of the sub-list on the same line as the bullet or number of theitem in the enclosing list.
While Markdown does not require a blank line before a sub-list, a blank linebetween items changes the inter-item spacing (typically by creating
<p>
paragraph tags). For consistent results, do not use blank linesbetween items unless you must (for sub-lists), in which case use blanklines between all the items at the same level (sub-list items do notrequire the blank lines unless there are sub-sub-lists).Markdown ignores the actual numbers given for enumerated lists andalways renumbers them starting with 1, but reStructuredText requiresthat the numbers be in sequential order; the number of the first itemmay or may not be preserved. For compatibility, always start enumeratedlists with 1 and number them sequentially. You should never mixenumerated and bulleted items (or different bullet symbols) at the samelevel; reStructuredText will reject it with an error (or, if there is ablank line between them, create a new list). On the other hand,Markdown processors will combine adjacent bulleted and enumerated lists(using the formatting of the first list); to create separate lists it isnot enough to have a blank line, there must be a non-list paragraphbetween them.
Because Markdown formatting requires additional indentation for extraparagraphs of item text in lists, the approach for monospaced paragraphsgiven above in Code or Console Example Blocks requires additionalindentation of at least eight spaces (not just four) for exampleblocks in lists.
Finally, it is a very good idea to make sure that your documentsource does not contain any tab characters, especially when workingwith multiple levels of sub-lists. Configure your text editor toexpand all tabs into spaces; this will help to ensure that the initialindentation is consistent and avoid errors if another editorinterprets the tabs differently.
The following two lists summarize and provide examples of the rules forlists compatible with Markdown and reStructuredText:
- Mark bulleted lists with one of three symbols followed by a space:
- asterisk (
*
) - hyphen (
-
) - plus sign (
+
)
- asterisk (
- Mark enumerated lists with a number, period (
.
) and a space. - The choice of symbol does not affect the output bullet style,which is solely determined by nesting level.Items can be continued on following lines indented at the samelevel as the item text on the first line, and will flow and wrapnormally.
- The source indentation of item text can vary for different items(but continuation lines must be indented by the same amount asthe item text that they are continuing).Additional paragraphs of item text (after a blank line) alsorequire this indentation, with the extra requirement that it befour to seven spaces more than the item symbol or number.
- These indentation requirements are the same for sub-list items(but apply to their symbol or number, not their item text).
- Blank lines between list items are optional, avoid them.
- If you do use them (for items with sub-lists or extraparagraphs) put blank lines between all items at that level.
A non-list paragraph is required to separate adjacent enumerated andbulleted lists, to keep Markdown from merging the second one into thefirst (and using the first style for both).
- Always put a blank line before the start of a list or sub-list.
- Use the same bullet symbol for all items in a bulleted list.
- Always start enumerated lists with 1.
- Use sequentially increasing numbers for succeeding list items.
- Do not mix numbers and/or different bullet symbols at one level
- (but this is okay for different levels or separate sublists).
- Indent sub-lists by the same amount as the item text;this must be 4-7 spaces more than the symbol or number.
- if enumerated, always start them with 1.
- (the same rules apply to sub-sub-lists, etcetera)
Additional non-sub-list paragraphs require the same indentation;example blocks (after double colon::
) must be indented atleast eight spaces more than the symbol or number, like this: - if enumerated, always start them with 1.
- Indent symbols or numbers the same amount for any one list level.
- (top-level list items should not have any leading indentation)
- Align two-digit enumerated items by first digit, not the period.
- Don't put leading zeros on enumerated items to align the periods
- (use spaces after period if you want to align the item text in source).
- Make sure there are no tab characters in initial indentation.
- Always put a blank line after the end of a (top-level) list.
Hyperlink URLs
Markdown and reStructuredText use different and incompatible syntax forarbitrary text hyperlinks, but reStructuredText will generate hyperlinksfor e-mail addresses or URLs, and Markdown will do so as well if theyare enclosed in angle brackets (
<>
). Some Markdown processors donot require the angle brackets, but there is little reason to omit them,as they hardly affect readability, and explicitly specify whether or notpunctuation at the end of the URL is really part of the link. Evenrelative URLs can be used if the protocol is explicitly specified:The latest version of this document can be found at<https://gist.github.com/1855764>; if you are viewing it there (viaHTTPS), you can download the Markdown/reStructuredText source at<https:/gists/1855764/download>. You can contact the author viae-mail at <[email protected]>.
(Using the URLs directly for hyperlinks also means that even if aMarkdown processor has link generation disabled, a human reader canalways copy and paste the URL.)
Horizontal Rules (Transitions)
You can create a horizontal rule (a 'transition' in reStructuredTextterminology) by placing four or more hyphens (
-
), asterisks (*
),or underscores (_
) on a line by themselves, with blank lines beforeand after and no indentation (trailing spaces are okay, but not leadingspaces). Although Markdown requires only three, and allows spacesbetween them, reStructuredText requires four repeated punctuationcharacters. Also, reStructuredText requires paragraphs before and afterthe transition (code blocks or enumerated/bulleted list items are okay,but section headers are not).Each of the following lines will produce a horizontal rule like theone above:
Incompatibilities
There are a few cases where Markdown or reStructuredText will interpretsomething as markup, although it is treated as ordinary text by the other,and these differences can cause problems for a document that is intendedto be processed by either formatter. In these cases, the solution isusually to add a backslash before the markup character so that it is nottreated specially by either markup processor.
(Square) Brackets
While the appearance of square brackets - [] - in text is not treatedspecially by reStructuredText, some Markdown processors may attempt toformat the contents as a hyperlink, even if there is no followingparenthetical URL or bracketed reference. To prevent this, put abackslash before the opening square bracket (you can also put it beforethe closing square bracket, but this is optional).
Solitary Backslash
Although Markdown only treats backslash as an escape character when itprecedes certain characters, reStructuredText treats backslash as anescape unless it is followed by whitespace (in which case it removes thebackslash and the whitespace). Because of this, a single backslashfollowed by whitespace, or a 'C' escape like n, that appears inMarkdown will be 'eaten' by reStructuredText. To prevent this, make sureto always escape any backslashes that you want to appear in the output.
Not-Incompatible Extensions
Both Markdown and reStructuredText have markup that is not interpretedby the other (either in the same or in an incompatible way), and whichis not too painful to read when rendered as ordinary text. HyperlinkURLs (as noted above) fall into this category for some basic Markdownimplementations that do not implement URL recognition.
Tables
Markdown has no support for tables (one of its biggest weaknesses); tocreate them requires embedded HTML (if that is even allowed). Somevariants have added table support (notably Pandoc Markdown, PHPMarkdown Extra, and GitHub Flavored Markdown [GFM]) but the syntax isnot consistent between all of them. The reStructuredText format hasthe additional advantage of being quite readable in original sourceform (basic monospaced ASCII layout). If you indent reStructuredTexttables by four or more spaces (and make sure that the previous paragraphdoes not end with a double colon
::
) you will get a nicelyformatted table in reStructuredText and a readable ASCII table inMarkdown. There are two flavors of table markup in reStructuredText,grid tables and simple tables. Grid tables are trickier to generate, butmore flexible, and look nicer in source format:Make sure previous paragraph does not end with
::
.Table Headings | Here | |
---|---|---|
Sub | Headings | Too |
cellspansrows | column spanning | |
normal | cell | |
multilinecellstoo |
|
A significant advantage of grid tables is that Pandoc Markdown supportsthem, which is not the case for simple tables, for which Pandoc uses asomewhat similar but incompatible format. However, for Pandoc toactually process the formatting, the four space indentation of the gridtables must be removed (to prevent monospaced code block formatting).
Simple tables are easier, but cells must be on a single line and cannotspan rows:
Note that lines between rows are optional and only needed to indicatewhere cells in the previous line span columns (by omitting the space).
Table Headings | Here | |
---|---|---|
Sub | Headings | Too |
column spanning | no | |
cell | cell | row |
column spanning | spans |
Apart from the ability to span rows and do block formatting within cellsin a grid table, the actual table formatting is not affected by the useof grid or simple tables, and depends only on the reStructuredTextprocessor and any style sheets it may use; for more visual compatibilityyou may want to use the table style that most closely resembles theoutput table.
Conversely, if you have a reason to prefer the 'pipe tables' formatdefined by PHP Markdown Extra and supported by GitHub Flavored Markdownand the latest version (1.10) of Pandoc, you can get reasonable results bymaking sure that the previous paragraph does end with a double colon
::
which will make the table display as monospaced ASCII inreStructuredText.Colons can be used to align columns in pipe tables:
Colons can be used to align columns in pipe tables:
Also, just as for list indentation, it is a very good idea to makesure that no tab characters are embedded in the tables; configure yourtext editor to expand all tabs into spaces; this will help to ensurethat the source ASCII display in reStructuredText or Markdown isproperly aligned.
Comments
There is no comment syntax for Markdown, but HTML comments can be usedwith Markdown processors that allow them (raw HTML is often disabledfor security or other reasons, possibly with whitelisted tags allowed;notably, GitHub and BitBucket README markdown disable HTML comments).Standard Markdown (but not most processors) requires blank lines beforeand after HTML blocks. Comments in reStructuredText use a differentsyntax, but it is possible to create comments that are entirelyinvisible in reStructuredText output, and only appear as periods inMarkdown output (unless HTML comments are disabled).
In the following comment examples, the reStructuredText comment /directive marker
..
is followed by two more periods so that thefollowing blank line does not terminate the comment. For most Markdownprocessors, you can use an
entity instead of the twoadditional periods to reduce the visual impact; but some Markdownprocessors (notably the Python Markdown used by BitBucket READMEprocessing) do not support entities outside of HTML blocks.The following block is completely hidden from reStructuredText output,and barely visible in Markdown output if HTML comments are allowed:
You can also use a variation of the above to include Markdown markupthat will be entirely ignored by reStructuredText:
You can use another variation of the above to include reStructuredTextmarkup that will be ignored by Markdown (except for the periods):
Note
This is a reStructuredText directive - the Markdownoutput should be just periods
Note that although HTML comments are usually marked with
<!-- -->
you should use three dashes instead of two: <!--- --->
as this isused by Pandoc to prevent passing the comment through to the output.Markdown Extensions
Unlike reStructuredText, which is virtually identical across all itsimplementations, there are a wide variety of semi-compatible Markdownextension styles; the most popular are MultiMarkdown and Markdown Extra(the latter implemented by PHP Markdown and Maruku, and partially byPython Markdown and Redcarpet); Pandoc has its own set of Markdownextensions, based on both Markdown Extra and reStructuredText; theseMarkdown extensions are the most similar to reStructuredText, while theMarkdown Extra extensions have a smaller overlap, and the MultiMarkdownextensions are only compatible with reStructuredText when they are alsoidentical to parts of Markdown Extra.
Definition Lists
Markdown Extra, MultiMarkdown, and Pandoc support a syntax that isfairly compatible with the definition list syntax in reStructuredText;by using the following format, definitions can be written that arerecognized by all of these processors. In reStructuredText, any linethat is followed immediately by an indented line is a definition term,with the following lines at the same indentation level forming thedefinition. Markdown Extra allows an optional blank line between theterm and definition lines, but requires the definition to begin with acolon (
:
) that is not indented by more than three spaces and isfollowed by a space and the definitionTo be recognized as a definition list item in both reStructuredText andMarkdown extensions, only a single term is allowed, and it must befollowed immediately (with no blank line) by the definition. Thedefinition must begin with an (indented) colon and a space and it andany continuation lines or additional paragraphs or definitions must allbe indented by the same amount (one to three spaces), as shown in thefollowing example:
: multi-line definitiona second line (will be subject to flow and wrapping)
a second paragraph in the definition
: first definition
: second definition
Fancy list numbers
Although most Markdown processors only support enumerated lists witharabic numbers followed by periods, Pandoc also supports other liststyles that are compatible with reStructuredText. In particular,letters (
A
) as well as roman numerals (IV
) and alternatepunctuation with parentheses ( (b)
or xiv)
) are recognized, andsequences starting with numbers other than 1 (or roman numeral I orletter A) have the actual starting number or letter preserved in output.Highlights the current line in the editor; really simple.
You can now also underline the the current lines thanks to@sniperbat. This isn't enabled by default, andyou can edit the colour and type of line.
When selecting more than one line of text, you can enable selection borders atthe top and bottom of the selections. This isn't enabled by default.Courtesy of @djak250
You can now toggle the highlighted line by:
cmd+alt+H
You can now toggle the hiding the highlight on selecting text by: cmd+shift+alt+H
You can now toggle the underline by:
cmd+alt+U
You can now toggle the selection borders by: cmd+shift+alt+U
I've moved this package to use the new decorations API and as such we can nolonger set arbitrary style on the lines. So, this means no more entering colours/opacity in the settings.
You can update the colours by either updating the
line-colors.less
fileonce you've installed the package. Or by adding the following to your style.less
I don't use the
.cursor-line
class as when you make selection on thesame line, you then lose the highlight.To remove unused settings delete them from your
config.cson
.