Markdown By Example · Simpletext 2 Simpletext Since Markdown is supposed to make reading and...

32

Transcript of Markdown By Example · Simpletext 2 Simpletext Since Markdown is supposed to make reading and...

Markdown By Example©2012 Tim Steinbach

This version was published on 2012-07-28

This is a Leanpub book, for sale at:

http://leanpub.com/markdown

Leanpub helps authors to self-publish in-progress ebooks.We call this idea Lean Publishing. To learn moreabout Lean Publishing, go to: http://leanpub.com/manifesto

To learn more about Leanpub, go to: http://leanpub.com

Contents

Preview i

ToDo iii

1 Simple text 1

PreviewThis book is a work-in-progress.

Please do not hesitate to point out any errors, spellingmistakes etc. Especially, let me know if there arepassages that are difficult to understand or chaptersthat require more explanation. If there are problemswith any of the code examples and/or exercises, youare more than welcome to create a Pull request¹ onGitHub or simply point out the error using any ofthe below channels of communication. In fact, anyfeedback is good feedback!

Contact me via

• Email²

• Twitter (@Tim_Steinbach³)

• LinkedIn⁴

• Creating an “issue” on GitHub⁵

¹https://github.com/NeQuissimus/MarkdownByExample/pulls²[email protected]³http://twitter.com/Tim_Steinbach⁴http://ca.linkedin.com/in/timsteinbach⁵https://github.com/NeQuissimus/MarkdownByExample/issues

i

Preview ii

The following ToDo list should outline all open tasksfor this book’s completion.

ToDoFirst iteration

• Acknowledgements

• Add to Reasons for Markdown

• Add to 3 - iAWriter

• Add to 3 - Marked

• Add to 7 - Code (after 7.16)

• Add to 10 - Layouts (before 10.2)

• Add to 10 - Pages (before 10.4)

Second iteration

• Codify in-text commands

• Put URLs, file names and folders in _

• 300 dpi images

• Spellcheck

• Add link to LeanPub video (once published)

iii

ToDo iv

• Sync links in repo & book

• No page breaks within code blocks

Third iteration

• Proof-reading

• Fill GitHub Wiki

• Repo as ZIP on GitHub

• Remove preview notice

• Remove ToDo list

1 Simple textThis chapter contains:

• Headlines

• Emphasis

• Lists

• Images

• Hyperlinks

• Code

• Output

Relevant source folders:

• /readme/

1

Simple text 2

Simple text

Since Markdown is supposed to make reading andwriting files easy without stripping the author of theability to create well formatted output, a Markdownfile is all about its contents and as little distractionas possible from formatting. We will take a look atmost of the formatting elements available for regularMarkdown files. A full syntax documentation can befound at DaringFireball¹.

In this chapter we will create a README file for afictional piece of software. By the end of it, we willhave used quite a few different ways of formattingtext, without ever shifting our focus from content tothe overhead of formatting that is usually requiredwith HTML or TeX. At all times will our README beeasy-to-read and still create a well-structured result,ready to be published with our software.

¹http://daringfireball.net/projects/markdown/syntax

Simple text 3

Headlines

The first step to our first Markdown file is - naturally- creating a new file. It should use the file extension.markdown. GitHub has its own .md extension, whichcan be used instead. Oncewe have created the file, it istime to edit it. The first thing we should do is create aheadline for the entire document. The first and largestheadline is called an H1, the second level is H2 andso forth, up to H6. Headlines can be created in twodifferent ways: H1 and H2 can just be underlined byequals signs or hyphens, such as this:

Headline 1

=========

Headline 2

----------

Regular text

For this method of creating headlines, the numberof underlining characters is irrelevant. While thisis a great way of making headlines obvious in yourdocument, you are limited to H1 and H2 headlines.For H3 through H6 you would have to mix the secondway of creating headlines with the aforementioned

Simple text 4

