Skip to content

Latest commit

 

History

History
2981 lines (2018 loc) · 59 KB

markdown-style-guide.md

File metadata and controls

2981 lines (2018 loc) · 59 KB

Markdown Style Guide

Markdown 风格指北


Here is the Markdown style guide I follow. It's not a mandatory standard.

References

Markdown Specification

All skippable to read

GFM Basic Syntax

You should know

( GFM - GitHub or GitLab Flavored Markdown )

Style Guide

All recommended to read!

Chinese Text Layout

All recommended to read!

Suggestions

Highly recommend to read the links in section "References → Style Guide" above.

I made my Markdown style guide below according to them. You can make your own guide as well.

Design Goals

  • Readable ( icehe: clean and tidy )
  • Easy to write and modify later
  • Diff friendly
  • Easy to remember and implement on editors ( icehe : not easy )
  • Provide rationale behind difficult choices

Many design choices come down to:

  • do you want to write fast ( writability )
  • or do you want people to read fast ( readability )

Guideline: Readability > Writability

General Rules

File

File Extention: Use .md

Rationale: Why not .mkd or .markdown?

  • Shorter
  • More popular
  • Does not have important conflicts

File Name: Prefer to base the file name on the top-header level

  • Replace upper case letters with lower case
  • Strip articles the, a, an from the start
  • Replace punctuation and white space characters by hyphens
  • Replace consecutive hyphens by a single hyphen
  • Strip surrounding hyphens

Good

file-name.md

Bad, multiple consecutive hyphens

file-name.md

Bad, surrounding hyphens

-file-name-.md

Rationale: why not underscore or camel case?

  • Hyphens are the most popular URL separator today, and markdown files are most often used in contexts where:

    • There are hyphen separated HTML files in the same project, possibly the same directory as the markdown files.

    • Filenames will be used directly on URLs. E.g.: GitHub blobs.

Whitespaces

New Lines
  • Don't use 2 or more consecutive empty lines,

    that is, more than two consecutive newline characters, except where they must appear literally such as in code blocks.

  • End files with a newline character, _and don't leave empty lines at the end of the file.~~

  • Don't use trailing whitespace unless it has a function such as indicating a line break.

Good

- list
- list

## Header

Good, code block

The markup language X requires you to use triple newlines to separate paragraphs:

    p1


    p2

Bad

- list
- list


## Header

Rationale: multiple empty lines occupy more vertical screen space, and do not significantly improve readability.

Spaces after sentences

Use a single space after sentences.

Bad, 2 spaces

First sentence.  Second sentence.

Good

First sentence. Second sentence.

Rationale: advantages over space-sentence:2:

  • Easier to edit
  • Usually not necessary if you use wrap:inner-sentence or wrap:sentence
  • space-sentence:2 gives a false sense of readability as it is ignored on the HTML output
  • More popular

Advantages of space-sentence:2:

  • Easier to see where sentences end

Line wrapping

Wrap Inner-Sentence

Try to keep lines under 80 characters by breaking large paragraphs logically at points such as:

  • Sentences: after a period ., question ? or exclamation mark !
  • Clauses: after words like and, which, if ... then, commas ,
  • Large phrases

Good

This is a very very very very very very very very very very very very very long not wrapped sentence.
Second sentence of of the paragraph,
third sentence of a paragraph
and the fourth one.

Rationale:

  • Diffs look better, since a change to a clause shows up as a single diff line.

  • Occasional visual wrapping does not significantly reduce the readability of Markdown, since the only language feature that can be indented to indicate hierarchy are nested lists.

  • At some point GitHub translated single newlines to line breaks in READMEs, and still does so on comments. Currently there is no major engine which does it, so it is safe to use newlines.

  • Some tools are not well adapted for long lines, e.g. Vim and git diff will not wrap lines by default.

    This can be configured however via git config --global core.pager 'less -r' for Git and set wrap for Vim.

Downsides:

  • Requires considerable writer effort, specially when modifying code.

  • Markdown does not look like the rendered output, in which there are no line breaks.

    Manual line breaking can make the Markdown more readable than the rendered output, which is bad because it gives a false sense of readability encouraging less readable long paragraphs.

  • Requires users of programming text editors like Vim, which are usually configured to not wrap, to toggle visual wrapping on. This can be automated, but EditorConfig gave it WONTFIX

  • Breaks some email systems, which always break a line on a single newline.

Other alternates:

  • Don't wrap lines.

    Rationale: very easy to edit. But diffs on huge lines are hard to read.

  • Always wrap at the end of the first word that exceeds 80 characters.

    Rationale: source code becomes is very readable and text editors support it automatically. But diffs will look bad, and changing lines will be hard.

  • Wrap Sentence

    Rationale: similar advantages as wrap:inner-sentence, but easier for people to follow since the rule is simple: break after the period. But may produce long lines with hard to read diffs.

    Notable occurrence: ProGit 2.

Code

Dollar Signs in Shell Code

Don't prefix shell code with dollar signs $ unless you will be showing the command output on the same code block.

If the goal is to clarify what the language is, do it on the preceding paragraph.

Rationale: harder to copy paste, noisier to read.

Good

echo a
echo a > file

Bad

$ echo a
$ echo a > file

Good, shows output

$ echo a
a
$ echo a > file

Good, language specified on preceding paragraph

Use the following Bash code:

echo a
echo a > file
What to Mark as Code

Use code blocks or inline code for:

  • Executables. E.g.:

    `gcc` is the best compiler available.

    Differentiate between tool and the name of related projects. E.g.: gcc vs GCC.

  • File paths

  • Version numbers

  • Capitalized explanation of abbreviations:

    xinetd stands for `eXtended Internet daemon`
  • Other terms related to computers that you don't want to add to your dictionary

Don't mark as code:

  • Names of projects. E.g.: GCC
  • Names of libraries. E.g.: libc, glibc
Spelling and Grammar

Use correct spelling and grammar.

Prefer writing in English, and in particular American English.

Rationale: American English speakers have the largest GDP, specially in the computing industry.

Use markup like URL or code on words which you do not want to add to your dictionary so that spell checkers can ignore them automatically.

Beware of case sensitive spelling errors, in particular for project, brand names or abbreviations:

  • Good: URL, LinkedIn, DoS attack
  • Bad: url, Linkedin, dos attack
  • When in doubt, prefer the same abbreviation as used on Wikipedia.

Avoid informal contractions

  • Good: biography, repository, directory
  • Bad: bio, repo, dir
Escape Newlines

( from Google Markdown style guide )

Escape any newlines in code blocks : Use a single backslash at the end of the line.

bazel run :target -- --flag \
    --foo=longlonglonglonglongvalue \
    --bar=anotherlonglonglonglonglonglonglonglonglonglongvalue

Rationale: Because most commandline snippets are intended to be copied and pasted directly into a terminal, it's best practice to escape any newlines.

Block elements

Line breaks

Avoid line breaks, as they don't have generally accepted semantic meaning.

In the rare case you absolutely need them, end a lines with exactly two spaces.

Header

Header Syntax

Use ATX-style headers

Bad, Setex-style headers

Header 1
========

Header 2
--------

Bad, both Setex-style and ATX-style headers

Header 1
========

Header 2
--------

### Header 3

Good, ATX-style headers

# Header 1

## Header 2

### Header 3

Rationale:

  • Advantages of Setex:

    • More visible.

      Not very important if you have syntax highlighting.

  • ATX advantages over Setex:

    • Easier to write because in Setex you have to match the number of characters in both lines for it to look good

    • Works for all levels, while Setex only goes up to level 2

    • Occupy only one screen line, while Setex occupies 2

Include a single space between the # and the text of the header.

Good

# Header

Bad

#Header

#  Header

Don't use the closing # character.

Bad

# Header #

Don't add spaces before the number sign #.

Bad

 # Header

Don't skip header levels.

Bad

# Header 1

### Header 3

Good

# Header 1

## Header 2

Surround headers by a single empty line except at the beginning of the file.

Bad

Before 1.
# Header 1

Before 2.
## Header 2
After 2.

Good

# Header 1

After 1.

## Header 2

After 2.

Avoid using two headers with the same content in the same markdown file.

Rationale: many markdown engines generate IDs for headers based on the header content.

Bad

## Dogs

### Anatomy

## Cats

### Anatomy

Good

## Dogs

### Anatomy of the Dog

## Cats

### Anatomy of the Cat
Top-Level Header

Exactly one top-level header in a markdown file.

Bad

# Dogs

# Cats

Good

# Animal

## Dogs

## Cats

If you target HTML output, write your documents so that it will have one and only one h1 element as the first thing in it that serves as the title of the document. This is the HTML top-level header.

How this h1 is produced may vary depending on your exact technology stack: some stacks may generate it from metadata, for example Jekyll through the front-matter.

Storing the top-level header as metadata has the advantage that it can be reused elsewhere more easily, e.g. on a global index, but the downside of lower portability.

If your target stack does not generate the top-level header in another way, include it in your markdown file. E.g., GitHub.

Top-level headers on index-like files such as README.md or index.md should serve as a title for their parent directory.

Downsides of top-level headers:

  • Take up one header level. This means that there are only 5 header levels left, and each new header will have one extra #, which looks worse and is harder to write.

  • Duplicate filename information, which most often can already be seen on a URL. In most cases, the filename can be trivially converted to a top-level, e.g.: some-filename.md to Some Filename.

Advantages of top-level headers:

  • More readable than URL's, especially for non-technically inclined users.
Header Case

Use an upper case letter as the first letter of a header, unless it is a word that always starts with lowercase letters, e.g. computer code.

Good

# Header

Good, computer code that always starts with lower case

# int main

Bad

# header

The other letters have the same case they would have in the middle of a sentence.

According to the Chicago Manual of Style (15th edition), the following rules should be applied to headers:_

  • Always capitalize the first and last words of titles and subtitles.

  • Always capitalize "major" words (nouns, pronouns, verbs, adjectives, adverbs, and some conjunctions).

  • Lowercase the conjunctions and, but, for, or, and nor.

  • Lowercase the articles the, a, and an.

  • Lowercase prepositions, regardless of length, except when they are stressed, are used adverbially or adjectivally, or are used as conjunctions.

  • Lowercase the words to and as.

  • Lowercase the second part of Latin species names.

Good Bad

# The header of the example

Bad Good

# The Header of the Example

As an exception, title case may be optionally used for the top-level header. Use this exception sparingly ( 保守地 ) , in cases where typographical ( 排字上的 ) perfection is important, e.g.: README of a project. ( icehe: I prefer "Chicago Manual of Style" to "AP Stylebook". )