underlining method. Or you decide to use the fol-lowing notation exclusively. Headlines can also becreated by prefixing a number of pound signs (#)followed by a space to the title. The specific numberof pound signs used define the header level. Code 7.1from above could also look like this, without changingthe final result:

# Headline 1

## Headline 2

Regular Text

Eventually, it is up to the author to decide which styleis preferred. It should be noted that for the rest of thisbook, we will use the pound symbol method.

The following example is designed to include themostimportant portions of the Markdown syntax. First,we will emphasize words, some by printing them inbold face. Secondly, we will talk about ordered andunordered lists. After that an image will be added toour README, before making use of hyperlinks. Thischapter will conclude with an example on how to usecode blocks with Markdown.

Simple text 5

Now let us lay out the headlines for our README file.During the remainder of this chapter we will then fillthe headlines with more contents.

# GoodTool

## What is GoodTool?

## Features

## Download

## Installation

## Screenshot

## API example

### Access to API factory (Java)

### Usage of API factory (Java)

## Contact

We can see that our software is called GoodTool,which is the title for the first headline. We have anumber of second-level and two third-level headlines.

Simple text 6

Text emphasis

We begin by filling the headline “What is Good-Tool?” with contents. Let the description be thesentence “GoodTool makes system monitoring easierthan ever before and is available for Windows andLinux operating systems”. Nothing is easier thanthis, we simply enter the sentence into our READMEfile. But we would like to emphasize that this is theeasiest monitoring tool ever by printing the words“ever before” in bold face. Additionally, the operatingsystems Windows and Linux should be emphasized,but not as much as the “ever before”.

Markdown once again allows us to choose betweentwo different ways of emphasizing text. We can eitheruse underscores (_) or asterisks (*). Surrounding textwith a since one of those characters causes regularemphasis of the given text. Doubling the surroundingcharacters causes a stronger emphasis, usually boldface print.

Simple text 7

Knowing this, it is now easy to accomplish our wishesfrom above with the following Markdown code:

## What is GoodTool?

GoodTool makes system monitoring easier than

**ever before** and is available for _Windows_

and _Linux_ operating systems.

While it is up to the author to choose underscoresand/or asterisks, this book will use underscores forsimple emphasis and double-asterisks for strong em-phasis. This way the author’s intention becomes veryclear and sometimes it is hard to see the differencebetween single or double underscores. The abovementioned convention clearly avoids this.

Simple text 8

Lists

Next up is the features headline. Here we would liketo list some of the most important features of our soft-ware. Lists are generally divided into two categories:Ordered lists and unordered lists. The former usuallymake use of Arabic or Roman numbers, the latter canuse any kind of character. For our features list wewill not need an ordered list because it does not reallymatter in which order we list them. (Markdown doeskeep the order of items in your list, but they do notneed to be numbered) Unordered lists can be createdby using one of the prefixes for unordered lists foreach item the list shall contain. Asterisks (*), hyphens(-) and pluses (+) are completely interchangeable, buthave to be followed by a space (similar to the waypound-symbol headlines are defined). The list of ourfeatures could therefore look like this:

## Features

* Fast

* Secure

* Easy-to-work-with GUI

Simple text 9

This will create an unordered list of our top threefeatures. We could have as well used hyphens orpluses. For the “Download” paragraph we will do justthat, the actual links to our software will be addedlater, once we learn about hyperlinks.

## Download

- Version 1.0

- Version 0.9

- Version 0.8

So far, this is what our README.markdown shouldlook like: (plus the additional headlines that we havenot yet worked with)

Simple text 10

# GoodTool

## What is GoodTool?

GoodTool makes system monitoring easier than

**ever before** and is available for _Windows_

and _Linux_ operating systems.

## Features

* Fast

* Secure

* Easy-to-work-with GUI

## Download

- Version 1.0

- Version 0.9

- Version 0.8

Simple text 11

For the installation instructions included in our file,we would like to use an ordered list. This makessense as the user will be guided through the processand should follow the instructions one step afteranother. Luckily, ordered lists are extremely easy inMarkdown. All we need to do is use Arabic numbersas prefixes. Our installation instructions could thenlook like this:

## Installation

1. Download GoodTool

2. Execute .exe or .sh file

3. Follow screen instructions

The ordered list would automatically be convertedinto the corresponding output elements.

Simple text 12

Images

Next, wewill need to add a screenshot to our READMEfile. This is probably the first thing you would nothave added to an ordinary README.txt file. After all,a text file is supposed to contain nothing but text. Thefact that Markdown files will have to be parsed andconverted comes in handy here, as images will not bevisible while editing our file but will be present in theresulting output. As we will see, the syntax for addingimages is very similar to that of hyperlinks. Bothsomewhat connect to external content and thereforehave almost the same notation.

An image link consists of three parts: The path tothe actual image file, a text used in case the imagecannot be found (alt text) and an image title. Theimage path is obviously required and so is the alttext, because the image file might have been movedor the given path be wrong. An image’s title attribute,however, is optional. The title is usually convertedinto a mouseover text in the resulting output of ourMarkdown file.

The screenshot of our GUI is called GoodToolGui.pngand will be added to our README like this:

Simple text 13

## Screenshot

![GUI Screenshot](GoodToolGui.png "Screenshot")

An exclamation mark suggests that the following isan image. The alt text for our image is in the squarebrackets, while the parentheses contain the path to ourimage and the optional title.

If an image is to be used on several occasions, thereis an easy way of dealing with this: Image references.Instead of using an image’s path and title each timewe would like to display said image, we can define itonce and use references to the definition. Referencesare usually defined at the very bottom of a documentand have a syntax consisting of ID, path and title. Ourscreenshot could have been defined as a reference:

## Screenshot

![GUI Screenshot][screenshot]

[screenshot]: GoodToolGui.png "Screenshot"

We have replaced the parentheses in our image tagwith the reference ID of the image we would liketo use. At the bottom of our document we havethen defined said reference ID with the path and title

Simple text 14

that we had previously used inside the parenthesesof our image tag. Now we could very easily reusethe screenshot reference without having to rememberthe image’s path. And should its path ever change- for example, if somebody moved all images into aseparate folder - it will only have to be altered once.There is no need for a risky “search and replace all”operation in your text editor. Since we will only havea single image in our example, we opt for the firstversion of the image tag, which saves us from havingto add the reference to the end of our file.

Simple text 15

Hyperlinks

Hyperlinks (or just links) are references to other con-tent. This other content might be an anchor inthe same document or external contents such as anInternet URL to a website or an image. For now,we will only look at links to external content becauseMarkdown does not directly support internal anchors.These have to be realized by adding custom HTMLcode to our file, something that will be covered in thechapter Markdown and HTML.

In our README file, we need links to external con-tents under two headlines: Downloads and Contact.While linking directly to files under the Downloadsheading, we will link to our website and offer alink to our email address under Contact. Creatinga hyperlink is very simple and should already seemfamiliar, since it closely resembles the syntax used forimages (and vice versa). Earlier, we added a list ofdownloadable versions. The last of the three, version0.8, we will use to link directly to the 0.8 file.

Simple text 16

## Download

- Version 1.0

- Version 0.9

- Version [0.8](http://rmrf.eu/

gt/0_8.zip "Link to 0.8")

As we can see, creating a hyperlink looks just like theimage tag, except there is no exclamation mark prefix.This is the only difference between the two! Again,the link title is optional.

Similar to our screenshot example, we could also wantto create references to our links and use those insteadof directly embedding the URL into our link. Just likethe reference to an image, a link reference works bycreating an ID and defining it (usually at the end ofthe document). For the remaining two versions wedefine the following links:

## Download

- Version [1.0][2]

- Version [0.9][1]

- Version [0.8](http://rmrf.eu/

gt/0_8.zip "Link to 0.8")

[1]: http://rmrf.eu/gt/0_9.zip "Link to 0.9"

[2]: http://rmrf.eu/gt/1_0.zip "Link to 1.0"

Simple text 17

As we can see, the parentheses have been replacedby a second pair of square brackets. Inside thesewe find reference IDs, which have been defined notunlike an image would have be defined. It is notnecessary to number the links but you can use anyID you wish. We could very well have named thelinks [Version10File] and [Version09File] instead. Theonly requirement with reference IDs is the fact thatthey must be unique within the document. (Note thatwhen using references, IDs must be unique amonghyperlinks and pictures. There cannot be an imageusing the same ID as a hyperlink)

Sometimes it is not necessary to hide a link behinda title and the actual URL should be displayed to thereader. This might be the case when referring to awebsite or an email address. Under our Contact head-line we will be using “Automatic Links”, hyperlinkswhose URL and title are identical. We would like thereader to know the URL to our website as well as ouremail address, instead of requiring them to click onthe link title. This could be achieved by defining alink with both the title and target location to the samevalue, using one of the linking methods we have usedbefore. But using automatic links, the work is donefor us:

Simple text 18

## Contact

Go to our website <http://rmrf.eu/>

or email to <[email protected]>

By surrounding the URL and email address withpointy brackets, we define them as automatic links.These will be turned into just what we indented -Links with identical title and location.

Simple text 19

Code

The last thing we would like to add is an exampleon how to use our tool’s API for programmers whowould like to extend or simply control the application.First, we will provide a short one-liner that will showthe reader how they can acquire access to our API.Code statements which are only a few lines long,can easily be expressed in Markdown by surroundingthem with grave accents (‘) aka “backticks”. Gen-erally, this is the preferred way of expressing codestatements which can be fit into a single line. Incase source code contains backticks, the ones definingthe code statement will be doubled. For longer state-ments, there is a more readable way of creating codeblocks - ordinary indentation. All lines that have beenindented by exactly four spaces are considered part ofa code block.

Simple text 20

### Single line statements

`Code statement`

``Code statement that includes ` character``

### Code block

Code Block

Indented

By Four

Spaces

If there are multiple code blocks without any regulartext in between them, they can be split with the end-of-block (EOB) character, since they would otherwiseall be considered part of the same code block. Thisis important as Markdown takes pride in keepingthe resulting HTML well-formed and structured andhaving multiple independent code examples withinthe same block would not conform to being well-formed and structured at all. The EOB character isa circumflex (ˆ) in an otherwise empty line.

Simple text 21

### Multiple code blocks

Code

Block1

Still Code Block 1

^

Code Block 2

Still Code Block 2

In our own README file we could create the APIexamples as follows: Accessing the API is a one-line statement, we will surround with backticks. Thesecond example will be an actual use case of theAPI, which will contain more than one line. Wewill therefore prefer the indentation syntax for theexample with multiple lines of code.

Simple text 22

## API examples

### Access to API factory (Java)

Get the API factory:

`GoodTool api = GoodTool.getAPI();`

### Usage of API factory (Java)

Set monitoring of only one CPU thread:

GoodTool api = GoodTool.getAPI();

api.setMonitoredThreads(1);

Simple text 23

Output

At this point, our README file is complete and thischapter is coming to an end. We have used headlines,used emphasis to highlight parts of our text, listeditems in ordered and unordered lists, added images,links and even source code. Now it is time to find outwhat the result of our (not so) hard work is. We runour Markdown file against bluecloth (one of the Rubygems we installed earlier) and have a look. In orderto run bluecloth and fetch the resulting HTML intoa file (it sends the HTML directly into our Terminalsession), we need to call it with our Markdown filebeing the first parameter and its result being streamedinto a new file.

1 $ bluecloth README.markdown > README.html

Provided the README file is in our current workingdirectory (if not, cd into it), we will get a nice HTMLfile. Open it with your browser and it should looksomething like Figure 7.1.

Simple text 24

Figure 7.1: Resulting output

Not so bad after all, is it? And our Markdown file isstill perfectly readable, unlike the HTML file createdby bluecloth!

If you still have trouble with Markdown syntax, thereis an additional example called “instructions” in theGitHub repository for this book. In this example thereare two files, one with instructions and one with a

Simple text 25

possible solution. At this point it should be notedthat comments in Markdown use the same notation asHTML comments (because they are effectively HTMLcomments) as the file for you to work on is full ofcomments.

The next chapter will be a “cheat sheet”, a short recol-lection of the Markdown syntax, short and compact.This way there is no need to flip through all the pastchapters trying to find a certain formatting syntax.

The following chapter will then use the README wejust created and make modifications by using HTMLand CSS directly. This will allow us to effectivelydesign the output our Markdown converter produces.This chapter will also serve as an introduction to therest of the book, which makes heavy use of not onlyMarkdown but also HTML, CSS and even JavaScript.