Rationale: why not Title case for all headers? It requires too much effort to decide if edge-case words should be upper case or not.

End of a Header

Indicate the end of a header's content that is not followed by a new header by an horizontal rule.

# Header

Content

---

Outside header.
Header Length

Keep headers as short as possible.

Instead of using a huge sentence, make the header a summary to the huge sentence, and write the huge sentence as the first paragraph beneath the header.

Rationale: if automatic IDs are generated by the implementation, it is:

  • Easier to refer to the header later while editing
  • Less likely that the IDs will break due to rephrasing
  • Easier to distinguish between different IDs

Good

# Huge header

Huge header that talks about a complex subject.

---

Content

Bad

# Huge header that talks about a complex subject

Content
Punctuation at the End of Headers

Don't add a trailing colon : to headers.

Rationale: every header is an introduction to what is about to come next, which is exactly the function of the colon.

Don't add a trailing period . to headers.

Rationale: every header consists of a single short sentence, so there is not need to add a sentence separator to it.

Good

# How to do make omelet

Bad

# How to do make omelet:

Bad

# How to do make omelet.
Header Synonyms

Headers serve as an index for users searching for keywords.

For this reason, you may want to give multiple keyword possibilities for a given header.

To do so, simply create a synonym header with empty content just before its main header.

E.g.:

# Purchase

# Buy

You give money and get something in return.

Every empty header with the same level as the following one is assumed to be a synonym. This is not the case if levels are different:

# Animals

## Dog

Blockquotes

Follow the greater than marker > by one space.

Good

> a

Bad

>a

Bad, 2 spaces

>  a

Use a greater than sign > for every line, including wrapped.

Bad

> Long line
that was wrapped.

Good

> Long line
> that was wrapped.

Don't use empty lines inside a single block quote.

Good

> a
>
> b

Bad

> a

> b

Lists

Marker
Unordered

Use the hyphen marker -.

Good

- a
- b

Bad

* a
* b
+ a
+ b

Rationale:

  • Asterisk * can be confused with bold or italic markers.
  • Plus sign + is not popular

Downsides:

  • * and + are more visible.
  • * is more visible
Ordered

Prefer lists only with the marker 1. for ordered lists, unless you intend to refer to items by their number in the same markdown file or externally.

Prefer lists with the marker 1., 2., 3. and etc. for ordered lists.

Prefer unordered lists unless you intent to refer to items by their number.

Best, we will never refer to the items of this list by their number

- a
- c
- b

Better, only 1.

1. a
1. c
1. b

Worse, we will never refer to the items of this list by their number

1. a
2. c
3. b

Acceptable, refer to them in the text

The output of the `ls` command is of the form:

    drwx------  2 ciro ciro        4096 Jul  5  2013 dir0
    drwx------  4 ciro ciro        4096 Apr 27 08:00 dir1
    1           2

Where:

1. permissions
2. number of files directory contains

Acceptable, meant to be referred by number from outside of the markdown file

Terms of use.

1. I will not do anything illegal.
2. I will not do anything that can harm the website.

Rationale:

  • If you want to change a list item in the middle of the list, you don't have to modify all items that follow it.

    Diffs will show only the significant line which was modified.

  • Content stays aligned without extra effort if the numbers reach 2 digits. E.g.: the following is not aligned:

    9. a
    10. b
  • References break when a new list item is added. To reduce this problem:

    • Keep references close to the list so authors are less likely to forget to update them

    • When referring from an external document, always refer to an specific version of the markdown file

Spaces Before List Marker

Do not add any space before list markers, except to obey the current level of indentation.

Bad

  - a
  - b

Good

- a
- b

Good, c is just following the indentation of b

-   a
-   b
    - c

Bad, c modified the indentation of b

-   a
-   b
      - c

Rationale:

  • Easier to type
  • Easier to reason about levels
Spaces After List Marker

list-space:mixed

If the content of every item of the list is fits in a single paragraph, use 1 space.

Otherwise, for every item of the list:

  • Use 3 spaces for unordered lists.

  • Use 2 spaces for ordered lists.

    One less than for unordered because the marker is 2 chars long.

( icehe : It's controversial. )

Bad, every item is one line long

-   a
-   b

Good

- a
- b

Bad, every item is one line long

1.  a
1.  b

Good

1. a
1. b

Bad, item is longer than one line

- item that
  is wrapped

- item 2

Good

-   item that
    is wrapped

-   item 2

Bad, item is longer than one line

- a

  par

- b

Good

-   a

    par

-   b
Rationale: list-space mixed vs 1

The advantages of list-space:1 are that

  • It removes the decision of how many spaces you should put after the list marker: it is always one.

    We could choose to always have list content indented as:

    -   a
    -   b

    but that is ugly.

  • You never need to change the indentation of the entire list because of a new item.

    This may happen in list-space:mixed if you have:

    - a
    - b

    and will add a multi-line item:

    -   a
    
    -   b
    
    -   c
    
        d

    Note how a and b were changed because of c.

The disadvantages of list-space:1

  • Creates three indentation levels for the language:

    • 4 for indented code blocks
    • 3 for ordered lists
    • 2 for unordered lists

    That means that you cannot easily configure your editor indent level to deal with all cases when you want to change the indentation level of multiple list item lines.

  • Is not implemented consistently across editors.

    In particular what should happen at:

    - a
    
            code

    This ( 2 spaces ):

    <pre><code>  code</code></pre>

    Or no spaces:

    <pre><code>code</code></pre>

    Likely the original markdown said no spaces:

    "To put a code block within a list item, the code block needs to be indented twice — 8 spaces or two tabs"

    But many implementations did otherwise.

    CommonMark adds the 2 spaces.

Indentation of Content Inside Lists

The indentation level of what comes inside list and of further list items must be the same as the first list item.

Bad

-   item that
  is wrapped

-   item 2

Good

-   item that
    is wrapped

-   item 2

Bad

-   item 1

  Content 1

-   item 2

      Content 2

Good, if it matches your spaces after list marker style

-   item 1

    Content 1

-   item 2

    Content 2

Bad

- item 1

    Content 1

- item 2

    Content 2

Good, if it matches your spaces after list marker style

- item 1

  Content 1

- item 2

  Content 2

Avoid starting a list item directly with indented code blocks because that is not consistently implemented. CommonMark states that a single space is assumed in that case:

-     code

  a
Empty Lines Inside Lists

If every item of a list is a single line long, don't add empty lines between items. Otherwise, add empty lines between every item.

Bad, single lines

- item 1

- item 2

- item 3

Good

- item 1
- item 2
- item 3

Bad, multiple lines

-   item that
    is wrapped
-   item 2
-   item 3

Good

-   item that
    is wrapped

-   item 2

-   item 3

Bad, multiple lines

-   item 1

    Paragraph.

-   item 2
-   item 3

Good

-   item 1.

    Paragraph.

-   item 2

-   item 3

Bad, multiple lines

-   item 1

    - item 11
    - item 12
    - item 13

-   item 2
-   item 3

Good

-   item 1

    - item 11
    - item 12
    - item 13

-   item 2

-   item 3

Rationale: it is hard to tell where multi-line list items start and end without empty lines.

Empty Lines Around Lists

Surround lists by one empty line.

Bad

Before.
- item
- item
After.

Good

Before.

- list
- list

After.
Case of First Letter of List Item

Each list item has the same case as it would have if it were concatenated with the sentence that comes before the list.

Good

I want to eat:

- apples
- bananas
- grapes

because it could be replaced with

I want to eat apples
I want to eat bananas
I want to eat grapes

Good

To ride a bike you have to:

- get on top of the bike. This step is easy.
- put your foot on the pedal.
- push the pedal. This is the most fun part.

because it could be replaced with

To ride a bike you have to get on top of the bike. This step is easy.
To ride a bike you have to put your foot on the pedal.
To ride a bike you have to push the pedal. This is the most fun part.

Good

# How to ride a bike

- Get on top of the bike.
- Put your feet on the pedal.
- Make the pedal turn.

because it could be replaced with

# How to ride a bike

Get on top of the bike.
Put your feet on the pedal.
Push the pedal.
Punctuation at the End of List Items

Punctuate at the end of list items if either it:

  • contains multiple sentences or paragraphs
  • starts with an upper case letter

Otherwise, omit the punctuation if it would be a period ..

Bad, single sentences

- apple.
- banana.
- orange.

Good

- apple
- banana
- orange

Idem

- go to the market
- then buy some fruit
- finally eat the fruit

Good, not terminated by period but by other punctuation

- go to the marked
- then buy fruit?
- of course!

Bad, multiple sentences

- go to the market
- then buy some fruit. Bad for wallet
- finally eat the fruit. Good for tummy

Good

- go to the market
- then buy some fruit. Bad for wallet.
- finally eat the fruit. Good for tummy.

Note: nothing forbids one list item from ending in period while another in the same list does not.

Bad, multiple paragraphs

-   go to the market

-   then buy some fruit

    Bad for wallet

-   finally eat the fruit

    Good for tummy

Good

-   go to the market

-   then buy some fruit.

    Bad for wallet.

-   finally eat the fruit.

    Good for tummy.

Bad, starts with upper case

- Go to the market
- Then buy some fruit
- Finally eat the fruit

Good

- Go to the market.
- Then buy some fruit.
- Finally eat the fruit.

Definition Lists

Avoid the definition list extension since it is not present in many implementations nor in CommonMark.

Instead, use either:

  • Formatted lists:

    • format the item be defined as either of bold, link or code
    • separate the item from the definition with a colon and a space : .
    • don't align definitions as it is harder to maintain and does not show on the HTML output

Good

- **apple**: red fruit
- **dog**: noisy animal

Good

-   **apple**: red fruit.

    Very tasty.

-   **dog**: noisy animal.

    Not tasty.

Good

- [apple](http://apple.com): red fruit
- [dot](http://dog.com): red fruit

Good

- `-f`: force
- `-r`: recursive

Bad, no colon

- **apple** red fruit
- **dog** noisy animal

Bad, space between term and colon

- **apple** : red fruit
- **dog** : noisy animal

Bad, definitions aligned

- **apple**: red fruit
- **dog**:   noisy animal
  • headers

Good

# Apple

Red fruit

# Dog

Noisy animal

Code Blocks

Only use fenced code blocks.

Comparison to indented code blocks:

  • Disadvantage: not part of the original markdown, thus less portable, but added to CommonMark.
  • Advantage: many implementations, including GitHub's, allow to specify the code language with it

Don't indent fenced code blocks.

Always specify the language of the code is applicable.

Good

```ruby
a = 1
```

Bad

```
a = 1
```

Horizontal Rules

Don't use horizontal rules except to indicate the end of a header.

Rationale:

  • Headers are better section separators since they say what a section is about.
  • Horizontal rules don't have a generally accepted semantic meaning. This guide gives them one.

Use 3 hyphens without spaces

---

Tables

Prefer lists to tables. Any tables in your Markdown should be small.

( from Google Markdown style guide )

Bad

Fruit | Attribute | Notes
--- | --- | --- | ---
Apple | [Juicy](https://example.com/SomeReallyReallyReallyReallyReallyReallyReallyReallyLongQuery), Firm, Sweet | Apples keep doctors away.
Banana | [Convenient](https://example.com/SomeDifferentReallyReallyReallyReallyReallyReallyReallyReallyLongQuery), Soft, Sweet | Contrary to popular belief, most apes prefer mangoes.

Good

Lists and subheadings usually suffice to present the same information in a slightly less compact, though much more edit-friendly way:

## Fruits

### Apple

- [Juicy](https://SomeReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongURL)
- Firm
- Sweet

Apples keep doctors away.

### Banana

- [Convenient](https://example.com/SomeDifferentReallyReallyReallyReallyReallyReallyReallyReallyLongQuery)
- Soft
- Sweet

Contrary to popular belief, most apes prefer mangoes.

Good

There are times when a small table is called for

|Transport       |Favored by    |Advantages                   |
|----------------|--------------|-----------------------------|
|Swallow         |Coconuts      |Otherwise unladen            |
|Bicycle         |Miss Gulch    |Weatherproof                 |
|X-34 landspeeder|Whiny farmboys|Cheap since the X-38 came out|

Rationale: Complex, large tables are difficult to read in source and most importantly, a pain to modify later.


Extension.

  • Surround tables by one empty line.
  • Don't indent tables.
  • Surround every line of the table by pipes.
  • Align all border pipes vertically.
  • Separate header from body by hyphens except at the aligned pipes |.
  • Pipes | must be surrounded by a space, except for outer pipes which only get one space internally, and pipes of the hyphen separator line.
  • Column width is determined by the longest cell in the column.

Good table

Before.

|h   |Long header|
|----|-----------|
|abc |def        |
|abc2|def2       |

After.

Rationale:

  • Unaligned tables tables are easier to write, but aligned tables are more readable, and people read code much more often than they edit it.

  • Preceding pipes make it easier to determine where a table starts and ends. Trailing pipes make it look better because of symmetry.

  • There exist tools which help keeping the table aligned. For example, Vim has the Tabular plugin which allows to align the entire table with :Tabular /|.

  • Why no spaces around pipes of the hyphen separator line, i.e.: |---| instead of | - |? No spaces looks better, works on GitHub.

    Downside: harder to implement automatic alignment in editors, as it requires a special rule for the separator line.

Separate Consecutive Elements

Separate consecutive:

  • lists
  • indented code blocks
  • blockquotes
  • list followed by external code block

with an empty HTML comment <!-- -->.

- list 1
- list 1

<!-- -->

- list 2
- list 2
    code 1
    code 1

<!-- -->

    code 2
    code 2
> blockquote 1
> blockquote 1

<!-- -->

> blockquote 2
> blockquote 2
- list
- list

<!-- -->

    code outside list
    code outside list

Span elements

Don't use inner spaces.

Good

**bold**
`code`
[link](http://a.com)
[text][name]

Bad

** bold **
` code `
[ link ]( http://a.com )
[text] [name]

For inline code in which the space is crucial:

  • explain in writing that the spaces must be there
  • add something after the space if possible

Good

Use the hyphen marker followed by one space `- a`  for unordered lists.

Rationale: most browsers don't render the surrounding spaces nor add them to the clipboard on copy.

Links

Reference-style Links

Links: use the trailing [] on implicit links.

Links: avoid using reference-style links.

Good

[a][]

Bad

[a]

Rationale: while omitting [] works on most major implementations, it is not specified in the documentation and not implemented in the original markdown.

Definitions:

  • must be the last thing on the file
  • must be sorted alphabetically by the ID
  • don't enclose URLs by angle brackets
  • align URLs and link names as in a table
  • link IDs use only lowercase letters. Rationale: they are case insensitive,
  • lowercase only is easier to write, and the readability gain of mixed case is not very big.

Good

[id2]:     http://long-url.com
[long id]: http://a.com        "name 1"

Bad, not ordered by id

[b]: http://a.com
[a]: http://b.com

Bad, not aligned

[id]: http://id.com
[long id]: http://long-id.com
Single or Double Quote Titles

Use double quotes, not single quotes.

# Class `Integer`

Rationale: single quotes do not work in all major implementations, double quotes do.

Short Link Titles

( from Google Markdown style guide )

Use informative Markdown link titles

Write the sentence naturally, then go back and wrap the most appropriate phrase with the link.

Bad

See the syntax guide for more info: [link](syntax_guide.md).
Or, check out the style guide [here](style_guide.md).
DO NOT DO THIS.

Good

See the [syntax guide](syntax_guide.md) for more info.
Or, check out the [style guide](style_guide.md).

Rationale:

  • Markdown link syntax allows you to set a link title, just as HTML does. Use it wisely.
  • Titling your links as "link" or "here" tells the reader precisely nothing when quickly scanning your doc and is a waste of space:

Emphasis

Bold

Use double asterisk format: **bold**.

Bad

__Bold content__

Good

**Bold content**

Rationale: more common and readable than the double underline __bold__ form.

Italic

Use single asterisk format: *italic*.

Use single underscore format: _italic_.

Bad

*Italic content*

Good

_Italic content_

Rationale:

  • more common and readable than the underscore form
  • consistent with the bold format, which also uses asterisks
Uppercase for Emphasis

Don't use uppercase for emphasis: use emphasis constructs like bold or italic instead.

Bad

EMPHASIS

Good

**Emphasis**

Rationale: CSS has text-transform:uppercase which can easily achieve the same effect consistently across the entire website if you really want uppercase letters.

Emphasis vs Headers

Don't use emphasis elements ( bold or italics ) to introduce a multi line named section: use headers instead.

  • Rationale: that is exactly the semantic meaning of headers, and not necessarily that of emphasis elements.

    As a consequence, many implementations add useful behaviors to headers and not to emphasis elements, such as automatic id to make it easier to refer to the header later on.

Good

# How to make omelets

Break an egg.

...

# How to bake bread

Open the flour sack.

...

Bad

**How to make omelets:**

Break an egg.

...

**How to bake bread:**

Open the flour sack.

...

Automatic Links

Automatic Links without Angle Brackets

Don't use automatic links without angle brackets.

Don't use automatic links with angle brackets.

Good Bad

<http://a.com>

Bad Good

http://a.com

Rationale: it is an extension, <> is easy to type and saner.

If you want literal links which are not autolinks, enclose them in code blocks.

E.g.:

`http://not-a-link.com`

Rationale: many tools automatically interpret any word starting with http as a link.

Content of Automatic Links

All automatic links must start with the string http.

In particular, don't use relative automatic links. Use bracket links instead for that purpose.

Good

[file.html](file.html)

Bad

<file.html>

Good

https://github.com

Good Bad

<https://github.com>

Bad

<github.com>

Rationale: it is hard to differentiate automatic links from HTML tags. What if you want a relative link to a file called script?

Email Automatic Links

Don't use email autolinks <[email protected]>. Use raw HTML instead.

Rationale: the original markdown specification states it:

"performs a bit of randomized decimal
and hex entity-encoding
to help obscure your address
from address-harvesting spambots."

Therefore, the output is random, ugly, and as the spec itself mentions:

"but an address published in this way
will probably eventually start receiving spam"

Bad

Good, e.g.

icehe.xyz#qq.com ( replace `#` with `@` )

Content

Document Layout

( from Google Markdown style guide )

In general, most documents benefit from some variation of the following layout:

# Document Title

Short introduction.

---

<!-- [TOC] -->

## Topic

Content.

## See also

- https://link-to-more-info
  • # Document Title: The first heading should be a level one heading, and should ideally be the same or nearly the same as the filename. The first level one heading is used as the page <title>.

  • author: Optional. If you'd like to claim ownership of the document or if you are very proud of it, add yourself under the title. However, revision history generally suffices.

  • Short introduction. 1 ~ 3 sentences providing a high-level overview of the topic. Imagine yourself as a complete newbie, who landed on your "Extending Foo" doc and needs to know the most basic assumptions you take for granted. "What is Foo? Why would I extend it?"

  • _[TOC]: if you use hosting that supports table of contents, such as Gitiles, put [TOC] after the short introduction. ~~See [TOC] documentation.~~~~

  • ## Topic: The rest of your headings should start from level 2.

  • ## See also: Put miscellaneous links at the bottom for the user who wants to know more or didn't find what she needed.

Character Line Limit

( from Google Markdown style guide )

Obey projects' character line limit wherever possible. Long URLs and tables are the usual suspects when breaking the rule. ( Headings also can't be wrapped, but we encourage keeping them short ). Otherwise, wrap your text:

Lorem ipsum dolor sit amet, nec eius volumus patrioque cu, nec et commodo
hendrerit, id nobis saperet fuisset ius.

*   Malorum moderatius vim eu. In vix dico persecuti. Te nam saperet percipitur
    interesset. See the [foo docs](https://gerrit.googlesource.com/gitiles/+/master/Documentation/markdown.md).

Often, inserting a newline before a long link preserves readability while minimizing the overflow:

Lorem ipsum dolor sit amet. See the
[foo docs](https://gerrit.googlesource.com/gitiles/+/master/Documentation/markdown.md)
for details.

Trailing Whitespace

( from Google Markdown style guide )

Don't use trailing whitespace, use a trailing backslash.

The CommonMark spec decrees that two spaces at the end of a line should insert a <br/> tag. However, many directories have a trailing whitespace presubmit check in place, and many IDEs will clean it up anyway.

Best practice is to avoid the need for a <br/> altogether. Markdown creates paragraph tags for you simply with newlines: get used to that.

Images

Use images sparingly, and prefer simple screenshots.

( from Google Markdown style guide )

Rationale:

  • This guide is designed around the idea that plain text gets users down to the business of communication faster with less reader distraction and author procrastination.

  • However, it's sometimes very helpful to show what you mean.

See image syntax.

HTML

Strongly prefer Markdown to HTML

( from Google Markdown style guide )

Rationale:

  • Please prefer standard Markdown syntax wherever possible and avoid HTML hacks. If you can't seem to accomplish what you want, reconsider whether you really need it. Except for big tables, Markdown meets almost all needs already.

  • Every bit of HTML or Javascript hacking reduces the readability and portability. This in turn limits the usefulness of integrations with other tools, which may either present the source as plain text or render it. See Philosophy.

    Gitiles does not render HTML.

Documentation Best Practices

( from Google Markdown style guide )

"Say what you mean, simply and directly." - Brian Kernighan

Contents:

  • Minimum viable documentation
  • Update docs with code
  • Delete dead documentation
  • Documentation is the story of your code

Minimum Viable Documentation

A small set of fresh and accurate docs are better than a sprawling, loose assembly of "documentation" in various states of disrepair.

Write short and useful documents. Cut out everything unnecessary, while also making a habit of continually massaging and improving every doc to suit your changing needs. Docs work best when they are alive but frequently trimmed, like a bonsai tree.

This guide ( Google Markdown style guide ) encourages engineers to take ownership of their docs and keep them up to date with the same zeal we keep our tests in good order. Strive for this.

  • Identify what you really need: release docs, API docs, testing guidelines.
  • Delete cruft frequently and in small batches.

Update Docs with Code

Change your documentation in the same CL ( Commit Log ) as the code change. This keeps your docs fresh, and is also a good place to explain to your reviewer what you're doing.

A good reviewer can at least insist that docstrings, header files, README.md files, and any other docs get updated alongside the CL.

Delete Dead Documentation

Dead docs are bad. They misinform, they slow down, they incite despair in engineers and laziness in team leads. They set a precedent for leaving behind messes in a code base. If your home is clean, most guests will be clean without being asked.

Just like any big cleaning project, it's easy to be overwhelmed. If your docs are in bad shape:

  • Take it slow, doc health is a gradual accumulation.
  • First delete what you're certain is wrong, ignore what's unclear.
  • Get your whole team involved. Devote time to quickly scan every doc and make a simple decision: Keep or delete?
  • Default to delete or leave behind if migrating. Stragglers can always be recovered.
  • Iterate.

Prefer the Good Over the Perfect

Your documentation should be as good as possible within a reasonable time frame.

The standards for a documentation review are different from the standards for code reviews. Reviewers can and should ask for improvements, but in general, the author should always be able to invoke the "Good Over Perfect Rule".

It's preferable to allow authors to quickly submit changes that improve the document, instead of forcing rounds of review until it's "perfect". Docs are never perfect, and tend to gradually improve as the team learns what they really need to write down.

Documentation is the Story of your Code

Writing excellent code doesn't end when your code compiles or even if your test coverage reaches 100%. It's easy to write something a computer understands, it's much harder to write something both a human and a computer understand. Your mission as a Code Health-conscious engineer is to write for humans first, computers second. Documentation is an important part of this skill.

There's a spectrum of engineering documentation that ranges from terse comments to detailed prose:

  1. Inline comments: The primary purpose of inline comments is to provide information that the code itself cannot contain, such as why the code is there.

  2. Method and class comments:

    • Method API documentation:

      The header / Javadoc / docstring comments that say _what methods do and how to use them. This documentation is the contract of how your code must behave. The intended audience is future programmers who will use and modify your code.

      It is often reasonable to say that any behavior documented here should have a test verifying it. This documentation details what arguments the method takes, what it returns, any "gotchas" or restrictions, and what exceptions it can throw or errors it can return. It does not usually explain why code behaves a particular way unless that's relevant to a developer's understanding of how to use the method. "Why" explanations are for inline comments. Think in practical terms when writing method documentation: "This is a hammer. You use it to pound nails."

    • Class / Module API documentation: The header / Javadoc / docstring comments for a class or a whole file. This documentation gives a brief overview of what the class / file does and often gives a few short examples of how you might use the class / file.

      Examples are particularly relevant when there's several distinct ways to use the class (some advanced, some simple). Always list the simplest use case first.

  3. README.md:

    A good README.md orients the new user to the directory and points to more detailed explanation and user guides:

    • What is this directory intended to hold?
    • Which files should the developer look at first? Are some files an API?
    • Who maintains this directory and where I can learn more?

    See the README.md guidelines.

README.md Files

( from Google Markdown style guide )

About README.md files.

  1. Overview
  2. Guidelines
  3. Filename
  4. Contents
  5. Example

Overview

README.md files are Markdown files that describe a directory. GitHub and Gitiles renders it when you browse the directory.

For example, the file /README.md is rendered when you view the contents of the containing directory:

https://github.com/google/styleguide/tree/gh-pages

Also README.md at HEAD ref is rendered by Gitiles when displaying repository index:

https://gerrit.googlesource.com/gitiles/

Guidelines

README.md files are intended to provide orientation for engineers browsing your code, especially first-time users. The README.md is likely the first file a reader encounters when they browse a directory that contains your code. In this way, it acts as a landing page for the directory.

We recommend that top-level directories for your code have an up-to-date README.md file. This is especially important for package directories that provide interfaces for other teams.

Filename

Use README.md.

Files named README are not displayed in the directory view in Gitiles.

Contents

At minimum, every package-level README.md should include or point to the following information:

  1. What is in this package/library and what's it used for.
  2. Who to contact.
  3. Status: whether this package/library is deprecated, or not for general release, etc.
  4. More info: where to go for more detailed documentation, such as:
    • An overview.md file for more detailed conceptual information.
    • Any API documentation for using this package/library.

Example

# APIs

This is the top-level directory for all externally-visible APIs,
plus some private APIs under `internal/` directories.
See [API Style Guide](docs/apistyle.md) for more information.

*TL;DR*: API definitions and configurations should be defined in `.proto` files,
checked into `apis/`.

...

Philosophy

( from Google Markdown style guide )

埏埴以為器,當其無,有器之用.

Clay becomes pottery through craft, but it's the emptiness that makes a pot useful.

- Laozi

Contents:

  • Radical simplicity
  • Readable source text
  • Minimum viable documentation
  • Better is better than perfect

Radical Simplicity

  • Scalability and interoperability are more important than a menagerie ( 动物展览 ) of unessential features. Scale comes from simplicity, speed, and ease. Interoperability ( 互操作性 ) comes from unadorned ( 朴素的 ), digestible content ( 容易消化的 ) .

  • Fewer distractions make for better writing and more productive reading.

  • New features should never interfere with the simplest use case and should remain invisible to users who don't need them.

  • This guide is designed for the average engineer -- the busy, just-want-to-go-back-to-coding engineer. Large and complex documentation is possible but not the primary focus.

  • Minimizing context switching makes people happier. Engineers should be able to interact with documentation using the same tools they use to read and write code.

Readable Source Text

  • Plain text not only suffices, it is superior. Markdown itself is not essential to this formula, but it is the best and most widely supported solution right now. HTML is generally not encouraged.

  • Content and presentation should not mingle ( 混合 ) . It should always be possible to ditch the renderer and read the essential information at source. Users should never have to touch the presentation layer if they don't want to.

  • Portability and future-proofing leave room for the unimagined integrations to come, and are best achieved by keeping the source as human-readable as possible.

  • Static content is better than dynamic, because content should not depend on the features of any one server. However, fresh is better than stale. We strive to balance these needs.

Minimum Viable Documentation

  • Docs thrive when they're treated like tests: a necessary chore one learns to savor because it rewards over time. See Best Practices.

  • Brief and utilitarian is better than long and exhaustive. The vast majority of users need only a small fraction of the author's total knowledge, but they need it quickly and often.

Better Is Better Than Perfect

  • Incremental improvement is better than prolonged ( 长时间的 ) debate. Patience and tolerance of imperfection allow projects to evolve organically ( 有机地 ) .

  • Don't lick the cookie, pass the plate. We're drowning in ( 溺死在 ) potentially impactful projects. Choose only those you can really handle and release those you can't.

补充 Mine

列表 Lists

不混用「编号列表」和「顺序列表」, 建议只使用「无序列表」

因为并非所有 Markdown 渲染引擎都支持

Good

- item a
    - item aa
- item b
    - item bb
    - item bc
        - item cat

Not recommended

1. item a
    1.1. item aa
2. item b
    2.1. item bb
    2.2. item bc
        - item cat

Bad

- 1. item a
    - item a
- 1. item b
    - 1. item bb
    - 2. item bc
        - item cat

缩进 Indent

尽量减少缩进

  • 能不用列表符 - 就能表达清楚层级结构的情况, 就别用 -
  • 列表的层次最好控制在 2 层以内, 最多 3 层

Bad

- 计划
    - 确认需求
        - 需求文档
        - 工作排期
    - 开发
        - 编写代码
        - 代码审查
    - 测试
        - 单元测试
        - 集成测试
        - 回归测试
    - 上线
        - 预览上线
            - 预览测试
        - 正式上线

Good

计划

- 确认需求
    - 需求文档
    - 工作排期
- 开发
    - 编写代码
    - 代码审查
- 测试
    - 单元测试
    - 集成测试
    - 回归测试
- 上线
    - 预览上线
    - 正式上线

Better

# 计划

确认需求

- 需求文档
- 工作排期

开发

- 编写代码
- 代码审查

测试

- 单元测试
- 集成测试
- 回归测试

上线

- 预览上线
- 正式上线

链接 Link

基于简单原则: 尽量少地格式化, 去表达同样的意思

如果 URL 链接不是太长, 而且自身能准确表达其网页内容, 就不要使用 [link](url) 语法了

Good

My image: https://hub.docker.com/r/icehe/alpine

Bad

My image: [icehe/alpine](https://hub.docker.com/r/icehe/alpine) @ hub.docker.com

脚注 Footnotes

尽量不使用脚注

表情 Emoji

尽量不使用表情符号

其它 Others

一行内容不要太长

短句方便阅读.

文档撰写方面, 对 "必须 / 应该 / 建议" 的字眼的使用, 请参考 RFC 2119

https://www.ietf.org/rfc/rfc2119.txt

Tools

Highly recommended to use

VS Code & Plugins

VS Code

Mardown Lint

Markdown Lint Tool mdl

当前规则

  • 由 markdown/lint/style.rb 文件声明, 详情如下

mdl styles

推荐通过 form 项目 CI 的 mdl(markdownlint)检查后, 才允许合并 MR

Remark Lint

remark-lint

  • 错误输出比 markdownlint 可读性更好

Other Lints

Asked on Stack Exchange: http://softwarerecs.stackexchange.com/questions/7138/markdown-lint-tool