Quellcode durchsuchen

Godeps: add spf13/cobra for etcdctlv3

Gyu-Ho Lee vor 10 Jahren
Ursprung
Commit
a6bb74e9ff
100 geänderte Dateien mit 19825 neuen und 1 gelöschten Zeilen
  1. 27 1
      Godeps/Godeps.json
  2. 21 0
      Godeps/_workspace/src/github.com/cpuguy83/go-md2man/LICENSE.md
  3. 19 0
      Godeps/_workspace/src/github.com/cpuguy83/go-md2man/md2man/md2man.go
  4. 269 0
      Godeps/_workspace/src/github.com/cpuguy83/go-md2man/md2man/roff.go
  5. 13 0
      Godeps/_workspace/src/github.com/inconshreveable/mousetrap/LICENSE
  6. 23 0
      Godeps/_workspace/src/github.com/inconshreveable/mousetrap/README.md
  7. 15 0
      Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_others.go
  8. 98 0
      Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows.go
  9. 46 0
      Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
  10. 8 0
      Godeps/_workspace/src/github.com/russross/blackfriday/.gitignore
  11. 18 0
      Godeps/_workspace/src/github.com/russross/blackfriday/.travis.yml
  12. 29 0
      Godeps/_workspace/src/github.com/russross/blackfriday/LICENSE.txt
  13. 267 0
      Godeps/_workspace/src/github.com/russross/blackfriday/README.md
  14. 1398 0
      Godeps/_workspace/src/github.com/russross/blackfriday/block.go
  15. 1532 0
      Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go
  16. 949 0
      Godeps/_workspace/src/github.com/russross/blackfriday/html.go
  17. 1133 0
      Godeps/_workspace/src/github.com/russross/blackfriday/inline.go
  18. 1153 0
      Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go
  19. 332 0
      Godeps/_workspace/src/github.com/russross/blackfriday/latex.go
  20. 926 0
      Godeps/_workspace/src/github.com/russross/blackfriday/markdown.go
  21. 128 0
      Godeps/_workspace/src/github.com/russross/blackfriday/ref_test.go
  22. 400 0
      Godeps/_workspace/src/github.com/russross/blackfriday/smartypants.go
  23. 17 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Amps and angle encoding.html
  24. 21 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Amps and angle encoding.text
  25. 18 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Auto links.html
  26. 13 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Auto links.text
  27. 123 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Backslash escapes.html
  28. 126 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Backslash escapes.text
  29. 15 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Blockquotes with code blocks.html
  30. 11 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Blockquotes with code blocks.text
  31. 18 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Blocks.html
  32. 14 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Blocks.text
  33. 5 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Spans.html
  34. 6 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Spans.text
  35. 14 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines no empty line before block.html
  36. 8 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines no empty line before block.text
  37. 8 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines.html
  38. 8 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines.text
  39. 71 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Horizontal rules.html
  40. 67 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Horizontal rules.text
  41. 15 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Advanced).html
  42. 15 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Advanced).text
  43. 72 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Simple).html
  44. 69 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Simple).text
  45. 13 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML comments.html
  46. 13 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML comments.text
  47. 11 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, inline style.html
  48. 12 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, inline style.text
  49. 52 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, reference style.html
  50. 71 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, reference style.text
  51. 9 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, shortcut references.html
  52. 20 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, shortcut references.text
  53. 3 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Literal quotes in titles.html
  54. 7 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Literal quotes in titles.text
  55. 314 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Basics.html
  56. 306 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Basics.text
  57. 946 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Syntax.html
  58. 888 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Syntax.text
  59. 9 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Nested blockquotes.html
  60. 5 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Nested blockquotes.text
  61. 166 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Ordered and unordered lists.html
  62. 131 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Ordered and unordered lists.text
  63. 7 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Strong and em together.html
  64. 7 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Strong and em together.text
  65. 26 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tabs.html
  66. 21 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tabs.text
  67. 9 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tidyness.html
  68. 5 0
      Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tidyness.text
  69. 10 0
      Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/.travis.yml
  70. 19 0
      Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/LICENSE
  71. 31 0
      Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/README.md
  72. 29 0
      Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main.go
  73. 35 0
      Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go
  74. 24 0
      Godeps/_workspace/src/github.com/spf13/cobra/.gitignore
  75. 3 0
      Godeps/_workspace/src/github.com/spf13/cobra/.mailmap
  76. 9 0
      Godeps/_workspace/src/github.com/spf13/cobra/.travis.yml
  77. 174 0
      Godeps/_workspace/src/github.com/spf13/cobra/LICENSE.txt
  78. 869 0
      Godeps/_workspace/src/github.com/spf13/cobra/README.md
  79. 425 0
      Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.go
  80. 149 0
      Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.md
  81. 94 0
      Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go
  82. 170 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra.go
  83. 128 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/add.go
  84. 347 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers.go
  85. 39 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers_test.go
  86. 226 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/init.go
  87. 1133 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/licenses.go
  88. 84 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/root.go
  89. 20 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra/main.go
  90. 1163 0
      Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go
  91. 1200 0
      Godeps/_workspace/src/github.com/spf13/cobra/command.go
  92. 114 0
      Godeps/_workspace/src/github.com/spf13/cobra/command_test.go
  93. 34 0
      Godeps/_workspace/src/github.com/spf13/cobra/doc_util.go
  94. 34 0
      Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go
  95. 227 0
      Godeps/_workspace/src/github.com/spf13/cobra/man_docs.go
  96. 25 0
      Godeps/_workspace/src/github.com/spf13/cobra/man_docs.md
  97. 94 0
      Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go
  98. 162 0
      Godeps/_workspace/src/github.com/spf13/cobra/md_docs.go
  99. 81 0
      Godeps/_workspace/src/github.com/spf13/cobra/md_docs.md
  100. 84 0
      Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go

+ 27 - 1
Godeps/Godeps.json

@@ -1,6 +1,6 @@
 {
 	"ImportPath": "github.com/coreos/etcd",
-	"GoVersion": "go1.5",
+	"GoVersion": "go1.5.1",
 	"Packages": [
 		"./..."
 	],
@@ -63,6 +63,11 @@
 			"ImportPath": "github.com/coreos/pkg/capnslog",
 			"Rev": "2c77715c4df99b5420ffcae14ead08f52104065d"
 		},
+		{
+			"ImportPath": "github.com/cpuguy83/go-md2man/md2man",
+			"Comment": "v1.0.4",
+			"Rev": "71acacd42f85e5e82f70a55327789582a5200a90"
+		},
 		{
 			"ImportPath": "github.com/gogo/protobuf/proto",
 			"Rev": "64f27bf06efee53589314a6e5a4af34cdd85adf6"
@@ -79,6 +84,10 @@
 			"ImportPath": "github.com/google/btree",
 			"Rev": "cc6329d4279e3f025a53a83c397d2339b5705c45"
 		},
+		{
+			"ImportPath": "github.com/inconshreveable/mousetrap",
+			"Rev": "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
+		},
 		{
 			"ImportPath": "github.com/jonboulle/clockwork",
 			"Rev": "72f9bd7c4e0c2a40055ab3d0f09654f730cce982"
@@ -109,10 +118,27 @@
 			"ImportPath": "github.com/prometheus/procfs",
 			"Rev": "454a56f35412459b5e684fd5ec0f9211b94f002a"
 		},
+		{
+			"ImportPath": "github.com/russross/blackfriday",
+			"Comment": "v1.4-2-g300106c",
+			"Rev": "300106c228d52c8941d4b3de6054a6062a86dda3"
+		},
+		{
+			"ImportPath": "github.com/shurcooL/sanitized_anchor_name",
+			"Rev": "10ef21a441db47d8b13ebcc5fd2310f636973c77"
+		},
 		{
 			"ImportPath": "github.com/spacejam/loghisto",
 			"Rev": "323309774dec8b7430187e46cd0793974ccca04a"
 		},
+		{
+			"ImportPath": "github.com/spf13/cobra",
+			"Rev": "1c44ec8d3f1552cac48999f9306da23c4d8a288b"
+		},
+		{
+			"ImportPath": "github.com/spf13/pflag",
+			"Rev": "08b1a584251b5b62f458943640fc8ebd4d50aaa5"
+		},
 		{
 			"ImportPath": "github.com/stretchr/testify/assert",
 			"Rev": "9cc77fa25329013ce07362c7742952ff887361f2"

+ 21 - 0
Godeps/_workspace/src/github.com/cpuguy83/go-md2man/LICENSE.md

@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2014 Brian Goff
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 19 - 0
Godeps/_workspace/src/github.com/cpuguy83/go-md2man/md2man/md2man.go

@@ -0,0 +1,19 @@
+package md2man
+
+import (
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/russross/blackfriday"
+)
+
+func Render(doc []byte) []byte {
+	renderer := RoffRenderer(0)
+	extensions := 0
+	extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
+	extensions |= blackfriday.EXTENSION_TABLES
+	extensions |= blackfriday.EXTENSION_FENCED_CODE
+	extensions |= blackfriday.EXTENSION_AUTOLINK
+	extensions |= blackfriday.EXTENSION_SPACE_HEADERS
+	extensions |= blackfriday.EXTENSION_FOOTNOTES
+	extensions |= blackfriday.EXTENSION_TITLEBLOCK
+
+	return blackfriday.Markdown(doc, renderer, extensions)
+}

+ 269 - 0
Godeps/_workspace/src/github.com/cpuguy83/go-md2man/md2man/roff.go

@@ -0,0 +1,269 @@
+package md2man
+
+import (
+	"bytes"
+	"fmt"
+	"html"
+	"strings"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/russross/blackfriday"
+)
+
+type roffRenderer struct{}
+
+func RoffRenderer(flags int) blackfriday.Renderer {
+	return &roffRenderer{}
+}
+
+func (r *roffRenderer) GetFlags() int {
+	return 0
+}
+
+func (r *roffRenderer) TitleBlock(out *bytes.Buffer, text []byte) {
+	out.WriteString(".TH ")
+
+	splitText := bytes.Split(text, []byte("\n"))
+	for i, line := range splitText {
+		line = bytes.TrimPrefix(line, []byte("% "))
+		if i == 0 {
+			line = bytes.Replace(line, []byte("("), []byte("\" \""), 1)
+			line = bytes.Replace(line, []byte(")"), []byte("\" \""), 1)
+		}
+		line = append([]byte("\""), line...)
+		line = append(line, []byte("\" ")...)
+		out.Write(line)
+	}
+
+	out.WriteString(" \"\"\n")
+}
+
+func (r *roffRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string) {
+	out.WriteString("\n.PP\n.RS\n\n.nf\n")
+	escapeSpecialChars(out, text)
+	out.WriteString("\n.fi\n.RE\n")
+}
+
+func (r *roffRenderer) BlockQuote(out *bytes.Buffer, text []byte) {
+	out.WriteString("\n.PP\n.RS\n")
+	out.Write(text)
+	out.WriteString("\n.RE\n")
+}
+
+func (r *roffRenderer) BlockHtml(out *bytes.Buffer, text []byte) {
+	out.Write(text)
+}
+
+func (r *roffRenderer) Header(out *bytes.Buffer, text func() bool, level int, id string) {
+	marker := out.Len()
+
+	switch {
+	case marker == 0:
+		// This is the doc header
+		out.WriteString(".TH ")
+	case level == 1:
+		out.WriteString("\n\n.SH ")
+	case level == 2:
+		out.WriteString("\n.SH ")
+	default:
+		out.WriteString("\n.SS ")
+	}
+
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+}
+
+func (r *roffRenderer) HRule(out *bytes.Buffer) {
+	out.WriteString("\n.ti 0\n\\l'\\n(.lu'\n")
+}
+
+func (r *roffRenderer) List(out *bytes.Buffer, text func() bool, flags int) {
+	marker := out.Len()
+	out.WriteString(".IP ")
+	if flags&blackfriday.LIST_TYPE_ORDERED != 0 {
+		out.WriteString("\\(bu 2")
+	} else {
+		out.WriteString("\\n+[step" + string(flags) + "]")
+	}
+	out.WriteString("\n")
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+
+}
+
+func (r *roffRenderer) ListItem(out *bytes.Buffer, text []byte, flags int) {
+	out.WriteString("\n\\item ")
+	out.Write(text)
+}
+
+func (r *roffRenderer) Paragraph(out *bytes.Buffer, text func() bool) {
+	marker := out.Len()
+	out.WriteString("\n.PP\n")
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+	if marker != 0 {
+		out.WriteString("\n")
+	}
+}
+
+// TODO: This might now work
+func (r *roffRenderer) Table(out *bytes.Buffer, header []byte, body []byte, columnData []int) {
+	out.WriteString(".TS\nallbox;\n")
+
+	out.Write(header)
+	out.Write(body)
+	out.WriteString("\n.TE\n")
+}
+
+func (r *roffRenderer) TableRow(out *bytes.Buffer, text []byte) {
+	if out.Len() > 0 {
+		out.WriteString("\n")
+	}
+	out.Write(text)
+	out.WriteString("\n")
+}
+
+func (r *roffRenderer) TableHeaderCell(out *bytes.Buffer, text []byte, align int) {
+	if out.Len() > 0 {
+		out.WriteString(" ")
+	}
+	out.Write(text)
+	out.WriteString(" ")
+}
+
+// TODO: This is probably broken
+func (r *roffRenderer) TableCell(out *bytes.Buffer, text []byte, align int) {
+	if out.Len() > 0 {
+		out.WriteString("\t")
+	}
+	out.Write(text)
+	out.WriteString("\t")
+}
+
+func (r *roffRenderer) Footnotes(out *bytes.Buffer, text func() bool) {
+
+}
+
+func (r *roffRenderer) FootnoteItem(out *bytes.Buffer, name, text []byte, flags int) {
+
+}
+
+func (r *roffRenderer) AutoLink(out *bytes.Buffer, link []byte, kind int) {
+	out.WriteString("\n\\[la]")
+	out.Write(link)
+	out.WriteString("\\[ra]")
+}
+
+func (r *roffRenderer) CodeSpan(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\fB\\fC")
+	escapeSpecialChars(out, text)
+	out.WriteString("\\fR")
+}
+
+func (r *roffRenderer) DoubleEmphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\fB")
+	out.Write(text)
+	out.WriteString("\\fP")
+}
+
+func (r *roffRenderer) Emphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\fI")
+	out.Write(text)
+	out.WriteString("\\fP")
+}
+
+func (r *roffRenderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
+}
+
+func (r *roffRenderer) LineBreak(out *bytes.Buffer) {
+	out.WriteString("\n.br\n")
+}
+
+func (r *roffRenderer) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
+	r.AutoLink(out, link, 0)
+}
+
+func (r *roffRenderer) RawHtmlTag(out *bytes.Buffer, tag []byte) {
+	out.Write(tag)
+}
+
+func (r *roffRenderer) TripleEmphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\s+2")
+	out.Write(text)
+	out.WriteString("\\s-2")
+}
+
+func (r *roffRenderer) StrikeThrough(out *bytes.Buffer, text []byte) {
+}
+
+func (r *roffRenderer) FootnoteRef(out *bytes.Buffer, ref []byte, id int) {
+
+}
+
+func (r *roffRenderer) Entity(out *bytes.Buffer, entity []byte) {
+	out.WriteString(html.UnescapeString(string(entity)))
+}
+
+func processFooterText(text []byte) []byte {
+	text = bytes.TrimPrefix(text, []byte("% "))
+	newText := []byte{}
+	textArr := strings.Split(string(text), ") ")
+
+	for i, w := range textArr {
+		if i == 0 {
+			w = strings.Replace(w, "(", "\" \"", 1)
+			w = fmt.Sprintf("\"%s\"", w)
+		} else {
+			w = fmt.Sprintf(" \"%s\"", w)
+		}
+		newText = append(newText, []byte(w)...)
+	}
+	newText = append(newText, []byte(" \"\"")...)
+
+	return newText
+}
+
+func (r *roffRenderer) NormalText(out *bytes.Buffer, text []byte) {
+	escapeSpecialChars(out, text)
+}
+
+func (r *roffRenderer) DocumentHeader(out *bytes.Buffer) {
+}
+
+func (r *roffRenderer) DocumentFooter(out *bytes.Buffer) {
+}
+
+func needsBackslash(c byte) bool {
+	for _, r := range []byte("-_&\\~") {
+		if c == r {
+			return true
+		}
+	}
+	return false
+}
+
+func escapeSpecialChars(out *bytes.Buffer, text []byte) {
+	for i := 0; i < len(text); i++ {
+		// directly copy normal characters
+		org := i
+
+		for i < len(text) && !needsBackslash(text[i]) {
+			i++
+		}
+		if i > org {
+			out.Write(text[org:i])
+		}
+
+		// escape a character
+		if i >= len(text) {
+			break
+		}
+		out.WriteByte('\\')
+		out.WriteByte(text[i])
+	}
+}

+ 13 - 0
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/LICENSE

@@ -0,0 +1,13 @@
+Copyright 2014 Alan Shreve
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.

+ 23 - 0
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/README.md

@@ -0,0 +1,23 @@
+# mousetrap
+
+mousetrap is a tiny library that answers a single question.
+
+On a Windows machine, was the process invoked by someone double clicking on
+the executable file while browsing in explorer?
+
+### Motivation
+
+Windows developers unfamiliar with command line tools will often "double-click"
+the executable for a tool. Because most CLI tools print the help and then exit
+when invoked without arguments, this is often very frustrating for those users.
+
+mousetrap provides a way to detect these invocations so that you can provide
+more helpful behavior and instructions on how to run the CLI tool. To see what
+this looks like, both from an organizational and a technical perspective, see
+https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
+
+### The interface
+
+The library exposes a single interface:
+
+    func StartedByExplorer() (bool)

+ 15 - 0
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_others.go

@@ -0,0 +1,15 @@
+// +build !windows
+
+package mousetrap
+
+// StartedByExplorer returns true if the program was invoked by the user
+// double-clicking on the executable from explorer.exe
+//
+// It is conservative and returns false if any of the internal calls fail.
+// It does not guarantee that the program was run from a terminal. It only can tell you
+// whether it was launched from explorer.exe
+//
+// On non-Windows platforms, it always returns false.
+func StartedByExplorer() bool {
+	return false
+}

+ 98 - 0
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows.go

@@ -0,0 +1,98 @@
+// +build windows
+// +build !go1.4
+
+package mousetrap
+
+import (
+	"fmt"
+	"os"
+	"syscall"
+	"unsafe"
+)
+
+const (
+	// defined by the Win32 API
+	th32cs_snapprocess uintptr = 0x2
+)
+
+var (
+	kernel                   = syscall.MustLoadDLL("kernel32.dll")
+	CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
+	Process32First           = kernel.MustFindProc("Process32FirstW")
+	Process32Next            = kernel.MustFindProc("Process32NextW")
+)
+
+// ProcessEntry32 structure defined by the Win32 API
+type processEntry32 struct {
+	dwSize              uint32
+	cntUsage            uint32
+	th32ProcessID       uint32
+	th32DefaultHeapID   int
+	th32ModuleID        uint32
+	cntThreads          uint32
+	th32ParentProcessID uint32
+	pcPriClassBase      int32
+	dwFlags             uint32
+	szExeFile           [syscall.MAX_PATH]uint16
+}
+
+func getProcessEntry(pid int) (pe *processEntry32, err error) {
+	snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
+	if snapshot == uintptr(syscall.InvalidHandle) {
+		err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
+		return
+	}
+	defer syscall.CloseHandle(syscall.Handle(snapshot))
+
+	var processEntry processEntry32
+	processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
+	ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
+	if ok == 0 {
+		err = fmt.Errorf("Process32First: %v", e1)
+		return
+	}
+
+	for {
+		if processEntry.th32ProcessID == uint32(pid) {
+			pe = &processEntry
+			return
+		}
+
+		ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
+		if ok == 0 {
+			err = fmt.Errorf("Process32Next: %v", e1)
+			return
+		}
+	}
+}
+
+func getppid() (pid int, err error) {
+	pe, err := getProcessEntry(os.Getpid())
+	if err != nil {
+		return
+	}
+
+	pid = int(pe.th32ParentProcessID)
+	return
+}
+
+// StartedByExplorer returns true if the program was invoked by the user double-clicking
+// on the executable from explorer.exe
+//
+// It is conservative and returns false if any of the internal calls fail.
+// It does not guarantee that the program was run from a terminal. It only can tell you
+// whether it was launched from explorer.exe
+func StartedByExplorer() bool {
+	ppid, err := getppid()
+	if err != nil {
+		return false
+	}
+
+	pe, err := getProcessEntry(ppid)
+	if err != nil {
+		return false
+	}
+
+	name := syscall.UTF16ToString(pe.szExeFile[:])
+	return name == "explorer.exe"
+}

+ 46 - 0
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows_1.4.go

@@ -0,0 +1,46 @@
+// +build windows
+// +build go1.4
+
+package mousetrap
+
+import (
+	"os"
+	"syscall"
+	"unsafe"
+)
+
+func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
+	snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
+	if err != nil {
+		return nil, err
+	}
+	defer syscall.CloseHandle(snapshot)
+	var procEntry syscall.ProcessEntry32
+	procEntry.Size = uint32(unsafe.Sizeof(procEntry))
+	if err = syscall.Process32First(snapshot, &procEntry); err != nil {
+		return nil, err
+	}
+	for {
+		if procEntry.ProcessID == uint32(pid) {
+			return &procEntry, nil
+		}
+		err = syscall.Process32Next(snapshot, &procEntry)
+		if err != nil {
+			return nil, err
+		}
+	}
+}
+
+// StartedByExplorer returns true if the program was invoked by the user double-clicking
+// on the executable from explorer.exe
+//
+// It is conservative and returns false if any of the internal calls fail.
+// It does not guarantee that the program was run from a terminal. It only can tell you
+// whether it was launched from explorer.exe
+func StartedByExplorer() bool {
+	pe, err := getProcessEntry(os.Getppid())
+	if err != nil {
+		return false
+	}
+	return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
+}

+ 8 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/.gitignore

@@ -0,0 +1,8 @@
+*.out
+*.swp
+*.8
+*.6
+_obj
+_test*
+markdown
+tags

+ 18 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/.travis.yml

@@ -0,0 +1,18 @@
+# Travis CI (http://travis-ci.org/) is a continuous integration service for
+# open source projects. This file configures it to run unit tests for
+# blackfriday.
+
+language: go
+
+go:
+    - 1.2
+    - 1.3
+    - 1.4
+    - 1.5
+
+install:
+    - go get -d -t -v ./...
+    - go build -v ./...
+
+script:
+    - go test -v ./...

+ 29 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/LICENSE.txt

@@ -0,0 +1,29 @@
+Blackfriday is distributed under the Simplified BSD License:
+
+> Copyright © 2011 Russ Ross
+> All rights reserved.
+>
+> Redistribution and use in source and binary forms, with or without
+> modification, are permitted provided that the following conditions
+> are met:
+>
+> 1.  Redistributions of source code must retain the above copyright
+>     notice, this list of conditions and the following disclaimer.
+>
+> 2.  Redistributions in binary form must reproduce the above
+>     copyright notice, this list of conditions and the following
+>     disclaimer in the documentation and/or other materials provided with
+>     the distribution.
+>
+> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+> "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+> LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+> FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+> COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+> INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+> BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+> LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+> LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+> ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+> POSSIBILITY OF SUCH DAMAGE.

+ 267 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/README.md

@@ -0,0 +1,267 @@
+Blackfriday [![Build Status](https://travis-ci.org/russross/blackfriday.svg?branch=master)](https://travis-ci.org/russross/blackfriday)
+===========
+
+Blackfriday is a [Markdown][1] processor implemented in [Go][2]. It
+is paranoid about its input (so you can safely feed it user-supplied
+data), it is fast, it supports common extensions (tables, smart
+punctuation substitutions, etc.), and it is safe for all utf-8
+(unicode) input.
+
+HTML output is currently supported, along with Smartypants
+extensions. An experimental LaTeX output engine is also included.
+
+It started as a translation from C of [Sundown][3].
+
+
+Installation
+------------
+
+Blackfriday is compatible with Go 1. If you are using an older
+release of Go, consider using v1.1 of blackfriday, which was based
+on the last stable release of Go prior to Go 1. You can find it as a
+tagged commit on github.
+
+With Go 1 and git installed:
+
+    go get github.com/russross/blackfriday
+
+will download, compile, and install the package into your `$GOPATH`
+directory hierarchy. Alternatively, you can achieve the same if you
+import it into a project:
+
+    import "github.com/russross/blackfriday"
+
+and `go get` without parameters.
+
+Usage
+-----
+
+For basic usage, it is as simple as getting your input into a byte
+slice and calling:
+
+    output := blackfriday.MarkdownBasic(input)
+
+This renders it with no extensions enabled. To get a more useful
+feature set, use this instead:
+
+    output := blackfriday.MarkdownCommon(input)
+
+### Sanitize untrusted content
+
+Blackfriday itself does nothing to protect against malicious content. If you are
+dealing with user-supplied markdown, we recommend running blackfriday's output
+through HTML sanitizer such as
+[Bluemonday](https://github.com/microcosm-cc/bluemonday).
+
+Here's an example of simple usage of blackfriday together with bluemonday:
+
+``` go
+import (
+    "github.com/microcosm-cc/bluemonday"
+    "github.com/russross/blackfriday"
+)
+
+// ...
+unsafe := blackfriday.MarkdownCommon(input)
+html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
+```
+
+### Custom options
+
+If you want to customize the set of options, first get a renderer
+(currently either the HTML or LaTeX output engines), then use it to
+call the more general `Markdown` function. For examples, see the
+implementations of `MarkdownBasic` and `MarkdownCommon` in
+`markdown.go`.
+
+You can also check out `blackfriday-tool` for a more complete example
+of how to use it. Download and install it using:
+
+    go get github.com/russross/blackfriday-tool
+
+This is a simple command-line tool that allows you to process a
+markdown file using a standalone program.  You can also browse the
+source directly on github if you are just looking for some example
+code:
+
+* <http://github.com/russross/blackfriday-tool>
+
+Note that if you have not already done so, installing
+`blackfriday-tool` will be sufficient to download and install
+blackfriday in addition to the tool itself. The tool binary will be
+installed in `$GOPATH/bin`.  This is a statically-linked binary that
+can be copied to wherever you need it without worrying about
+dependencies and library versions.
+
+
+Features
+--------
+
+All features of Sundown are supported, including:
+
+*   **Compatibility**. The Markdown v1.0.3 test suite passes with
+    the `--tidy` option.  Without `--tidy`, the differences are
+    mostly in whitespace and entity escaping, where blackfriday is
+    more consistent and cleaner.
+
+*   **Common extensions**, including table support, fenced code
+    blocks, autolinks, strikethroughs, non-strict emphasis, etc.
+
+*   **Safety**. Blackfriday is paranoid when parsing, making it safe
+    to feed untrusted user input without fear of bad things
+    happening. The test suite stress tests this and there are no
+    known inputs that make it crash.  If you find one, please let me
+    know and send me the input that does it.
+
+    NOTE: "safety" in this context means *runtime safety only*. In order to
+    protect yourself agains JavaScript injection in untrusted content, see
+    [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content).
+
+*   **Fast processing**. It is fast enough to render on-demand in
+    most web applications without having to cache the output.
+
+*   **Thread safety**. You can run multiple parsers in different
+    goroutines without ill effect. There is no dependence on global
+    shared state.
+
+*   **Minimal dependencies**. Blackfriday only depends on standard
+    library packages in Go. The source code is pretty
+    self-contained, so it is easy to add to any project, including
+    Google App Engine projects.
+
+*   **Standards compliant**. Output successfully validates using the
+    W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional.
+
+
+Extensions
+----------
+
+In addition to the standard markdown syntax, this package
+implements the following extensions:
+
+*   **Intra-word emphasis supression**. The `_` character is
+    commonly used inside words when discussing code, so having
+    markdown interpret it as an emphasis command is usually the
+    wrong thing. Blackfriday lets you treat all emphasis markers as
+    normal characters when they occur inside a word.
+
+*   **Tables**. Tables can be created by drawing them in the input
+    using a simple syntax:
+
+    ```
+    Name    | Age
+    --------|------
+    Bob     | 27
+    Alice   | 23
+    ```
+
+*   **Fenced code blocks**. In addition to the normal 4-space
+    indentation to mark code blocks, you can explicitly mark them
+    and supply a language (to make syntax highlighting simple). Just
+    mark it like this:
+
+        ``` go
+        func getTrue() bool {
+            return true
+        }
+        ```
+
+    You can use 3 or more backticks to mark the beginning of the
+    block, and the same number to mark the end of the block.
+
+*   **Definition lists**. A simple definition list is made of a single-line
+    term followed by a colon and the definition for that term.
+
+        Cat
+        : Fluffy animal everyone likes
+        
+        Internet
+        : Vector of transmission for pictures of cats
+
+    Terms must be separated from the previous definition by a blank line.
+
+*   **Footnotes**. A marker in the text that will become a superscript number;
+    a footnote definition that will be placed in a list of footnotes at the
+    end of the document. A footnote looks like this:
+
+        This is a footnote.[^1]
+        
+        [^1]: the footnote text.
+
+*   **Autolinking**. Blackfriday can find URLs that have not been
+    explicitly marked as links and turn them into links.
+
+*   **Strikethrough**. Use two tildes (`~~`) to mark text that
+    should be crossed out.
+
+*   **Hard line breaks**. With this extension enabled (it is off by
+    default in the `MarkdownBasic` and `MarkdownCommon` convenience
+    functions), newlines in the input translate into line breaks in
+    the output.
+
+*   **Smart quotes**. Smartypants-style punctuation substitution is
+    supported, turning normal double- and single-quote marks into
+    curly quotes, etc.
+
+*   **LaTeX-style dash parsing** is an additional option, where `--`
+    is translated into `&ndash;`, and `---` is translated into
+    `&mdash;`. This differs from most smartypants processors, which
+    turn a single hyphen into an ndash and a double hyphen into an
+    mdash.
+
+*   **Smart fractions**, where anything that looks like a fraction
+    is translated into suitable HTML (instead of just a few special
+    cases like most smartypant processors). For example, `4/5`
+    becomes `<sup>4</sup>&frasl;<sub>5</sub>`, which renders as
+    <sup>4</sup>&frasl;<sub>5</sub>.
+
+
+Other renderers
+---------------
+
+Blackfriday is structured to allow alternative rendering engines. Here
+are a few of note:
+
+*   [github_flavored_markdown](https://godoc.org/github.com/shurcooL/github_flavored_markdown):
+    provides a GitHub Flavored Markdown renderer with fenced code block
+    highlighting, clickable header anchor links.
+
+    It's not customizable, and its goal is to produce HTML output
+    equivalent to the [GitHub Markdown API endpoint](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode),
+    except the rendering is performed locally.
+
+*   [markdownfmt](https://github.com/shurcooL/markdownfmt): like gofmt,
+    but for markdown.
+
+*   LaTeX output: renders output as LaTeX. This is currently part of the
+    main Blackfriday repository, but may be split into its own project
+    in the future. If you are interested in owning and maintaining the
+    LaTeX output component, please be in touch.
+
+    It renders some basic documents, but is only experimental at this
+    point. In particular, it does not do any inline escaping, so input
+    that happens to look like LaTeX code will be passed through without
+    modification.
+    
+*   [Md2Vim](https://github.com/FooSoft/md2vim): transforms markdown files into vimdoc format.
+
+
+Todo
+----
+
+*   More unit testing
+*   Improve unicode support. It does not understand all unicode
+    rules (about what constitutes a letter, a punctuation symbol,
+    etc.), so it may fail to detect word boundaries correctly in
+    some instances. It is safe on all utf-8 input.
+
+
+License
+-------
+
+[Blackfriday is distributed under the Simplified BSD License](LICENSE.txt)
+
+
+   [1]: http://daringfireball.net/projects/markdown/ "Markdown"
+   [2]: http://golang.org/ "Go Language"
+   [3]: https://github.com/vmg/sundown "Sundown"

+ 1398 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/block.go

@@ -0,0 +1,1398 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+// Functions to parse block-level elements.
+//
+
+package blackfriday
+
+import (
+	"bytes"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name"
+)
+
+// Parse block-level data.
+// Note: this function and many that it calls assume that
+// the input buffer ends with a newline.
+func (p *parser) block(out *bytes.Buffer, data []byte) {
+	if len(data) == 0 || data[len(data)-1] != '\n' {
+		panic("block input is missing terminating newline")
+	}
+
+	// this is called recursively: enforce a maximum depth
+	if p.nesting >= p.maxNesting {
+		return
+	}
+	p.nesting++
+
+	// parse out one block-level construct at a time
+	for len(data) > 0 {
+		// prefixed header:
+		//
+		// # Header 1
+		// ## Header 2
+		// ...
+		// ###### Header 6
+		if p.isPrefixHeader(data) {
+			data = data[p.prefixHeader(out, data):]
+			continue
+		}
+
+		// block of preformatted HTML:
+		//
+		// <div>
+		//     ...
+		// </div>
+		if data[0] == '<' {
+			if i := p.html(out, data, true); i > 0 {
+				data = data[i:]
+				continue
+			}
+		}
+
+		// title block
+		//
+		// % stuff
+		// % more stuff
+		// % even more stuff
+		if p.flags&EXTENSION_TITLEBLOCK != 0 {
+			if data[0] == '%' {
+				if i := p.titleBlock(out, data, true); i > 0 {
+					data = data[i:]
+					continue
+				}
+			}
+		}
+
+		// blank lines.  note: returns the # of bytes to skip
+		if i := p.isEmpty(data); i > 0 {
+			data = data[i:]
+			continue
+		}
+
+		// indented code block:
+		//
+		//     func max(a, b int) int {
+		//         if a > b {
+		//             return a
+		//         }
+		//         return b
+		//      }
+		if p.codePrefix(data) > 0 {
+			data = data[p.code(out, data):]
+			continue
+		}
+
+		// fenced code block:
+		//
+		// ``` go
+		// func fact(n int) int {
+		//     if n <= 1 {
+		//         return n
+		//     }
+		//     return n * fact(n-1)
+		// }
+		// ```
+		if p.flags&EXTENSION_FENCED_CODE != 0 {
+			if i := p.fencedCode(out, data, true); i > 0 {
+				data = data[i:]
+				continue
+			}
+		}
+
+		// horizontal rule:
+		//
+		// ------
+		// or
+		// ******
+		// or
+		// ______
+		if p.isHRule(data) {
+			p.r.HRule(out)
+			var i int
+			for i = 0; data[i] != '\n'; i++ {
+			}
+			data = data[i:]
+			continue
+		}
+
+		// block quote:
+		//
+		// > A big quote I found somewhere
+		// > on the web
+		if p.quotePrefix(data) > 0 {
+			data = data[p.quote(out, data):]
+			continue
+		}
+
+		// table:
+		//
+		// Name  | Age | Phone
+		// ------|-----|---------
+		// Bob   | 31  | 555-1234
+		// Alice | 27  | 555-4321
+		if p.flags&EXTENSION_TABLES != 0 {
+			if i := p.table(out, data); i > 0 {
+				data = data[i:]
+				continue
+			}
+		}
+
+		// an itemized/unordered list:
+		//
+		// * Item 1
+		// * Item 2
+		//
+		// also works with + or -
+		if p.uliPrefix(data) > 0 {
+			data = data[p.list(out, data, 0):]
+			continue
+		}
+
+		// a numbered/ordered list:
+		//
+		// 1. Item 1
+		// 2. Item 2
+		if p.oliPrefix(data) > 0 {
+			data = data[p.list(out, data, LIST_TYPE_ORDERED):]
+			continue
+		}
+
+		// definition lists:
+		//
+		// Term 1
+		// :   Definition a
+		// :   Definition b
+		//
+		// Term 2
+		// :   Definition c
+		if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
+			if p.dliPrefix(data) > 0 {
+				data = data[p.list(out, data, LIST_TYPE_DEFINITION):]
+				continue
+			}
+		}
+
+		// anything else must look like a normal paragraph
+		// note: this finds underlined headers, too
+		data = data[p.paragraph(out, data):]
+	}
+
+	p.nesting--
+}
+
+func (p *parser) isPrefixHeader(data []byte) bool {
+	if data[0] != '#' {
+		return false
+	}
+
+	if p.flags&EXTENSION_SPACE_HEADERS != 0 {
+		level := 0
+		for level < 6 && data[level] == '#' {
+			level++
+		}
+		if data[level] != ' ' {
+			return false
+		}
+	}
+	return true
+}
+
+func (p *parser) prefixHeader(out *bytes.Buffer, data []byte) int {
+	level := 0
+	for level < 6 && data[level] == '#' {
+		level++
+	}
+	i := skipChar(data, level, ' ')
+	end := skipUntilChar(data, i, '\n')
+	skip := end
+	id := ""
+	if p.flags&EXTENSION_HEADER_IDS != 0 {
+		j, k := 0, 0
+		// find start/end of header id
+		for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ {
+		}
+		for k = j + 1; k < end && data[k] != '}'; k++ {
+		}
+		// extract header id iff found
+		if j < end && k < end {
+			id = string(data[j+2 : k])
+			end = j
+			skip = k + 1
+			for end > 0 && data[end-1] == ' ' {
+				end--
+			}
+		}
+	}
+	for end > 0 && data[end-1] == '#' {
+		if isBackslashEscaped(data, end-1) {
+			break
+		}
+		end--
+	}
+	for end > 0 && data[end-1] == ' ' {
+		end--
+	}
+	if end > i {
+		if id == "" && p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
+			id = sanitized_anchor_name.Create(string(data[i:end]))
+		}
+		work := func() bool {
+			p.inline(out, data[i:end])
+			return true
+		}
+		p.r.Header(out, work, level, id)
+	}
+	return skip
+}
+
+func (p *parser) isUnderlinedHeader(data []byte) int {
+	// test of level 1 header
+	if data[0] == '=' {
+		i := skipChar(data, 1, '=')
+		i = skipChar(data, i, ' ')
+		if data[i] == '\n' {
+			return 1
+		} else {
+			return 0
+		}
+	}
+
+	// test of level 2 header
+	if data[0] == '-' {
+		i := skipChar(data, 1, '-')
+		i = skipChar(data, i, ' ')
+		if data[i] == '\n' {
+			return 2
+		} else {
+			return 0
+		}
+	}
+
+	return 0
+}
+
+func (p *parser) titleBlock(out *bytes.Buffer, data []byte, doRender bool) int {
+	if data[0] != '%' {
+		return 0
+	}
+	splitData := bytes.Split(data, []byte("\n"))
+	var i int
+	for idx, b := range splitData {
+		if !bytes.HasPrefix(b, []byte("%")) {
+			i = idx // - 1
+			break
+		}
+	}
+
+	data = bytes.Join(splitData[0:i], []byte("\n"))
+	p.r.TitleBlock(out, data)
+
+	return len(data)
+}
+
+func (p *parser) html(out *bytes.Buffer, data []byte, doRender bool) int {
+	var i, j int
+
+	// identify the opening tag
+	if data[0] != '<' {
+		return 0
+	}
+	curtag, tagfound := p.htmlFindTag(data[1:])
+
+	// handle special cases
+	if !tagfound {
+		// check for an HTML comment
+		if size := p.htmlComment(out, data, doRender); size > 0 {
+			return size
+		}
+
+		// check for an <hr> tag
+		if size := p.htmlHr(out, data, doRender); size > 0 {
+			return size
+		}
+
+		// no special case recognized
+		return 0
+	}
+
+	// look for an unindented matching closing tag
+	// followed by a blank line
+	found := false
+	/*
+		closetag := []byte("\n</" + curtag + ">")
+		j = len(curtag) + 1
+		for !found {
+			// scan for a closing tag at the beginning of a line
+			if skip := bytes.Index(data[j:], closetag); skip >= 0 {
+				j += skip + len(closetag)
+			} else {
+				break
+			}
+
+			// see if it is the only thing on the line
+			if skip := p.isEmpty(data[j:]); skip > 0 {
+				// see if it is followed by a blank line/eof
+				j += skip
+				if j >= len(data) {
+					found = true
+					i = j
+				} else {
+					if skip := p.isEmpty(data[j:]); skip > 0 {
+						j += skip
+						found = true
+						i = j
+					}
+				}
+			}
+		}
+	*/
+
+	// if not found, try a second pass looking for indented match
+	// but not if tag is "ins" or "del" (following original Markdown.pl)
+	if !found && curtag != "ins" && curtag != "del" {
+		i = 1
+		for i < len(data) {
+			i++
+			for i < len(data) && !(data[i-1] == '<' && data[i] == '/') {
+				i++
+			}
+
+			if i+2+len(curtag) >= len(data) {
+				break
+			}
+
+			j = p.htmlFindEnd(curtag, data[i-1:])
+
+			if j > 0 {
+				i += j - 1
+				found = true
+				break
+			}
+		}
+	}
+
+	if !found {
+		return 0
+	}
+
+	// the end of the block has been found
+	if doRender {
+		// trim newlines
+		end := i
+		for end > 0 && data[end-1] == '\n' {
+			end--
+		}
+		p.r.BlockHtml(out, data[:end])
+	}
+
+	return i
+}
+
+// HTML comment, lax form
+func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int {
+	i := p.inlineHtmlComment(out, data)
+	// needs to end with a blank line
+	if j := p.isEmpty(data[i:]); j > 0 {
+		size := i + j
+		if doRender {
+			// trim trailing newlines
+			end := size
+			for end > 0 && data[end-1] == '\n' {
+				end--
+			}
+			p.r.BlockHtml(out, data[:end])
+		}
+		return size
+	}
+	return 0
+}
+
+// HR, which is the only self-closing block tag considered
+func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int {
+	if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') {
+		return 0
+	}
+	if data[3] != ' ' && data[3] != '/' && data[3] != '>' {
+		// not an <hr> tag after all; at least not a valid one
+		return 0
+	}
+
+	i := 3
+	for data[i] != '>' && data[i] != '\n' {
+		i++
+	}
+
+	if data[i] == '>' {
+		i++
+		if j := p.isEmpty(data[i:]); j > 0 {
+			size := i + j
+			if doRender {
+				// trim newlines
+				end := size
+				for end > 0 && data[end-1] == '\n' {
+					end--
+				}
+				p.r.BlockHtml(out, data[:end])
+			}
+			return size
+		}
+	}
+
+	return 0
+}
+
+func (p *parser) htmlFindTag(data []byte) (string, bool) {
+	i := 0
+	for isalnum(data[i]) {
+		i++
+	}
+	key := string(data[:i])
+	if _, ok := blockTags[key]; ok {
+		return key, true
+	}
+	return "", false
+}
+
+func (p *parser) htmlFindEnd(tag string, data []byte) int {
+	// assume data[0] == '<' && data[1] == '/' already tested
+
+	// check if tag is a match
+	closetag := []byte("</" + tag + ">")
+	if !bytes.HasPrefix(data, closetag) {
+		return 0
+	}
+	i := len(closetag)
+
+	// check that the rest of the line is blank
+	skip := 0
+	if skip = p.isEmpty(data[i:]); skip == 0 {
+		return 0
+	}
+	i += skip
+	skip = 0
+
+	if i >= len(data) {
+		return i
+	}
+
+	if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
+		return i
+	}
+	if skip = p.isEmpty(data[i:]); skip == 0 {
+		// following line must be blank
+		return 0
+	}
+
+	return i + skip
+}
+
+func (p *parser) isEmpty(data []byte) int {
+	// it is okay to call isEmpty on an empty buffer
+	if len(data) == 0 {
+		return 0
+	}
+
+	var i int
+	for i = 0; i < len(data) && data[i] != '\n'; i++ {
+		if data[i] != ' ' && data[i] != '\t' {
+			return 0
+		}
+	}
+	return i + 1
+}
+
+func (p *parser) isHRule(data []byte) bool {
+	i := 0
+
+	// skip up to three spaces
+	for i < 3 && data[i] == ' ' {
+		i++
+	}
+
+	// look at the hrule char
+	if data[i] != '*' && data[i] != '-' && data[i] != '_' {
+		return false
+	}
+	c := data[i]
+
+	// the whole line must be the char or whitespace
+	n := 0
+	for data[i] != '\n' {
+		switch {
+		case data[i] == c:
+			n++
+		case data[i] != ' ':
+			return false
+		}
+		i++
+	}
+
+	return n >= 3
+}
+
+func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (skip int, marker string) {
+	i, size := 0, 0
+	skip = 0
+
+	// skip up to three spaces
+	for i < len(data) && i < 3 && data[i] == ' ' {
+		i++
+	}
+	if i >= len(data) {
+		return
+	}
+
+	// check for the marker characters: ~ or `
+	if data[i] != '~' && data[i] != '`' {
+		return
+	}
+
+	c := data[i]
+
+	// the whole line must be the same char or whitespace
+	for i < len(data) && data[i] == c {
+		size++
+		i++
+	}
+
+	if i >= len(data) {
+		return
+	}
+
+	// the marker char must occur at least 3 times
+	if size < 3 {
+		return
+	}
+	marker = string(data[i-size : i])
+
+	// if this is the end marker, it must match the beginning marker
+	if oldmarker != "" && marker != oldmarker {
+		return
+	}
+
+	if syntax != nil {
+		syn := 0
+		i = skipChar(data, i, ' ')
+
+		if i >= len(data) {
+			return
+		}
+
+		syntaxStart := i
+
+		if data[i] == '{' {
+			i++
+			syntaxStart++
+
+			for i < len(data) && data[i] != '}' && data[i] != '\n' {
+				syn++
+				i++
+			}
+
+			if i >= len(data) || data[i] != '}' {
+				return
+			}
+
+			// strip all whitespace at the beginning and the end
+			// of the {} block
+			for syn > 0 && isspace(data[syntaxStart]) {
+				syntaxStart++
+				syn--
+			}
+
+			for syn > 0 && isspace(data[syntaxStart+syn-1]) {
+				syn--
+			}
+
+			i++
+		} else {
+			for i < len(data) && !isspace(data[i]) {
+				syn++
+				i++
+			}
+		}
+
+		language := string(data[syntaxStart : syntaxStart+syn])
+		*syntax = &language
+	}
+
+	i = skipChar(data, i, ' ')
+	if i >= len(data) || data[i] != '\n' {
+		return
+	}
+
+	skip = i + 1
+	return
+}
+
+func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int {
+	var lang *string
+	beg, marker := p.isFencedCode(data, &lang, "")
+	if beg == 0 || beg >= len(data) {
+		return 0
+	}
+
+	var work bytes.Buffer
+
+	for {
+		// safe to assume beg < len(data)
+
+		// check for the end of the code block
+		fenceEnd, _ := p.isFencedCode(data[beg:], nil, marker)
+		if fenceEnd != 0 {
+			beg += fenceEnd
+			break
+		}
+
+		// copy the current line
+		end := skipUntilChar(data, beg, '\n') + 1
+
+		// did we reach the end of the buffer without a closing marker?
+		if end >= len(data) {
+			return 0
+		}
+
+		// verbatim copy to the working buffer
+		if doRender {
+			work.Write(data[beg:end])
+		}
+		beg = end
+	}
+
+	syntax := ""
+	if lang != nil {
+		syntax = *lang
+	}
+
+	if doRender {
+		p.r.BlockCode(out, work.Bytes(), syntax)
+	}
+
+	return beg
+}
+
+func (p *parser) table(out *bytes.Buffer, data []byte) int {
+	var header bytes.Buffer
+	i, columns := p.tableHeader(&header, data)
+	if i == 0 {
+		return 0
+	}
+
+	var body bytes.Buffer
+
+	for i < len(data) {
+		pipes, rowStart := 0, i
+		for ; data[i] != '\n'; i++ {
+			if data[i] == '|' {
+				pipes++
+			}
+		}
+
+		if pipes == 0 {
+			i = rowStart
+			break
+		}
+
+		// include the newline in data sent to tableRow
+		i++
+		p.tableRow(&body, data[rowStart:i], columns, false)
+	}
+
+	p.r.Table(out, header.Bytes(), body.Bytes(), columns)
+
+	return i
+}
+
+// check if the specified position is preceded by an odd number of backslashes
+func isBackslashEscaped(data []byte, i int) bool {
+	backslashes := 0
+	for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' {
+		backslashes++
+	}
+	return backslashes&1 == 1
+}
+
+func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) {
+	i := 0
+	colCount := 1
+	for i = 0; data[i] != '\n'; i++ {
+		if data[i] == '|' && !isBackslashEscaped(data, i) {
+			colCount++
+		}
+	}
+
+	// doesn't look like a table header
+	if colCount == 1 {
+		return
+	}
+
+	// include the newline in the data sent to tableRow
+	header := data[:i+1]
+
+	// column count ignores pipes at beginning or end of line
+	if data[0] == '|' {
+		colCount--
+	}
+	if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) {
+		colCount--
+	}
+
+	columns = make([]int, colCount)
+
+	// move on to the header underline
+	i++
+	if i >= len(data) {
+		return
+	}
+
+	if data[i] == '|' && !isBackslashEscaped(data, i) {
+		i++
+	}
+	i = skipChar(data, i, ' ')
+
+	// each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3
+	// and trailing | optional on last column
+	col := 0
+	for data[i] != '\n' {
+		dashes := 0
+
+		if data[i] == ':' {
+			i++
+			columns[col] |= TABLE_ALIGNMENT_LEFT
+			dashes++
+		}
+		for data[i] == '-' {
+			i++
+			dashes++
+		}
+		if data[i] == ':' {
+			i++
+			columns[col] |= TABLE_ALIGNMENT_RIGHT
+			dashes++
+		}
+		for data[i] == ' ' {
+			i++
+		}
+
+		// end of column test is messy
+		switch {
+		case dashes < 3:
+			// not a valid column
+			return
+
+		case data[i] == '|' && !isBackslashEscaped(data, i):
+			// marker found, now skip past trailing whitespace
+			col++
+			i++
+			for data[i] == ' ' {
+				i++
+			}
+
+			// trailing junk found after last column
+			if col >= colCount && data[i] != '\n' {
+				return
+			}
+
+		case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount:
+			// something else found where marker was required
+			return
+
+		case data[i] == '\n':
+			// marker is optional for the last column
+			col++
+
+		default:
+			// trailing junk found after last column
+			return
+		}
+	}
+	if col != colCount {
+		return
+	}
+
+	p.tableRow(out, header, columns, true)
+	size = i + 1
+	return
+}
+
+func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) {
+	i, col := 0, 0
+	var rowWork bytes.Buffer
+
+	if data[i] == '|' && !isBackslashEscaped(data, i) {
+		i++
+	}
+
+	for col = 0; col < len(columns) && i < len(data); col++ {
+		for data[i] == ' ' {
+			i++
+		}
+
+		cellStart := i
+
+		for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' {
+			i++
+		}
+
+		cellEnd := i
+
+		// skip the end-of-cell marker, possibly taking us past end of buffer
+		i++
+
+		for cellEnd > cellStart && data[cellEnd-1] == ' ' {
+			cellEnd--
+		}
+
+		var cellWork bytes.Buffer
+		p.inline(&cellWork, data[cellStart:cellEnd])
+
+		if header {
+			p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col])
+		} else {
+			p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col])
+		}
+	}
+
+	// pad it out with empty columns to get the right number
+	for ; col < len(columns); col++ {
+		if header {
+			p.r.TableHeaderCell(&rowWork, nil, columns[col])
+		} else {
+			p.r.TableCell(&rowWork, nil, columns[col])
+		}
+	}
+
+	// silently ignore rows with too many cells
+
+	p.r.TableRow(out, rowWork.Bytes())
+}
+
+// returns blockquote prefix length
+func (p *parser) quotePrefix(data []byte) int {
+	i := 0
+	for i < 3 && data[i] == ' ' {
+		i++
+	}
+	if data[i] == '>' {
+		if data[i+1] == ' ' {
+			return i + 2
+		}
+		return i + 1
+	}
+	return 0
+}
+
+// blockquote ends with at least one blank line
+// followed by something without a blockquote prefix
+func (p *parser) terminateBlockquote(data []byte, beg, end int) bool {
+	if p.isEmpty(data[beg:]) <= 0 {
+		return false
+	}
+	if end >= len(data) {
+		return true
+	}
+	return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0
+}
+
+// parse a blockquote fragment
+func (p *parser) quote(out *bytes.Buffer, data []byte) int {
+	var raw bytes.Buffer
+	beg, end := 0, 0
+	for beg < len(data) {
+		end = beg
+		// Step over whole lines, collecting them. While doing that, check for
+		// fenced code and if one's found, incorporate it altogether,
+		// irregardless of any contents inside it
+		for data[end] != '\n' {
+			if p.flags&EXTENSION_FENCED_CODE != 0 {
+				if i := p.fencedCode(out, data[end:], false); i > 0 {
+					// -1 to compensate for the extra end++ after the loop:
+					end += i - 1
+					break
+				}
+			}
+			end++
+		}
+		end++
+
+		if pre := p.quotePrefix(data[beg:]); pre > 0 {
+			// skip the prefix
+			beg += pre
+		} else if p.terminateBlockquote(data, beg, end) {
+			break
+		}
+
+		// this line is part of the blockquote
+		raw.Write(data[beg:end])
+		beg = end
+	}
+
+	var cooked bytes.Buffer
+	p.block(&cooked, raw.Bytes())
+	p.r.BlockQuote(out, cooked.Bytes())
+	return end
+}
+
+// returns prefix length for block code
+func (p *parser) codePrefix(data []byte) int {
+	if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' {
+		return 4
+	}
+	return 0
+}
+
+func (p *parser) code(out *bytes.Buffer, data []byte) int {
+	var work bytes.Buffer
+
+	i := 0
+	for i < len(data) {
+		beg := i
+		for data[i] != '\n' {
+			i++
+		}
+		i++
+
+		blankline := p.isEmpty(data[beg:i]) > 0
+		if pre := p.codePrefix(data[beg:i]); pre > 0 {
+			beg += pre
+		} else if !blankline {
+			// non-empty, non-prefixed line breaks the pre
+			i = beg
+			break
+		}
+
+		// verbatim copy to the working buffeu
+		if blankline {
+			work.WriteByte('\n')
+		} else {
+			work.Write(data[beg:i])
+		}
+	}
+
+	// trim all the \n off the end of work
+	workbytes := work.Bytes()
+	eol := len(workbytes)
+	for eol > 0 && workbytes[eol-1] == '\n' {
+		eol--
+	}
+	if eol != len(workbytes) {
+		work.Truncate(eol)
+	}
+
+	work.WriteByte('\n')
+
+	p.r.BlockCode(out, work.Bytes(), "")
+
+	return i
+}
+
+// returns unordered list item prefix
+func (p *parser) uliPrefix(data []byte) int {
+	i := 0
+
+	// start with up to 3 spaces
+	for i < 3 && data[i] == ' ' {
+		i++
+	}
+
+	// need a *, +, or - followed by a space
+	if (data[i] != '*' && data[i] != '+' && data[i] != '-') ||
+		data[i+1] != ' ' {
+		return 0
+	}
+	return i + 2
+}
+
+// returns ordered list item prefix
+func (p *parser) oliPrefix(data []byte) int {
+	i := 0
+
+	// start with up to 3 spaces
+	for i < 3 && data[i] == ' ' {
+		i++
+	}
+
+	// count the digits
+	start := i
+	for data[i] >= '0' && data[i] <= '9' {
+		i++
+	}
+
+	// we need >= 1 digits followed by a dot and a space
+	if start == i || data[i] != '.' || data[i+1] != ' ' {
+		return 0
+	}
+	return i + 2
+}
+
+// returns definition list item prefix
+func (p *parser) dliPrefix(data []byte) int {
+	i := 0
+
+	// need a : followed by a spaces
+	if data[i] != ':' || data[i+1] != ' ' {
+		return 0
+	}
+	for data[i] == ' ' {
+		i++
+	}
+	return i + 2
+}
+
+// parse ordered or unordered list block
+func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int {
+	i := 0
+	flags |= LIST_ITEM_BEGINNING_OF_LIST
+	work := func() bool {
+		for i < len(data) {
+			skip := p.listItem(out, data[i:], &flags)
+			i += skip
+
+			if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 {
+				break
+			}
+			flags &= ^LIST_ITEM_BEGINNING_OF_LIST
+		}
+		return true
+	}
+
+	p.r.List(out, work, flags)
+	return i
+}
+
+// Parse a single list item.
+// Assumes initial prefix is already removed if this is a sublist.
+func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int {
+	// keep track of the indentation of the first line
+	itemIndent := 0
+	for itemIndent < 3 && data[itemIndent] == ' ' {
+		itemIndent++
+	}
+
+	i := p.uliPrefix(data)
+	if i == 0 {
+		i = p.oliPrefix(data)
+	}
+	if i == 0 {
+		i = p.dliPrefix(data)
+		// reset definition term flag
+		if i > 0 {
+			*flags &= ^LIST_TYPE_TERM
+		}
+	}
+	if i == 0 {
+		// if in defnition list, set term flag and continue
+		if *flags&LIST_TYPE_DEFINITION != 0 {
+			*flags |= LIST_TYPE_TERM
+		} else {
+			return 0
+		}
+	}
+
+	// skip leading whitespace on first line
+	for data[i] == ' ' {
+		i++
+	}
+
+	// find the end of the line
+	line := i
+	for i > 0 && data[i-1] != '\n' {
+		i++
+	}
+
+	// get working buffer
+	var raw bytes.Buffer
+
+	// put the first line into the working buffer
+	raw.Write(data[line:i])
+	line = i
+
+	// process the following lines
+	containsBlankLine := false
+	sublist := 0
+
+gatherlines:
+	for line < len(data) {
+		i++
+
+		// find the end of this line
+		for data[i-1] != '\n' {
+			i++
+		}
+
+		// if it is an empty line, guess that it is part of this item
+		// and move on to the next line
+		if p.isEmpty(data[line:i]) > 0 {
+			containsBlankLine = true
+			line = i
+			continue
+		}
+
+		// calculate the indentation
+		indent := 0
+		for indent < 4 && line+indent < i && data[line+indent] == ' ' {
+			indent++
+		}
+
+		chunk := data[line+indent : i]
+
+		// evaluate how this line fits in
+		switch {
+		// is this a nested list item?
+		case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) ||
+			p.oliPrefix(chunk) > 0 ||
+			p.dliPrefix(chunk) > 0:
+
+			if containsBlankLine {
+				*flags |= LIST_ITEM_CONTAINS_BLOCK
+			}
+
+			// to be a nested list, it must be indented more
+			// if not, it is the next item in the same list
+			if indent <= itemIndent {
+				break gatherlines
+			}
+
+			// is this the first item in the nested list?
+			if sublist == 0 {
+				sublist = raw.Len()
+			}
+
+		// is this a nested prefix header?
+		case p.isPrefixHeader(chunk):
+			// if the header is not indented, it is not nested in the list
+			// and thus ends the list
+			if containsBlankLine && indent < 4 {
+				*flags |= LIST_ITEM_END_OF_LIST
+				break gatherlines
+			}
+			*flags |= LIST_ITEM_CONTAINS_BLOCK
+
+		// anything following an empty line is only part
+		// of this item if it is indented 4 spaces
+		// (regardless of the indentation of the beginning of the item)
+		case containsBlankLine && indent < 4:
+			if *flags&LIST_TYPE_DEFINITION != 0 && i < len(data)-1 {
+				// is the next item still a part of this list?
+				next := i
+				for data[next] != '\n' {
+					next++
+				}
+				for next < len(data)-1 && data[next] == '\n' {
+					next++
+				}
+				if i < len(data)-1 && data[i] != ':' && data[next] != ':' {
+					*flags |= LIST_ITEM_END_OF_LIST
+				}
+			} else {
+				*flags |= LIST_ITEM_END_OF_LIST
+			}
+			break gatherlines
+
+		// a blank line means this should be parsed as a block
+		case containsBlankLine:
+			raw.WriteByte('\n')
+			*flags |= LIST_ITEM_CONTAINS_BLOCK
+		}
+
+		// if this line was preceeded by one or more blanks,
+		// re-introduce the blank into the buffer
+		if containsBlankLine {
+			containsBlankLine = false
+			raw.WriteByte('\n')
+
+		}
+
+		// add the line into the working buffer without prefix
+		raw.Write(data[line+indent : i])
+
+		line = i
+	}
+
+	rawBytes := raw.Bytes()
+
+	// render the contents of the list item
+	var cooked bytes.Buffer
+	if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 && *flags&LIST_TYPE_TERM == 0 {
+		// intermediate render of block item, except for definition term
+		if sublist > 0 {
+			p.block(&cooked, rawBytes[:sublist])
+			p.block(&cooked, rawBytes[sublist:])
+		} else {
+			p.block(&cooked, rawBytes)
+		}
+	} else {
+		// intermediate render of inline item
+		if sublist > 0 {
+			p.inline(&cooked, rawBytes[:sublist])
+			p.block(&cooked, rawBytes[sublist:])
+		} else {
+			p.inline(&cooked, rawBytes)
+		}
+	}
+
+	// render the actual list item
+	cookedBytes := cooked.Bytes()
+	parsedEnd := len(cookedBytes)
+
+	// strip trailing newlines
+	for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' {
+		parsedEnd--
+	}
+	p.r.ListItem(out, cookedBytes[:parsedEnd], *flags)
+
+	return line
+}
+
+// render a single paragraph that has already been parsed out
+func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) {
+	if len(data) == 0 {
+		return
+	}
+
+	// trim leading spaces
+	beg := 0
+	for data[beg] == ' ' {
+		beg++
+	}
+
+	// trim trailing newline
+	end := len(data) - 1
+
+	// trim trailing spaces
+	for end > beg && data[end-1] == ' ' {
+		end--
+	}
+
+	work := func() bool {
+		p.inline(out, data[beg:end])
+		return true
+	}
+	p.r.Paragraph(out, work)
+}
+
+func (p *parser) paragraph(out *bytes.Buffer, data []byte) int {
+	// prev: index of 1st char of previous line
+	// line: index of 1st char of current line
+	// i: index of cursor/end of current line
+	var prev, line, i int
+
+	// keep going until we find something to mark the end of the paragraph
+	for i < len(data) {
+		// mark the beginning of the current line
+		prev = line
+		current := data[i:]
+		line = i
+
+		// did we find a blank line marking the end of the paragraph?
+		if n := p.isEmpty(current); n > 0 {
+			// did this blank line followed by a definition list item?
+			if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
+				if i < len(data)-1 && data[i+1] == ':' {
+					return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
+				}
+			}
+
+			p.renderParagraph(out, data[:i])
+			return i + n
+		}
+
+		// an underline under some text marks a header, so our paragraph ended on prev line
+		if i > 0 {
+			if level := p.isUnderlinedHeader(current); level > 0 {
+				// render the paragraph
+				p.renderParagraph(out, data[:prev])
+
+				// ignore leading and trailing whitespace
+				eol := i - 1
+				for prev < eol && data[prev] == ' ' {
+					prev++
+				}
+				for eol > prev && data[eol-1] == ' ' {
+					eol--
+				}
+
+				// render the header
+				// this ugly double closure avoids forcing variables onto the heap
+				work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool {
+					return func() bool {
+						pp.inline(o, d)
+						return true
+					}
+				}(out, p, data[prev:eol])
+
+				id := ""
+				if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 {
+					id = sanitized_anchor_name.Create(string(data[prev:eol]))
+				}
+
+				p.r.Header(out, work, level, id)
+
+				// find the end of the underline
+				for data[i] != '\n' {
+					i++
+				}
+				return i
+			}
+		}
+
+		// if the next line starts a block of HTML, then the paragraph ends here
+		if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 {
+			if data[i] == '<' && p.html(out, current, false) > 0 {
+				// rewind to before the HTML block
+				p.renderParagraph(out, data[:i])
+				return i
+			}
+		}
+
+		// if there's a prefixed header or a horizontal rule after this, paragraph is over
+		if p.isPrefixHeader(current) || p.isHRule(current) {
+			p.renderParagraph(out, data[:i])
+			return i
+		}
+
+		// if there's a fenced code block, paragraph is over
+		if p.flags&EXTENSION_FENCED_CODE != 0 {
+			if p.fencedCode(out, current, false) > 0 {
+				p.renderParagraph(out, data[:i])
+				return i
+			}
+		}
+
+		// if there's a definition list item, prev line is a definition term
+		if p.flags&EXTENSION_DEFINITION_LISTS != 0 {
+			if p.dliPrefix(current) != 0 {
+				return p.list(out, data[prev:], LIST_TYPE_DEFINITION)
+			}
+		}
+
+		// if there's a list after this, paragraph is over
+		if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 {
+			if p.uliPrefix(current) != 0 ||
+				p.oliPrefix(current) != 0 ||
+				p.quotePrefix(current) != 0 ||
+				p.codePrefix(current) != 0 {
+				p.renderParagraph(out, data[:i])
+				return i
+			}
+		}
+
+		// otherwise, scan to the beginning of the next line
+		for data[i] != '\n' {
+			i++
+		}
+		i++
+	}
+
+	p.renderParagraph(out, data[:i])
+	return i
+}

+ 1532 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/block_test.go

@@ -0,0 +1,1532 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+// Unit tests for block parsing
+//
+
+package blackfriday
+
+import (
+	"strings"
+	"testing"
+)
+
+func runMarkdownBlockWithRenderer(input string, extensions int, renderer Renderer) string {
+	return string(Markdown([]byte(input), renderer, extensions))
+}
+
+func runMarkdownBlock(input string, extensions int) string {
+	htmlFlags := 0
+	htmlFlags |= HTML_USE_XHTML
+
+	renderer := HtmlRenderer(htmlFlags, "", "")
+
+	return runMarkdownBlockWithRenderer(input, extensions, renderer)
+}
+
+func runnerWithRendererParameters(parameters HtmlRendererParameters) func(string, int) string {
+	return func(input string, extensions int) string {
+		htmlFlags := 0
+		htmlFlags |= HTML_USE_XHTML
+
+		renderer := HtmlRendererWithParameters(htmlFlags, "", "", parameters)
+
+		return runMarkdownBlockWithRenderer(input, extensions, renderer)
+	}
+}
+
+func doTestsBlock(t *testing.T, tests []string, extensions int) {
+	doTestsBlockWithRunner(t, tests, extensions, runMarkdownBlock)
+}
+
+func doTestsBlockWithRunner(t *testing.T, tests []string, extensions int, runner func(string, int) string) {
+	// catch and report panics
+	var candidate string
+	defer func() {
+		if err := recover(); err != nil {
+			t.Errorf("\npanic while processing [%#v]: %s\n", candidate, err)
+		}
+	}()
+
+	for i := 0; i+1 < len(tests); i += 2 {
+		input := tests[i]
+		candidate = input
+		expected := tests[i+1]
+		actual := runner(candidate, extensions)
+		if actual != expected {
+			t.Errorf("\nInput   [%#v]\nExpected[%#v]\nActual  [%#v]",
+				candidate, expected, actual)
+		}
+
+		// now test every substring to stress test bounds checking
+		if !testing.Short() {
+			for start := 0; start < len(input); start++ {
+				for end := start + 1; end <= len(input); end++ {
+					candidate = input[start:end]
+					_ = runMarkdownBlock(candidate, extensions)
+				}
+			}
+		}
+	}
+}
+
+func TestPrefixHeaderNoExtensions(t *testing.T) {
+	var tests = []string{
+		"# Header 1\n",
+		"<h1>Header 1</h1>\n",
+
+		"## Header 2\n",
+		"<h2>Header 2</h2>\n",
+
+		"### Header 3\n",
+		"<h3>Header 3</h3>\n",
+
+		"#### Header 4\n",
+		"<h4>Header 4</h4>\n",
+
+		"##### Header 5\n",
+		"<h5>Header 5</h5>\n",
+
+		"###### Header 6\n",
+		"<h6>Header 6</h6>\n",
+
+		"####### Header 7\n",
+		"<h6># Header 7</h6>\n",
+
+		"#Header 1\n",
+		"<h1>Header 1</h1>\n",
+
+		"##Header 2\n",
+		"<h2>Header 2</h2>\n",
+
+		"###Header 3\n",
+		"<h3>Header 3</h3>\n",
+
+		"####Header 4\n",
+		"<h4>Header 4</h4>\n",
+
+		"#####Header 5\n",
+		"<h5>Header 5</h5>\n",
+
+		"######Header 6\n",
+		"<h6>Header 6</h6>\n",
+
+		"#######Header 7\n",
+		"<h6>#Header 7</h6>\n",
+
+		"Hello\n# Header 1\nGoodbye\n",
+		"<p>Hello</p>\n\n<h1>Header 1</h1>\n\n<p>Goodbye</p>\n",
+
+		"* List\n# Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1>Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"* List\n#Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1>Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n    # Nested header\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li><p>Nested list</p>\n\n" +
+			"<h1>Nested header</h1></li>\n</ul></li>\n</ul>\n",
+
+		"#Header 1 \\#\n",
+		"<h1>Header 1 #</h1>\n",
+
+		"#Header 1 \\# foo\n",
+		"<h1>Header 1 # foo</h1>\n",
+
+		"#Header 1 #\\##\n",
+		"<h1>Header 1 ##</h1>\n",
+	}
+	doTestsBlock(t, tests, 0)
+}
+
+func TestPrefixHeaderSpaceExtension(t *testing.T) {
+	var tests = []string{
+		"# Header 1\n",
+		"<h1>Header 1</h1>\n",
+
+		"## Header 2\n",
+		"<h2>Header 2</h2>\n",
+
+		"### Header 3\n",
+		"<h3>Header 3</h3>\n",
+
+		"#### Header 4\n",
+		"<h4>Header 4</h4>\n",
+
+		"##### Header 5\n",
+		"<h5>Header 5</h5>\n",
+
+		"###### Header 6\n",
+		"<h6>Header 6</h6>\n",
+
+		"####### Header 7\n",
+		"<p>####### Header 7</p>\n",
+
+		"#Header 1\n",
+		"<p>#Header 1</p>\n",
+
+		"##Header 2\n",
+		"<p>##Header 2</p>\n",
+
+		"###Header 3\n",
+		"<p>###Header 3</p>\n",
+
+		"####Header 4\n",
+		"<p>####Header 4</p>\n",
+
+		"#####Header 5\n",
+		"<p>#####Header 5</p>\n",
+
+		"######Header 6\n",
+		"<p>######Header 6</p>\n",
+
+		"#######Header 7\n",
+		"<p>#######Header 7</p>\n",
+
+		"Hello\n# Header 1\nGoodbye\n",
+		"<p>Hello</p>\n\n<h1>Header 1</h1>\n\n<p>Goodbye</p>\n",
+
+		"* List\n# Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1>Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"* List\n#Header\n* List\n",
+		"<ul>\n<li>List\n#Header</li>\n<li>List</li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n    # Nested header\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li><p>Nested list</p>\n\n" +
+			"<h1>Nested header</h1></li>\n</ul></li>\n</ul>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_SPACE_HEADERS)
+}
+
+func TestPrefixHeaderIdExtension(t *testing.T) {
+	var tests = []string{
+		"# Header 1 {#someid}\n",
+		"<h1 id=\"someid\">Header 1</h1>\n",
+
+		"# Header 1 {#someid}   \n",
+		"<h1 id=\"someid\">Header 1</h1>\n",
+
+		"# Header 1         {#someid}\n",
+		"<h1 id=\"someid\">Header 1</h1>\n",
+
+		"# Header 1 {#someid\n",
+		"<h1>Header 1 {#someid</h1>\n",
+
+		"# Header 1 {#someid\n",
+		"<h1>Header 1 {#someid</h1>\n",
+
+		"# Header 1 {#someid}}\n",
+		"<h1 id=\"someid\">Header 1</h1>\n\n<p>}</p>\n",
+
+		"## Header 2 {#someid}\n",
+		"<h2 id=\"someid\">Header 2</h2>\n",
+
+		"### Header 3 {#someid}\n",
+		"<h3 id=\"someid\">Header 3</h3>\n",
+
+		"#### Header 4 {#someid}\n",
+		"<h4 id=\"someid\">Header 4</h4>\n",
+
+		"##### Header 5 {#someid}\n",
+		"<h5 id=\"someid\">Header 5</h5>\n",
+
+		"###### Header 6 {#someid}\n",
+		"<h6 id=\"someid\">Header 6</h6>\n",
+
+		"####### Header 7 {#someid}\n",
+		"<h6 id=\"someid\"># Header 7</h6>\n",
+
+		"# Header 1 # {#someid}\n",
+		"<h1 id=\"someid\">Header 1</h1>\n",
+
+		"## Header 2 ## {#someid}\n",
+		"<h2 id=\"someid\">Header 2</h2>\n",
+
+		"Hello\n# Header 1\nGoodbye\n",
+		"<p>Hello</p>\n\n<h1>Header 1</h1>\n\n<p>Goodbye</p>\n",
+
+		"* List\n# Header {#someid}\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"someid\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"* List\n#Header {#someid}\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"someid\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n    # Nested header {#someid}\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li><p>Nested list</p>\n\n" +
+			"<h1 id=\"someid\">Nested header</h1></li>\n</ul></li>\n</ul>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_HEADER_IDS)
+}
+
+func TestPrefixHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) {
+	var tests = []string{
+		"# header 1 {#someid}\n",
+		"<h1 id=\"PRE:someid:POST\">header 1</h1>\n",
+
+		"## header 2 {#someid}\n",
+		"<h2 id=\"PRE:someid:POST\">header 2</h2>\n",
+
+		"### header 3 {#someid}\n",
+		"<h3 id=\"PRE:someid:POST\">header 3</h3>\n",
+
+		"#### header 4 {#someid}\n",
+		"<h4 id=\"PRE:someid:POST\">header 4</h4>\n",
+
+		"##### header 5 {#someid}\n",
+		"<h5 id=\"PRE:someid:POST\">header 5</h5>\n",
+
+		"###### header 6 {#someid}\n",
+		"<h6 id=\"PRE:someid:POST\">header 6</h6>\n",
+
+		"####### header 7 {#someid}\n",
+		"<h6 id=\"PRE:someid:POST\"># header 7</h6>\n",
+
+		"# header 1 # {#someid}\n",
+		"<h1 id=\"PRE:someid:POST\">header 1</h1>\n",
+
+		"## header 2 ## {#someid}\n",
+		"<h2 id=\"PRE:someid:POST\">header 2</h2>\n",
+
+		"* List\n# Header {#someid}\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"PRE:someid:POST\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"* List\n#Header {#someid}\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"PRE:someid:POST\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n    # Nested header {#someid}\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li><p>Nested list</p>\n\n" +
+			"<h1 id=\"PRE:someid:POST\">Nested header</h1></li>\n</ul></li>\n</ul>\n",
+	}
+
+	parameters := HtmlRendererParameters{
+		HeaderIDPrefix: "PRE:",
+		HeaderIDSuffix: ":POST",
+	}
+
+	doTestsBlockWithRunner(t, tests, EXTENSION_HEADER_IDS, runnerWithRendererParameters(parameters))
+}
+
+func TestPrefixAutoHeaderIdExtension(t *testing.T) {
+	var tests = []string{
+		"# Header 1\n",
+		"<h1 id=\"header-1\">Header 1</h1>\n",
+
+		"# Header 1   \n",
+		"<h1 id=\"header-1\">Header 1</h1>\n",
+
+		"## Header 2\n",
+		"<h2 id=\"header-2\">Header 2</h2>\n",
+
+		"### Header 3\n",
+		"<h3 id=\"header-3\">Header 3</h3>\n",
+
+		"#### Header 4\n",
+		"<h4 id=\"header-4\">Header 4</h4>\n",
+
+		"##### Header 5\n",
+		"<h5 id=\"header-5\">Header 5</h5>\n",
+
+		"###### Header 6\n",
+		"<h6 id=\"header-6\">Header 6</h6>\n",
+
+		"####### Header 7\n",
+		"<h6 id=\"header-7\"># Header 7</h6>\n",
+
+		"Hello\n# Header 1\nGoodbye\n",
+		"<p>Hello</p>\n\n<h1 id=\"header-1\">Header 1</h1>\n\n<p>Goodbye</p>\n",
+
+		"* List\n# Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"header\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"* List\n#Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"header\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n    # Nested header\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li><p>Nested list</p>\n\n" +
+			"<h1 id=\"nested-header\">Nested header</h1></li>\n</ul></li>\n</ul>\n",
+
+		"# Header\n\n# Header\n",
+		"<h1 id=\"header\">Header</h1>\n\n<h1 id=\"header-1\">Header</h1>\n",
+
+		"# Header 1\n\n# Header 1",
+		"<h1 id=\"header-1\">Header 1</h1>\n\n<h1 id=\"header-1-1\">Header 1</h1>\n",
+
+		"# Header\n\n# Header 1\n\n# Header\n\n# Header",
+		"<h1 id=\"header\">Header</h1>\n\n<h1 id=\"header-1\">Header 1</h1>\n\n<h1 id=\"header-1-1\">Header</h1>\n\n<h1 id=\"header-1-2\">Header</h1>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS)
+}
+
+func TestPrefixAutoHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) {
+	var tests = []string{
+		"# Header 1\n",
+		"<h1 id=\"PRE:header-1:POST\">Header 1</h1>\n",
+
+		"# Header 1   \n",
+		"<h1 id=\"PRE:header-1:POST\">Header 1</h1>\n",
+
+		"## Header 2\n",
+		"<h2 id=\"PRE:header-2:POST\">Header 2</h2>\n",
+
+		"### Header 3\n",
+		"<h3 id=\"PRE:header-3:POST\">Header 3</h3>\n",
+
+		"#### Header 4\n",
+		"<h4 id=\"PRE:header-4:POST\">Header 4</h4>\n",
+
+		"##### Header 5\n",
+		"<h5 id=\"PRE:header-5:POST\">Header 5</h5>\n",
+
+		"###### Header 6\n",
+		"<h6 id=\"PRE:header-6:POST\">Header 6</h6>\n",
+
+		"####### Header 7\n",
+		"<h6 id=\"PRE:header-7:POST\"># Header 7</h6>\n",
+
+		"Hello\n# Header 1\nGoodbye\n",
+		"<p>Hello</p>\n\n<h1 id=\"PRE:header-1:POST\">Header 1</h1>\n\n<p>Goodbye</p>\n",
+
+		"* List\n# Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"PRE:header:POST\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"* List\n#Header\n* List\n",
+		"<ul>\n<li><p>List</p>\n\n<h1 id=\"PRE:header:POST\">Header</h1></li>\n\n<li><p>List</p></li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n    # Nested header\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li><p>Nested list</p>\n\n" +
+			"<h1 id=\"PRE:nested-header:POST\">Nested header</h1></li>\n</ul></li>\n</ul>\n",
+
+		"# Header\n\n# Header\n",
+		"<h1 id=\"PRE:header:POST\">Header</h1>\n\n<h1 id=\"PRE:header-1:POST\">Header</h1>\n",
+
+		"# Header 1\n\n# Header 1",
+		"<h1 id=\"PRE:header-1:POST\">Header 1</h1>\n\n<h1 id=\"PRE:header-1-1:POST\">Header 1</h1>\n",
+
+		"# Header\n\n# Header 1\n\n# Header\n\n# Header",
+		"<h1 id=\"PRE:header:POST\">Header</h1>\n\n<h1 id=\"PRE:header-1:POST\">Header 1</h1>\n\n<h1 id=\"PRE:header-1-1:POST\">Header</h1>\n\n<h1 id=\"PRE:header-1-2:POST\">Header</h1>\n",
+	}
+
+	parameters := HtmlRendererParameters{
+		HeaderIDPrefix: "PRE:",
+		HeaderIDSuffix: ":POST",
+	}
+
+	doTestsBlockWithRunner(t, tests, EXTENSION_AUTO_HEADER_IDS, runnerWithRendererParameters(parameters))
+}
+
+func TestPrefixMultipleHeaderExtensions(t *testing.T) {
+	var tests = []string{
+		"# Header\n\n# Header {#header}\n\n# Header 1",
+		"<h1 id=\"header\">Header</h1>\n\n<h1 id=\"header-1\">Header</h1>\n\n<h1 id=\"header-1-1\">Header 1</h1>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS|EXTENSION_HEADER_IDS)
+}
+
+func TestUnderlineHeaders(t *testing.T) {
+	var tests = []string{
+		"Header 1\n========\n",
+		"<h1>Header 1</h1>\n",
+
+		"Header 2\n--------\n",
+		"<h2>Header 2</h2>\n",
+
+		"A\n=\n",
+		"<h1>A</h1>\n",
+
+		"B\n-\n",
+		"<h2>B</h2>\n",
+
+		"Paragraph\nHeader\n=\n",
+		"<p>Paragraph</p>\n\n<h1>Header</h1>\n",
+
+		"Header\n===\nParagraph\n",
+		"<h1>Header</h1>\n\n<p>Paragraph</p>\n",
+
+		"Header\n===\nAnother header\n---\n",
+		"<h1>Header</h1>\n\n<h2>Another header</h2>\n",
+
+		"   Header\n======\n",
+		"<h1>Header</h1>\n",
+
+		"    Code\n========\n",
+		"<pre><code>Code\n</code></pre>\n\n<p>========</p>\n",
+
+		"Header with *inline*\n=====\n",
+		"<h1>Header with <em>inline</em></h1>\n",
+
+		"*   List\n    * Sublist\n    Not a header\n    ------\n",
+		"<ul>\n<li>List\n\n<ul>\n<li>Sublist\nNot a header\n------</li>\n</ul></li>\n</ul>\n",
+
+		"Paragraph\n\n\n\n\nHeader\n===\n",
+		"<p>Paragraph</p>\n\n<h1>Header</h1>\n",
+
+		"Trailing space \n====        \n\n",
+		"<h1>Trailing space</h1>\n",
+
+		"Trailing spaces\n====        \n\n",
+		"<h1>Trailing spaces</h1>\n",
+
+		"Double underline\n=====\n=====\n",
+		"<h1>Double underline</h1>\n\n<p>=====</p>\n",
+	}
+	doTestsBlock(t, tests, 0)
+}
+
+func TestUnderlineHeadersAutoIDs(t *testing.T) {
+	var tests = []string{
+		"Header 1\n========\n",
+		"<h1 id=\"header-1\">Header 1</h1>\n",
+
+		"Header 2\n--------\n",
+		"<h2 id=\"header-2\">Header 2</h2>\n",
+
+		"A\n=\n",
+		"<h1 id=\"a\">A</h1>\n",
+
+		"B\n-\n",
+		"<h2 id=\"b\">B</h2>\n",
+
+		"Paragraph\nHeader\n=\n",
+		"<p>Paragraph</p>\n\n<h1 id=\"header\">Header</h1>\n",
+
+		"Header\n===\nParagraph\n",
+		"<h1 id=\"header\">Header</h1>\n\n<p>Paragraph</p>\n",
+
+		"Header\n===\nAnother header\n---\n",
+		"<h1 id=\"header\">Header</h1>\n\n<h2 id=\"another-header\">Another header</h2>\n",
+
+		"   Header\n======\n",
+		"<h1 id=\"header\">Header</h1>\n",
+
+		"Header with *inline*\n=====\n",
+		"<h1 id=\"header-with-inline\">Header with <em>inline</em></h1>\n",
+
+		"Paragraph\n\n\n\n\nHeader\n===\n",
+		"<p>Paragraph</p>\n\n<h1 id=\"header\">Header</h1>\n",
+
+		"Trailing space \n====        \n\n",
+		"<h1 id=\"trailing-space\">Trailing space</h1>\n",
+
+		"Trailing spaces\n====        \n\n",
+		"<h1 id=\"trailing-spaces\">Trailing spaces</h1>\n",
+
+		"Double underline\n=====\n=====\n",
+		"<h1 id=\"double-underline\">Double underline</h1>\n\n<p>=====</p>\n",
+
+		"Header\n======\n\nHeader\n======\n",
+		"<h1 id=\"header\">Header</h1>\n\n<h1 id=\"header-1\">Header</h1>\n",
+
+		"Header 1\n========\n\nHeader 1\n========\n",
+		"<h1 id=\"header-1\">Header 1</h1>\n\n<h1 id=\"header-1-1\">Header 1</h1>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS)
+}
+
+func TestHorizontalRule(t *testing.T) {
+	var tests = []string{
+		"-\n",
+		"<p>-</p>\n",
+
+		"--\n",
+		"<p>--</p>\n",
+
+		"---\n",
+		"<hr />\n",
+
+		"----\n",
+		"<hr />\n",
+
+		"*\n",
+		"<p>*</p>\n",
+
+		"**\n",
+		"<p>**</p>\n",
+
+		"***\n",
+		"<hr />\n",
+
+		"****\n",
+		"<hr />\n",
+
+		"_\n",
+		"<p>_</p>\n",
+
+		"__\n",
+		"<p>__</p>\n",
+
+		"___\n",
+		"<hr />\n",
+
+		"____\n",
+		"<hr />\n",
+
+		"-*-\n",
+		"<p>-*-</p>\n",
+
+		"- - -\n",
+		"<hr />\n",
+
+		"* * *\n",
+		"<hr />\n",
+
+		"_ _ _\n",
+		"<hr />\n",
+
+		"-----*\n",
+		"<p>-----*</p>\n",
+
+		"   ------   \n",
+		"<hr />\n",
+
+		"Hello\n***\n",
+		"<p>Hello</p>\n\n<hr />\n",
+
+		"---\n***\n___\n",
+		"<hr />\n\n<hr />\n\n<hr />\n",
+	}
+	doTestsBlock(t, tests, 0)
+}
+
+func TestUnorderedList(t *testing.T) {
+	var tests = []string{
+		"* Hello\n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"* Yin\n* Yang\n",
+		"<ul>\n<li>Yin</li>\n<li>Yang</li>\n</ul>\n",
+
+		"* Ting\n* Bong\n* Goo\n",
+		"<ul>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ul>\n",
+
+		"* Yin\n\n* Yang\n",
+		"<ul>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ul>\n",
+
+		"* Ting\n\n* Bong\n* Goo\n",
+		"<ul>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ul>\n",
+
+		"+ Hello\n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"+ Yin\n+ Yang\n",
+		"<ul>\n<li>Yin</li>\n<li>Yang</li>\n</ul>\n",
+
+		"+ Ting\n+ Bong\n+ Goo\n",
+		"<ul>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ul>\n",
+
+		"+ Yin\n\n+ Yang\n",
+		"<ul>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ul>\n",
+
+		"+ Ting\n\n+ Bong\n+ Goo\n",
+		"<ul>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ul>\n",
+
+		"- Hello\n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"- Yin\n- Yang\n",
+		"<ul>\n<li>Yin</li>\n<li>Yang</li>\n</ul>\n",
+
+		"- Ting\n- Bong\n- Goo\n",
+		"<ul>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ul>\n",
+
+		"- Yin\n\n- Yang\n",
+		"<ul>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ul>\n",
+
+		"- Ting\n\n- Bong\n- Goo\n",
+		"<ul>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ul>\n",
+
+		"*Hello\n",
+		"<p>*Hello</p>\n",
+
+		"*   Hello \n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"*   Hello \n    Next line \n",
+		"<ul>\n<li>Hello\nNext line</li>\n</ul>\n",
+
+		"Paragraph\n* No linebreak\n",
+		"<p>Paragraph\n* No linebreak</p>\n",
+
+		"Paragraph\n\n* Linebreak\n",
+		"<p>Paragraph</p>\n\n<ul>\n<li>Linebreak</li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n",
+		"<ul>\n<li>List\n\n<ul>\n<li>Nested list</li>\n</ul></li>\n</ul>\n",
+
+		"*   List\n\n    * Nested list\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li>Nested list</li>\n</ul></li>\n</ul>\n",
+
+		"*   List\n    Second line\n\n    + Nested\n",
+		"<ul>\n<li><p>List\nSecond line</p>\n\n<ul>\n<li>Nested</li>\n</ul></li>\n</ul>\n",
+
+		"*   List\n    + Nested\n\n    Continued\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li>Nested</li>\n</ul>\n\n<p>Continued</p></li>\n</ul>\n",
+
+		"*   List\n   * shallow indent\n",
+		"<ul>\n<li>List\n\n<ul>\n<li>shallow indent</li>\n</ul></li>\n</ul>\n",
+
+		"* List\n" +
+			" * shallow indent\n" +
+			"  * part of second list\n" +
+			"   * still second\n" +
+			"    * almost there\n" +
+			"     * third level\n",
+		"<ul>\n" +
+			"<li>List\n\n" +
+			"<ul>\n" +
+			"<li>shallow indent</li>\n" +
+			"<li>part of second list</li>\n" +
+			"<li>still second</li>\n" +
+			"<li>almost there\n\n" +
+			"<ul>\n" +
+			"<li>third level</li>\n" +
+			"</ul></li>\n" +
+			"</ul></li>\n" +
+			"</ul>\n",
+
+		"* List\n        extra indent, same paragraph\n",
+		"<ul>\n<li>List\n    extra indent, same paragraph</li>\n</ul>\n",
+
+		"* List\n\n        code block\n",
+		"<ul>\n<li><p>List</p>\n\n<pre><code>code block\n</code></pre></li>\n</ul>\n",
+
+		"* List\n\n          code block with spaces\n",
+		"<ul>\n<li><p>List</p>\n\n<pre><code>  code block with spaces\n</code></pre></li>\n</ul>\n",
+
+		"* List\n\n    * sublist\n\n    normal text\n\n    * another sublist\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li>sublist</li>\n</ul>\n\n<p>normal text</p>\n\n<ul>\n<li>another sublist</li>\n</ul></li>\n</ul>\n",
+	}
+	doTestsBlock(t, tests, 0)
+}
+
+func TestOrderedList(t *testing.T) {
+	var tests = []string{
+		"1. Hello\n",
+		"<ol>\n<li>Hello</li>\n</ol>\n",
+
+		"1. Yin\n2. Yang\n",
+		"<ol>\n<li>Yin</li>\n<li>Yang</li>\n</ol>\n",
+
+		"1. Ting\n2. Bong\n3. Goo\n",
+		"<ol>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ol>\n",
+
+		"1. Yin\n\n2. Yang\n",
+		"<ol>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ol>\n",
+
+		"1. Ting\n\n2. Bong\n3. Goo\n",
+		"<ol>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ol>\n",
+
+		"1 Hello\n",
+		"<p>1 Hello</p>\n",
+
+		"1.Hello\n",
+		"<p>1.Hello</p>\n",
+
+		"1.  Hello \n",
+		"<ol>\n<li>Hello</li>\n</ol>\n",
+
+		"1.  Hello \n    Next line \n",
+		"<ol>\n<li>Hello\nNext line</li>\n</ol>\n",
+
+		"Paragraph\n1. No linebreak\n",
+		"<p>Paragraph\n1. No linebreak</p>\n",
+
+		"Paragraph\n\n1. Linebreak\n",
+		"<p>Paragraph</p>\n\n<ol>\n<li>Linebreak</li>\n</ol>\n",
+
+		"1.  List\n    1. Nested list\n",
+		"<ol>\n<li>List\n\n<ol>\n<li>Nested list</li>\n</ol></li>\n</ol>\n",
+
+		"1.  List\n\n    1. Nested list\n",
+		"<ol>\n<li><p>List</p>\n\n<ol>\n<li>Nested list</li>\n</ol></li>\n</ol>\n",
+
+		"1.  List\n    Second line\n\n    1. Nested\n",
+		"<ol>\n<li><p>List\nSecond line</p>\n\n<ol>\n<li>Nested</li>\n</ol></li>\n</ol>\n",
+
+		"1.  List\n    1. Nested\n\n    Continued\n",
+		"<ol>\n<li><p>List</p>\n\n<ol>\n<li>Nested</li>\n</ol>\n\n<p>Continued</p></li>\n</ol>\n",
+
+		"1.  List\n   1. shallow indent\n",
+		"<ol>\n<li>List\n\n<ol>\n<li>shallow indent</li>\n</ol></li>\n</ol>\n",
+
+		"1. List\n" +
+			" 1. shallow indent\n" +
+			"  2. part of second list\n" +
+			"   3. still second\n" +
+			"    4. almost there\n" +
+			"     1. third level\n",
+		"<ol>\n" +
+			"<li>List\n\n" +
+			"<ol>\n" +
+			"<li>shallow indent</li>\n" +
+			"<li>part of second list</li>\n" +
+			"<li>still second</li>\n" +
+			"<li>almost there\n\n" +
+			"<ol>\n" +
+			"<li>third level</li>\n" +
+			"</ol></li>\n" +
+			"</ol></li>\n" +
+			"</ol>\n",
+
+		"1. List\n        extra indent, same paragraph\n",
+		"<ol>\n<li>List\n    extra indent, same paragraph</li>\n</ol>\n",
+
+		"1. List\n\n        code block\n",
+		"<ol>\n<li><p>List</p>\n\n<pre><code>code block\n</code></pre></li>\n</ol>\n",
+
+		"1. List\n\n          code block with spaces\n",
+		"<ol>\n<li><p>List</p>\n\n<pre><code>  code block with spaces\n</code></pre></li>\n</ol>\n",
+
+		"1. List\n    * Mixted list\n",
+		"<ol>\n<li>List\n\n<ul>\n<li>Mixted list</li>\n</ul></li>\n</ol>\n",
+
+		"1. List\n * Mixed list\n",
+		"<ol>\n<li>List\n\n<ul>\n<li>Mixed list</li>\n</ul></li>\n</ol>\n",
+
+		"* Start with unordered\n 1. Ordered\n",
+		"<ul>\n<li>Start with unordered\n\n<ol>\n<li>Ordered</li>\n</ol></li>\n</ul>\n",
+
+		"* Start with unordered\n    1. Ordered\n",
+		"<ul>\n<li>Start with unordered\n\n<ol>\n<li>Ordered</li>\n</ol></li>\n</ul>\n",
+
+		"1. numbers\n1. are ignored\n",
+		"<ol>\n<li>numbers</li>\n<li>are ignored</li>\n</ol>\n",
+	}
+	doTestsBlock(t, tests, 0)
+}
+
+func TestDefinitionList(t *testing.T) {
+	var tests = []string{
+		"Term 1\n:   Definition a\n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a</dd>\n</dl>\n",
+
+		"Term 1\n:   Definition a \n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a</dd>\n</dl>\n",
+
+		"Term 1\n:   Definition a\n:   Definition b\n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a</dd>\n<dd>Definition b</dd>\n</dl>\n",
+
+		"Term 1\n:   Definition a\n\nTerm 2\n:   Definition b\n",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd>Definition a</dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd>Definition b</dd>\n" +
+			"</dl>\n",
+
+		"Term 1\n:   Definition a\n\nTerm 2\n:   Definition b\n\nTerm 3\n:   Definition c\n",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd>Definition a</dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd>Definition b</dd>\n" +
+			"<dt>Term 3</dt>\n" +
+			"<dd>Definition c</dd>\n" +
+			"</dl>\n",
+
+		"Term 1\n:   Definition a\n:   Definition b\n\nTerm 2\n:   Definition c\n",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd>Definition a</dd>\n" +
+			"<dd>Definition b</dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd>Definition c</dd>\n" +
+			"</dl>\n",
+
+		"Term 1\n\n:   Definition a\n\nTerm 2\n\n:   Definition b\n",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd><p>Definition a</p></dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd><p>Definition b</p></dd>\n" +
+			"</dl>\n",
+
+		"Term 1\n\n:   Definition a\n\n:   Definition b\n\nTerm 2\n\n:   Definition c\n",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd><p>Definition a</p></dd>\n" +
+			"<dd><p>Definition b</p></dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd><p>Definition c</p></dd>\n" +
+			"</dl>\n",
+
+		"Term 1\n:   Definition a\nNext line\n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a\nNext line</dd>\n</dl>\n",
+
+		"Term 1\n:   Definition a\n  Next line\n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a\nNext line</dd>\n</dl>\n",
+
+		"Term 1\n:   Definition a \n  Next line \n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a\nNext line</dd>\n</dl>\n",
+
+		"Term 1\n:   Definition a\nNext line\n\nTerm 2\n:   Definition b",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd>Definition a\nNext line</dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd>Definition b</dd>\n" +
+			"</dl>\n",
+
+		"Term 1\n: Definition a\n",
+		"<dl>\n<dt>Term 1</dt>\n<dd>Definition a</dd>\n</dl>\n",
+
+		"Term 1\n:Definition a\n",
+		"<p>Term 1\n:Definition a</p>\n",
+
+		"Term 1\n\n:   Definition a\n\nTerm 2\n\n:   Definition b\n\nText 1",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd><p>Definition a</p></dd>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd><p>Definition b</p></dd>\n" +
+			"</dl>\n" +
+			"\n<p>Text 1</p>\n",
+
+		"Term 1\n\n:   Definition a\n\nText 1\n\nTerm 2\n\n:   Definition b\n\nText 2",
+		"<dl>\n" +
+			"<dt>Term 1</dt>\n" +
+			"<dd><p>Definition a</p></dd>\n" +
+			"</dl>\n" +
+			"\n<p>Text 1</p>\n" +
+			"\n<dl>\n" +
+			"<dt>Term 2</dt>\n" +
+			"<dd><p>Definition b</p></dd>\n" +
+			"</dl>\n" +
+			"\n<p>Text 2</p>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_DEFINITION_LISTS)
+}
+
+func TestPreformattedHtml(t *testing.T) {
+	var tests = []string{
+		"<div></div>\n",
+		"<div></div>\n",
+
+		"<div>\n</div>\n",
+		"<div>\n</div>\n",
+
+		"<div>\n</div>\nParagraph\n",
+		"<p><div>\n</div>\nParagraph</p>\n",
+
+		"<div class=\"foo\">\n</div>\n",
+		"<div class=\"foo\">\n</div>\n",
+
+		"<div>\nAnything here\n</div>\n",
+		"<div>\nAnything here\n</div>\n",
+
+		"<div>\n  Anything here\n</div>\n",
+		"<div>\n  Anything here\n</div>\n",
+
+		"<div>\nAnything here\n  </div>\n",
+		"<div>\nAnything here\n  </div>\n",
+
+		"<div>\nThis is *not* &proceessed\n</div>\n",
+		"<div>\nThis is *not* &proceessed\n</div>\n",
+
+		"<faketag>\n  Something\n</faketag>\n",
+		"<p><faketag>\n  Something\n</faketag></p>\n",
+
+		"<div>\n  Something here\n</divv>\n",
+		"<p><div>\n  Something here\n</divv></p>\n",
+
+		"Paragraph\n<div>\nHere? >&<\n</div>\n",
+		"<p>Paragraph\n<div>\nHere? &gt;&amp;&lt;\n</div></p>\n",
+
+		"Paragraph\n\n<div>\nHow about here? >&<\n</div>\n",
+		"<p>Paragraph</p>\n\n<div>\nHow about here? >&<\n</div>\n",
+
+		"Paragraph\n<div>\nHere? >&<\n</div>\nAnd here?\n",
+		"<p>Paragraph\n<div>\nHere? &gt;&amp;&lt;\n</div>\nAnd here?</p>\n",
+
+		"Paragraph\n\n<div>\nHow about here? >&<\n</div>\nAnd here?\n",
+		"<p>Paragraph</p>\n\n<p><div>\nHow about here? &gt;&amp;&lt;\n</div>\nAnd here?</p>\n",
+
+		"Paragraph\n<div>\nHere? >&<\n</div>\n\nAnd here?\n",
+		"<p>Paragraph\n<div>\nHere? &gt;&amp;&lt;\n</div></p>\n\n<p>And here?</p>\n",
+
+		"Paragraph\n\n<div>\nHow about here? >&<\n</div>\n\nAnd here?\n",
+		"<p>Paragraph</p>\n\n<div>\nHow about here? >&<\n</div>\n\n<p>And here?</p>\n",
+	}
+	doTestsBlock(t, tests, 0)
+}
+
+func TestPreformattedHtmlLax(t *testing.T) {
+	var tests = []string{
+		"Paragraph\n<div>\nHere? >&<\n</div>\n",
+		"<p>Paragraph</p>\n\n<div>\nHere? >&<\n</div>\n",
+
+		"Paragraph\n\n<div>\nHow about here? >&<\n</div>\n",
+		"<p>Paragraph</p>\n\n<div>\nHow about here? >&<\n</div>\n",
+
+		"Paragraph\n<div>\nHere? >&<\n</div>\nAnd here?\n",
+		"<p>Paragraph</p>\n\n<div>\nHere? >&<\n</div>\n\n<p>And here?</p>\n",
+
+		"Paragraph\n\n<div>\nHow about here? >&<\n</div>\nAnd here?\n",
+		"<p>Paragraph</p>\n\n<div>\nHow about here? >&<\n</div>\n\n<p>And here?</p>\n",
+
+		"Paragraph\n<div>\nHere? >&<\n</div>\n\nAnd here?\n",
+		"<p>Paragraph</p>\n\n<div>\nHere? >&<\n</div>\n\n<p>And here?</p>\n",
+
+		"Paragraph\n\n<div>\nHow about here? >&<\n</div>\n\nAnd here?\n",
+		"<p>Paragraph</p>\n\n<div>\nHow about here? >&<\n</div>\n\n<p>And here?</p>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_LAX_HTML_BLOCKS)
+}
+
+func TestFencedCodeBlock(t *testing.T) {
+	var tests = []string{
+		"``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n",
+		"<pre><code class=\"language-go\">func foo() bool {\n\treturn true;\n}\n</code></pre>\n",
+
+		"``` c\n/* special & char < > \" escaping */\n```\n",
+		"<pre><code class=\"language-c\">/* special &amp; char &lt; &gt; &quot; escaping */\n</code></pre>\n",
+
+		"``` c\nno *inline* processing ~~of text~~\n```\n",
+		"<pre><code class=\"language-c\">no *inline* processing ~~of text~~\n</code></pre>\n",
+
+		"```\nNo language\n```\n",
+		"<pre><code>No language\n</code></pre>\n",
+
+		"``` {ocaml}\nlanguage in braces\n```\n",
+		"<pre><code class=\"language-ocaml\">language in braces\n</code></pre>\n",
+
+		"```    {ocaml}      \nwith extra whitespace\n```\n",
+		"<pre><code class=\"language-ocaml\">with extra whitespace\n</code></pre>\n",
+
+		"```{   ocaml   }\nwith extra whitespace\n```\n",
+		"<pre><code class=\"language-ocaml\">with extra whitespace\n</code></pre>\n",
+
+		"~ ~~ java\nWith whitespace\n~~~\n",
+		"<p>~ ~~ java\nWith whitespace\n~~~</p>\n",
+
+		"~~\nonly two\n~~\n",
+		"<p>~~\nonly two\n~~</p>\n",
+
+		"```` python\nextra\n````\n",
+		"<pre><code class=\"language-python\">extra\n</code></pre>\n",
+
+		"~~~ perl\nthree to start, four to end\n~~~~\n",
+		"<p>~~~ perl\nthree to start, four to end\n~~~~</p>\n",
+
+		"~~~~ perl\nfour to start, three to end\n~~~\n",
+		"<p>~~~~ perl\nfour to start, three to end\n~~~</p>\n",
+
+		"~~~ bash\ntildes\n~~~\n",
+		"<pre><code class=\"language-bash\">tildes\n</code></pre>\n",
+
+		"``` lisp\nno ending\n",
+		"<p>``` lisp\nno ending</p>\n",
+
+		"~~~ lisp\nend with language\n~~~ lisp\n",
+		"<p>~~~ lisp\nend with language\n~~~ lisp</p>\n",
+
+		"```\nmismatched begin and end\n~~~\n",
+		"<p>```\nmismatched begin and end\n~~~</p>\n",
+
+		"~~~\nmismatched begin and end\n```\n",
+		"<p>~~~\nmismatched begin and end\n```</p>\n",
+
+		"   ``` oz\nleading spaces\n```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		"  ``` oz\nleading spaces\n ```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		" ``` oz\nleading spaces\n  ```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		"``` oz\nleading spaces\n   ```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		"    ``` oz\nleading spaces\n    ```\n",
+		"<pre><code>``` oz\n</code></pre>\n\n<p>leading spaces\n    ```</p>\n",
+
+		"Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n",
+		"<p>Bla bla</p>\n\n<pre><code class=\"language-oz\">code blocks breakup paragraphs\n</code></pre>\n\n<p>Bla Bla</p>\n",
+
+		"Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nAnd some text after a fenced code block",
+		"<p>Some text before a fenced code block</p>\n\n<pre><code class=\"language-oz\">code blocks breakup paragraphs\n</code></pre>\n\n<p>And some text after a fenced code block</p>\n",
+
+		"`",
+		"<p>`</p>\n",
+
+		"Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n\n``` oz\nmultiple code blocks work okay\n```\n\nBla Bla\n",
+		"<p>Bla bla</p>\n\n<pre><code class=\"language-oz\">code blocks breakup paragraphs\n</code></pre>\n\n<p>Bla Bla</p>\n\n<pre><code class=\"language-oz\">multiple code blocks work okay\n</code></pre>\n\n<p>Bla Bla</p>\n",
+
+		"Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nSome text in between\n``` oz\nmultiple code blocks work okay\n```\nAnd some text after a fenced code block",
+		"<p>Some text before a fenced code block</p>\n\n<pre><code class=\"language-oz\">code blocks breakup paragraphs\n</code></pre>\n\n<p>Some text in between</p>\n\n<pre><code class=\"language-oz\">multiple code blocks work okay\n</code></pre>\n\n<p>And some text after a fenced code block</p>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_FENCED_CODE)
+}
+
+func TestFencedCodeInsideBlockquotes(t *testing.T) {
+	cat := func(s ...string) string { return strings.Join(s, "\n") }
+	var tests = []string{
+		cat("> ```go",
+			"package moo",
+			"",
+			"```",
+			""),
+		`<blockquote>
+<pre><code class="language-go">package moo
+
+</code></pre>
+</blockquote>
+`,
+		// -------------------------------------------
+		cat("> foo",
+			"> ",
+			"> ```go",
+			"package moo",
+			"```",
+			"> ",
+			"> goo.",
+			""),
+		`<blockquote>
+<p>foo</p>
+
+<pre><code class="language-go">package moo
+</code></pre>
+
+<p>goo.</p>
+</blockquote>
+`,
+		// -------------------------------------------
+		cat("> foo",
+			"> ",
+			"> quote",
+			"continues",
+			"```",
+			""),
+		`<blockquote>
+<p>foo</p>
+
+<p>quote
+continues
+` + "```" + `</p>
+</blockquote>
+`,
+		// -------------------------------------------
+		cat("> foo",
+			"> ",
+			"> ```go",
+			"package moo",
+			"```",
+			"> ",
+			"> goo.",
+			"> ",
+			"> ```go",
+			"package zoo",
+			"```",
+			"> ",
+			"> woo.",
+			""),
+		`<blockquote>
+<p>foo</p>
+
+<pre><code class="language-go">package moo
+</code></pre>
+
+<p>goo.</p>
+
+<pre><code class="language-go">package zoo
+</code></pre>
+
+<p>woo.</p>
+</blockquote>
+`,
+	}
+
+	// These 2 alternative forms of blockquoted fenced code blocks should produce same output.
+	forms := [2]string{
+		cat("> plain quoted text",
+			"> ```fenced",
+			"code",
+			" with leading single space correctly preserved",
+			"okay",
+			"```",
+			"> rest of quoted text"),
+		cat("> plain quoted text",
+			"> ```fenced",
+			"> code",
+			">  with leading single space correctly preserved",
+			"> okay",
+			"> ```",
+			"> rest of quoted text"),
+	}
+	want := `<blockquote>
+<p>plain quoted text</p>
+
+<pre><code class="language-fenced">code
+ with leading single space correctly preserved
+okay
+</code></pre>
+
+<p>rest of quoted text</p>
+</blockquote>
+`
+	tests = append(tests, forms[0], want)
+	tests = append(tests, forms[1], want)
+
+	doTestsBlock(t, tests, EXTENSION_FENCED_CODE)
+}
+
+func TestTable(t *testing.T) {
+	var tests = []string{
+		"a | b\n---|---\nc | d\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td>c</td>\n<td>d</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"a | b\n---|--\nc | d\n",
+		"<p>a | b\n---|--\nc | d</p>\n",
+
+		"|a|b|c|d|\n|----|----|----|---|\n|e|f|g|h|\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n<th>c</th>\n<th>d</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td>e</td>\n<td>f</td>\n<td>g</td>\n<td>h</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"*a*|__b__|[c](C)|d\n---|---|---|---\ne|f|g|h\n",
+		"<table>\n<thead>\n<tr>\n<th><em>a</em></th>\n<th><strong>b</strong></th>\n<th><a href=\"C\">c</a></th>\n<th>d</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td>e</td>\n<td>f</td>\n<td>g</td>\n<td>h</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"a|b|c\n---|---|---\nd|e|f\ng|h\ni|j|k|l|m\nn|o|p\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n<th>c</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td>d</td>\n<td>e</td>\n<td>f</td>\n</tr>\n\n" +
+			"<tr>\n<td>g</td>\n<td>h</td>\n<td></td>\n</tr>\n\n" +
+			"<tr>\n<td>i</td>\n<td>j</td>\n<td>k</td>\n</tr>\n\n" +
+			"<tr>\n<td>n</td>\n<td>o</td>\n<td>p</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"a|b|c\n---|---|---\n*d*|__e__|f\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n<th>c</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td><em>d</em></td>\n<td><strong>e</strong></td>\n<td>f</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"a|b|c|d\n:--|--:|:-:|---\ne|f|g|h\n",
+		"<table>\n<thead>\n<tr>\n<th align=\"left\">a</th>\n<th align=\"right\">b</th>\n" +
+			"<th align=\"center\">c</th>\n<th>d</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td align=\"left\">e</td>\n<td align=\"right\">f</td>\n" +
+			"<td align=\"center\">g</td>\n<td>h</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"a|b|c\n---|---|---\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n<th>c</th>\n</tr>\n</thead>\n\n<tbody>\n</tbody>\n</table>\n",
+
+		"a| b|c | d | e\n---|---|---|---|---\nf| g|h | i |j\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n<th>c</th>\n<th>d</th>\n<th>e</th>\n</tr>\n</thead>\n\n" +
+			"<tbody>\n<tr>\n<td>f</td>\n<td>g</td>\n<td>h</td>\n<td>i</td>\n<td>j</td>\n</tr>\n</tbody>\n</table>\n",
+
+		"a|b\\|c|d\n---|---|---\nf|g\\|h|i\n",
+		"<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b|c</th>\n<th>d</th>\n</tr>\n</thead>\n\n<tbody>\n<tr>\n<td>f</td>\n<td>g|h</td>\n<td>i</td>\n</tr>\n</tbody>\n</table>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_TABLES)
+}
+
+func TestUnorderedListWith_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) {
+	var tests = []string{
+		"* Hello\n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"* Yin\n* Yang\n",
+		"<ul>\n<li>Yin</li>\n<li>Yang</li>\n</ul>\n",
+
+		"* Ting\n* Bong\n* Goo\n",
+		"<ul>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ul>\n",
+
+		"* Yin\n\n* Yang\n",
+		"<ul>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ul>\n",
+
+		"* Ting\n\n* Bong\n* Goo\n",
+		"<ul>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ul>\n",
+
+		"+ Hello\n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"+ Yin\n+ Yang\n",
+		"<ul>\n<li>Yin</li>\n<li>Yang</li>\n</ul>\n",
+
+		"+ Ting\n+ Bong\n+ Goo\n",
+		"<ul>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ul>\n",
+
+		"+ Yin\n\n+ Yang\n",
+		"<ul>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ul>\n",
+
+		"+ Ting\n\n+ Bong\n+ Goo\n",
+		"<ul>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ul>\n",
+
+		"- Hello\n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"- Yin\n- Yang\n",
+		"<ul>\n<li>Yin</li>\n<li>Yang</li>\n</ul>\n",
+
+		"- Ting\n- Bong\n- Goo\n",
+		"<ul>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ul>\n",
+
+		"- Yin\n\n- Yang\n",
+		"<ul>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ul>\n",
+
+		"- Ting\n\n- Bong\n- Goo\n",
+		"<ul>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ul>\n",
+
+		"*Hello\n",
+		"<p>*Hello</p>\n",
+
+		"*   Hello \n",
+		"<ul>\n<li>Hello</li>\n</ul>\n",
+
+		"*   Hello \n    Next line \n",
+		"<ul>\n<li>Hello\nNext line</li>\n</ul>\n",
+
+		"Paragraph\n* No linebreak\n",
+		"<p>Paragraph</p>\n\n<ul>\n<li>No linebreak</li>\n</ul>\n",
+
+		"Paragraph\n\n* Linebreak\n",
+		"<p>Paragraph</p>\n\n<ul>\n<li>Linebreak</li>\n</ul>\n",
+
+		"*   List\n    * Nested list\n",
+		"<ul>\n<li>List\n\n<ul>\n<li>Nested list</li>\n</ul></li>\n</ul>\n",
+
+		"*   List\n\n    * Nested list\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li>Nested list</li>\n</ul></li>\n</ul>\n",
+
+		"*   List\n    Second line\n\n    + Nested\n",
+		"<ul>\n<li><p>List\nSecond line</p>\n\n<ul>\n<li>Nested</li>\n</ul></li>\n</ul>\n",
+
+		"*   List\n    + Nested\n\n    Continued\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li>Nested</li>\n</ul>\n\n<p>Continued</p></li>\n</ul>\n",
+
+		"*   List\n   * shallow indent\n",
+		"<ul>\n<li>List\n\n<ul>\n<li>shallow indent</li>\n</ul></li>\n</ul>\n",
+
+		"* List\n" +
+			" * shallow indent\n" +
+			"  * part of second list\n" +
+			"   * still second\n" +
+			"    * almost there\n" +
+			"     * third level\n",
+		"<ul>\n" +
+			"<li>List\n\n" +
+			"<ul>\n" +
+			"<li>shallow indent</li>\n" +
+			"<li>part of second list</li>\n" +
+			"<li>still second</li>\n" +
+			"<li>almost there\n\n" +
+			"<ul>\n" +
+			"<li>third level</li>\n" +
+			"</ul></li>\n" +
+			"</ul></li>\n" +
+			"</ul>\n",
+
+		"* List\n        extra indent, same paragraph\n",
+		"<ul>\n<li>List\n    extra indent, same paragraph</li>\n</ul>\n",
+
+		"* List\n\n        code block\n",
+		"<ul>\n<li><p>List</p>\n\n<pre><code>code block\n</code></pre></li>\n</ul>\n",
+
+		"* List\n\n          code block with spaces\n",
+		"<ul>\n<li><p>List</p>\n\n<pre><code>  code block with spaces\n</code></pre></li>\n</ul>\n",
+
+		"* List\n\n    * sublist\n\n    normal text\n\n    * another sublist\n",
+		"<ul>\n<li><p>List</p>\n\n<ul>\n<li>sublist</li>\n</ul>\n\n<p>normal text</p>\n\n<ul>\n<li>another sublist</li>\n</ul></li>\n</ul>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK)
+}
+
+func TestOrderedList_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) {
+	var tests = []string{
+		"1. Hello\n",
+		"<ol>\n<li>Hello</li>\n</ol>\n",
+
+		"1. Yin\n2. Yang\n",
+		"<ol>\n<li>Yin</li>\n<li>Yang</li>\n</ol>\n",
+
+		"1. Ting\n2. Bong\n3. Goo\n",
+		"<ol>\n<li>Ting</li>\n<li>Bong</li>\n<li>Goo</li>\n</ol>\n",
+
+		"1. Yin\n\n2. Yang\n",
+		"<ol>\n<li><p>Yin</p></li>\n\n<li><p>Yang</p></li>\n</ol>\n",
+
+		"1. Ting\n\n2. Bong\n3. Goo\n",
+		"<ol>\n<li><p>Ting</p></li>\n\n<li><p>Bong</p></li>\n\n<li><p>Goo</p></li>\n</ol>\n",
+
+		"1 Hello\n",
+		"<p>1 Hello</p>\n",
+
+		"1.Hello\n",
+		"<p>1.Hello</p>\n",
+
+		"1.  Hello \n",
+		"<ol>\n<li>Hello</li>\n</ol>\n",
+
+		"1.  Hello \n    Next line \n",
+		"<ol>\n<li>Hello\nNext line</li>\n</ol>\n",
+
+		"Paragraph\n1. No linebreak\n",
+		"<p>Paragraph</p>\n\n<ol>\n<li>No linebreak</li>\n</ol>\n",
+
+		"Paragraph\n\n1. Linebreak\n",
+		"<p>Paragraph</p>\n\n<ol>\n<li>Linebreak</li>\n</ol>\n",
+
+		"1.  List\n    1. Nested list\n",
+		"<ol>\n<li>List\n\n<ol>\n<li>Nested list</li>\n</ol></li>\n</ol>\n",
+
+		"1.  List\n\n    1. Nested list\n",
+		"<ol>\n<li><p>List</p>\n\n<ol>\n<li>Nested list</li>\n</ol></li>\n</ol>\n",
+
+		"1.  List\n    Second line\n\n    1. Nested\n",
+		"<ol>\n<li><p>List\nSecond line</p>\n\n<ol>\n<li>Nested</li>\n</ol></li>\n</ol>\n",
+
+		"1.  List\n    1. Nested\n\n    Continued\n",
+		"<ol>\n<li><p>List</p>\n\n<ol>\n<li>Nested</li>\n</ol>\n\n<p>Continued</p></li>\n</ol>\n",
+
+		"1.  List\n   1. shallow indent\n",
+		"<ol>\n<li>List\n\n<ol>\n<li>shallow indent</li>\n</ol></li>\n</ol>\n",
+
+		"1. List\n" +
+			" 1. shallow indent\n" +
+			"  2. part of second list\n" +
+			"   3. still second\n" +
+			"    4. almost there\n" +
+			"     1. third level\n",
+		"<ol>\n" +
+			"<li>List\n\n" +
+			"<ol>\n" +
+			"<li>shallow indent</li>\n" +
+			"<li>part of second list</li>\n" +
+			"<li>still second</li>\n" +
+			"<li>almost there\n\n" +
+			"<ol>\n" +
+			"<li>third level</li>\n" +
+			"</ol></li>\n" +
+			"</ol></li>\n" +
+			"</ol>\n",
+
+		"1. List\n        extra indent, same paragraph\n",
+		"<ol>\n<li>List\n    extra indent, same paragraph</li>\n</ol>\n",
+
+		"1. List\n\n        code block\n",
+		"<ol>\n<li><p>List</p>\n\n<pre><code>code block\n</code></pre></li>\n</ol>\n",
+
+		"1. List\n\n          code block with spaces\n",
+		"<ol>\n<li><p>List</p>\n\n<pre><code>  code block with spaces\n</code></pre></li>\n</ol>\n",
+
+		"1. List\n    * Mixted list\n",
+		"<ol>\n<li>List\n\n<ul>\n<li>Mixted list</li>\n</ul></li>\n</ol>\n",
+
+		"1. List\n * Mixed list\n",
+		"<ol>\n<li>List\n\n<ul>\n<li>Mixed list</li>\n</ul></li>\n</ol>\n",
+
+		"* Start with unordered\n 1. Ordered\n",
+		"<ul>\n<li>Start with unordered\n\n<ol>\n<li>Ordered</li>\n</ol></li>\n</ul>\n",
+
+		"* Start with unordered\n    1. Ordered\n",
+		"<ul>\n<li>Start with unordered\n\n<ol>\n<li>Ordered</li>\n</ol></li>\n</ul>\n",
+
+		"1. numbers\n1. are ignored\n",
+		"<ol>\n<li>numbers</li>\n<li>are ignored</li>\n</ol>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK)
+}
+
+func TestFencedCodeBlock_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) {
+	var tests = []string{
+		"``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n",
+		"<pre><code class=\"language-go\">func foo() bool {\n\treturn true;\n}\n</code></pre>\n",
+
+		"``` c\n/* special & char < > \" escaping */\n```\n",
+		"<pre><code class=\"language-c\">/* special &amp; char &lt; &gt; &quot; escaping */\n</code></pre>\n",
+
+		"``` c\nno *inline* processing ~~of text~~\n```\n",
+		"<pre><code class=\"language-c\">no *inline* processing ~~of text~~\n</code></pre>\n",
+
+		"```\nNo language\n```\n",
+		"<pre><code>No language\n</code></pre>\n",
+
+		"``` {ocaml}\nlanguage in braces\n```\n",
+		"<pre><code class=\"language-ocaml\">language in braces\n</code></pre>\n",
+
+		"```    {ocaml}      \nwith extra whitespace\n```\n",
+		"<pre><code class=\"language-ocaml\">with extra whitespace\n</code></pre>\n",
+
+		"```{   ocaml   }\nwith extra whitespace\n```\n",
+		"<pre><code class=\"language-ocaml\">with extra whitespace\n</code></pre>\n",
+
+		"~ ~~ java\nWith whitespace\n~~~\n",
+		"<p>~ ~~ java\nWith whitespace\n~~~</p>\n",
+
+		"~~\nonly two\n~~\n",
+		"<p>~~\nonly two\n~~</p>\n",
+
+		"```` python\nextra\n````\n",
+		"<pre><code class=\"language-python\">extra\n</code></pre>\n",
+
+		"~~~ perl\nthree to start, four to end\n~~~~\n",
+		"<p>~~~ perl\nthree to start, four to end\n~~~~</p>\n",
+
+		"~~~~ perl\nfour to start, three to end\n~~~\n",
+		"<p>~~~~ perl\nfour to start, three to end\n~~~</p>\n",
+
+		"~~~ bash\ntildes\n~~~\n",
+		"<pre><code class=\"language-bash\">tildes\n</code></pre>\n",
+
+		"``` lisp\nno ending\n",
+		"<p>``` lisp\nno ending</p>\n",
+
+		"~~~ lisp\nend with language\n~~~ lisp\n",
+		"<p>~~~ lisp\nend with language\n~~~ lisp</p>\n",
+
+		"```\nmismatched begin and end\n~~~\n",
+		"<p>```\nmismatched begin and end\n~~~</p>\n",
+
+		"~~~\nmismatched begin and end\n```\n",
+		"<p>~~~\nmismatched begin and end\n```</p>\n",
+
+		"   ``` oz\nleading spaces\n```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		"  ``` oz\nleading spaces\n ```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		" ``` oz\nleading spaces\n  ```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		"``` oz\nleading spaces\n   ```\n",
+		"<pre><code class=\"language-oz\">leading spaces\n</code></pre>\n",
+
+		"    ``` oz\nleading spaces\n    ```\n",
+		"<pre><code>``` oz\n</code></pre>\n\n<p>leading spaces</p>\n\n<pre><code>```\n</code></pre>\n",
+	}
+	doTestsBlock(t, tests, EXTENSION_FENCED_CODE|EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK)
+}
+
+func TestTitleBlock_EXTENSION_TITLEBLOCK(t *testing.T) {
+	var tests = []string{
+		"% Some title\n" +
+			"% Another title line\n" +
+			"% Yep, more here too\n",
+		"<h1 class=\"title\">" +
+			"Some title\n" +
+			"Another title line\n" +
+			"Yep, more here too\n" +
+			"</h1>",
+	}
+	doTestsBlock(t, tests, EXTENSION_TITLEBLOCK)
+}
+
+func TestBlockComments(t *testing.T) {
+	var tests = []string{
+		"Some text\n\n<!-- comment -->\n",
+		"<p>Some text</p>\n\n<!-- comment -->\n",
+
+		"Some text\n\n<!--\n\nmultiline\ncomment\n-->\n",
+		"<p>Some text</p>\n\n<!--\n\nmultiline\ncomment\n-->\n",
+
+		"Some text\n\n<!--\n\n<div><p>Commented</p>\n<span>html</span></div>\n-->\n",
+		"<p>Some text</p>\n\n<!--\n\n<div><p>Commented</p>\n<span>html</span></div>\n-->\n",
+	}
+	doTestsBlock(t, tests, 0)
+}

+ 949 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/html.go

@@ -0,0 +1,949 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+//
+// HTML rendering backend
+//
+//
+
+package blackfriday
+
+import (
+	"bytes"
+	"fmt"
+	"regexp"
+	"strconv"
+	"strings"
+)
+
+// Html renderer configuration options.
+const (
+	HTML_SKIP_HTML                 = 1 << iota // skip preformatted HTML blocks
+	HTML_SKIP_STYLE                            // skip embedded <style> elements
+	HTML_SKIP_IMAGES                           // skip embedded images
+	HTML_SKIP_LINKS                            // skip all links
+	HTML_SAFELINK                              // only link to trusted protocols
+	HTML_NOFOLLOW_LINKS                        // only link with rel="nofollow"
+	HTML_NOREFERRER_LINKS                      // only link with rel="noreferrer"
+	HTML_HREF_TARGET_BLANK                     // add a blank target
+	HTML_TOC                                   // generate a table of contents
+	HTML_OMIT_CONTENTS                         // skip the main contents (for a standalone table of contents)
+	HTML_COMPLETE_PAGE                         // generate a complete HTML page
+	HTML_USE_XHTML                             // generate XHTML output instead of HTML
+	HTML_USE_SMARTYPANTS                       // enable smart punctuation substitutions
+	HTML_SMARTYPANTS_FRACTIONS                 // enable smart fractions (with HTML_USE_SMARTYPANTS)
+	HTML_SMARTYPANTS_DASHES                    // enable smart dashes (with HTML_USE_SMARTYPANTS)
+	HTML_SMARTYPANTS_LATEX_DASHES              // enable LaTeX-style dashes (with HTML_USE_SMARTYPANTS and HTML_SMARTYPANTS_DASHES)
+	HTML_SMARTYPANTS_ANGLED_QUOTES             // enable angled double quotes (with HTML_USE_SMARTYPANTS) for double quotes rendering
+	HTML_FOOTNOTE_RETURN_LINKS                 // generate a link at the end of a footnote to return to the source
+)
+
+var (
+	alignments = []string{
+		"left",
+		"right",
+		"center",
+	}
+
+	// TODO: improve this regexp to catch all possible entities:
+	htmlEntity = regexp.MustCompile(`&[a-z]{2,5};`)
+)
+
+type HtmlRendererParameters struct {
+	// Prepend this text to each relative URL.
+	AbsolutePrefix string
+	// Add this text to each footnote anchor, to ensure uniqueness.
+	FootnoteAnchorPrefix string
+	// Show this text inside the <a> tag for a footnote return link, if the
+	// HTML_FOOTNOTE_RETURN_LINKS flag is enabled. If blank, the string
+	// <sup>[return]</sup> is used.
+	FootnoteReturnLinkContents string
+	// If set, add this text to the front of each Header ID, to ensure
+	// uniqueness.
+	HeaderIDPrefix string
+	// If set, add this text to the back of each Header ID, to ensure uniqueness.
+	HeaderIDSuffix string
+}
+
+// Html is a type that implements the Renderer interface for HTML output.
+//
+// Do not create this directly, instead use the HtmlRenderer function.
+type Html struct {
+	flags    int    // HTML_* options
+	closeTag string // how to end singleton tags: either " />" or ">"
+	title    string // document title
+	css      string // optional css file url (used with HTML_COMPLETE_PAGE)
+
+	parameters HtmlRendererParameters
+
+	// table of contents data
+	tocMarker    int
+	headerCount  int
+	currentLevel int
+	toc          *bytes.Buffer
+
+	// Track header IDs to prevent ID collision in a single generation.
+	headerIDs map[string]int
+
+	smartypants *smartypantsRenderer
+}
+
+const (
+	xhtmlClose = " />"
+	htmlClose  = ">"
+)
+
+// HtmlRenderer creates and configures an Html object, which
+// satisfies the Renderer interface.
+//
+// flags is a set of HTML_* options ORed together.
+// title is the title of the document, and css is a URL for the document's
+// stylesheet.
+// title and css are only used when HTML_COMPLETE_PAGE is selected.
+func HtmlRenderer(flags int, title string, css string) Renderer {
+	return HtmlRendererWithParameters(flags, title, css, HtmlRendererParameters{})
+}
+
+func HtmlRendererWithParameters(flags int, title string,
+	css string, renderParameters HtmlRendererParameters) Renderer {
+	// configure the rendering engine
+	closeTag := htmlClose
+	if flags&HTML_USE_XHTML != 0 {
+		closeTag = xhtmlClose
+	}
+
+	if renderParameters.FootnoteReturnLinkContents == "" {
+		renderParameters.FootnoteReturnLinkContents = `<sup>[return]</sup>`
+	}
+
+	return &Html{
+		flags:      flags,
+		closeTag:   closeTag,
+		title:      title,
+		css:        css,
+		parameters: renderParameters,
+
+		headerCount:  0,
+		currentLevel: 0,
+		toc:          new(bytes.Buffer),
+
+		headerIDs: make(map[string]int),
+
+		smartypants: smartypants(flags),
+	}
+}
+
+// Using if statements is a bit faster than a switch statement. As the compiler
+// improves, this should be unnecessary this is only worthwhile because
+// attrEscape is the single largest CPU user in normal use.
+// Also tried using map, but that gave a ~3x slowdown.
+func escapeSingleChar(char byte) (string, bool) {
+	if char == '"' {
+		return "&quot;", true
+	}
+	if char == '&' {
+		return "&amp;", true
+	}
+	if char == '<' {
+		return "&lt;", true
+	}
+	if char == '>' {
+		return "&gt;", true
+	}
+	return "", false
+}
+
+func attrEscape(out *bytes.Buffer, src []byte) {
+	org := 0
+	for i, ch := range src {
+		if entity, ok := escapeSingleChar(ch); ok {
+			if i > org {
+				// copy all the normal characters since the last escape
+				out.Write(src[org:i])
+			}
+			org = i + 1
+			out.WriteString(entity)
+		}
+	}
+	if org < len(src) {
+		out.Write(src[org:])
+	}
+}
+
+func entityEscapeWithSkip(out *bytes.Buffer, src []byte, skipRanges [][]int) {
+	end := 0
+	for _, rang := range skipRanges {
+		attrEscape(out, src[end:rang[0]])
+		out.Write(src[rang[0]:rang[1]])
+		end = rang[1]
+	}
+	attrEscape(out, src[end:])
+}
+
+func (options *Html) GetFlags() int {
+	return options.flags
+}
+
+func (options *Html) TitleBlock(out *bytes.Buffer, text []byte) {
+	text = bytes.TrimPrefix(text, []byte("% "))
+	text = bytes.Replace(text, []byte("\n% "), []byte("\n"), -1)
+	out.WriteString("<h1 class=\"title\">")
+	out.Write(text)
+	out.WriteString("\n</h1>")
+}
+
+func (options *Html) Header(out *bytes.Buffer, text func() bool, level int, id string) {
+	marker := out.Len()
+	doubleSpace(out)
+
+	if id == "" && options.flags&HTML_TOC != 0 {
+		id = fmt.Sprintf("toc_%d", options.headerCount)
+	}
+
+	if id != "" {
+		id = options.ensureUniqueHeaderID(id)
+
+		if options.parameters.HeaderIDPrefix != "" {
+			id = options.parameters.HeaderIDPrefix + id
+		}
+
+		if options.parameters.HeaderIDSuffix != "" {
+			id = id + options.parameters.HeaderIDSuffix
+		}
+
+		out.WriteString(fmt.Sprintf("<h%d id=\"%s\">", level, id))
+	} else {
+		out.WriteString(fmt.Sprintf("<h%d>", level))
+	}
+
+	tocMarker := out.Len()
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+
+	// are we building a table of contents?
+	if options.flags&HTML_TOC != 0 {
+		options.TocHeaderWithAnchor(out.Bytes()[tocMarker:], level, id)
+	}
+
+	out.WriteString(fmt.Sprintf("</h%d>\n", level))
+}
+
+func (options *Html) BlockHtml(out *bytes.Buffer, text []byte) {
+	if options.flags&HTML_SKIP_HTML != 0 {
+		return
+	}
+
+	doubleSpace(out)
+	out.Write(text)
+	out.WriteByte('\n')
+}
+
+func (options *Html) HRule(out *bytes.Buffer) {
+	doubleSpace(out)
+	out.WriteString("<hr")
+	out.WriteString(options.closeTag)
+	out.WriteByte('\n')
+}
+
+func (options *Html) BlockCode(out *bytes.Buffer, text []byte, lang string) {
+	doubleSpace(out)
+
+	// parse out the language names/classes
+	count := 0
+	for _, elt := range strings.Fields(lang) {
+		if elt[0] == '.' {
+			elt = elt[1:]
+		}
+		if len(elt) == 0 {
+			continue
+		}
+		if count == 0 {
+			out.WriteString("<pre><code class=\"language-")
+		} else {
+			out.WriteByte(' ')
+		}
+		attrEscape(out, []byte(elt))
+		count++
+	}
+
+	if count == 0 {
+		out.WriteString("<pre><code>")
+	} else {
+		out.WriteString("\">")
+	}
+
+	attrEscape(out, text)
+	out.WriteString("</code></pre>\n")
+}
+
+func (options *Html) BlockQuote(out *bytes.Buffer, text []byte) {
+	doubleSpace(out)
+	out.WriteString("<blockquote>\n")
+	out.Write(text)
+	out.WriteString("</blockquote>\n")
+}
+
+func (options *Html) Table(out *bytes.Buffer, header []byte, body []byte, columnData []int) {
+	doubleSpace(out)
+	out.WriteString("<table>\n<thead>\n")
+	out.Write(header)
+	out.WriteString("</thead>\n\n<tbody>\n")
+	out.Write(body)
+	out.WriteString("</tbody>\n</table>\n")
+}
+
+func (options *Html) TableRow(out *bytes.Buffer, text []byte) {
+	doubleSpace(out)
+	out.WriteString("<tr>\n")
+	out.Write(text)
+	out.WriteString("\n</tr>\n")
+}
+
+func (options *Html) TableHeaderCell(out *bytes.Buffer, text []byte, align int) {
+	doubleSpace(out)
+	switch align {
+	case TABLE_ALIGNMENT_LEFT:
+		out.WriteString("<th align=\"left\">")
+	case TABLE_ALIGNMENT_RIGHT:
+		out.WriteString("<th align=\"right\">")
+	case TABLE_ALIGNMENT_CENTER:
+		out.WriteString("<th align=\"center\">")
+	default:
+		out.WriteString("<th>")
+	}
+
+	out.Write(text)
+	out.WriteString("</th>")
+}
+
+func (options *Html) TableCell(out *bytes.Buffer, text []byte, align int) {
+	doubleSpace(out)
+	switch align {
+	case TABLE_ALIGNMENT_LEFT:
+		out.WriteString("<td align=\"left\">")
+	case TABLE_ALIGNMENT_RIGHT:
+		out.WriteString("<td align=\"right\">")
+	case TABLE_ALIGNMENT_CENTER:
+		out.WriteString("<td align=\"center\">")
+	default:
+		out.WriteString("<td>")
+	}
+
+	out.Write(text)
+	out.WriteString("</td>")
+}
+
+func (options *Html) Footnotes(out *bytes.Buffer, text func() bool) {
+	out.WriteString("<div class=\"footnotes\">\n")
+	options.HRule(out)
+	options.List(out, text, LIST_TYPE_ORDERED)
+	out.WriteString("</div>\n")
+}
+
+func (options *Html) FootnoteItem(out *bytes.Buffer, name, text []byte, flags int) {
+	if flags&LIST_ITEM_CONTAINS_BLOCK != 0 || flags&LIST_ITEM_BEGINNING_OF_LIST != 0 {
+		doubleSpace(out)
+	}
+	slug := slugify(name)
+	out.WriteString(`<li id="`)
+	out.WriteString(`fn:`)
+	out.WriteString(options.parameters.FootnoteAnchorPrefix)
+	out.Write(slug)
+	out.WriteString(`">`)
+	out.Write(text)
+	if options.flags&HTML_FOOTNOTE_RETURN_LINKS != 0 {
+		out.WriteString(` <a class="footnote-return" href="#`)
+		out.WriteString(`fnref:`)
+		out.WriteString(options.parameters.FootnoteAnchorPrefix)
+		out.Write(slug)
+		out.WriteString(`">`)
+		out.WriteString(options.parameters.FootnoteReturnLinkContents)
+		out.WriteString(`</a>`)
+	}
+	out.WriteString("</li>\n")
+}
+
+func (options *Html) List(out *bytes.Buffer, text func() bool, flags int) {
+	marker := out.Len()
+	doubleSpace(out)
+
+	if flags&LIST_TYPE_DEFINITION != 0 {
+		out.WriteString("<dl>")
+	} else if flags&LIST_TYPE_ORDERED != 0 {
+		out.WriteString("<ol>")
+	} else {
+		out.WriteString("<ul>")
+	}
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+	if flags&LIST_TYPE_DEFINITION != 0 {
+		out.WriteString("</dl>\n")
+	} else if flags&LIST_TYPE_ORDERED != 0 {
+		out.WriteString("</ol>\n")
+	} else {
+		out.WriteString("</ul>\n")
+	}
+}
+
+func (options *Html) ListItem(out *bytes.Buffer, text []byte, flags int) {
+	if (flags&LIST_ITEM_CONTAINS_BLOCK != 0 && flags&LIST_TYPE_DEFINITION == 0) ||
+		flags&LIST_ITEM_BEGINNING_OF_LIST != 0 {
+		doubleSpace(out)
+	}
+	if flags&LIST_TYPE_TERM != 0 {
+		out.WriteString("<dt>")
+	} else if flags&LIST_TYPE_DEFINITION != 0 {
+		out.WriteString("<dd>")
+	} else {
+		out.WriteString("<li>")
+	}
+	out.Write(text)
+	if flags&LIST_TYPE_TERM != 0 {
+		out.WriteString("</dt>\n")
+	} else if flags&LIST_TYPE_DEFINITION != 0 {
+		out.WriteString("</dd>\n")
+	} else {
+		out.WriteString("</li>\n")
+	}
+}
+
+func (options *Html) Paragraph(out *bytes.Buffer, text func() bool) {
+	marker := out.Len()
+	doubleSpace(out)
+
+	out.WriteString("<p>")
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+	out.WriteString("</p>\n")
+}
+
+func (options *Html) AutoLink(out *bytes.Buffer, link []byte, kind int) {
+	skipRanges := htmlEntity.FindAllIndex(link, -1)
+	if options.flags&HTML_SAFELINK != 0 && !isSafeLink(link) && kind != LINK_TYPE_EMAIL {
+		// mark it but don't link it if it is not a safe link: no smartypants
+		out.WriteString("<tt>")
+		entityEscapeWithSkip(out, link, skipRanges)
+		out.WriteString("</tt>")
+		return
+	}
+
+	out.WriteString("<a href=\"")
+	if kind == LINK_TYPE_EMAIL {
+		out.WriteString("mailto:")
+	} else {
+		options.maybeWriteAbsolutePrefix(out, link)
+	}
+
+	entityEscapeWithSkip(out, link, skipRanges)
+
+	var relAttrs []string
+	if options.flags&HTML_NOFOLLOW_LINKS != 0 && !isRelativeLink(link) {
+		relAttrs = append(relAttrs, "nofollow")
+	}
+	if options.flags&HTML_NOREFERRER_LINKS != 0 && !isRelativeLink(link) {
+		relAttrs = append(relAttrs, "noreferrer")
+	}
+	if len(relAttrs) > 0 {
+		out.WriteString(fmt.Sprintf("\" rel=\"%s", strings.Join(relAttrs, " ")))
+	}
+
+	// blank target only add to external link
+	if options.flags&HTML_HREF_TARGET_BLANK != 0 && !isRelativeLink(link) {
+		out.WriteString("\" target=\"_blank")
+	}
+
+	out.WriteString("\">")
+
+	// Pretty print: if we get an email address as
+	// an actual URI, e.g. `mailto:foo@bar.com`, we don't
+	// want to print the `mailto:` prefix
+	switch {
+	case bytes.HasPrefix(link, []byte("mailto://")):
+		attrEscape(out, link[len("mailto://"):])
+	case bytes.HasPrefix(link, []byte("mailto:")):
+		attrEscape(out, link[len("mailto:"):])
+	default:
+		entityEscapeWithSkip(out, link, skipRanges)
+	}
+
+	out.WriteString("</a>")
+}
+
+func (options *Html) CodeSpan(out *bytes.Buffer, text []byte) {
+	out.WriteString("<code>")
+	attrEscape(out, text)
+	out.WriteString("</code>")
+}
+
+func (options *Html) DoubleEmphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("<strong>")
+	out.Write(text)
+	out.WriteString("</strong>")
+}
+
+func (options *Html) Emphasis(out *bytes.Buffer, text []byte) {
+	if len(text) == 0 {
+		return
+	}
+	out.WriteString("<em>")
+	out.Write(text)
+	out.WriteString("</em>")
+}
+
+func (options *Html) maybeWriteAbsolutePrefix(out *bytes.Buffer, link []byte) {
+	if options.parameters.AbsolutePrefix != "" && isRelativeLink(link) && link[0] != '.' {
+		out.WriteString(options.parameters.AbsolutePrefix)
+		if link[0] != '/' {
+			out.WriteByte('/')
+		}
+	}
+}
+
+func (options *Html) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
+	if options.flags&HTML_SKIP_IMAGES != 0 {
+		return
+	}
+
+	out.WriteString("<img src=\"")
+	options.maybeWriteAbsolutePrefix(out, link)
+	attrEscape(out, link)
+	out.WriteString("\" alt=\"")
+	if len(alt) > 0 {
+		attrEscape(out, alt)
+	}
+	if len(title) > 0 {
+		out.WriteString("\" title=\"")
+		attrEscape(out, title)
+	}
+
+	out.WriteByte('"')
+	out.WriteString(options.closeTag)
+}
+
+func (options *Html) LineBreak(out *bytes.Buffer) {
+	out.WriteString("<br")
+	out.WriteString(options.closeTag)
+	out.WriteByte('\n')
+}
+
+func (options *Html) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
+	if options.flags&HTML_SKIP_LINKS != 0 {
+		// write the link text out but don't link it, just mark it with typewriter font
+		out.WriteString("<tt>")
+		attrEscape(out, content)
+		out.WriteString("</tt>")
+		return
+	}
+
+	if options.flags&HTML_SAFELINK != 0 && !isSafeLink(link) {
+		// write the link text out but don't link it, just mark it with typewriter font
+		out.WriteString("<tt>")
+		attrEscape(out, content)
+		out.WriteString("</tt>")
+		return
+	}
+
+	out.WriteString("<a href=\"")
+	options.maybeWriteAbsolutePrefix(out, link)
+	attrEscape(out, link)
+	if len(title) > 0 {
+		out.WriteString("\" title=\"")
+		attrEscape(out, title)
+	}
+	var relAttrs []string
+	if options.flags&HTML_NOFOLLOW_LINKS != 0 && !isRelativeLink(link) {
+		relAttrs = append(relAttrs, "nofollow")
+	}
+	if options.flags&HTML_NOREFERRER_LINKS != 0 && !isRelativeLink(link) {
+		relAttrs = append(relAttrs, "noreferrer")
+	}
+	if len(relAttrs) > 0 {
+		out.WriteString(fmt.Sprintf("\" rel=\"%s", strings.Join(relAttrs, " ")))
+	}
+
+	// blank target only add to external link
+	if options.flags&HTML_HREF_TARGET_BLANK != 0 && !isRelativeLink(link) {
+		out.WriteString("\" target=\"_blank")
+	}
+
+	out.WriteString("\">")
+	out.Write(content)
+	out.WriteString("</a>")
+	return
+}
+
+func (options *Html) RawHtmlTag(out *bytes.Buffer, text []byte) {
+	if options.flags&HTML_SKIP_HTML != 0 {
+		return
+	}
+	if options.flags&HTML_SKIP_STYLE != 0 && isHtmlTag(text, "style") {
+		return
+	}
+	if options.flags&HTML_SKIP_LINKS != 0 && isHtmlTag(text, "a") {
+		return
+	}
+	if options.flags&HTML_SKIP_IMAGES != 0 && isHtmlTag(text, "img") {
+		return
+	}
+	out.Write(text)
+}
+
+func (options *Html) TripleEmphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("<strong><em>")
+	out.Write(text)
+	out.WriteString("</em></strong>")
+}
+
+func (options *Html) StrikeThrough(out *bytes.Buffer, text []byte) {
+	out.WriteString("<del>")
+	out.Write(text)
+	out.WriteString("</del>")
+}
+
+func (options *Html) FootnoteRef(out *bytes.Buffer, ref []byte, id int) {
+	slug := slugify(ref)
+	out.WriteString(`<sup class="footnote-ref" id="`)
+	out.WriteString(`fnref:`)
+	out.WriteString(options.parameters.FootnoteAnchorPrefix)
+	out.Write(slug)
+	out.WriteString(`"><a rel="footnote" href="#`)
+	out.WriteString(`fn:`)
+	out.WriteString(options.parameters.FootnoteAnchorPrefix)
+	out.Write(slug)
+	out.WriteString(`">`)
+	out.WriteString(strconv.Itoa(id))
+	out.WriteString(`</a></sup>`)
+}
+
+func (options *Html) Entity(out *bytes.Buffer, entity []byte) {
+	out.Write(entity)
+}
+
+func (options *Html) NormalText(out *bytes.Buffer, text []byte) {
+	if options.flags&HTML_USE_SMARTYPANTS != 0 {
+		options.Smartypants(out, text)
+	} else {
+		attrEscape(out, text)
+	}
+}
+
+func (options *Html) Smartypants(out *bytes.Buffer, text []byte) {
+	smrt := smartypantsData{false, false}
+
+	// first do normal entity escaping
+	var escaped bytes.Buffer
+	attrEscape(&escaped, text)
+	text = escaped.Bytes()
+
+	mark := 0
+	for i := 0; i < len(text); i++ {
+		if action := options.smartypants[text[i]]; action != nil {
+			if i > mark {
+				out.Write(text[mark:i])
+			}
+
+			previousChar := byte(0)
+			if i > 0 {
+				previousChar = text[i-1]
+			}
+			i += action(out, &smrt, previousChar, text[i:])
+			mark = i + 1
+		}
+	}
+
+	if mark < len(text) {
+		out.Write(text[mark:])
+	}
+}
+
+func (options *Html) DocumentHeader(out *bytes.Buffer) {
+	if options.flags&HTML_COMPLETE_PAGE == 0 {
+		return
+	}
+
+	ending := ""
+	if options.flags&HTML_USE_XHTML != 0 {
+		out.WriteString("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" ")
+		out.WriteString("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n")
+		out.WriteString("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n")
+		ending = " /"
+	} else {
+		out.WriteString("<!DOCTYPE html>\n")
+		out.WriteString("<html>\n")
+	}
+	out.WriteString("<head>\n")
+	out.WriteString("  <title>")
+	options.NormalText(out, []byte(options.title))
+	out.WriteString("</title>\n")
+	out.WriteString("  <meta name=\"GENERATOR\" content=\"Blackfriday Markdown Processor v")
+	out.WriteString(VERSION)
+	out.WriteString("\"")
+	out.WriteString(ending)
+	out.WriteString(">\n")
+	out.WriteString("  <meta charset=\"utf-8\"")
+	out.WriteString(ending)
+	out.WriteString(">\n")
+	if options.css != "" {
+		out.WriteString("  <link rel=\"stylesheet\" type=\"text/css\" href=\"")
+		attrEscape(out, []byte(options.css))
+		out.WriteString("\"")
+		out.WriteString(ending)
+		out.WriteString(">\n")
+	}
+	out.WriteString("</head>\n")
+	out.WriteString("<body>\n")
+
+	options.tocMarker = out.Len()
+}
+
+func (options *Html) DocumentFooter(out *bytes.Buffer) {
+	// finalize and insert the table of contents
+	if options.flags&HTML_TOC != 0 {
+		options.TocFinalize()
+
+		// now we have to insert the table of contents into the document
+		var temp bytes.Buffer
+
+		// start by making a copy of everything after the document header
+		temp.Write(out.Bytes()[options.tocMarker:])
+
+		// now clear the copied material from the main output buffer
+		out.Truncate(options.tocMarker)
+
+		// corner case spacing issue
+		if options.flags&HTML_COMPLETE_PAGE != 0 {
+			out.WriteByte('\n')
+		}
+
+		// insert the table of contents
+		out.WriteString("<nav>\n")
+		out.Write(options.toc.Bytes())
+		out.WriteString("</nav>\n")
+
+		// corner case spacing issue
+		if options.flags&HTML_COMPLETE_PAGE == 0 && options.flags&HTML_OMIT_CONTENTS == 0 {
+			out.WriteByte('\n')
+		}
+
+		// write out everything that came after it
+		if options.flags&HTML_OMIT_CONTENTS == 0 {
+			out.Write(temp.Bytes())
+		}
+	}
+
+	if options.flags&HTML_COMPLETE_PAGE != 0 {
+		out.WriteString("\n</body>\n")
+		out.WriteString("</html>\n")
+	}
+
+}
+
+func (options *Html) TocHeaderWithAnchor(text []byte, level int, anchor string) {
+	for level > options.currentLevel {
+		switch {
+		case bytes.HasSuffix(options.toc.Bytes(), []byte("</li>\n")):
+			// this sublist can nest underneath a header
+			size := options.toc.Len()
+			options.toc.Truncate(size - len("</li>\n"))
+
+		case options.currentLevel > 0:
+			options.toc.WriteString("<li>")
+		}
+		if options.toc.Len() > 0 {
+			options.toc.WriteByte('\n')
+		}
+		options.toc.WriteString("<ul>\n")
+		options.currentLevel++
+	}
+
+	for level < options.currentLevel {
+		options.toc.WriteString("</ul>")
+		if options.currentLevel > 1 {
+			options.toc.WriteString("</li>\n")
+		}
+		options.currentLevel--
+	}
+
+	options.toc.WriteString("<li><a href=\"#")
+	if anchor != "" {
+		options.toc.WriteString(anchor)
+	} else {
+		options.toc.WriteString("toc_")
+		options.toc.WriteString(strconv.Itoa(options.headerCount))
+	}
+	options.toc.WriteString("\">")
+	options.headerCount++
+
+	options.toc.Write(text)
+
+	options.toc.WriteString("</a></li>\n")
+}
+
+func (options *Html) TocHeader(text []byte, level int) {
+	options.TocHeaderWithAnchor(text, level, "")
+}
+
+func (options *Html) TocFinalize() {
+	for options.currentLevel > 1 {
+		options.toc.WriteString("</ul></li>\n")
+		options.currentLevel--
+	}
+
+	if options.currentLevel > 0 {
+		options.toc.WriteString("</ul>\n")
+	}
+}
+
+func isHtmlTag(tag []byte, tagname string) bool {
+	found, _ := findHtmlTagPos(tag, tagname)
+	return found
+}
+
+// Look for a character, but ignore it when it's in any kind of quotes, it
+// might be JavaScript
+func skipUntilCharIgnoreQuotes(html []byte, start int, char byte) int {
+	inSingleQuote := false
+	inDoubleQuote := false
+	inGraveQuote := false
+	i := start
+	for i < len(html) {
+		switch {
+		case html[i] == char && !inSingleQuote && !inDoubleQuote && !inGraveQuote:
+			return i
+		case html[i] == '\'':
+			inSingleQuote = !inSingleQuote
+		case html[i] == '"':
+			inDoubleQuote = !inDoubleQuote
+		case html[i] == '`':
+			inGraveQuote = !inGraveQuote
+		}
+		i++
+	}
+	return start
+}
+
+func findHtmlTagPos(tag []byte, tagname string) (bool, int) {
+	i := 0
+	if i < len(tag) && tag[0] != '<' {
+		return false, -1
+	}
+	i++
+	i = skipSpace(tag, i)
+
+	if i < len(tag) && tag[i] == '/' {
+		i++
+	}
+
+	i = skipSpace(tag, i)
+	j := 0
+	for ; i < len(tag); i, j = i+1, j+1 {
+		if j >= len(tagname) {
+			break
+		}
+
+		if strings.ToLower(string(tag[i]))[0] != tagname[j] {
+			return false, -1
+		}
+	}
+
+	if i == len(tag) {
+		return false, -1
+	}
+
+	rightAngle := skipUntilCharIgnoreQuotes(tag, i, '>')
+	if rightAngle > i {
+		return true, rightAngle
+	}
+
+	return false, -1
+}
+
+func skipUntilChar(text []byte, start int, char byte) int {
+	i := start
+	for i < len(text) && text[i] != char {
+		i++
+	}
+	return i
+}
+
+func skipSpace(tag []byte, i int) int {
+	for i < len(tag) && isspace(tag[i]) {
+		i++
+	}
+	return i
+}
+
+func skipChar(data []byte, start int, char byte) int {
+	i := start
+	for i < len(data) && data[i] == char {
+		i++
+	}
+	return i
+}
+
+func doubleSpace(out *bytes.Buffer) {
+	if out.Len() > 0 {
+		out.WriteByte('\n')
+	}
+}
+
+func isRelativeLink(link []byte) (yes bool) {
+	// a tag begin with '#'
+	if link[0] == '#' {
+		return true
+	}
+
+	// link begin with '/' but not '//', the second maybe a protocol relative link
+	if len(link) >= 2 && link[0] == '/' && link[1] != '/' {
+		return true
+	}
+
+	// only the root '/'
+	if len(link) == 1 && link[0] == '/' {
+		return true
+	}
+
+	// current directory : begin with "./"
+	if bytes.HasPrefix(link, []byte("./")) {
+		return true
+	}
+
+	// parent directory : begin with "../"
+	if bytes.HasPrefix(link, []byte("../")) {
+		return true
+	}
+
+	return false
+}
+
+func (options *Html) ensureUniqueHeaderID(id string) string {
+	for count, found := options.headerIDs[id]; found; count, found = options.headerIDs[id] {
+		tmp := fmt.Sprintf("%s-%d", id, count+1)
+
+		if _, tmpFound := options.headerIDs[tmp]; !tmpFound {
+			options.headerIDs[id] = count + 1
+			id = tmp
+		} else {
+			id = id + "-1"
+		}
+	}
+
+	if _, found := options.headerIDs[id]; !found {
+		options.headerIDs[id] = 0
+	}
+
+	return id
+}

+ 1133 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/inline.go

@@ -0,0 +1,1133 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+// Functions to parse inline elements.
+//
+
+package blackfriday
+
+import (
+	"bytes"
+	"regexp"
+	"strconv"
+)
+
+var (
+	urlRe    = `((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+`
+	anchorRe = regexp.MustCompile(`^(<a\shref="` + urlRe + `"(\stitle="[^"<>]+")?\s?>` + urlRe + `<\/a>)`)
+)
+
+// Functions to parse text within a block
+// Each function returns the number of chars taken care of
+// data is the complete block being rendered
+// offset is the number of valid chars before the current cursor
+
+func (p *parser) inline(out *bytes.Buffer, data []byte) {
+	// this is called recursively: enforce a maximum depth
+	if p.nesting >= p.maxNesting {
+		return
+	}
+	p.nesting++
+
+	i, end := 0, 0
+	for i < len(data) {
+		// copy inactive chars into the output
+		for end < len(data) && p.inlineCallback[data[end]] == nil {
+			end++
+		}
+
+		p.r.NormalText(out, data[i:end])
+
+		if end >= len(data) {
+			break
+		}
+		i = end
+
+		// call the trigger
+		handler := p.inlineCallback[data[end]]
+		if consumed := handler(p, out, data, i); consumed == 0 {
+			// no action from the callback; buffer the byte for later
+			end = i + 1
+		} else {
+			// skip past whatever the callback used
+			i += consumed
+			end = i
+		}
+	}
+
+	p.nesting--
+}
+
+// single and double emphasis parsing
+func emphasis(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	data = data[offset:]
+	c := data[0]
+	ret := 0
+
+	if len(data) > 2 && data[1] != c {
+		// whitespace cannot follow an opening emphasis;
+		// strikethrough only takes two characters '~~'
+		if c == '~' || isspace(data[1]) {
+			return 0
+		}
+		if ret = helperEmphasis(p, out, data[1:], c); ret == 0 {
+			return 0
+		}
+
+		return ret + 1
+	}
+
+	if len(data) > 3 && data[1] == c && data[2] != c {
+		if isspace(data[2]) {
+			return 0
+		}
+		if ret = helperDoubleEmphasis(p, out, data[2:], c); ret == 0 {
+			return 0
+		}
+
+		return ret + 2
+	}
+
+	if len(data) > 4 && data[1] == c && data[2] == c && data[3] != c {
+		if c == '~' || isspace(data[3]) {
+			return 0
+		}
+		if ret = helperTripleEmphasis(p, out, data, 3, c); ret == 0 {
+			return 0
+		}
+
+		return ret + 3
+	}
+
+	return 0
+}
+
+func codeSpan(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	data = data[offset:]
+
+	nb := 0
+
+	// count the number of backticks in the delimiter
+	for nb < len(data) && data[nb] == '`' {
+		nb++
+	}
+
+	// find the next delimiter
+	i, end := 0, 0
+	for end = nb; end < len(data) && i < nb; end++ {
+		if data[end] == '`' {
+			i++
+		} else {
+			i = 0
+		}
+	}
+
+	// no matching delimiter?
+	if i < nb && end >= len(data) {
+		return 0
+	}
+
+	// trim outside whitespace
+	fBegin := nb
+	for fBegin < end && data[fBegin] == ' ' {
+		fBegin++
+	}
+
+	fEnd := end - nb
+	for fEnd > fBegin && data[fEnd-1] == ' ' {
+		fEnd--
+	}
+
+	// render the code span
+	if fBegin != fEnd {
+		p.r.CodeSpan(out, data[fBegin:fEnd])
+	}
+
+	return end
+
+}
+
+// newline preceded by two spaces becomes <br>
+// newline without two spaces works when EXTENSION_HARD_LINE_BREAK is enabled
+func lineBreak(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	// remove trailing spaces from out
+	outBytes := out.Bytes()
+	end := len(outBytes)
+	eol := end
+	for eol > 0 && outBytes[eol-1] == ' ' {
+		eol--
+	}
+	out.Truncate(eol)
+
+	precededByTwoSpaces := offset >= 2 && data[offset-2] == ' ' && data[offset-1] == ' '
+	precededByBackslash := offset >= 1 && data[offset-1] == '\\' // see http://spec.commonmark.org/0.18/#example-527
+	precededByBackslash = precededByBackslash && p.flags&EXTENSION_BACKSLASH_LINE_BREAK != 0
+
+	// should there be a hard line break here?
+	if p.flags&EXTENSION_HARD_LINE_BREAK == 0 && !precededByTwoSpaces && !precededByBackslash {
+		return 0
+	}
+
+	if precededByBackslash && eol > 0 {
+		out.Truncate(eol - 1)
+	}
+	p.r.LineBreak(out)
+	return 1
+}
+
+type linkType int
+
+const (
+	linkNormal linkType = iota
+	linkImg
+	linkDeferredFootnote
+	linkInlineFootnote
+)
+
+func isReferenceStyleLink(data []byte, pos int, t linkType) bool {
+	if t == linkDeferredFootnote {
+		return false
+	}
+	return pos < len(data)-1 && data[pos] == '[' && data[pos+1] != '^'
+}
+
+// '[': parse a link or an image or a footnote
+func link(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	// no links allowed inside regular links, footnote, and deferred footnotes
+	if p.insideLink && (offset > 0 && data[offset-1] == '[' || len(data)-1 > offset && data[offset+1] == '^') {
+		return 0
+	}
+
+	var t linkType
+	switch {
+	// special case: ![^text] == deferred footnote (that follows something with
+	// an exclamation point)
+	case p.flags&EXTENSION_FOOTNOTES != 0 && len(data)-1 > offset && data[offset+1] == '^':
+		t = linkDeferredFootnote
+	// ![alt] == image
+	case offset > 0 && data[offset-1] == '!':
+		t = linkImg
+	// ^[text] == inline footnote
+	// [^refId] == deferred footnote
+	case p.flags&EXTENSION_FOOTNOTES != 0:
+		if offset > 0 && data[offset-1] == '^' {
+			t = linkInlineFootnote
+		} else if len(data)-1 > offset && data[offset+1] == '^' {
+			t = linkDeferredFootnote
+		}
+	// [text] == regular link
+	default:
+		t = linkNormal
+	}
+
+	data = data[offset:]
+
+	var (
+		i                       = 1
+		noteId                  int
+		title, link, altContent []byte
+		textHasNl               = false
+	)
+
+	if t == linkDeferredFootnote {
+		i++
+	}
+
+	// look for the matching closing bracket
+	for level := 1; level > 0 && i < len(data); i++ {
+		switch {
+		case data[i] == '\n':
+			textHasNl = true
+
+		case data[i-1] == '\\':
+			continue
+
+		case data[i] == '[':
+			level++
+
+		case data[i] == ']':
+			level--
+			if level <= 0 {
+				i-- // compensate for extra i++ in for loop
+			}
+		}
+	}
+
+	if i >= len(data) {
+		return 0
+	}
+
+	txtE := i
+	i++
+
+	// skip any amount of whitespace or newline
+	// (this is much more lax than original markdown syntax)
+	for i < len(data) && isspace(data[i]) {
+		i++
+	}
+
+	// inline style link
+	switch {
+	case i < len(data) && data[i] == '(':
+		// skip initial whitespace
+		i++
+
+		for i < len(data) && isspace(data[i]) {
+			i++
+		}
+
+		linkB := i
+
+		// look for link end: ' " )
+	findlinkend:
+		for i < len(data) {
+			switch {
+			case data[i] == '\\':
+				i += 2
+
+			case data[i] == ')' || data[i] == '\'' || data[i] == '"':
+				break findlinkend
+
+			default:
+				i++
+			}
+		}
+
+		if i >= len(data) {
+			return 0
+		}
+		linkE := i
+
+		// look for title end if present
+		titleB, titleE := 0, 0
+		if data[i] == '\'' || data[i] == '"' {
+			i++
+			titleB = i
+
+		findtitleend:
+			for i < len(data) {
+				switch {
+				case data[i] == '\\':
+					i += 2
+
+				case data[i] == ')':
+					break findtitleend
+
+				default:
+					i++
+				}
+			}
+
+			if i >= len(data) {
+				return 0
+			}
+
+			// skip whitespace after title
+			titleE = i - 1
+			for titleE > titleB && isspace(data[titleE]) {
+				titleE--
+			}
+
+			// check for closing quote presence
+			if data[titleE] != '\'' && data[titleE] != '"' {
+				titleB, titleE = 0, 0
+				linkE = i
+			}
+		}
+
+		// remove whitespace at the end of the link
+		for linkE > linkB && isspace(data[linkE-1]) {
+			linkE--
+		}
+
+		// remove optional angle brackets around the link
+		if data[linkB] == '<' {
+			linkB++
+		}
+		if data[linkE-1] == '>' {
+			linkE--
+		}
+
+		// build escaped link and title
+		if linkE > linkB {
+			link = data[linkB:linkE]
+		}
+
+		if titleE > titleB {
+			title = data[titleB:titleE]
+		}
+
+		i++
+
+	// reference style link
+	case isReferenceStyleLink(data, i, t):
+		var id []byte
+		altContentConsidered := false
+
+		// look for the id
+		i++
+		linkB := i
+		for i < len(data) && data[i] != ']' {
+			i++
+		}
+		if i >= len(data) {
+			return 0
+		}
+		linkE := i
+
+		// find the reference
+		if linkB == linkE {
+			if textHasNl {
+				var b bytes.Buffer
+
+				for j := 1; j < txtE; j++ {
+					switch {
+					case data[j] != '\n':
+						b.WriteByte(data[j])
+					case data[j-1] != ' ':
+						b.WriteByte(' ')
+					}
+				}
+
+				id = b.Bytes()
+			} else {
+				id = data[1:txtE]
+				altContentConsidered = true
+			}
+		} else {
+			id = data[linkB:linkE]
+		}
+
+		// find the reference with matching id
+		lr, ok := p.getRef(string(id))
+		if !ok {
+			return 0
+		}
+
+		// keep link and title from reference
+		link = lr.link
+		title = lr.title
+		if altContentConsidered {
+			altContent = lr.text
+		}
+		i++
+
+	// shortcut reference style link or reference or inline footnote
+	default:
+		var id []byte
+
+		// craft the id
+		if textHasNl {
+			var b bytes.Buffer
+
+			for j := 1; j < txtE; j++ {
+				switch {
+				case data[j] != '\n':
+					b.WriteByte(data[j])
+				case data[j-1] != ' ':
+					b.WriteByte(' ')
+				}
+			}
+
+			id = b.Bytes()
+		} else {
+			if t == linkDeferredFootnote {
+				id = data[2:txtE] // get rid of the ^
+			} else {
+				id = data[1:txtE]
+			}
+		}
+
+		if t == linkInlineFootnote {
+			// create a new reference
+			noteId = len(p.notes) + 1
+
+			var fragment []byte
+			if len(id) > 0 {
+				if len(id) < 16 {
+					fragment = make([]byte, len(id))
+				} else {
+					fragment = make([]byte, 16)
+				}
+				copy(fragment, slugify(id))
+			} else {
+				fragment = append([]byte("footnote-"), []byte(strconv.Itoa(noteId))...)
+			}
+
+			ref := &reference{
+				noteId:   noteId,
+				hasBlock: false,
+				link:     fragment,
+				title:    id,
+			}
+
+			p.notes = append(p.notes, ref)
+
+			link = ref.link
+			title = ref.title
+		} else {
+			// find the reference with matching id
+			lr, ok := p.getRef(string(id))
+			if !ok {
+				return 0
+			}
+
+			if t == linkDeferredFootnote {
+				lr.noteId = len(p.notes) + 1
+				p.notes = append(p.notes, lr)
+			}
+
+			// keep link and title from reference
+			link = lr.link
+			// if inline footnote, title == footnote contents
+			title = lr.title
+			noteId = lr.noteId
+		}
+
+		// rewind the whitespace
+		i = txtE + 1
+	}
+
+	// build content: img alt is escaped, link content is parsed
+	var content bytes.Buffer
+	if txtE > 1 {
+		if t == linkImg {
+			content.Write(data[1:txtE])
+		} else {
+			// links cannot contain other links, so turn off link parsing temporarily
+			insideLink := p.insideLink
+			p.insideLink = true
+			p.inline(&content, data[1:txtE])
+			p.insideLink = insideLink
+		}
+	}
+
+	var uLink []byte
+	if t == linkNormal || t == linkImg {
+		if len(link) > 0 {
+			var uLinkBuf bytes.Buffer
+			unescapeText(&uLinkBuf, link)
+			uLink = uLinkBuf.Bytes()
+		}
+
+		// links need something to click on and somewhere to go
+		if len(uLink) == 0 || (t == linkNormal && content.Len() == 0) {
+			return 0
+		}
+	}
+
+	// call the relevant rendering function
+	switch t {
+	case linkNormal:
+		if len(altContent) > 0 {
+			p.r.Link(out, uLink, title, altContent)
+		} else {
+			p.r.Link(out, uLink, title, content.Bytes())
+		}
+
+	case linkImg:
+		outSize := out.Len()
+		outBytes := out.Bytes()
+		if outSize > 0 && outBytes[outSize-1] == '!' {
+			out.Truncate(outSize - 1)
+		}
+
+		p.r.Image(out, uLink, title, content.Bytes())
+
+	case linkInlineFootnote:
+		outSize := out.Len()
+		outBytes := out.Bytes()
+		if outSize > 0 && outBytes[outSize-1] == '^' {
+			out.Truncate(outSize - 1)
+		}
+
+		p.r.FootnoteRef(out, link, noteId)
+
+	case linkDeferredFootnote:
+		p.r.FootnoteRef(out, link, noteId)
+
+	default:
+		return 0
+	}
+
+	return i
+}
+
+func (p *parser) inlineHtmlComment(out *bytes.Buffer, data []byte) int {
+	if len(data) < 5 {
+		return 0
+	}
+	if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' {
+		return 0
+	}
+	i := 5
+	// scan for an end-of-comment marker, across lines if necessary
+	for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') {
+		i++
+	}
+	// no end-of-comment marker
+	if i >= len(data) {
+		return 0
+	}
+	return i + 1
+}
+
+// '<' when tags or autolinks are allowed
+func leftAngle(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	data = data[offset:]
+	altype := LINK_TYPE_NOT_AUTOLINK
+	end := tagLength(data, &altype)
+	if size := p.inlineHtmlComment(out, data); size > 0 {
+		end = size
+	}
+	if end > 2 {
+		if altype != LINK_TYPE_NOT_AUTOLINK {
+			var uLink bytes.Buffer
+			unescapeText(&uLink, data[1:end+1-2])
+			if uLink.Len() > 0 {
+				p.r.AutoLink(out, uLink.Bytes(), altype)
+			}
+		} else {
+			p.r.RawHtmlTag(out, data[:end])
+		}
+	}
+
+	return end
+}
+
+// '\\' backslash escape
+var escapeChars = []byte("\\`*_{}[]()#+-.!:|&<>~")
+
+func escape(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	data = data[offset:]
+
+	if len(data) > 1 {
+		if bytes.IndexByte(escapeChars, data[1]) < 0 {
+			return 0
+		}
+
+		p.r.NormalText(out, data[1:2])
+	}
+
+	return 2
+}
+
+func unescapeText(ob *bytes.Buffer, src []byte) {
+	i := 0
+	for i < len(src) {
+		org := i
+		for i < len(src) && src[i] != '\\' {
+			i++
+		}
+
+		if i > org {
+			ob.Write(src[org:i])
+		}
+
+		if i+1 >= len(src) {
+			break
+		}
+
+		ob.WriteByte(src[i+1])
+		i += 2
+	}
+}
+
+// '&' escaped when it doesn't belong to an entity
+// valid entities are assumed to be anything matching &#?[A-Za-z0-9]+;
+func entity(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	data = data[offset:]
+
+	end := 1
+
+	if end < len(data) && data[end] == '#' {
+		end++
+	}
+
+	for end < len(data) && isalnum(data[end]) {
+		end++
+	}
+
+	if end < len(data) && data[end] == ';' {
+		end++ // real entity
+	} else {
+		return 0 // lone '&'
+	}
+
+	p.r.Entity(out, data[:end])
+
+	return end
+}
+
+func linkEndsWithEntity(data []byte, linkEnd int) bool {
+	entityRanges := htmlEntity.FindAllIndex(data[:linkEnd], -1)
+	return entityRanges != nil && entityRanges[len(entityRanges)-1][1] == linkEnd
+}
+
+func autoLink(p *parser, out *bytes.Buffer, data []byte, offset int) int {
+	// quick check to rule out most false hits on ':'
+	if p.insideLink || len(data) < offset+3 || data[offset+1] != '/' || data[offset+2] != '/' {
+		return 0
+	}
+
+	// Now a more expensive check to see if we're not inside an anchor element
+	anchorStart := offset
+	offsetFromAnchor := 0
+	for anchorStart > 0 && data[anchorStart] != '<' {
+		anchorStart--
+		offsetFromAnchor++
+	}
+
+	anchorStr := anchorRe.Find(data[anchorStart:])
+	if anchorStr != nil {
+		out.Write(anchorStr[offsetFromAnchor:])
+		return len(anchorStr) - offsetFromAnchor
+	}
+
+	// scan backward for a word boundary
+	rewind := 0
+	for offset-rewind > 0 && rewind <= 7 && isletter(data[offset-rewind-1]) {
+		rewind++
+	}
+	if rewind > 6 { // longest supported protocol is "mailto" which has 6 letters
+		return 0
+	}
+
+	origData := data
+	data = data[offset-rewind:]
+
+	if !isSafeLink(data) {
+		return 0
+	}
+
+	linkEnd := 0
+	for linkEnd < len(data) && !isEndOfLink(data[linkEnd]) {
+		linkEnd++
+	}
+
+	// Skip punctuation at the end of the link
+	if (data[linkEnd-1] == '.' || data[linkEnd-1] == ',') && data[linkEnd-2] != '\\' {
+		linkEnd--
+	}
+
+	// But don't skip semicolon if it's a part of escaped entity:
+	if data[linkEnd-1] == ';' && data[linkEnd-2] != '\\' && !linkEndsWithEntity(data, linkEnd) {
+		linkEnd--
+	}
+
+	// See if the link finishes with a punctuation sign that can be closed.
+	var copen byte
+	switch data[linkEnd-1] {
+	case '"':
+		copen = '"'
+	case '\'':
+		copen = '\''
+	case ')':
+		copen = '('
+	case ']':
+		copen = '['
+	case '}':
+		copen = '{'
+	default:
+		copen = 0
+	}
+
+	if copen != 0 {
+		bufEnd := offset - rewind + linkEnd - 2
+
+		openDelim := 1
+
+		/* Try to close the final punctuation sign in this same line;
+		 * if we managed to close it outside of the URL, that means that it's
+		 * not part of the URL. If it closes inside the URL, that means it
+		 * is part of the URL.
+		 *
+		 * Examples:
+		 *
+		 *      foo http://www.pokemon.com/Pikachu_(Electric) bar
+		 *              => http://www.pokemon.com/Pikachu_(Electric)
+		 *
+		 *      foo (http://www.pokemon.com/Pikachu_(Electric)) bar
+		 *              => http://www.pokemon.com/Pikachu_(Electric)
+		 *
+		 *      foo http://www.pokemon.com/Pikachu_(Electric)) bar
+		 *              => http://www.pokemon.com/Pikachu_(Electric))
+		 *
+		 *      (foo http://www.pokemon.com/Pikachu_(Electric)) bar
+		 *              => foo http://www.pokemon.com/Pikachu_(Electric)
+		 */
+
+		for bufEnd >= 0 && origData[bufEnd] != '\n' && openDelim != 0 {
+			if origData[bufEnd] == data[linkEnd-1] {
+				openDelim++
+			}
+
+			if origData[bufEnd] == copen {
+				openDelim--
+			}
+
+			bufEnd--
+		}
+
+		if openDelim == 0 {
+			linkEnd--
+		}
+	}
+
+	// we were triggered on the ':', so we need to rewind the output a bit
+	if out.Len() >= rewind {
+		out.Truncate(len(out.Bytes()) - rewind)
+	}
+
+	var uLink bytes.Buffer
+	unescapeText(&uLink, data[:linkEnd])
+
+	if uLink.Len() > 0 {
+		p.r.AutoLink(out, uLink.Bytes(), LINK_TYPE_NORMAL)
+	}
+
+	return linkEnd - rewind
+}
+
+func isEndOfLink(char byte) bool {
+	return isspace(char) || char == '<'
+}
+
+var validUris = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")}
+var validPaths = [][]byte{[]byte("/"), []byte("./"), []byte("../")}
+
+func isSafeLink(link []byte) bool {
+	for _, path := range validPaths {
+		if len(link) >= len(path) && bytes.Equal(link[:len(path)], path) {
+			if len(link) == len(path) {
+				return true
+			} else if isalnum(link[len(path)]) {
+				return true
+			}
+		}
+	}
+
+	for _, prefix := range validUris {
+		// TODO: handle unicode here
+		// case-insensitive prefix test
+		if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) {
+			return true
+		}
+	}
+
+	return false
+}
+
+// return the length of the given tag, or 0 is it's not valid
+func tagLength(data []byte, autolink *int) int {
+	var i, j int
+
+	// a valid tag can't be shorter than 3 chars
+	if len(data) < 3 {
+		return 0
+	}
+
+	// begins with a '<' optionally followed by '/', followed by letter or number
+	if data[0] != '<' {
+		return 0
+	}
+	if data[1] == '/' {
+		i = 2
+	} else {
+		i = 1
+	}
+
+	if !isalnum(data[i]) {
+		return 0
+	}
+
+	// scheme test
+	*autolink = LINK_TYPE_NOT_AUTOLINK
+
+	// try to find the beginning of an URI
+	for i < len(data) && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-') {
+		i++
+	}
+
+	if i > 1 && i < len(data) && data[i] == '@' {
+		if j = isMailtoAutoLink(data[i:]); j != 0 {
+			*autolink = LINK_TYPE_EMAIL
+			return i + j
+		}
+	}
+
+	if i > 2 && i < len(data) && data[i] == ':' {
+		*autolink = LINK_TYPE_NORMAL
+		i++
+	}
+
+	// complete autolink test: no whitespace or ' or "
+	switch {
+	case i >= len(data):
+		*autolink = LINK_TYPE_NOT_AUTOLINK
+	case *autolink != 0:
+		j = i
+
+		for i < len(data) {
+			if data[i] == '\\' {
+				i += 2
+			} else if data[i] == '>' || data[i] == '\'' || data[i] == '"' || isspace(data[i]) {
+				break
+			} else {
+				i++
+			}
+
+		}
+
+		if i >= len(data) {
+			return 0
+		}
+		if i > j && data[i] == '>' {
+			return i + 1
+		}
+
+		// one of the forbidden chars has been found
+		*autolink = LINK_TYPE_NOT_AUTOLINK
+	}
+
+	// look for something looking like a tag end
+	for i < len(data) && data[i] != '>' {
+		i++
+	}
+	if i >= len(data) {
+		return 0
+	}
+	return i + 1
+}
+
+// look for the address part of a mail autolink and '>'
+// this is less strict than the original markdown e-mail address matching
+func isMailtoAutoLink(data []byte) int {
+	nb := 0
+
+	// address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@'
+	for i := 0; i < len(data); i++ {
+		if isalnum(data[i]) {
+			continue
+		}
+
+		switch data[i] {
+		case '@':
+			nb++
+
+		case '-', '.', '_':
+			break
+
+		case '>':
+			if nb == 1 {
+				return i + 1
+			} else {
+				return 0
+			}
+		default:
+			return 0
+		}
+	}
+
+	return 0
+}
+
+// look for the next emph char, skipping other constructs
+func helperFindEmphChar(data []byte, c byte) int {
+	i := 0
+
+	for i < len(data) {
+		for i < len(data) && data[i] != c && data[i] != '`' && data[i] != '[' {
+			i++
+		}
+		if i >= len(data) {
+			return 0
+		}
+		// do not count escaped chars
+		if i != 0 && data[i-1] == '\\' {
+			i++
+			continue
+		}
+		if data[i] == c {
+			return i
+		}
+
+		if data[i] == '`' {
+			// skip a code span
+			tmpI := 0
+			i++
+			for i < len(data) && data[i] != '`' {
+				if tmpI == 0 && data[i] == c {
+					tmpI = i
+				}
+				i++
+			}
+			if i >= len(data) {
+				return tmpI
+			}
+			i++
+		} else if data[i] == '[' {
+			// skip a link
+			tmpI := 0
+			i++
+			for i < len(data) && data[i] != ']' {
+				if tmpI == 0 && data[i] == c {
+					tmpI = i
+				}
+				i++
+			}
+			i++
+			for i < len(data) && (data[i] == ' ' || data[i] == '\n') {
+				i++
+			}
+			if i >= len(data) {
+				return tmpI
+			}
+			if data[i] != '[' && data[i] != '(' { // not a link
+				if tmpI > 0 {
+					return tmpI
+				} else {
+					continue
+				}
+			}
+			cc := data[i]
+			i++
+			for i < len(data) && data[i] != cc {
+				if tmpI == 0 && data[i] == c {
+					return i
+				}
+				i++
+			}
+			if i >= len(data) {
+				return tmpI
+			}
+			i++
+		}
+	}
+	return 0
+}
+
+func helperEmphasis(p *parser, out *bytes.Buffer, data []byte, c byte) int {
+	i := 0
+
+	// skip one symbol if coming from emph3
+	if len(data) > 1 && data[0] == c && data[1] == c {
+		i = 1
+	}
+
+	for i < len(data) {
+		length := helperFindEmphChar(data[i:], c)
+		if length == 0 {
+			return 0
+		}
+		i += length
+		if i >= len(data) {
+			return 0
+		}
+
+		if i+1 < len(data) && data[i+1] == c {
+			i++
+			continue
+		}
+
+		if data[i] == c && !isspace(data[i-1]) {
+
+			if p.flags&EXTENSION_NO_INTRA_EMPHASIS != 0 {
+				if !(i+1 == len(data) || isspace(data[i+1]) || ispunct(data[i+1])) {
+					continue
+				}
+			}
+
+			var work bytes.Buffer
+			p.inline(&work, data[:i])
+			p.r.Emphasis(out, work.Bytes())
+			return i + 1
+		}
+	}
+
+	return 0
+}
+
+func helperDoubleEmphasis(p *parser, out *bytes.Buffer, data []byte, c byte) int {
+	i := 0
+
+	for i < len(data) {
+		length := helperFindEmphChar(data[i:], c)
+		if length == 0 {
+			return 0
+		}
+		i += length
+
+		if i+1 < len(data) && data[i] == c && data[i+1] == c && i > 0 && !isspace(data[i-1]) {
+			var work bytes.Buffer
+			p.inline(&work, data[:i])
+
+			if work.Len() > 0 {
+				// pick the right renderer
+				if c == '~' {
+					p.r.StrikeThrough(out, work.Bytes())
+				} else {
+					p.r.DoubleEmphasis(out, work.Bytes())
+				}
+			}
+			return i + 2
+		}
+		i++
+	}
+	return 0
+}
+
+func helperTripleEmphasis(p *parser, out *bytes.Buffer, data []byte, offset int, c byte) int {
+	i := 0
+	origData := data
+	data = data[offset:]
+
+	for i < len(data) {
+		length := helperFindEmphChar(data[i:], c)
+		if length == 0 {
+			return 0
+		}
+		i += length
+
+		// skip whitespace preceded symbols
+		if data[i] != c || isspace(data[i-1]) {
+			continue
+		}
+
+		switch {
+		case i+2 < len(data) && data[i+1] == c && data[i+2] == c:
+			// triple symbol found
+			var work bytes.Buffer
+
+			p.inline(&work, data[:i])
+			if work.Len() > 0 {
+				p.r.TripleEmphasis(out, work.Bytes())
+			}
+			return i + 3
+		case (i+1 < len(data) && data[i+1] == c):
+			// double symbol found, hand over to emph1
+			length = helperEmphasis(p, out, origData[offset-2:], c)
+			if length == 0 {
+				return 0
+			} else {
+				return length - 2
+			}
+		default:
+			// single symbol found, hand over to emph2
+			length = helperDoubleEmphasis(p, out, origData[offset-1:], c)
+			if length == 0 {
+				return 0
+			} else {
+				return length - 1
+			}
+		}
+	}
+	return 0
+}

+ 1153 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/inline_test.go

@@ -0,0 +1,1153 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+// Unit tests for inline parsing
+//
+
+package blackfriday
+
+import (
+	"regexp"
+	"testing"
+
+	"strings"
+)
+
+func runMarkdownInline(input string, opts Options, htmlFlags int, params HtmlRendererParameters) string {
+	opts.Extensions |= EXTENSION_AUTOLINK
+	opts.Extensions |= EXTENSION_STRIKETHROUGH
+
+	htmlFlags |= HTML_USE_XHTML
+
+	renderer := HtmlRendererWithParameters(htmlFlags, "", "", params)
+
+	return string(MarkdownOptions([]byte(input), renderer, opts))
+}
+
+func doTestsInline(t *testing.T, tests []string) {
+	doTestsInlineParam(t, tests, Options{}, 0, HtmlRendererParameters{})
+}
+
+func doLinkTestsInline(t *testing.T, tests []string) {
+	doTestsInline(t, tests)
+
+	prefix := "http://localhost"
+	params := HtmlRendererParameters{AbsolutePrefix: prefix}
+	transformTests := transformLinks(tests, prefix)
+	doTestsInlineParam(t, transformTests, Options{}, 0, params)
+	doTestsInlineParam(t, transformTests, Options{}, commonHtmlFlags, params)
+}
+
+func doSafeTestsInline(t *testing.T, tests []string) {
+	doTestsInlineParam(t, tests, Options{}, HTML_SAFELINK, HtmlRendererParameters{})
+
+	// All the links in this test should not have the prefix appended, so
+	// just rerun it with different parameters and the same expectations.
+	prefix := "http://localhost"
+	params := HtmlRendererParameters{AbsolutePrefix: prefix}
+	transformTests := transformLinks(tests, prefix)
+	doTestsInlineParam(t, transformTests, Options{}, HTML_SAFELINK, params)
+}
+
+func doTestsInlineParam(t *testing.T, tests []string, opts Options, htmlFlags int,
+	params HtmlRendererParameters) {
+	// catch and report panics
+	var candidate string
+	/*
+		defer func() {
+			if err := recover(); err != nil {
+				t.Errorf("\npanic while processing [%#v] (%v)\n", candidate, err)
+			}
+		}()
+	*/
+
+	for i := 0; i+1 < len(tests); i += 2 {
+		input := tests[i]
+		candidate = input
+		expected := tests[i+1]
+		actual := runMarkdownInline(candidate, opts, htmlFlags, params)
+		if actual != expected {
+			t.Errorf("\nInput   [%#v]\nExpected[%#v]\nActual  [%#v]",
+				candidate, expected, actual)
+		}
+
+		// now test every substring to stress test bounds checking
+		if !testing.Short() {
+			for start := 0; start < len(input); start++ {
+				for end := start + 1; end <= len(input); end++ {
+					candidate = input[start:end]
+					_ = runMarkdownInline(candidate, opts, htmlFlags, params)
+				}
+			}
+		}
+	}
+}
+
+func transformLinks(tests []string, prefix string) []string {
+	newTests := make([]string, len(tests))
+	anchorRe := regexp.MustCompile(`<a href="/(.*?)"`)
+	imgRe := regexp.MustCompile(`<img src="/(.*?)"`)
+	for i, test := range tests {
+		if i%2 == 1 {
+			test = anchorRe.ReplaceAllString(test, `<a href="`+prefix+`/$1"`)
+			test = imgRe.ReplaceAllString(test, `<img src="`+prefix+`/$1"`)
+		}
+		newTests[i] = test
+	}
+	return newTests
+}
+
+func TestEmphasis(t *testing.T) {
+	var tests = []string{
+		"nothing inline\n",
+		"<p>nothing inline</p>\n",
+
+		"simple *inline* test\n",
+		"<p>simple <em>inline</em> test</p>\n",
+
+		"*at the* beginning\n",
+		"<p><em>at the</em> beginning</p>\n",
+
+		"at the *end*\n",
+		"<p>at the <em>end</em></p>\n",
+
+		"*try two* in *one line*\n",
+		"<p><em>try two</em> in <em>one line</em></p>\n",
+
+		"over *two\nlines* test\n",
+		"<p>over <em>two\nlines</em> test</p>\n",
+
+		"odd *number of* markers* here\n",
+		"<p>odd <em>number of</em> markers* here</p>\n",
+
+		"odd *number\nof* markers* here\n",
+		"<p>odd <em>number\nof</em> markers* here</p>\n",
+
+		"simple _inline_ test\n",
+		"<p>simple <em>inline</em> test</p>\n",
+
+		"_at the_ beginning\n",
+		"<p><em>at the</em> beginning</p>\n",
+
+		"at the _end_\n",
+		"<p>at the <em>end</em></p>\n",
+
+		"_try two_ in _one line_\n",
+		"<p><em>try two</em> in <em>one line</em></p>\n",
+
+		"over _two\nlines_ test\n",
+		"<p>over <em>two\nlines</em> test</p>\n",
+
+		"odd _number of_ markers_ here\n",
+		"<p>odd <em>number of</em> markers_ here</p>\n",
+
+		"odd _number\nof_ markers_ here\n",
+		"<p>odd <em>number\nof</em> markers_ here</p>\n",
+
+		"mix of *markers_\n",
+		"<p>mix of *markers_</p>\n",
+
+		"*What is A\\* algorithm?*\n",
+		"<p><em>What is A* algorithm?</em></p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestReferenceOverride(t *testing.T) {
+	var tests = []string{
+		"test [ref1][]\n",
+		"<p>test <a href=\"http://www.ref1.com/\" title=\"Reference 1\">ref1</a></p>\n",
+
+		"test [my ref][ref1]\n",
+		"<p>test <a href=\"http://www.ref1.com/\" title=\"Reference 1\">my ref</a></p>\n",
+
+		"test [ref2][]\n\n[ref2]: http://www.leftalone.com/ (Ref left alone)\n",
+		"<p>test <a href=\"http://www.overridden.com/\" title=\"Reference Overridden\">ref2</a></p>\n",
+
+		"test [ref3][]\n\n[ref3]: http://www.leftalone.com/ (Ref left alone)\n",
+		"<p>test <a href=\"http://www.leftalone.com/\" title=\"Ref left alone\">ref3</a></p>\n",
+
+		"test [ref4][]\n\n[ref4]: http://zombo.com/ (You can do anything)\n",
+		"<p>test [ref4][]</p>\n",
+
+		"test [!(*http.ServeMux).ServeHTTP][] complicated ref\n",
+		"<p>test <a href=\"http://localhost:6060/pkg/net/http/#ServeMux.ServeHTTP\" title=\"ServeHTTP docs\">!(*http.ServeMux).ServeHTTP</a> complicated ref</p>\n",
+
+		"test [ref5][]\n",
+		"<p>test <a href=\"http://www.ref5.com/\" title=\"Reference 5\">Moo</a></p>\n",
+	}
+	doTestsInlineParam(t, tests, Options{
+		ReferenceOverride: func(reference string) (rv *Reference, overridden bool) {
+			switch reference {
+			case "ref1":
+				// just an overriden reference exists without definition
+				return &Reference{
+					Link:  "http://www.ref1.com/",
+					Title: "Reference 1"}, true
+			case "ref2":
+				// overridden exists and reference defined
+				return &Reference{
+					Link:  "http://www.overridden.com/",
+					Title: "Reference Overridden"}, true
+			case "ref3":
+				// not overridden and reference defined
+				return nil, false
+			case "ref4":
+				// overridden missing and defined
+				return nil, true
+			case "!(*http.ServeMux).ServeHTTP":
+				return &Reference{
+					Link:  "http://localhost:6060/pkg/net/http/#ServeMux.ServeHTTP",
+					Title: "ServeHTTP docs"}, true
+			case "ref5":
+				return &Reference{
+					Link:  "http://www.ref5.com/",
+					Title: "Reference 5",
+					Text:  "Moo",
+				}, true
+			}
+			return nil, false
+		}}, 0, HtmlRendererParameters{})
+}
+
+func TestStrong(t *testing.T) {
+	var tests = []string{
+		"nothing inline\n",
+		"<p>nothing inline</p>\n",
+
+		"simple **inline** test\n",
+		"<p>simple <strong>inline</strong> test</p>\n",
+
+		"**at the** beginning\n",
+		"<p><strong>at the</strong> beginning</p>\n",
+
+		"at the **end**\n",
+		"<p>at the <strong>end</strong></p>\n",
+
+		"**try two** in **one line**\n",
+		"<p><strong>try two</strong> in <strong>one line</strong></p>\n",
+
+		"over **two\nlines** test\n",
+		"<p>over <strong>two\nlines</strong> test</p>\n",
+
+		"odd **number of** markers** here\n",
+		"<p>odd <strong>number of</strong> markers** here</p>\n",
+
+		"odd **number\nof** markers** here\n",
+		"<p>odd <strong>number\nof</strong> markers** here</p>\n",
+
+		"simple __inline__ test\n",
+		"<p>simple <strong>inline</strong> test</p>\n",
+
+		"__at the__ beginning\n",
+		"<p><strong>at the</strong> beginning</p>\n",
+
+		"at the __end__\n",
+		"<p>at the <strong>end</strong></p>\n",
+
+		"__try two__ in __one line__\n",
+		"<p><strong>try two</strong> in <strong>one line</strong></p>\n",
+
+		"over __two\nlines__ test\n",
+		"<p>over <strong>two\nlines</strong> test</p>\n",
+
+		"odd __number of__ markers__ here\n",
+		"<p>odd <strong>number of</strong> markers__ here</p>\n",
+
+		"odd __number\nof__ markers__ here\n",
+		"<p>odd <strong>number\nof</strong> markers__ here</p>\n",
+
+		"mix of **markers__\n",
+		"<p>mix of **markers__</p>\n",
+
+		"**`/usr`** : this folder is named `usr`\n",
+		"<p><strong><code>/usr</code></strong> : this folder is named <code>usr</code></p>\n",
+
+		"**`/usr`** :\n\n this folder is named `usr`\n",
+		"<p><strong><code>/usr</code></strong> :</p>\n\n<p>this folder is named <code>usr</code></p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestEmphasisMix(t *testing.T) {
+	var tests = []string{
+		"***triple emphasis***\n",
+		"<p><strong><em>triple emphasis</em></strong></p>\n",
+
+		"***triple\nemphasis***\n",
+		"<p><strong><em>triple\nemphasis</em></strong></p>\n",
+
+		"___triple emphasis___\n",
+		"<p><strong><em>triple emphasis</em></strong></p>\n",
+
+		"***triple emphasis___\n",
+		"<p>***triple emphasis___</p>\n",
+
+		"*__triple emphasis__*\n",
+		"<p><em><strong>triple emphasis</strong></em></p>\n",
+
+		"__*triple emphasis*__\n",
+		"<p><strong><em>triple emphasis</em></strong></p>\n",
+
+		"**improper *nesting** is* bad\n",
+		"<p><strong>improper *nesting</strong> is* bad</p>\n",
+
+		"*improper **nesting* is** bad\n",
+		"<p>*improper <strong>nesting* is</strong> bad</p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestEmphasisLink(t *testing.T) {
+	var tests = []string{
+		"[first](before) *text[second] (inside)text* [third](after)\n",
+		"<p><a href=\"before\">first</a> <em>text<a href=\"inside\">second</a>text</em> <a href=\"after\">third</a></p>\n",
+
+		"*incomplete [link] definition*\n",
+		"<p><em>incomplete [link] definition</em></p>\n",
+
+		"*it's [emphasis*] (not link)\n",
+		"<p><em>it's [emphasis</em>] (not link)</p>\n",
+
+		"*it's [emphasis*] and *[asterisk]\n",
+		"<p><em>it's [emphasis</em>] and *[asterisk]</p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestStrikeThrough(t *testing.T) {
+	var tests = []string{
+		"nothing inline\n",
+		"<p>nothing inline</p>\n",
+
+		"simple ~~inline~~ test\n",
+		"<p>simple <del>inline</del> test</p>\n",
+
+		"~~at the~~ beginning\n",
+		"<p><del>at the</del> beginning</p>\n",
+
+		"at the ~~end~~\n",
+		"<p>at the <del>end</del></p>\n",
+
+		"~~try two~~ in ~~one line~~\n",
+		"<p><del>try two</del> in <del>one line</del></p>\n",
+
+		"over ~~two\nlines~~ test\n",
+		"<p>over <del>two\nlines</del> test</p>\n",
+
+		"odd ~~number of~~ markers~~ here\n",
+		"<p>odd <del>number of</del> markers~~ here</p>\n",
+
+		"odd ~~number\nof~~ markers~~ here\n",
+		"<p>odd <del>number\nof</del> markers~~ here</p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestCodeSpan(t *testing.T) {
+	var tests = []string{
+		"`source code`\n",
+		"<p><code>source code</code></p>\n",
+
+		"` source code with spaces `\n",
+		"<p><code>source code with spaces</code></p>\n",
+
+		"` source code with spaces `not here\n",
+		"<p><code>source code with spaces</code>not here</p>\n",
+
+		"a `single marker\n",
+		"<p>a `single marker</p>\n",
+
+		"a single multi-tick marker with ``` no text\n",
+		"<p>a single multi-tick marker with ``` no text</p>\n",
+
+		"markers with ` ` a space\n",
+		"<p>markers with  a space</p>\n",
+
+		"`source code` and a `stray\n",
+		"<p><code>source code</code> and a `stray</p>\n",
+
+		"`source *with* _awkward characters_ in it`\n",
+		"<p><code>source *with* _awkward characters_ in it</code></p>\n",
+
+		"`split over\ntwo lines`\n",
+		"<p><code>split over\ntwo lines</code></p>\n",
+
+		"```multiple ticks``` for the marker\n",
+		"<p><code>multiple ticks</code> for the marker</p>\n",
+
+		"```multiple ticks `with` ticks inside```\n",
+		"<p><code>multiple ticks `with` ticks inside</code></p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestLineBreak(t *testing.T) {
+	var tests = []string{
+		"this line  \nhas a break\n",
+		"<p>this line<br />\nhas a break</p>\n",
+
+		"this line \ndoes not\n",
+		"<p>this line\ndoes not</p>\n",
+
+		"this line\\\ndoes not\n",
+		"<p>this line\\\ndoes not</p>\n",
+
+		"this line\\ \ndoes not\n",
+		"<p>this line\\\ndoes not</p>\n",
+
+		"this has an   \nextra space\n",
+		"<p>this has an<br />\nextra space</p>\n",
+	}
+	doTestsInline(t, tests)
+
+	tests = []string{
+		"this line  \nhas a break\n",
+		"<p>this line<br />\nhas a break</p>\n",
+
+		"this line \ndoes not\n",
+		"<p>this line\ndoes not</p>\n",
+
+		"this line\\\nhas a break\n",
+		"<p>this line<br />\nhas a break</p>\n",
+
+		"this line\\ \ndoes not\n",
+		"<p>this line\\\ndoes not</p>\n",
+
+		"this has an   \nextra space\n",
+		"<p>this has an<br />\nextra space</p>\n",
+	}
+	doTestsInlineParam(t, tests, Options{
+		Extensions: EXTENSION_BACKSLASH_LINE_BREAK},
+		0, HtmlRendererParameters{})
+}
+
+func TestInlineLink(t *testing.T) {
+	var tests = []string{
+		"[foo](/bar/)\n",
+		"<p><a href=\"/bar/\">foo</a></p>\n",
+
+		"[foo with a title](/bar/ \"title\")\n",
+		"<p><a href=\"/bar/\" title=\"title\">foo with a title</a></p>\n",
+
+		"[foo with a title](/bar/\t\"title\")\n",
+		"<p><a href=\"/bar/\" title=\"title\">foo with a title</a></p>\n",
+
+		"[foo with a title](/bar/ \"title\"  )\n",
+		"<p><a href=\"/bar/\" title=\"title\">foo with a title</a></p>\n",
+
+		"[foo with a title](/bar/ title with no quotes)\n",
+		"<p><a href=\"/bar/ title with no quotes\">foo with a title</a></p>\n",
+
+		"[foo]()\n",
+		"<p>[foo]()</p>\n",
+
+		"![foo](/bar/)\n",
+		"<p><img src=\"/bar/\" alt=\"foo\" /></p>\n",
+
+		"![foo with a title](/bar/ \"title\")\n",
+		"<p><img src=\"/bar/\" alt=\"foo with a title\" title=\"title\" /></p>\n",
+
+		"![foo with a title](/bar/\t\"title\")\n",
+		"<p><img src=\"/bar/\" alt=\"foo with a title\" title=\"title\" /></p>\n",
+
+		"![foo with a title](/bar/ \"title\"  )\n",
+		"<p><img src=\"/bar/\" alt=\"foo with a title\" title=\"title\" /></p>\n",
+
+		"![foo with a title](/bar/ title with no quotes)\n",
+		"<p><img src=\"/bar/ title with no quotes\" alt=\"foo with a title\" /></p>\n",
+
+		"![](img.jpg)\n",
+		"<p><img src=\"img.jpg\" alt=\"\" /></p>\n",
+
+		"[link](url)\n",
+		"<p><a href=\"url\">link</a></p>\n",
+
+		"![foo]()\n",
+		"<p>![foo]()</p>\n",
+
+		"[a link]\t(/with_a_tab/)\n",
+		"<p><a href=\"/with_a_tab/\">a link</a></p>\n",
+
+		"[a link]  (/with_spaces/)\n",
+		"<p><a href=\"/with_spaces/\">a link</a></p>\n",
+
+		"[text (with) [[nested] (brackets)]](/url/)\n",
+		"<p><a href=\"/url/\">text (with) [[nested] (brackets)]</a></p>\n",
+
+		"[text (with) [broken nested] (brackets)]](/url/)\n",
+		"<p>[text (with) <a href=\"brackets\">broken nested</a>]](/url/)</p>\n",
+
+		"[text\nwith a newline](/link/)\n",
+		"<p><a href=\"/link/\">text\nwith a newline</a></p>\n",
+
+		"[text in brackets] [followed](/by a link/)\n",
+		"<p>[text in brackets] <a href=\"/by a link/\">followed</a></p>\n",
+
+		"[link with\\] a closing bracket](/url/)\n",
+		"<p><a href=\"/url/\">link with] a closing bracket</a></p>\n",
+
+		"[link with\\[ an opening bracket](/url/)\n",
+		"<p><a href=\"/url/\">link with[ an opening bracket</a></p>\n",
+
+		"[link with\\) a closing paren](/url/)\n",
+		"<p><a href=\"/url/\">link with) a closing paren</a></p>\n",
+
+		"[link with\\( an opening paren](/url/)\n",
+		"<p><a href=\"/url/\">link with( an opening paren</a></p>\n",
+
+		"[link](  with whitespace)\n",
+		"<p><a href=\"with whitespace\">link</a></p>\n",
+
+		"[link](  with whitespace   )\n",
+		"<p><a href=\"with whitespace\">link</a></p>\n",
+
+		"[![image](someimage)](with image)\n",
+		"<p><a href=\"with image\"><img src=\"someimage\" alt=\"image\" /></a></p>\n",
+
+		"[link](url \"one quote)\n",
+		"<p><a href=\"url &quot;one quote\">link</a></p>\n",
+
+		"[link](url 'one quote)\n",
+		"<p><a href=\"url 'one quote\">link</a></p>\n",
+
+		"[link](<url>)\n",
+		"<p><a href=\"url\">link</a></p>\n",
+
+		"[link & ampersand](/url/)\n",
+		"<p><a href=\"/url/\">link &amp; ampersand</a></p>\n",
+
+		"[link &amp; ampersand](/url/)\n",
+		"<p><a href=\"/url/\">link &amp; ampersand</a></p>\n",
+
+		"[link](/url/&query)\n",
+		"<p><a href=\"/url/&amp;query\">link</a></p>\n",
+
+		"[[t]](/t)\n",
+		"<p><a href=\"/t\">[t]</a></p>\n",
+
+		"[link](</>)\n",
+		"<p><a href=\"/\">link</a></p>\n",
+
+		"[link](<./>)\n",
+		"<p><a href=\"./\">link</a></p>\n",
+
+		"[link](<../>)\n",
+		"<p><a href=\"../\">link</a></p>\n",
+	}
+	doLinkTestsInline(t, tests)
+
+}
+
+func TestRelAttrLink(t *testing.T) {
+	var nofollowTests = []string{
+		"[foo](http://bar.com/foo/)\n",
+		"<p><a href=\"http://bar.com/foo/\" rel=\"nofollow\">foo</a></p>\n",
+
+		"[foo](/bar/)\n",
+		"<p><a href=\"/bar/\">foo</a></p>\n",
+
+		"[foo](/)\n",
+		"<p><a href=\"/\">foo</a></p>\n",
+
+		"[foo](./)\n",
+		"<p><a href=\"./\">foo</a></p>\n",
+
+		"[foo](../)\n",
+		"<p><a href=\"../\">foo</a></p>\n",
+
+		"[foo](../bar)\n",
+		"<p><a href=\"../bar\">foo</a></p>\n",
+	}
+	doTestsInlineParam(t, nofollowTests, Options{}, HTML_SAFELINK|HTML_NOFOLLOW_LINKS,
+		HtmlRendererParameters{})
+
+	var noreferrerTests = []string{
+		"[foo](http://bar.com/foo/)\n",
+		"<p><a href=\"http://bar.com/foo/\" rel=\"noreferrer\">foo</a></p>\n",
+
+		"[foo](/bar/)\n",
+		"<p><a href=\"/bar/\">foo</a></p>\n",
+	}
+	doTestsInlineParam(t, noreferrerTests, Options{}, HTML_SAFELINK|HTML_NOREFERRER_LINKS,
+		HtmlRendererParameters{})
+
+	var nofollownoreferrerTests = []string{
+		"[foo](http://bar.com/foo/)\n",
+		"<p><a href=\"http://bar.com/foo/\" rel=\"nofollow noreferrer\">foo</a></p>\n",
+
+		"[foo](/bar/)\n",
+		"<p><a href=\"/bar/\">foo</a></p>\n",
+	}
+	doTestsInlineParam(t, nofollownoreferrerTests, Options{}, HTML_SAFELINK|HTML_NOFOLLOW_LINKS|HTML_NOREFERRER_LINKS,
+		HtmlRendererParameters{})
+}
+
+func TestHrefTargetBlank(t *testing.T) {
+	var tests = []string{
+		// internal link
+		"[foo](/bar/)\n",
+		"<p><a href=\"/bar/\">foo</a></p>\n",
+
+		"[foo](/)\n",
+		"<p><a href=\"/\">foo</a></p>\n",
+
+		"[foo](./)\n",
+		"<p><a href=\"./\">foo</a></p>\n",
+
+		"[foo](./bar)\n",
+		"<p><a href=\"./bar\">foo</a></p>\n",
+
+		"[foo](../)\n",
+		"<p><a href=\"../\">foo</a></p>\n",
+
+		"[foo](../bar)\n",
+		"<p><a href=\"../bar\">foo</a></p>\n",
+
+		"[foo](http://example.com)\n",
+		"<p><a href=\"http://example.com\" target=\"_blank\">foo</a></p>\n",
+	}
+	doTestsInlineParam(t, tests, Options{}, HTML_SAFELINK|HTML_HREF_TARGET_BLANK, HtmlRendererParameters{})
+}
+
+func TestSafeInlineLink(t *testing.T) {
+	var tests = []string{
+		"[foo](/bar/)\n",
+		"<p><a href=\"/bar/\">foo</a></p>\n",
+
+		"[foo](/)\n",
+		"<p><a href=\"/\">foo</a></p>\n",
+
+		"[foo](./)\n",
+		"<p><a href=\"./\">foo</a></p>\n",
+
+		"[foo](../)\n",
+		"<p><a href=\"../\">foo</a></p>\n",
+
+		"[foo](http://bar/)\n",
+		"<p><a href=\"http://bar/\">foo</a></p>\n",
+
+		"[foo](https://bar/)\n",
+		"<p><a href=\"https://bar/\">foo</a></p>\n",
+
+		"[foo](ftp://bar/)\n",
+		"<p><a href=\"ftp://bar/\">foo</a></p>\n",
+
+		"[foo](mailto://bar/)\n",
+		"<p><a href=\"mailto://bar/\">foo</a></p>\n",
+
+		// Not considered safe
+		"[foo](baz://bar/)\n",
+		"<p><tt>foo</tt></p>\n",
+	}
+	doSafeTestsInline(t, tests)
+}
+
+func TestReferenceLink(t *testing.T) {
+	var tests = []string{
+		"[link][ref]\n",
+		"<p>[link][ref]</p>\n",
+
+		"[link][ref]\n   [ref]: /url/ \"title\"\n",
+		"<p><a href=\"/url/\" title=\"title\">link</a></p>\n",
+
+		"[link][ref]\n   [ref]: /url/\n",
+		"<p><a href=\"/url/\">link</a></p>\n",
+
+		"   [ref]: /url/\n",
+		"",
+
+		"   [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n",
+		"",
+
+		"   [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n    [4spaces]: /url/\n",
+		"<pre><code>[4spaces]: /url/\n</code></pre>\n",
+
+		"[hmm](ref2)\n   [ref]: /url/\n[ref2]: /url/\n [ref3]: /url/\n",
+		"<p><a href=\"ref2\">hmm</a></p>\n",
+
+		"[ref]\n",
+		"<p>[ref]</p>\n",
+
+		"[ref]\n   [ref]: /url/ \"title\"\n",
+		"<p><a href=\"/url/\" title=\"title\">ref</a></p>\n",
+
+		"[ref]\n   [ref]: ../url/ \"title\"\n",
+		"<p><a href=\"../url/\" title=\"title\">ref</a></p>\n",
+	}
+	doLinkTestsInline(t, tests)
+}
+
+func TestTags(t *testing.T) {
+	var tests = []string{
+		"a <span>tag</span>\n",
+		"<p>a <span>tag</span></p>\n",
+
+		"<span>tag</span>\n",
+		"<p><span>tag</span></p>\n",
+
+		"<span>mismatch</spandex>\n",
+		"<p><span>mismatch</spandex></p>\n",
+
+		"a <singleton /> tag\n",
+		"<p>a <singleton /> tag</p>\n",
+	}
+	doTestsInline(t, tests)
+}
+
+func TestAutoLink(t *testing.T) {
+	var tests = []string{
+		"http://foo.com/\n",
+		"<p><a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"1 http://foo.com/\n",
+		"<p>1 <a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"1http://foo.com/\n",
+		"<p>1<a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"1.http://foo.com/\n",
+		"<p>1.<a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"1. http://foo.com/\n",
+		"<ol>\n<li><a href=\"http://foo.com/\">http://foo.com/</a></li>\n</ol>\n",
+
+		"-http://foo.com/\n",
+		"<p>-<a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"- http://foo.com/\n",
+		"<ul>\n<li><a href=\"http://foo.com/\">http://foo.com/</a></li>\n</ul>\n",
+
+		"_http://foo.com/\n",
+		"<p>_<a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"令狐http://foo.com/\n",
+		"<p>令狐<a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"令狐 http://foo.com/\n",
+		"<p>令狐 <a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"ahttp://foo.com/\n",
+		"<p>ahttp://foo.com/</p>\n",
+
+		">http://foo.com/\n",
+		"<blockquote>\n<p><a href=\"http://foo.com/\">http://foo.com/</a></p>\n</blockquote>\n",
+
+		"> http://foo.com/\n",
+		"<blockquote>\n<p><a href=\"http://foo.com/\">http://foo.com/</a></p>\n</blockquote>\n",
+
+		"go to <http://foo.com/>\n",
+		"<p>go to <a href=\"http://foo.com/\">http://foo.com/</a></p>\n",
+
+		"a secure <https://link.org>\n",
+		"<p>a secure <a href=\"https://link.org\">https://link.org</a></p>\n",
+
+		"an email <mailto:some@one.com>\n",
+		"<p>an email <a href=\"mailto:some@one.com\">some@one.com</a></p>\n",
+
+		"an email <mailto://some@one.com>\n",
+		"<p>an email <a href=\"mailto://some@one.com\">some@one.com</a></p>\n",
+
+		"an email <some@one.com>\n",
+		"<p>an email <a href=\"mailto:some@one.com\">some@one.com</a></p>\n",
+
+		"an ftp <ftp://old.com>\n",
+		"<p>an ftp <a href=\"ftp://old.com\">ftp://old.com</a></p>\n",
+
+		"an ftp <ftp:old.com>\n",
+		"<p>an ftp <a href=\"ftp:old.com\">ftp:old.com</a></p>\n",
+
+		"a link with <http://new.com?query=foo&bar>\n",
+		"<p>a link with <a href=\"http://new.com?query=foo&amp;bar\">" +
+			"http://new.com?query=foo&amp;bar</a></p>\n",
+
+		"quotes mean a tag <http://new.com?query=\"foo\"&bar>\n",
+		"<p>quotes mean a tag <http://new.com?query=\"foo\"&bar></p>\n",
+
+		"quotes mean a tag <http://new.com?query='foo'&bar>\n",
+		"<p>quotes mean a tag <http://new.com?query='foo'&bar></p>\n",
+
+		"unless escaped <http://new.com?query=\\\"foo\\\"&bar>\n",
+		"<p>unless escaped <a href=\"http://new.com?query=&quot;foo&quot;&amp;bar\">" +
+			"http://new.com?query=&quot;foo&quot;&amp;bar</a></p>\n",
+
+		"even a > can be escaped <http://new.com?q=\\>&etc>\n",
+		"<p>even a &gt; can be escaped <a href=\"http://new.com?q=&gt;&amp;etc\">" +
+			"http://new.com?q=&gt;&amp;etc</a></p>\n",
+
+		"<a href=\"http://fancy.com\">http://fancy.com</a>\n",
+		"<p><a href=\"http://fancy.com\">http://fancy.com</a></p>\n",
+
+		"<a href=\"http://fancy.com\">This is a link</a>\n",
+		"<p><a href=\"http://fancy.com\">This is a link</a></p>\n",
+
+		"<a href=\"http://www.fancy.com/A_B.pdf\">http://www.fancy.com/A_B.pdf</a>\n",
+		"<p><a href=\"http://www.fancy.com/A_B.pdf\">http://www.fancy.com/A_B.pdf</a></p>\n",
+
+		"(<a href=\"http://www.fancy.com/A_B\">http://www.fancy.com/A_B</a> (\n",
+		"<p>(<a href=\"http://www.fancy.com/A_B\">http://www.fancy.com/A_B</a> (</p>\n",
+
+		"(<a href=\"http://www.fancy.com/A_B\">http://www.fancy.com/A_B</a> (part two: <a href=\"http://www.fancy.com/A_B\">http://www.fancy.com/A_B</a>)).\n",
+		"<p>(<a href=\"http://www.fancy.com/A_B\">http://www.fancy.com/A_B</a> (part two: <a href=\"http://www.fancy.com/A_B\">http://www.fancy.com/A_B</a>)).</p>\n",
+
+		"http://www.foo.com<br />\n",
+		"<p><a href=\"http://www.foo.com\">http://www.foo.com</a><br /></p>\n",
+
+		"http://foo.com/viewtopic.php?f=18&amp;t=297",
+		"<p><a href=\"http://foo.com/viewtopic.php?f=18&amp;t=297\">http://foo.com/viewtopic.php?f=18&amp;t=297</a></p>\n",
+
+		"http://foo.com/viewtopic.php?param=&quot;18&quot;zz",
+		"<p><a href=\"http://foo.com/viewtopic.php?param=&quot;18&quot;zz\">http://foo.com/viewtopic.php?param=&quot;18&quot;zz</a></p>\n",
+
+		"http://foo.com/viewtopic.php?param=&quot;18&quot;",
+		"<p><a href=\"http://foo.com/viewtopic.php?param=&quot;18&quot;\">http://foo.com/viewtopic.php?param=&quot;18&quot;</a></p>\n",
+	}
+	doLinkTestsInline(t, tests)
+}
+
+var footnoteTests = []string{
+	"testing footnotes.[^a]\n\n[^a]: This is the note\n",
+	`<p>testing footnotes.<sup class="footnote-ref" id="fnref:a"><a rel="footnote" href="#fn:a">1</a></sup></p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:a">This is the note
+</li>
+</ol>
+</div>
+`,
+
+	`testing long[^b] notes.
+
+[^b]: Paragraph 1
+
+	Paragraph 2
+
+	` + "```\n\tsome code\n\t```" + `
+
+	Paragraph 3
+
+No longer in the footnote
+`,
+	`<p>testing long<sup class="footnote-ref" id="fnref:b"><a rel="footnote" href="#fn:b">1</a></sup> notes.</p>
+
+<p>No longer in the footnote</p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:b"><p>Paragraph 1</p>
+
+<p>Paragraph 2</p>
+
+<p><code>
+some code
+</code></p>
+
+<p>Paragraph 3</p>
+</li>
+</ol>
+</div>
+`,
+
+	`testing[^c] multiple[^d] notes.
+
+[^c]: this is [note] c
+
+
+omg
+
+[^d]: this is note d
+
+what happens here
+
+[note]: /link/c
+
+`,
+	`<p>testing<sup class="footnote-ref" id="fnref:c"><a rel="footnote" href="#fn:c">1</a></sup> multiple<sup class="footnote-ref" id="fnref:d"><a rel="footnote" href="#fn:d">2</a></sup> notes.</p>
+
+<p>omg</p>
+
+<p>what happens here</p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:c">this is <a href="/link/c">note</a> c
+</li>
+<li id="fn:d">this is note d
+</li>
+</ol>
+</div>
+`,
+
+	"testing inline^[this is the note] notes.\n",
+	`<p>testing inline<sup class="footnote-ref" id="fnref:this-is-the-note"><a rel="footnote" href="#fn:this-is-the-note">1</a></sup> notes.</p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:this-is-the-note">this is the note</li>
+</ol>
+</div>
+`,
+
+	"testing multiple[^1] types^[inline note] of notes[^2]\n\n[^2]: the second deferred note\n[^1]: the first deferred note\n\n\twhich happens to be a block\n",
+	`<p>testing multiple<sup class="footnote-ref" id="fnref:1"><a rel="footnote" href="#fn:1">1</a></sup> types<sup class="footnote-ref" id="fnref:inline-note"><a rel="footnote" href="#fn:inline-note">2</a></sup> of notes<sup class="footnote-ref" id="fnref:2"><a rel="footnote" href="#fn:2">3</a></sup></p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:1"><p>the first deferred note</p>
+
+<p>which happens to be a block</p>
+</li>
+<li id="fn:inline-note">inline note</li>
+<li id="fn:2">the second deferred note
+</li>
+</ol>
+</div>
+`,
+
+	`This is a footnote[^1]^[and this is an inline footnote]
+
+[^1]: the footnote text.
+
+    may be multiple paragraphs.
+`,
+	`<p>This is a footnote<sup class="footnote-ref" id="fnref:1"><a rel="footnote" href="#fn:1">1</a></sup><sup class="footnote-ref" id="fnref:and-this-is-an-i"><a rel="footnote" href="#fn:and-this-is-an-i">2</a></sup></p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:1"><p>the footnote text.</p>
+
+<p>may be multiple paragraphs.</p>
+</li>
+<li id="fn:and-this-is-an-i">and this is an inline footnote</li>
+</ol>
+</div>
+`,
+
+	"empty footnote[^]\n\n[^]: fn text",
+	"<p>empty footnote<sup class=\"footnote-ref\" id=\"fnref:\"><a rel=\"footnote\" href=\"#fn:\">1</a></sup></p>\n<div class=\"footnotes\">\n\n<hr />\n\n<ol>\n<li id=\"fn:\">fn text\n</li>\n</ol>\n</div>\n",
+
+	"Some text.[^note1]\n\n[^note1]: fn1",
+	"<p>Some text.<sup class=\"footnote-ref\" id=\"fnref:note1\"><a rel=\"footnote\" href=\"#fn:note1\">1</a></sup></p>\n<div class=\"footnotes\">\n\n<hr />\n\n<ol>\n<li id=\"fn:note1\">fn1\n</li>\n</ol>\n</div>\n",
+
+	"Some text.[^note1][^note2]\n\n[^note1]: fn1\n[^note2]: fn2\n",
+	"<p>Some text.<sup class=\"footnote-ref\" id=\"fnref:note1\"><a rel=\"footnote\" href=\"#fn:note1\">1</a></sup><sup class=\"footnote-ref\" id=\"fnref:note2\"><a rel=\"footnote\" href=\"#fn:note2\">2</a></sup></p>\n<div class=\"footnotes\">\n\n<hr />\n\n<ol>\n<li id=\"fn:note1\">fn1\n</li>\n<li id=\"fn:note2\">fn2\n</li>\n</ol>\n</div>\n",
+
+	`Bla bla [^1] [WWW][w3]
+
+[^1]: This is a footnote
+
+[w3]: http://www.w3.org/
+`,
+	`<p>Bla bla <sup class="footnote-ref" id="fnref:1"><a rel="footnote" href="#fn:1">1</a></sup> <a href="http://www.w3.org/">WWW</a></p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:1">This is a footnote
+</li>
+</ol>
+</div>
+`,
+
+	`This is exciting![^fn1]
+
+[^fn1]: Fine print
+`,
+	`<p>This is exciting!<sup class="footnote-ref" id="fnref:fn1"><a rel="footnote" href="#fn:fn1">1</a></sup></p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:fn1">Fine print
+</li>
+</ol>
+</div>
+`,
+}
+
+func TestFootnotes(t *testing.T) {
+	doTestsInlineParam(t, footnoteTests, Options{Extensions: EXTENSION_FOOTNOTES}, 0, HtmlRendererParameters{})
+}
+
+func TestFootnotesWithParameters(t *testing.T) {
+	tests := make([]string, len(footnoteTests))
+
+	prefix := "testPrefix"
+	returnText := "ret"
+	re := regexp.MustCompile(`(?ms)<li id="fn:(\S+?)">(.*?)</li>`)
+
+	// Transform the test expectations to match the parameters we're using.
+	for i, test := range footnoteTests {
+		if i%2 == 1 {
+			test = strings.Replace(test, "fn:", "fn:"+prefix, -1)
+			test = strings.Replace(test, "fnref:", "fnref:"+prefix, -1)
+			test = re.ReplaceAllString(test, `<li id="fn:$1">$2 <a class="footnote-return" href="#fnref:$1">ret</a></li>`)
+		}
+		tests[i] = test
+	}
+
+	params := HtmlRendererParameters{
+		FootnoteAnchorPrefix:       prefix,
+		FootnoteReturnLinkContents: returnText,
+	}
+
+	doTestsInlineParam(t, tests, Options{Extensions: EXTENSION_FOOTNOTES}, HTML_FOOTNOTE_RETURN_LINKS, params)
+}
+
+func TestNestedFootnotes(t *testing.T) {
+	var tests = []string{
+		`Paragraph.[^fn1]
+
+[^fn1]:
+  Asterisk[^fn2]
+
+[^fn2]:
+  Obelisk`,
+		`<p>Paragraph.<sup class="footnote-ref" id="fnref:fn1"><a rel="footnote" href="#fn:fn1">1</a></sup></p>
+<div class="footnotes">
+
+<hr />
+
+<ol>
+<li id="fn:fn1">Asterisk<sup class="footnote-ref" id="fnref:fn2"><a rel="footnote" href="#fn:fn2">2</a></sup>
+</li>
+<li id="fn:fn2">Obelisk
+</li>
+</ol>
+</div>
+`,
+	}
+	doTestsInlineParam(t, tests, Options{Extensions: EXTENSION_FOOTNOTES}, 0,
+		HtmlRendererParameters{})
+}
+
+func TestInlineComments(t *testing.T) {
+	var tests = []string{
+		"Hello <!-- there ->\n",
+		"<p>Hello &lt;!&mdash; there &ndash;&gt;</p>\n",
+
+		"Hello <!-- there -->\n",
+		"<p>Hello <!-- there --></p>\n",
+
+		"Hello <!-- there -->",
+		"<p>Hello <!-- there --></p>\n",
+
+		"Hello <!---->\n",
+		"<p>Hello <!----></p>\n",
+
+		"Hello <!-- there -->\na",
+		"<p>Hello <!-- there -->\na</p>\n",
+
+		"* list <!-- item -->\n",
+		"<ul>\n<li>list <!-- item --></li>\n</ul>\n",
+
+		"<!-- Front --> comment\n",
+		"<p><!-- Front --> comment</p>\n",
+
+		"blahblah\n<!--- foo -->\nrhubarb\n",
+		"<p>blahblah\n<!--- foo -->\nrhubarb</p>\n",
+	}
+	doTestsInlineParam(t, tests, Options{}, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_DASHES, HtmlRendererParameters{})
+}
+
+func TestSmartDoubleQuotes(t *testing.T) {
+	var tests = []string{
+		"this should be normal \"quoted\" text.\n",
+		"<p>this should be normal &ldquo;quoted&rdquo; text.</p>\n",
+		"this \" single double\n",
+		"<p>this &ldquo; single double</p>\n",
+		"two pair of \"some\" quoted \"text\".\n",
+		"<p>two pair of &ldquo;some&rdquo; quoted &ldquo;text&rdquo;.</p>\n"}
+
+	doTestsInlineParam(t, tests, Options{}, HTML_USE_SMARTYPANTS, HtmlRendererParameters{})
+}
+
+func TestSmartAngledDoubleQuotes(t *testing.T) {
+	var tests = []string{
+		"this should be angled \"quoted\" text.\n",
+		"<p>this should be angled &laquo;quoted&raquo; text.</p>\n",
+		"this \" single double\n",
+		"<p>this &laquo; single double</p>\n",
+		"two pair of \"some\" quoted \"text\".\n",
+		"<p>two pair of &laquo;some&raquo; quoted &laquo;text&raquo;.</p>\n"}
+
+	doTestsInlineParam(t, tests, Options{}, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_ANGLED_QUOTES, HtmlRendererParameters{})
+}
+
+func TestSmartFractions(t *testing.T) {
+	var tests = []string{
+		"1/2, 1/4 and 3/4; 1/4th and 3/4ths\n",
+		"<p>&frac12;, &frac14; and &frac34;; &frac14;th and &frac34;ths</p>\n",
+		"1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.\n",
+		"<p>1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.</p>\n"}
+
+	doTestsInlineParam(t, tests, Options{}, HTML_USE_SMARTYPANTS, HtmlRendererParameters{})
+
+	tests = []string{
+		"1/2, 2/3, 81/100 and 1000000/1048576.\n",
+		"<p><sup>1</sup>&frasl;<sub>2</sub>, <sup>2</sup>&frasl;<sub>3</sub>, <sup>81</sup>&frasl;<sub>100</sub> and <sup>1000000</sup>&frasl;<sub>1048576</sub>.</p>\n",
+		"1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.\n",
+		"<p>1/2/2015, 1/4/2015, 3/4/2015; 2015/1/2, 2015/1/4, 2015/3/4.</p>\n"}
+
+	doTestsInlineParam(t, tests, Options{}, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_FRACTIONS, HtmlRendererParameters{})
+}
+
+func TestDisableSmartDashes(t *testing.T) {
+	doTestsInlineParam(t, []string{
+		"foo - bar\n",
+		"<p>foo - bar</p>\n",
+		"foo -- bar\n",
+		"<p>foo -- bar</p>\n",
+		"foo --- bar\n",
+		"<p>foo --- bar</p>\n",
+	}, Options{}, 0, HtmlRendererParameters{})
+	doTestsInlineParam(t, []string{
+		"foo - bar\n",
+		"<p>foo &ndash; bar</p>\n",
+		"foo -- bar\n",
+		"<p>foo &mdash; bar</p>\n",
+		"foo --- bar\n",
+		"<p>foo &mdash;&ndash; bar</p>\n",
+	}, Options{}, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_DASHES, HtmlRendererParameters{})
+	doTestsInlineParam(t, []string{
+		"foo - bar\n",
+		"<p>foo - bar</p>\n",
+		"foo -- bar\n",
+		"<p>foo &ndash; bar</p>\n",
+		"foo --- bar\n",
+		"<p>foo &mdash; bar</p>\n",
+	}, Options{}, HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_LATEX_DASHES|HTML_SMARTYPANTS_DASHES,
+		HtmlRendererParameters{})
+	doTestsInlineParam(t, []string{
+		"foo - bar\n",
+		"<p>foo - bar</p>\n",
+		"foo -- bar\n",
+		"<p>foo -- bar</p>\n",
+		"foo --- bar\n",
+		"<p>foo --- bar</p>\n",
+	}, Options{},
+		HTML_USE_SMARTYPANTS|HTML_SMARTYPANTS_LATEX_DASHES,
+		HtmlRendererParameters{})
+}

+ 332 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/latex.go

@@ -0,0 +1,332 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+//
+// LaTeX rendering backend
+//
+//
+
+package blackfriday
+
+import (
+	"bytes"
+)
+
+// Latex is a type that implements the Renderer interface for LaTeX output.
+//
+// Do not create this directly, instead use the LatexRenderer function.
+type Latex struct {
+}
+
+// LatexRenderer creates and configures a Latex object, which
+// satisfies the Renderer interface.
+//
+// flags is a set of LATEX_* options ORed together (currently no such options
+// are defined).
+func LatexRenderer(flags int) Renderer {
+	return &Latex{}
+}
+
+func (options *Latex) GetFlags() int {
+	return 0
+}
+
+// render code chunks using verbatim, or listings if we have a language
+func (options *Latex) BlockCode(out *bytes.Buffer, text []byte, lang string) {
+	if lang == "" {
+		out.WriteString("\n\\begin{verbatim}\n")
+	} else {
+		out.WriteString("\n\\begin{lstlisting}[language=")
+		out.WriteString(lang)
+		out.WriteString("]\n")
+	}
+	out.Write(text)
+	if lang == "" {
+		out.WriteString("\n\\end{verbatim}\n")
+	} else {
+		out.WriteString("\n\\end{lstlisting}\n")
+	}
+}
+
+func (options *Latex) TitleBlock(out *bytes.Buffer, text []byte) {
+
+}
+
+func (options *Latex) BlockQuote(out *bytes.Buffer, text []byte) {
+	out.WriteString("\n\\begin{quotation}\n")
+	out.Write(text)
+	out.WriteString("\n\\end{quotation}\n")
+}
+
+func (options *Latex) BlockHtml(out *bytes.Buffer, text []byte) {
+	// a pretty lame thing to do...
+	out.WriteString("\n\\begin{verbatim}\n")
+	out.Write(text)
+	out.WriteString("\n\\end{verbatim}\n")
+}
+
+func (options *Latex) Header(out *bytes.Buffer, text func() bool, level int, id string) {
+	marker := out.Len()
+
+	switch level {
+	case 1:
+		out.WriteString("\n\\section{")
+	case 2:
+		out.WriteString("\n\\subsection{")
+	case 3:
+		out.WriteString("\n\\subsubsection{")
+	case 4:
+		out.WriteString("\n\\paragraph{")
+	case 5:
+		out.WriteString("\n\\subparagraph{")
+	case 6:
+		out.WriteString("\n\\textbf{")
+	}
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+	out.WriteString("}\n")
+}
+
+func (options *Latex) HRule(out *bytes.Buffer) {
+	out.WriteString("\n\\HRule\n")
+}
+
+func (options *Latex) List(out *bytes.Buffer, text func() bool, flags int) {
+	marker := out.Len()
+	if flags&LIST_TYPE_ORDERED != 0 {
+		out.WriteString("\n\\begin{enumerate}\n")
+	} else {
+		out.WriteString("\n\\begin{itemize}\n")
+	}
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+	if flags&LIST_TYPE_ORDERED != 0 {
+		out.WriteString("\n\\end{enumerate}\n")
+	} else {
+		out.WriteString("\n\\end{itemize}\n")
+	}
+}
+
+func (options *Latex) ListItem(out *bytes.Buffer, text []byte, flags int) {
+	out.WriteString("\n\\item ")
+	out.Write(text)
+}
+
+func (options *Latex) Paragraph(out *bytes.Buffer, text func() bool) {
+	marker := out.Len()
+	out.WriteString("\n")
+	if !text() {
+		out.Truncate(marker)
+		return
+	}
+	out.WriteString("\n")
+}
+
+func (options *Latex) Table(out *bytes.Buffer, header []byte, body []byte, columnData []int) {
+	out.WriteString("\n\\begin{tabular}{")
+	for _, elt := range columnData {
+		switch elt {
+		case TABLE_ALIGNMENT_LEFT:
+			out.WriteByte('l')
+		case TABLE_ALIGNMENT_RIGHT:
+			out.WriteByte('r')
+		default:
+			out.WriteByte('c')
+		}
+	}
+	out.WriteString("}\n")
+	out.Write(header)
+	out.WriteString(" \\\\\n\\hline\n")
+	out.Write(body)
+	out.WriteString("\n\\end{tabular}\n")
+}
+
+func (options *Latex) TableRow(out *bytes.Buffer, text []byte) {
+	if out.Len() > 0 {
+		out.WriteString(" \\\\\n")
+	}
+	out.Write(text)
+}
+
+func (options *Latex) TableHeaderCell(out *bytes.Buffer, text []byte, align int) {
+	if out.Len() > 0 {
+		out.WriteString(" & ")
+	}
+	out.Write(text)
+}
+
+func (options *Latex) TableCell(out *bytes.Buffer, text []byte, align int) {
+	if out.Len() > 0 {
+		out.WriteString(" & ")
+	}
+	out.Write(text)
+}
+
+// TODO: this
+func (options *Latex) Footnotes(out *bytes.Buffer, text func() bool) {
+
+}
+
+func (options *Latex) FootnoteItem(out *bytes.Buffer, name, text []byte, flags int) {
+
+}
+
+func (options *Latex) AutoLink(out *bytes.Buffer, link []byte, kind int) {
+	out.WriteString("\\href{")
+	if kind == LINK_TYPE_EMAIL {
+		out.WriteString("mailto:")
+	}
+	out.Write(link)
+	out.WriteString("}{")
+	out.Write(link)
+	out.WriteString("}")
+}
+
+func (options *Latex) CodeSpan(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\texttt{")
+	escapeSpecialChars(out, text)
+	out.WriteString("}")
+}
+
+func (options *Latex) DoubleEmphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\textbf{")
+	out.Write(text)
+	out.WriteString("}")
+}
+
+func (options *Latex) Emphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\textit{")
+	out.Write(text)
+	out.WriteString("}")
+}
+
+func (options *Latex) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte) {
+	if bytes.HasPrefix(link, []byte("http://")) || bytes.HasPrefix(link, []byte("https://")) {
+		// treat it like a link
+		out.WriteString("\\href{")
+		out.Write(link)
+		out.WriteString("}{")
+		out.Write(alt)
+		out.WriteString("}")
+	} else {
+		out.WriteString("\\includegraphics{")
+		out.Write(link)
+		out.WriteString("}")
+	}
+}
+
+func (options *Latex) LineBreak(out *bytes.Buffer) {
+	out.WriteString(" \\\\\n")
+}
+
+func (options *Latex) Link(out *bytes.Buffer, link []byte, title []byte, content []byte) {
+	out.WriteString("\\href{")
+	out.Write(link)
+	out.WriteString("}{")
+	out.Write(content)
+	out.WriteString("}")
+}
+
+func (options *Latex) RawHtmlTag(out *bytes.Buffer, tag []byte) {
+}
+
+func (options *Latex) TripleEmphasis(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\textbf{\\textit{")
+	out.Write(text)
+	out.WriteString("}}")
+}
+
+func (options *Latex) StrikeThrough(out *bytes.Buffer, text []byte) {
+	out.WriteString("\\sout{")
+	out.Write(text)
+	out.WriteString("}")
+}
+
+// TODO: this
+func (options *Latex) FootnoteRef(out *bytes.Buffer, ref []byte, id int) {
+
+}
+
+func needsBackslash(c byte) bool {
+	for _, r := range []byte("_{}%$&\\~#") {
+		if c == r {
+			return true
+		}
+	}
+	return false
+}
+
+func escapeSpecialChars(out *bytes.Buffer, text []byte) {
+	for i := 0; i < len(text); i++ {
+		// directly copy normal characters
+		org := i
+
+		for i < len(text) && !needsBackslash(text[i]) {
+			i++
+		}
+		if i > org {
+			out.Write(text[org:i])
+		}
+
+		// escape a character
+		if i >= len(text) {
+			break
+		}
+		out.WriteByte('\\')
+		out.WriteByte(text[i])
+	}
+}
+
+func (options *Latex) Entity(out *bytes.Buffer, entity []byte) {
+	// TODO: convert this into a unicode character or something
+	out.Write(entity)
+}
+
+func (options *Latex) NormalText(out *bytes.Buffer, text []byte) {
+	escapeSpecialChars(out, text)
+}
+
+// header and footer
+func (options *Latex) DocumentHeader(out *bytes.Buffer) {
+	out.WriteString("\\documentclass{article}\n")
+	out.WriteString("\n")
+	out.WriteString("\\usepackage{graphicx}\n")
+	out.WriteString("\\usepackage{listings}\n")
+	out.WriteString("\\usepackage[margin=1in]{geometry}\n")
+	out.WriteString("\\usepackage[utf8]{inputenc}\n")
+	out.WriteString("\\usepackage{verbatim}\n")
+	out.WriteString("\\usepackage[normalem]{ulem}\n")
+	out.WriteString("\\usepackage{hyperref}\n")
+	out.WriteString("\n")
+	out.WriteString("\\hypersetup{colorlinks,%\n")
+	out.WriteString("  citecolor=black,%\n")
+	out.WriteString("  filecolor=black,%\n")
+	out.WriteString("  linkcolor=black,%\n")
+	out.WriteString("  urlcolor=black,%\n")
+	out.WriteString("  pdfstartview=FitH,%\n")
+	out.WriteString("  breaklinks=true,%\n")
+	out.WriteString("  pdfauthor={Blackfriday Markdown Processor v")
+	out.WriteString(VERSION)
+	out.WriteString("}}\n")
+	out.WriteString("\n")
+	out.WriteString("\\newcommand{\\HRule}{\\rule{\\linewidth}{0.5mm}}\n")
+	out.WriteString("\\addtolength{\\parskip}{0.5\\baselineskip}\n")
+	out.WriteString("\\parindent=0pt\n")
+	out.WriteString("\n")
+	out.WriteString("\\begin{document}\n")
+}
+
+func (options *Latex) DocumentFooter(out *bytes.Buffer) {
+	out.WriteString("\n\\end{document}\n")
+}

+ 926 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/markdown.go

@@ -0,0 +1,926 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+//
+// Markdown parsing and processing
+//
+//
+
+// Blackfriday markdown processor.
+//
+// Translates plain text with simple formatting rules into HTML or LaTeX.
+package blackfriday
+
+import (
+	"bytes"
+	"fmt"
+	"strings"
+	"unicode/utf8"
+)
+
+const VERSION = "1.4"
+
+// These are the supported markdown parsing extensions.
+// OR these values together to select multiple extensions.
+const (
+	EXTENSION_NO_INTRA_EMPHASIS          = 1 << iota // ignore emphasis markers inside words
+	EXTENSION_TABLES                                 // render tables
+	EXTENSION_FENCED_CODE                            // render fenced code blocks
+	EXTENSION_AUTOLINK                               // detect embedded URLs that are not explicitly marked
+	EXTENSION_STRIKETHROUGH                          // strikethrough text using ~~test~~
+	EXTENSION_LAX_HTML_BLOCKS                        // loosen up HTML block parsing rules
+	EXTENSION_SPACE_HEADERS                          // be strict about prefix header rules
+	EXTENSION_HARD_LINE_BREAK                        // translate newlines into line breaks
+	EXTENSION_TAB_SIZE_EIGHT                         // expand tabs to eight spaces instead of four
+	EXTENSION_FOOTNOTES                              // Pandoc-style footnotes
+	EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK             // No need to insert an empty line to start a (code, quote, ordered list, unordered list) block
+	EXTENSION_HEADER_IDS                             // specify header IDs  with {#id}
+	EXTENSION_TITLEBLOCK                             // Titleblock ala pandoc
+	EXTENSION_AUTO_HEADER_IDS                        // Create the header ID from the text
+	EXTENSION_BACKSLASH_LINE_BREAK                   // translate trailing backslashes into line breaks
+	EXTENSION_DEFINITION_LISTS                       // render definition lists
+
+	commonHtmlFlags = 0 |
+		HTML_USE_XHTML |
+		HTML_USE_SMARTYPANTS |
+		HTML_SMARTYPANTS_FRACTIONS |
+		HTML_SMARTYPANTS_DASHES |
+		HTML_SMARTYPANTS_LATEX_DASHES
+
+	commonExtensions = 0 |
+		EXTENSION_NO_INTRA_EMPHASIS |
+		EXTENSION_TABLES |
+		EXTENSION_FENCED_CODE |
+		EXTENSION_AUTOLINK |
+		EXTENSION_STRIKETHROUGH |
+		EXTENSION_SPACE_HEADERS |
+		EXTENSION_HEADER_IDS |
+		EXTENSION_BACKSLASH_LINE_BREAK |
+		EXTENSION_DEFINITION_LISTS
+)
+
+// These are the possible flag values for the link renderer.
+// Only a single one of these values will be used; they are not ORed together.
+// These are mostly of interest if you are writing a new output format.
+const (
+	LINK_TYPE_NOT_AUTOLINK = iota
+	LINK_TYPE_NORMAL
+	LINK_TYPE_EMAIL
+)
+
+// These are the possible flag values for the ListItem renderer.
+// Multiple flag values may be ORed together.
+// These are mostly of interest if you are writing a new output format.
+const (
+	LIST_TYPE_ORDERED = 1 << iota
+	LIST_TYPE_DEFINITION
+	LIST_TYPE_TERM
+	LIST_ITEM_CONTAINS_BLOCK
+	LIST_ITEM_BEGINNING_OF_LIST
+	LIST_ITEM_END_OF_LIST
+)
+
+// These are the possible flag values for the table cell renderer.
+// Only a single one of these values will be used; they are not ORed together.
+// These are mostly of interest if you are writing a new output format.
+const (
+	TABLE_ALIGNMENT_LEFT = 1 << iota
+	TABLE_ALIGNMENT_RIGHT
+	TABLE_ALIGNMENT_CENTER = (TABLE_ALIGNMENT_LEFT | TABLE_ALIGNMENT_RIGHT)
+)
+
+// The size of a tab stop.
+const (
+	TAB_SIZE_DEFAULT = 4
+	TAB_SIZE_EIGHT   = 8
+)
+
+// blockTags is a set of tags that are recognized as HTML block tags.
+// Any of these can be included in markdown text without special escaping.
+var blockTags = map[string]struct{}{
+	"blockquote": struct{}{},
+	"del":        struct{}{},
+	"div":        struct{}{},
+	"dl":         struct{}{},
+	"fieldset":   struct{}{},
+	"form":       struct{}{},
+	"h1":         struct{}{},
+	"h2":         struct{}{},
+	"h3":         struct{}{},
+	"h4":         struct{}{},
+	"h5":         struct{}{},
+	"h6":         struct{}{},
+	"iframe":     struct{}{},
+	"ins":        struct{}{},
+	"math":       struct{}{},
+	"noscript":   struct{}{},
+	"ol":         struct{}{},
+	"pre":        struct{}{},
+	"p":          struct{}{},
+	"script":     struct{}{},
+	"style":      struct{}{},
+	"table":      struct{}{},
+	"ul":         struct{}{},
+
+	// HTML5
+	"address":    struct{}{},
+	"article":    struct{}{},
+	"aside":      struct{}{},
+	"canvas":     struct{}{},
+	"figcaption": struct{}{},
+	"figure":     struct{}{},
+	"footer":     struct{}{},
+	"header":     struct{}{},
+	"hgroup":     struct{}{},
+	"main":       struct{}{},
+	"nav":        struct{}{},
+	"output":     struct{}{},
+	"progress":   struct{}{},
+	"section":    struct{}{},
+	"video":      struct{}{},
+}
+
+// Renderer is the rendering interface.
+// This is mostly of interest if you are implementing a new rendering format.
+//
+// When a byte slice is provided, it contains the (rendered) contents of the
+// element.
+//
+// When a callback is provided instead, it will write the contents of the
+// respective element directly to the output buffer and return true on success.
+// If the callback returns false, the rendering function should reset the
+// output buffer as though it had never been called.
+//
+// Currently Html and Latex implementations are provided
+type Renderer interface {
+	// block-level callbacks
+	BlockCode(out *bytes.Buffer, text []byte, lang string)
+	BlockQuote(out *bytes.Buffer, text []byte)
+	BlockHtml(out *bytes.Buffer, text []byte)
+	Header(out *bytes.Buffer, text func() bool, level int, id string)
+	HRule(out *bytes.Buffer)
+	List(out *bytes.Buffer, text func() bool, flags int)
+	ListItem(out *bytes.Buffer, text []byte, flags int)
+	Paragraph(out *bytes.Buffer, text func() bool)
+	Table(out *bytes.Buffer, header []byte, body []byte, columnData []int)
+	TableRow(out *bytes.Buffer, text []byte)
+	TableHeaderCell(out *bytes.Buffer, text []byte, flags int)
+	TableCell(out *bytes.Buffer, text []byte, flags int)
+	Footnotes(out *bytes.Buffer, text func() bool)
+	FootnoteItem(out *bytes.Buffer, name, text []byte, flags int)
+	TitleBlock(out *bytes.Buffer, text []byte)
+
+	// Span-level callbacks
+	AutoLink(out *bytes.Buffer, link []byte, kind int)
+	CodeSpan(out *bytes.Buffer, text []byte)
+	DoubleEmphasis(out *bytes.Buffer, text []byte)
+	Emphasis(out *bytes.Buffer, text []byte)
+	Image(out *bytes.Buffer, link []byte, title []byte, alt []byte)
+	LineBreak(out *bytes.Buffer)
+	Link(out *bytes.Buffer, link []byte, title []byte, content []byte)
+	RawHtmlTag(out *bytes.Buffer, tag []byte)
+	TripleEmphasis(out *bytes.Buffer, text []byte)
+	StrikeThrough(out *bytes.Buffer, text []byte)
+	FootnoteRef(out *bytes.Buffer, ref []byte, id int)
+
+	// Low-level callbacks
+	Entity(out *bytes.Buffer, entity []byte)
+	NormalText(out *bytes.Buffer, text []byte)
+
+	// Header and footer
+	DocumentHeader(out *bytes.Buffer)
+	DocumentFooter(out *bytes.Buffer)
+
+	GetFlags() int
+}
+
+// Callback functions for inline parsing. One such function is defined
+// for each character that triggers a response when parsing inline data.
+type inlineParser func(p *parser, out *bytes.Buffer, data []byte, offset int) int
+
+// Parser holds runtime state used by the parser.
+// This is constructed by the Markdown function.
+type parser struct {
+	r              Renderer
+	refOverride    ReferenceOverrideFunc
+	refs           map[string]*reference
+	inlineCallback [256]inlineParser
+	flags          int
+	nesting        int
+	maxNesting     int
+	insideLink     bool
+
+	// Footnotes need to be ordered as well as available to quickly check for
+	// presence. If a ref is also a footnote, it's stored both in refs and here
+	// in notes. Slice is nil if footnotes not enabled.
+	notes []*reference
+}
+
+func (p *parser) getRef(refid string) (ref *reference, found bool) {
+	if p.refOverride != nil {
+		r, overridden := p.refOverride(refid)
+		if overridden {
+			if r == nil {
+				return nil, false
+			}
+			return &reference{
+				link:     []byte(r.Link),
+				title:    []byte(r.Title),
+				noteId:   0,
+				hasBlock: false,
+				text:     []byte(r.Text)}, true
+		}
+	}
+	// refs are case insensitive
+	ref, found = p.refs[strings.ToLower(refid)]
+	return ref, found
+}
+
+//
+//
+// Public interface
+//
+//
+
+// Reference represents the details of a link.
+// See the documentation in Options for more details on use-case.
+type Reference struct {
+	// Link is usually the URL the reference points to.
+	Link string
+	// Title is the alternate text describing the link in more detail.
+	Title string
+	// Text is the optional text to override the ref with if the syntax used was
+	// [refid][]
+	Text string
+}
+
+// ReferenceOverrideFunc is expected to be called with a reference string and
+// return either a valid Reference type that the reference string maps to or
+// nil. If overridden is false, the default reference logic will be executed.
+// See the documentation in Options for more details on use-case.
+type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool)
+
+// Options represents configurable overrides and callbacks (in addition to the
+// extension flag set) for configuring a Markdown parse.
+type Options struct {
+	// Extensions is a flag set of bit-wise ORed extension bits. See the
+	// EXTENSION_* flags defined in this package.
+	Extensions int
+
+	// ReferenceOverride is an optional function callback that is called every
+	// time a reference is resolved.
+	//
+	// In Markdown, the link reference syntax can be made to resolve a link to
+	// a reference instead of an inline URL, in one of the following ways:
+	//
+	//  * [link text][refid]
+	//  * [refid][]
+	//
+	// Usually, the refid is defined at the bottom of the Markdown document. If
+	// this override function is provided, the refid is passed to the override
+	// function first, before consulting the defined refids at the bottom. If
+	// the override function indicates an override did not occur, the refids at
+	// the bottom will be used to fill in the link details.
+	ReferenceOverride ReferenceOverrideFunc
+}
+
+// MarkdownBasic is a convenience function for simple rendering.
+// It processes markdown input with no extensions enabled.
+func MarkdownBasic(input []byte) []byte {
+	// set up the HTML renderer
+	htmlFlags := HTML_USE_XHTML
+	renderer := HtmlRenderer(htmlFlags, "", "")
+
+	// set up the parser
+	return MarkdownOptions(input, renderer, Options{Extensions: 0})
+}
+
+// Call Markdown with most useful extensions enabled
+// MarkdownCommon is a convenience function for simple rendering.
+// It processes markdown input with common extensions enabled, including:
+//
+// * Smartypants processing with smart fractions and LaTeX dashes
+//
+// * Intra-word emphasis suppression
+//
+// * Tables
+//
+// * Fenced code blocks
+//
+// * Autolinking
+//
+// * Strikethrough support
+//
+// * Strict header parsing
+//
+// * Custom Header IDs
+func MarkdownCommon(input []byte) []byte {
+	// set up the HTML renderer
+	renderer := HtmlRenderer(commonHtmlFlags, "", "")
+	return MarkdownOptions(input, renderer, Options{
+		Extensions: commonExtensions})
+}
+
+// Markdown is the main rendering function.
+// It parses and renders a block of markdown-encoded text.
+// The supplied Renderer is used to format the output, and extensions dictates
+// which non-standard extensions are enabled.
+//
+// To use the supplied Html or LaTeX renderers, see HtmlRenderer and
+// LatexRenderer, respectively.
+func Markdown(input []byte, renderer Renderer, extensions int) []byte {
+	return MarkdownOptions(input, renderer, Options{
+		Extensions: extensions})
+}
+
+// MarkdownOptions is just like Markdown but takes additional options through
+// the Options struct.
+func MarkdownOptions(input []byte, renderer Renderer, opts Options) []byte {
+	// no point in parsing if we can't render
+	if renderer == nil {
+		return nil
+	}
+
+	extensions := opts.Extensions
+
+	// fill in the render structure
+	p := new(parser)
+	p.r = renderer
+	p.flags = extensions
+	p.refOverride = opts.ReferenceOverride
+	p.refs = make(map[string]*reference)
+	p.maxNesting = 16
+	p.insideLink = false
+
+	// register inline parsers
+	p.inlineCallback['*'] = emphasis
+	p.inlineCallback['_'] = emphasis
+	if extensions&EXTENSION_STRIKETHROUGH != 0 {
+		p.inlineCallback['~'] = emphasis
+	}
+	p.inlineCallback['`'] = codeSpan
+	p.inlineCallback['\n'] = lineBreak
+	p.inlineCallback['['] = link
+	p.inlineCallback['<'] = leftAngle
+	p.inlineCallback['\\'] = escape
+	p.inlineCallback['&'] = entity
+
+	if extensions&EXTENSION_AUTOLINK != 0 {
+		p.inlineCallback[':'] = autoLink
+	}
+
+	if extensions&EXTENSION_FOOTNOTES != 0 {
+		p.notes = make([]*reference, 0)
+	}
+
+	first := firstPass(p, input)
+	second := secondPass(p, first)
+	return second
+}
+
+// first pass:
+// - extract references
+// - expand tabs
+// - normalize newlines
+// - copy everything else
+func firstPass(p *parser, input []byte) []byte {
+	var out bytes.Buffer
+	tabSize := TAB_SIZE_DEFAULT
+	if p.flags&EXTENSION_TAB_SIZE_EIGHT != 0 {
+		tabSize = TAB_SIZE_EIGHT
+	}
+	beg, end := 0, 0
+	lastFencedCodeBlockEnd := 0
+	for beg < len(input) { // iterate over lines
+		if end = isReference(p, input[beg:], tabSize); end > 0 {
+			beg += end
+		} else { // skip to the next line
+			end = beg
+			for end < len(input) && input[end] != '\n' && input[end] != '\r' {
+				end++
+			}
+
+			if p.flags&EXTENSION_FENCED_CODE != 0 {
+				// track fenced code block boundaries to suppress tab expansion
+				// inside them:
+				if beg >= lastFencedCodeBlockEnd {
+					if i := p.fencedCode(&out, input[beg:], false); i > 0 {
+						lastFencedCodeBlockEnd = beg + i
+					}
+				}
+			}
+
+			// add the line body if present
+			if end > beg {
+				if end < lastFencedCodeBlockEnd { // Do not expand tabs while inside fenced code blocks.
+					out.Write(input[beg:end])
+				} else {
+					expandTabs(&out, input[beg:end], tabSize)
+				}
+			}
+			out.WriteByte('\n')
+
+			if end < len(input) && input[end] == '\r' {
+				end++
+			}
+			if end < len(input) && input[end] == '\n' {
+				end++
+			}
+
+			beg = end
+		}
+	}
+
+	// empty input?
+	if out.Len() == 0 {
+		out.WriteByte('\n')
+	}
+
+	return out.Bytes()
+}
+
+// second pass: actual rendering
+func secondPass(p *parser, input []byte) []byte {
+	var output bytes.Buffer
+
+	p.r.DocumentHeader(&output)
+	p.block(&output, input)
+
+	if p.flags&EXTENSION_FOOTNOTES != 0 && len(p.notes) > 0 {
+		p.r.Footnotes(&output, func() bool {
+			flags := LIST_ITEM_BEGINNING_OF_LIST
+			for i := 0; i < len(p.notes); i += 1 {
+				ref := p.notes[i]
+				var buf bytes.Buffer
+				if ref.hasBlock {
+					flags |= LIST_ITEM_CONTAINS_BLOCK
+					p.block(&buf, ref.title)
+				} else {
+					p.inline(&buf, ref.title)
+				}
+				p.r.FootnoteItem(&output, ref.link, buf.Bytes(), flags)
+				flags &^= LIST_ITEM_BEGINNING_OF_LIST | LIST_ITEM_CONTAINS_BLOCK
+			}
+
+			return true
+		})
+	}
+
+	p.r.DocumentFooter(&output)
+
+	if p.nesting != 0 {
+		panic("Nesting level did not end at zero")
+	}
+
+	return output.Bytes()
+}
+
+//
+// Link references
+//
+// This section implements support for references that (usually) appear
+// as footnotes in a document, and can be referenced anywhere in the document.
+// The basic format is:
+//
+//    [1]: http://www.google.com/ "Google"
+//    [2]: http://www.github.com/ "Github"
+//
+// Anywhere in the document, the reference can be linked by referring to its
+// label, i.e., 1 and 2 in this example, as in:
+//
+//    This library is hosted on [Github][2], a git hosting site.
+//
+// Actual footnotes as specified in Pandoc and supported by some other Markdown
+// libraries such as php-markdown are also taken care of. They look like this:
+//
+//    This sentence needs a bit of further explanation.[^note]
+//
+//    [^note]: This is the explanation.
+//
+// Footnotes should be placed at the end of the document in an ordered list.
+// Inline footnotes such as:
+//
+//    Inline footnotes^[Not supported.] also exist.
+//
+// are not yet supported.
+
+// References are parsed and stored in this struct.
+type reference struct {
+	link     []byte
+	title    []byte
+	noteId   int // 0 if not a footnote ref
+	hasBlock bool
+	text     []byte
+}
+
+func (r *reference) String() string {
+	return fmt.Sprintf("{link: %q, title: %q, text: %q, noteId: %d, hasBlock: %v}",
+		r.link, r.title, r.text, r.noteId, r.hasBlock)
+}
+
+// Check whether or not data starts with a reference link.
+// If so, it is parsed and stored in the list of references
+// (in the render struct).
+// Returns the number of bytes to skip to move past it,
+// or zero if the first line is not a reference.
+func isReference(p *parser, data []byte, tabSize int) int {
+	// up to 3 optional leading spaces
+	if len(data) < 4 {
+		return 0
+	}
+	i := 0
+	for i < 3 && data[i] == ' ' {
+		i++
+	}
+
+	noteId := 0
+
+	// id part: anything but a newline between brackets
+	if data[i] != '[' {
+		return 0
+	}
+	i++
+	if p.flags&EXTENSION_FOOTNOTES != 0 {
+		if i < len(data) && data[i] == '^' {
+			// we can set it to anything here because the proper noteIds will
+			// be assigned later during the second pass. It just has to be != 0
+			noteId = 1
+			i++
+		}
+	}
+	idOffset := i
+	for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' {
+		i++
+	}
+	if i >= len(data) || data[i] != ']' {
+		return 0
+	}
+	idEnd := i
+
+	// spacer: colon (space | tab)* newline? (space | tab)*
+	i++
+	if i >= len(data) || data[i] != ':' {
+		return 0
+	}
+	i++
+	for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
+		i++
+	}
+	if i < len(data) && (data[i] == '\n' || data[i] == '\r') {
+		i++
+		if i < len(data) && data[i] == '\n' && data[i-1] == '\r' {
+			i++
+		}
+	}
+	for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
+		i++
+	}
+	if i >= len(data) {
+		return 0
+	}
+
+	var (
+		linkOffset, linkEnd   int
+		titleOffset, titleEnd int
+		lineEnd               int
+		raw                   []byte
+		hasBlock              bool
+	)
+
+	if p.flags&EXTENSION_FOOTNOTES != 0 && noteId != 0 {
+		linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize)
+		lineEnd = linkEnd
+	} else {
+		linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i)
+	}
+	if lineEnd == 0 {
+		return 0
+	}
+
+	// a valid ref has been found
+
+	ref := &reference{
+		noteId:   noteId,
+		hasBlock: hasBlock,
+	}
+
+	if noteId > 0 {
+		// reusing the link field for the id since footnotes don't have links
+		ref.link = data[idOffset:idEnd]
+		// if footnote, it's not really a title, it's the contained text
+		ref.title = raw
+	} else {
+		ref.link = data[linkOffset:linkEnd]
+		ref.title = data[titleOffset:titleEnd]
+	}
+
+	// id matches are case-insensitive
+	id := string(bytes.ToLower(data[idOffset:idEnd]))
+
+	p.refs[id] = ref
+
+	return lineEnd
+}
+
+func scanLinkRef(p *parser, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) {
+	// link: whitespace-free sequence, optionally between angle brackets
+	if data[i] == '<' {
+		i++
+	}
+	linkOffset = i
+	for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' {
+		i++
+	}
+	if i == len(data) {
+		return
+	}
+	linkEnd = i
+	if data[linkOffset] == '<' && data[linkEnd-1] == '>' {
+		linkOffset++
+		linkEnd--
+	}
+
+	// optional spacer: (space | tab)* (newline | '\'' | '"' | '(' )
+	for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
+		i++
+	}
+	if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' {
+		return
+	}
+
+	// compute end-of-line
+	if i >= len(data) || data[i] == '\r' || data[i] == '\n' {
+		lineEnd = i
+	}
+	if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' {
+		lineEnd++
+	}
+
+	// optional (space|tab)* spacer after a newline
+	if lineEnd > 0 {
+		i = lineEnd + 1
+		for i < len(data) && (data[i] == ' ' || data[i] == '\t') {
+			i++
+		}
+	}
+
+	// optional title: any non-newline sequence enclosed in '"() alone on its line
+	if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') {
+		i++
+		titleOffset = i
+
+		// look for EOL
+		for i < len(data) && data[i] != '\n' && data[i] != '\r' {
+			i++
+		}
+		if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' {
+			titleEnd = i + 1
+		} else {
+			titleEnd = i
+		}
+
+		// step back
+		i--
+		for i > titleOffset && (data[i] == ' ' || data[i] == '\t') {
+			i--
+		}
+		if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') {
+			lineEnd = titleEnd
+			titleEnd = i
+		}
+	}
+
+	return
+}
+
+// The first bit of this logic is the same as (*parser).listItem, but the rest
+// is much simpler. This function simply finds the entire block and shifts it
+// over by one tab if it is indeed a block (just returns the line if it's not).
+// blockEnd is the end of the section in the input buffer, and contents is the
+// extracted text that was shifted over one tab. It will need to be rendered at
+// the end of the document.
+func scanFootnote(p *parser, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) {
+	if i == 0 || len(data) == 0 {
+		return
+	}
+
+	// skip leading whitespace on first line
+	for i < len(data) && data[i] == ' ' {
+		i++
+	}
+
+	blockStart = i
+
+	// find the end of the line
+	blockEnd = i
+	for i < len(data) && data[i-1] != '\n' {
+		i++
+	}
+
+	// get working buffer
+	var raw bytes.Buffer
+
+	// put the first line into the working buffer
+	raw.Write(data[blockEnd:i])
+	blockEnd = i
+
+	// process the following lines
+	containsBlankLine := false
+
+gatherLines:
+	for blockEnd < len(data) {
+		i++
+
+		// find the end of this line
+		for i < len(data) && data[i-1] != '\n' {
+			i++
+		}
+
+		// if it is an empty line, guess that it is part of this item
+		// and move on to the next line
+		if p.isEmpty(data[blockEnd:i]) > 0 {
+			containsBlankLine = true
+			blockEnd = i
+			continue
+		}
+
+		n := 0
+		if n = isIndented(data[blockEnd:i], indentSize); n == 0 {
+			// this is the end of the block.
+			// we don't want to include this last line in the index.
+			break gatherLines
+		}
+
+		// if there were blank lines before this one, insert a new one now
+		if containsBlankLine {
+			raw.WriteByte('\n')
+			containsBlankLine = false
+		}
+
+		// get rid of that first tab, write to buffer
+		raw.Write(data[blockEnd+n : i])
+		hasBlock = true
+
+		blockEnd = i
+	}
+
+	if data[blockEnd-1] != '\n' {
+		raw.WriteByte('\n')
+	}
+
+	contents = raw.Bytes()
+
+	return
+}
+
+//
+//
+// Miscellaneous helper functions
+//
+//
+
+// Test if a character is a punctuation symbol.
+// Taken from a private function in regexp in the stdlib.
+func ispunct(c byte) bool {
+	for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") {
+		if c == r {
+			return true
+		}
+	}
+	return false
+}
+
+// Test if a character is a whitespace character.
+func isspace(c byte) bool {
+	return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
+}
+
+// Test if a character is letter.
+func isletter(c byte) bool {
+	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
+}
+
+// Test if a character is a letter or a digit.
+// TODO: check when this is looking for ASCII alnum and when it should use unicode
+func isalnum(c byte) bool {
+	return (c >= '0' && c <= '9') || isletter(c)
+}
+
+// Replace tab characters with spaces, aligning to the next TAB_SIZE column.
+// always ends output with a newline
+func expandTabs(out *bytes.Buffer, line []byte, tabSize int) {
+	// first, check for common cases: no tabs, or only tabs at beginning of line
+	i, prefix := 0, 0
+	slowcase := false
+	for i = 0; i < len(line); i++ {
+		if line[i] == '\t' {
+			if prefix == i {
+				prefix++
+			} else {
+				slowcase = true
+				break
+			}
+		}
+	}
+
+	// no need to decode runes if all tabs are at the beginning of the line
+	if !slowcase {
+		for i = 0; i < prefix*tabSize; i++ {
+			out.WriteByte(' ')
+		}
+		out.Write(line[prefix:])
+		return
+	}
+
+	// the slow case: we need to count runes to figure out how
+	// many spaces to insert for each tab
+	column := 0
+	i = 0
+	for i < len(line) {
+		start := i
+		for i < len(line) && line[i] != '\t' {
+			_, size := utf8.DecodeRune(line[i:])
+			i += size
+			column++
+		}
+
+		if i > start {
+			out.Write(line[start:i])
+		}
+
+		if i >= len(line) {
+			break
+		}
+
+		for {
+			out.WriteByte(' ')
+			column++
+			if column%tabSize == 0 {
+				break
+			}
+		}
+
+		i++
+	}
+}
+
+// Find if a line counts as indented or not.
+// Returns number of characters the indent is (0 = not indented).
+func isIndented(data []byte, indentSize int) int {
+	if len(data) == 0 {
+		return 0
+	}
+	if data[0] == '\t' {
+		return 1
+	}
+	if len(data) < indentSize {
+		return 0
+	}
+	for i := 0; i < indentSize; i++ {
+		if data[i] != ' ' {
+			return 0
+		}
+	}
+	return indentSize
+}
+
+// Create a url-safe slug for fragments
+func slugify(in []byte) []byte {
+	if len(in) == 0 {
+		return in
+	}
+	out := make([]byte, 0, len(in))
+	sym := false
+
+	for _, ch := range in {
+		if isalnum(ch) {
+			sym = false
+			out = append(out, ch)
+		} else if sym {
+			continue
+		} else {
+			out = append(out, '-')
+			sym = true
+		}
+	}
+	var a, b int
+	var ch byte
+	for a, ch = range out {
+		if ch != '-' {
+			break
+		}
+	}
+	for b = len(out) - 1; b > 0; b-- {
+		if out[b] != '-' {
+			break
+		}
+	}
+	return out[a : b+1]
+}

+ 128 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/ref_test.go

@@ -0,0 +1,128 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+// Markdown 1.0.3 reference tests
+//
+
+package blackfriday
+
+import (
+	"io/ioutil"
+	"path/filepath"
+	"testing"
+)
+
+func runMarkdownReference(input string, flag int) string {
+	renderer := HtmlRenderer(0, "", "")
+	return string(Markdown([]byte(input), renderer, flag))
+}
+
+func doTestsReference(t *testing.T, files []string, flag int) {
+	// catch and report panics
+	var candidate string
+	defer func() {
+		if err := recover(); err != nil {
+			t.Errorf("\npanic while processing [%#v]\n", candidate)
+		}
+	}()
+
+	for _, basename := range files {
+		filename := filepath.Join("testdata", basename+".text")
+		inputBytes, err := ioutil.ReadFile(filename)
+		if err != nil {
+			t.Errorf("Couldn't open '%s', error: %v\n", filename, err)
+			continue
+		}
+		input := string(inputBytes)
+
+		filename = filepath.Join("testdata", basename+".html")
+		expectedBytes, err := ioutil.ReadFile(filename)
+		if err != nil {
+			t.Errorf("Couldn't open '%s', error: %v\n", filename, err)
+			continue
+		}
+		expected := string(expectedBytes)
+
+		// fmt.Fprintf(os.Stderr, "processing %s ...", filename)
+		actual := string(runMarkdownReference(input, flag))
+		if actual != expected {
+			t.Errorf("\n    [%#v]\nExpected[%#v]\nActual  [%#v]",
+				basename+".text", expected, actual)
+		}
+		// fmt.Fprintf(os.Stderr, " ok\n")
+
+		// now test every prefix of every input to check for
+		// bounds checking
+		if !testing.Short() {
+			start, max := 0, len(input)
+			for end := start + 1; end <= max; end++ {
+				candidate = input[start:end]
+				// fmt.Fprintf(os.Stderr, "  %s %d:%d/%d\n", filename, start, end, max)
+				_ = runMarkdownReference(candidate, flag)
+			}
+		}
+	}
+}
+
+func TestReference(t *testing.T) {
+	files := []string{
+		"Amps and angle encoding",
+		"Auto links",
+		"Backslash escapes",
+		"Blockquotes with code blocks",
+		"Code Blocks",
+		"Code Spans",
+		"Hard-wrapped paragraphs with list-like lines",
+		"Horizontal rules",
+		"Inline HTML (Advanced)",
+		"Inline HTML (Simple)",
+		"Inline HTML comments",
+		"Links, inline style",
+		"Links, reference style",
+		"Links, shortcut references",
+		"Literal quotes in titles",
+		"Markdown Documentation - Basics",
+		"Markdown Documentation - Syntax",
+		"Nested blockquotes",
+		"Ordered and unordered lists",
+		"Strong and em together",
+		"Tabs",
+		"Tidyness",
+	}
+	doTestsReference(t, files, 0)
+}
+
+func TestReference_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) {
+	files := []string{
+		"Amps and angle encoding",
+		"Auto links",
+		"Backslash escapes",
+		"Blockquotes with code blocks",
+		"Code Blocks",
+		"Code Spans",
+		"Hard-wrapped paragraphs with list-like lines no empty line before block",
+		"Horizontal rules",
+		"Inline HTML (Advanced)",
+		"Inline HTML (Simple)",
+		"Inline HTML comments",
+		"Links, inline style",
+		"Links, reference style",
+		"Links, shortcut references",
+		"Literal quotes in titles",
+		"Markdown Documentation - Basics",
+		"Markdown Documentation - Syntax",
+		"Nested blockquotes",
+		"Ordered and unordered lists",
+		"Strong and em together",
+		"Tabs",
+		"Tidyness",
+	}
+	doTestsReference(t, files, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK)
+}

+ 400 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/smartypants.go

@@ -0,0 +1,400 @@
+//
+// Blackfriday Markdown Processor
+// Available at http://github.com/russross/blackfriday
+//
+// Copyright © 2011 Russ Ross <russ@russross.com>.
+// Distributed under the Simplified BSD License.
+// See README.md for details.
+//
+
+//
+//
+// SmartyPants rendering
+//
+//
+
+package blackfriday
+
+import (
+	"bytes"
+)
+
+type smartypantsData struct {
+	inSingleQuote bool
+	inDoubleQuote bool
+}
+
+func wordBoundary(c byte) bool {
+	return c == 0 || isspace(c) || ispunct(c)
+}
+
+func tolower(c byte) byte {
+	if c >= 'A' && c <= 'Z' {
+		return c - 'A' + 'a'
+	}
+	return c
+}
+
+func isdigit(c byte) bool {
+	return c >= '0' && c <= '9'
+}
+
+func smartQuoteHelper(out *bytes.Buffer, previousChar byte, nextChar byte, quote byte, isOpen *bool) bool {
+	// edge of the buffer is likely to be a tag that we don't get to see,
+	// so we treat it like text sometimes
+
+	// enumerate all sixteen possibilities for (previousChar, nextChar)
+	// each can be one of {0, space, punct, other}
+	switch {
+	case previousChar == 0 && nextChar == 0:
+		// context is not any help here, so toggle
+		*isOpen = !*isOpen
+	case isspace(previousChar) && nextChar == 0:
+		// [ "] might be [ "<code>foo...]
+		*isOpen = true
+	case ispunct(previousChar) && nextChar == 0:
+		// [!"] hmm... could be [Run!"] or [("<code>...]
+		*isOpen = false
+	case /* isnormal(previousChar) && */ nextChar == 0:
+		// [a"] is probably a close
+		*isOpen = false
+	case previousChar == 0 && isspace(nextChar):
+		// [" ] might be [...foo</code>" ]
+		*isOpen = false
+	case isspace(previousChar) && isspace(nextChar):
+		// [ " ] context is not any help here, so toggle
+		*isOpen = !*isOpen
+	case ispunct(previousChar) && isspace(nextChar):
+		// [!" ] is probably a close
+		*isOpen = false
+	case /* isnormal(previousChar) && */ isspace(nextChar):
+		// [a" ] this is one of the easy cases
+		*isOpen = false
+	case previousChar == 0 && ispunct(nextChar):
+		// ["!] hmm... could be ["$1.95] or [</code>"!...]
+		*isOpen = false
+	case isspace(previousChar) && ispunct(nextChar):
+		// [ "!] looks more like [ "$1.95]
+		*isOpen = true
+	case ispunct(previousChar) && ispunct(nextChar):
+		// [!"!] context is not any help here, so toggle
+		*isOpen = !*isOpen
+	case /* isnormal(previousChar) && */ ispunct(nextChar):
+		// [a"!] is probably a close
+		*isOpen = false
+	case previousChar == 0 /* && isnormal(nextChar) */ :
+		// ["a] is probably an open
+		*isOpen = true
+	case isspace(previousChar) /* && isnormal(nextChar) */ :
+		// [ "a] this is one of the easy cases
+		*isOpen = true
+	case ispunct(previousChar) /* && isnormal(nextChar) */ :
+		// [!"a] is probably an open
+		*isOpen = true
+	default:
+		// [a'b] maybe a contraction?
+		*isOpen = false
+	}
+
+	out.WriteByte('&')
+	if *isOpen {
+		out.WriteByte('l')
+	} else {
+		out.WriteByte('r')
+	}
+	out.WriteByte(quote)
+	out.WriteString("quo;")
+	return true
+}
+
+func smartSingleQuote(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if len(text) >= 2 {
+		t1 := tolower(text[1])
+
+		if t1 == '\'' {
+			nextChar := byte(0)
+			if len(text) >= 3 {
+				nextChar = text[2]
+			}
+			if smartQuoteHelper(out, previousChar, nextChar, 'd', &smrt.inDoubleQuote) {
+				return 1
+			}
+		}
+
+		if (t1 == 's' || t1 == 't' || t1 == 'm' || t1 == 'd') && (len(text) < 3 || wordBoundary(text[2])) {
+			out.WriteString("&rsquo;")
+			return 0
+		}
+
+		if len(text) >= 3 {
+			t2 := tolower(text[2])
+
+			if ((t1 == 'r' && t2 == 'e') || (t1 == 'l' && t2 == 'l') || (t1 == 'v' && t2 == 'e')) &&
+				(len(text) < 4 || wordBoundary(text[3])) {
+				out.WriteString("&rsquo;")
+				return 0
+			}
+		}
+	}
+
+	nextChar := byte(0)
+	if len(text) > 1 {
+		nextChar = text[1]
+	}
+	if smartQuoteHelper(out, previousChar, nextChar, 's', &smrt.inSingleQuote) {
+		return 0
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartParens(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if len(text) >= 3 {
+		t1 := tolower(text[1])
+		t2 := tolower(text[2])
+
+		if t1 == 'c' && t2 == ')' {
+			out.WriteString("&copy;")
+			return 2
+		}
+
+		if t1 == 'r' && t2 == ')' {
+			out.WriteString("&reg;")
+			return 2
+		}
+
+		if len(text) >= 4 && t1 == 't' && t2 == 'm' && text[3] == ')' {
+			out.WriteString("&trade;")
+			return 3
+		}
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartDash(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if len(text) >= 2 {
+		if text[1] == '-' {
+			out.WriteString("&mdash;")
+			return 1
+		}
+
+		if wordBoundary(previousChar) && wordBoundary(text[1]) {
+			out.WriteString("&ndash;")
+			return 0
+		}
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartDashLatex(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if len(text) >= 3 && text[1] == '-' && text[2] == '-' {
+		out.WriteString("&mdash;")
+		return 2
+	}
+	if len(text) >= 2 && text[1] == '-' {
+		out.WriteString("&ndash;")
+		return 1
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartAmpVariant(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte, quote byte) int {
+	if bytes.HasPrefix(text, []byte("&quot;")) {
+		nextChar := byte(0)
+		if len(text) >= 7 {
+			nextChar = text[6]
+		}
+		if smartQuoteHelper(out, previousChar, nextChar, quote, &smrt.inDoubleQuote) {
+			return 5
+		}
+	}
+
+	if bytes.HasPrefix(text, []byte("&#0;")) {
+		return 3
+	}
+
+	out.WriteByte('&')
+	return 0
+}
+
+func smartAmp(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	return smartAmpVariant(out, smrt, previousChar, text, 'd')
+}
+
+func smartAmpAngledQuote(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	return smartAmpVariant(out, smrt, previousChar, text, 'a')
+}
+
+func smartPeriod(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if len(text) >= 3 && text[1] == '.' && text[2] == '.' {
+		out.WriteString("&hellip;")
+		return 2
+	}
+
+	if len(text) >= 5 && text[1] == ' ' && text[2] == '.' && text[3] == ' ' && text[4] == '.' {
+		out.WriteString("&hellip;")
+		return 4
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartBacktick(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if len(text) >= 2 && text[1] == '`' {
+		nextChar := byte(0)
+		if len(text) >= 3 {
+			nextChar = text[2]
+		}
+		if smartQuoteHelper(out, previousChar, nextChar, 'd', &smrt.inDoubleQuote) {
+			return 1
+		}
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartNumberGeneric(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 {
+		// is it of the form digits/digits(word boundary)?, i.e., \d+/\d+\b
+		// note: check for regular slash (/) or fraction slash (⁄, 0x2044, or 0xe2 81 84 in utf-8)
+		//       and avoid changing dates like 1/23/2005 into fractions.
+		numEnd := 0
+		for len(text) > numEnd && isdigit(text[numEnd]) {
+			numEnd++
+		}
+		if numEnd == 0 {
+			out.WriteByte(text[0])
+			return 0
+		}
+		denStart := numEnd + 1
+		if len(text) > numEnd+3 && text[numEnd] == 0xe2 && text[numEnd+1] == 0x81 && text[numEnd+2] == 0x84 {
+			denStart = numEnd + 3
+		} else if len(text) < numEnd+2 || text[numEnd] != '/' {
+			out.WriteByte(text[0])
+			return 0
+		}
+		denEnd := denStart
+		for len(text) > denEnd && isdigit(text[denEnd]) {
+			denEnd++
+		}
+		if denEnd == denStart {
+			out.WriteByte(text[0])
+			return 0
+		}
+		if len(text) == denEnd || wordBoundary(text[denEnd]) && text[denEnd] != '/' {
+			out.WriteString("<sup>")
+			out.Write(text[:numEnd])
+			out.WriteString("</sup>&frasl;<sub>")
+			out.Write(text[denStart:denEnd])
+			out.WriteString("</sub>")
+			return denEnd - 1
+		}
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartNumber(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 {
+		if text[0] == '1' && text[1] == '/' && text[2] == '2' {
+			if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' {
+				out.WriteString("&frac12;")
+				return 2
+			}
+		}
+
+		if text[0] == '1' && text[1] == '/' && text[2] == '4' {
+			if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 5 && tolower(text[3]) == 't' && tolower(text[4]) == 'h') {
+				out.WriteString("&frac14;")
+				return 2
+			}
+		}
+
+		if text[0] == '3' && text[1] == '/' && text[2] == '4' {
+			if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 6 && tolower(text[3]) == 't' && tolower(text[4]) == 'h' && tolower(text[5]) == 's') {
+				out.WriteString("&frac34;")
+				return 2
+			}
+		}
+	}
+
+	out.WriteByte(text[0])
+	return 0
+}
+
+func smartDoubleQuoteVariant(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte, quote byte) int {
+	nextChar := byte(0)
+	if len(text) > 1 {
+		nextChar = text[1]
+	}
+	if !smartQuoteHelper(out, previousChar, nextChar, quote, &smrt.inDoubleQuote) {
+		out.WriteString("&quot;")
+	}
+
+	return 0
+}
+
+func smartDoubleQuote(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	return smartDoubleQuoteVariant(out, smrt, previousChar, text, 'd')
+}
+
+func smartAngledDoubleQuote(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	return smartDoubleQuoteVariant(out, smrt, previousChar, text, 'a')
+}
+
+func smartLeftAngle(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int {
+	i := 0
+
+	for i < len(text) && text[i] != '>' {
+		i++
+	}
+
+	out.Write(text[:i+1])
+	return i
+}
+
+type smartCallback func(out *bytes.Buffer, smrt *smartypantsData, previousChar byte, text []byte) int
+
+type smartypantsRenderer [256]smartCallback
+
+func smartypants(flags int) *smartypantsRenderer {
+	r := new(smartypantsRenderer)
+	if flags&HTML_SMARTYPANTS_ANGLED_QUOTES == 0 {
+		r['"'] = smartDoubleQuote
+		r['&'] = smartAmp
+	} else {
+		r['"'] = smartAngledDoubleQuote
+		r['&'] = smartAmpAngledQuote
+	}
+	r['\''] = smartSingleQuote
+	r['('] = smartParens
+	if flags&HTML_SMARTYPANTS_DASHES != 0 {
+		if flags&HTML_SMARTYPANTS_LATEX_DASHES == 0 {
+			r['-'] = smartDash
+		} else {
+			r['-'] = smartDashLatex
+		}
+	}
+	r['.'] = smartPeriod
+	if flags&HTML_SMARTYPANTS_FRACTIONS == 0 {
+		r['1'] = smartNumber
+		r['3'] = smartNumber
+	} else {
+		for ch := '1'; ch <= '9'; ch++ {
+			r[ch] = smartNumberGeneric
+		}
+	}
+	r['<'] = smartLeftAngle
+	r['`'] = smartBacktick
+	return r
+}

+ 17 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Amps and angle encoding.html

@@ -0,0 +1,17 @@
+<p>AT&amp;T has an ampersand in their name.</p>
+
+<p>AT&amp;T is another way to write it.</p>
+
+<p>This &amp; that.</p>
+
+<p>4 &lt; 5.</p>
+
+<p>6 &gt; 5.</p>
+
+<p>Here's a <a href="http://example.com/?foo=1&amp;bar=2">link</a> with an ampersand in the URL.</p>
+
+<p>Here's a link with an amersand in the link text: <a href="http://att.com/" title="AT&amp;T">AT&amp;T</a>.</p>
+
+<p>Here's an inline <a href="/script?foo=1&amp;bar=2">link</a>.</p>
+
+<p>Here's an inline <a href="/script?foo=1&amp;bar=2">link</a>.</p>

+ 21 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Amps and angle encoding.text

@@ -0,0 +1,21 @@
+AT&T has an ampersand in their name.
+
+AT&amp;T is another way to write it.
+
+This & that.
+
+4 < 5.
+
+6 > 5.
+
+Here's a [link] [1] with an ampersand in the URL.
+
+Here's a link with an amersand in the link text: [AT&T] [2].
+
+Here's an inline [link](/script?foo=1&bar=2).
+
+Here's an inline [link](</script?foo=1&bar=2>).
+
+
+[1]: http://example.com/?foo=1&bar=2
+[2]: http://att.com/  "AT&T"

+ 18 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Auto links.html

@@ -0,0 +1,18 @@
+<p>Link: <a href="http://example.com/">http://example.com/</a>.</p>
+
+<p>With an ampersand: <a href="http://example.com/?foo=1&amp;bar=2">http://example.com/?foo=1&amp;bar=2</a></p>
+
+<ul>
+<li>In a list?</li>
+<li><a href="http://example.com/">http://example.com/</a></li>
+<li>It should.</li>
+</ul>
+
+<blockquote>
+<p>Blockquoted: <a href="http://example.com/">http://example.com/</a></p>
+</blockquote>
+
+<p>Auto-links should not occur here: <code>&lt;http://example.com/&gt;</code></p>
+
+<pre><code>or here: &lt;http://example.com/&gt;
+</code></pre>

+ 13 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Auto links.text

@@ -0,0 +1,13 @@
+Link: <http://example.com/>.
+
+With an ampersand: <http://example.com/?foo=1&bar=2>
+
+* In a list?
+* <http://example.com/>
+* It should.
+
+> Blockquoted: <http://example.com/>
+
+Auto-links should not occur here: `<http://example.com/>`
+
+	or here: <http://example.com/>

+ 123 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Backslash escapes.html

@@ -0,0 +1,123 @@
+<p>These should all get escaped:</p>
+
+<p>Backslash: \</p>
+
+<p>Backtick: `</p>
+
+<p>Asterisk: *</p>
+
+<p>Underscore: _</p>
+
+<p>Left brace: {</p>
+
+<p>Right brace: }</p>
+
+<p>Left bracket: [</p>
+
+<p>Right bracket: ]</p>
+
+<p>Left paren: (</p>
+
+<p>Right paren: )</p>
+
+<p>Greater-than: &gt;</p>
+
+<p>Hash: #</p>
+
+<p>Period: .</p>
+
+<p>Bang: !</p>
+
+<p>Plus: +</p>
+
+<p>Minus: -</p>
+
+<p>Tilde: ~</p>
+
+<p>These should not, because they occur within a code block:</p>
+
+<pre><code>Backslash: \\
+
+Backtick: \`
+
+Asterisk: \*
+
+Underscore: \_
+
+Left brace: \{
+
+Right brace: \}
+
+Left bracket: \[
+
+Right bracket: \]
+
+Left paren: \(
+
+Right paren: \)
+
+Greater-than: \&gt;
+
+Hash: \#
+
+Period: \.
+
+Bang: \!
+
+Plus: \+
+
+Minus: \-
+
+Tilde: \~
+</code></pre>
+
+<p>Nor should these, which occur in code spans:</p>
+
+<p>Backslash: <code>\\</code></p>
+
+<p>Backtick: <code>\`</code></p>
+
+<p>Asterisk: <code>\*</code></p>
+
+<p>Underscore: <code>\_</code></p>
+
+<p>Left brace: <code>\{</code></p>
+
+<p>Right brace: <code>\}</code></p>
+
+<p>Left bracket: <code>\[</code></p>
+
+<p>Right bracket: <code>\]</code></p>
+
+<p>Left paren: <code>\(</code></p>
+
+<p>Right paren: <code>\)</code></p>
+
+<p>Greater-than: <code>\&gt;</code></p>
+
+<p>Hash: <code>\#</code></p>
+
+<p>Period: <code>\.</code></p>
+
+<p>Bang: <code>\!</code></p>
+
+<p>Plus: <code>\+</code></p>
+
+<p>Minus: <code>\-</code></p>
+
+<p>Tilde: <code>\~</code></p>
+
+<p>These should get escaped, even though they're matching pairs for
+other Markdown constructs:</p>
+
+<p>*asterisks*</p>
+
+<p>_underscores_</p>
+
+<p>`backticks`</p>
+
+<p>This is a code span with a literal backslash-backtick sequence: <code>\`</code></p>
+
+<p>This is a tag with unescaped backticks <span attr='`ticks`'>bar</span>.</p>
+
+<p>This is a tag with backslashes <span attr='\\backslashes\\'>bar</span>.</p>

+ 126 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Backslash escapes.text

@@ -0,0 +1,126 @@
+These should all get escaped:
+
+Backslash: \\
+
+Backtick: \`
+
+Asterisk: \*
+
+Underscore: \_
+
+Left brace: \{
+
+Right brace: \}
+
+Left bracket: \[
+
+Right bracket: \]
+
+Left paren: \(
+
+Right paren: \)
+
+Greater-than: \>
+
+Hash: \#
+
+Period: \.
+
+Bang: \!
+
+Plus: \+
+
+Minus: \-
+
+Tilde: \~
+
+
+
+These should not, because they occur within a code block:
+
+	Backslash: \\
+
+	Backtick: \`
+
+	Asterisk: \*
+
+	Underscore: \_
+
+	Left brace: \{
+
+	Right brace: \}
+
+	Left bracket: \[
+
+	Right bracket: \]
+
+	Left paren: \(
+
+	Right paren: \)
+
+	Greater-than: \>
+
+	Hash: \#
+
+	Period: \.
+
+	Bang: \!
+
+	Plus: \+
+
+	Minus: \-
+
+	Tilde: \~
+
+
+Nor should these, which occur in code spans:
+
+Backslash: `\\`
+
+Backtick: `` \` ``
+
+Asterisk: `\*`
+
+Underscore: `\_`
+
+Left brace: `\{`
+
+Right brace: `\}`
+
+Left bracket: `\[`
+
+Right bracket: `\]`
+
+Left paren: `\(`
+
+Right paren: `\)`
+
+Greater-than: `\>`
+
+Hash: `\#`
+
+Period: `\.`
+
+Bang: `\!`
+
+Plus: `\+`
+
+Minus: `\-`
+
+Tilde: `\~`
+
+
+These should get escaped, even though they're matching pairs for
+other Markdown constructs:
+
+\*asterisks\*
+
+\_underscores\_
+
+\`backticks\`
+
+This is a code span with a literal backslash-backtick sequence: `` \` ``
+
+This is a tag with unescaped backticks <span attr='`ticks`'>bar</span>.
+
+This is a tag with backslashes <span attr='\\backslashes\\'>bar</span>.

+ 15 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Blockquotes with code blocks.html

@@ -0,0 +1,15 @@
+<blockquote>
+<p>Example:</p>
+
+<pre><code>sub status {
+    print &quot;working&quot;;
+}
+</code></pre>
+
+<p>Or:</p>
+
+<pre><code>sub status {
+    return &quot;working&quot;;
+}
+</code></pre>
+</blockquote>

+ 11 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Blockquotes with code blocks.text

@@ -0,0 +1,11 @@
+> Example:
+> 
+>     sub status {
+>         print "working";
+>     }
+> 
+> Or:
+> 
+>     sub status {
+>         return "working";
+>     }

+ 18 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Blocks.html

@@ -0,0 +1,18 @@
+<pre><code>code block on the first line
+</code></pre>
+
+<p>Regular text.</p>
+
+<pre><code>code block indented by spaces
+</code></pre>
+
+<p>Regular text.</p>
+
+<pre><code>the lines in this block  
+all contain trailing spaces  
+</code></pre>
+
+<p>Regular Text.</p>
+
+<pre><code>code block on the last line
+</code></pre>

+ 14 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Blocks.text

@@ -0,0 +1,14 @@
+	code block on the first line
+	
+Regular text.
+
+    code block indented by spaces
+
+Regular text.
+
+	the lines in this block  
+	all contain trailing spaces  
+
+Regular Text.
+
+	code block on the last line

+ 5 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Spans.html

@@ -0,0 +1,5 @@
+<p><code>&lt;test a=&quot;</code> content of attribute <code>&quot;&gt;</code></p>
+
+<p>Fix for backticks within HTML tag: <span attr='`ticks`'>like this</span></p>
+
+<p>Here's how you put <code>`backticks`</code> in a code span.</p>

+ 6 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Code Spans.text

@@ -0,0 +1,6 @@
+`<test a="` content of attribute `">`
+
+Fix for backticks within HTML tag: <span attr='`ticks`'>like this</span>
+
+Here's how you put `` `backticks` `` in a code span.
+

+ 14 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines no empty line before block.html

@@ -0,0 +1,14 @@
+<p>In Markdown 1.0.0 and earlier. Version</p>
+
+<ol>
+<li>This line turns into a list item.
+Because a hard-wrapped line in the
+middle of a paragraph looked like a
+list item.</li>
+</ol>
+
+<p>Here's one with a bullet.</p>
+
+<ul>
+<li>criminey.</li>
+</ul>

+ 8 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines no empty line before block.text

@@ -0,0 +1,8 @@
+In Markdown 1.0.0 and earlier. Version
+8. This line turns into a list item.
+Because a hard-wrapped line in the
+middle of a paragraph looked like a
+list item.
+
+Here's one with a bullet.
+* criminey.

+ 8 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines.html

@@ -0,0 +1,8 @@
+<p>In Markdown 1.0.0 and earlier. Version
+8. This line turns into a list item.
+Because a hard-wrapped line in the
+middle of a paragraph looked like a
+list item.</p>
+
+<p>Here's one with a bullet.
+* criminey.</p>

+ 8 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Hard-wrapped paragraphs with list-like lines.text

@@ -0,0 +1,8 @@
+In Markdown 1.0.0 and earlier. Version
+8. This line turns into a list item.
+Because a hard-wrapped line in the
+middle of a paragraph looked like a
+list item.
+
+Here's one with a bullet.
+* criminey.

+ 71 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Horizontal rules.html

@@ -0,0 +1,71 @@
+<p>Dashes:</p>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<pre><code>---
+</code></pre>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<pre><code>- - -
+</code></pre>
+
+<p>Asterisks:</p>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<pre><code>***
+</code></pre>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<pre><code>* * *
+</code></pre>
+
+<p>Underscores:</p>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<pre><code>___
+</code></pre>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<hr>
+
+<pre><code>_ _ _
+</code></pre>

+ 67 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Horizontal rules.text

@@ -0,0 +1,67 @@
+Dashes:
+
+---
+
+ ---
+ 
+  ---
+
+   ---
+
+	---
+
+- - -
+
+ - - -
+ 
+  - - -
+
+   - - -
+
+	- - -
+
+
+Asterisks:
+
+***
+
+ ***
+ 
+  ***
+
+   ***
+
+	***
+
+* * *
+
+ * * *
+ 
+  * * *
+
+   * * *
+
+	* * *
+
+
+Underscores:
+
+___
+
+ ___
+ 
+  ___
+
+   ___
+
+    ___
+
+_ _ _
+
+ _ _ _
+ 
+  _ _ _
+
+   _ _ _
+
+    _ _ _

+ 15 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Advanced).html

@@ -0,0 +1,15 @@
+<p>Simple block on one line:</p>
+
+<div>foo</div>
+
+<p>And nested without indentation:</p>
+
+<div>
+<div>
+<div>
+foo
+</div>
+<div style=">"/>
+</div>
+<div>bar</div>
+</div>

+ 15 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Advanced).text

@@ -0,0 +1,15 @@
+Simple block on one line:
+
+<div>foo</div>
+
+And nested without indentation:
+
+<div>
+<div>
+<div>
+foo
+</div>
+<div style=">"/>
+</div>
+<div>bar</div>
+</div>

+ 72 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Simple).html

@@ -0,0 +1,72 @@
+<p>Here's a simple block:</p>
+
+<div>
+    foo
+</div>
+
+<p>This should be a code block, though:</p>
+
+<pre><code>&lt;div&gt;
+    foo
+&lt;/div&gt;
+</code></pre>
+
+<p>As should this:</p>
+
+<pre><code>&lt;div&gt;foo&lt;/div&gt;
+</code></pre>
+
+<p>Now, nested:</p>
+
+<div>
+    <div>
+        <div>
+            foo
+        </div>
+    </div>
+</div>
+
+<p>This should just be an HTML comment:</p>
+
+<!-- Comment -->
+
+<p>Multiline:</p>
+
+<!--
+Blah
+Blah
+-->
+
+<p>Code block:</p>
+
+<pre><code>&lt;!-- Comment --&gt;
+</code></pre>
+
+<p>Just plain comment, with trailing spaces on the line:</p>
+
+<!-- foo -->   
+
+<p>Code:</p>
+
+<pre><code>&lt;hr /&gt;
+</code></pre>
+
+<p>Hr's:</p>
+
+<hr>
+
+<hr/>
+
+<hr />
+
+<hr>   
+
+<hr/>  
+
+<hr /> 
+
+<hr class="foo" id="bar" />
+
+<hr class="foo" id="bar"/>
+
+<hr class="foo" id="bar" >

+ 69 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML (Simple).text

@@ -0,0 +1,69 @@
+Here's a simple block:
+
+<div>
+	foo
+</div>
+
+This should be a code block, though:
+
+	<div>
+		foo
+	</div>
+
+As should this:
+
+	<div>foo</div>
+
+Now, nested:
+
+<div>
+	<div>
+		<div>
+			foo
+		</div>
+	</div>
+</div>
+
+This should just be an HTML comment:
+
+<!-- Comment -->
+
+Multiline:
+
+<!--
+Blah
+Blah
+-->
+
+Code block:
+
+	<!-- Comment -->
+
+Just plain comment, with trailing spaces on the line:
+
+<!-- foo -->   
+
+Code:
+
+	<hr />
+	
+Hr's:
+
+<hr>
+
+<hr/>
+
+<hr />
+
+<hr>   
+
+<hr/>  
+
+<hr /> 
+
+<hr class="foo" id="bar" />
+
+<hr class="foo" id="bar"/>
+
+<hr class="foo" id="bar" >
+

+ 13 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML comments.html

@@ -0,0 +1,13 @@
+<p>Paragraph one.</p>
+
+<!-- This is a simple comment -->
+
+<!--
+    This is another comment.
+-->
+
+<p>Paragraph two.</p>
+
+<!-- one comment block -- -- with two comments -->
+
+<p>The end.</p>

+ 13 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Inline HTML comments.text

@@ -0,0 +1,13 @@
+Paragraph one.
+
+<!-- This is a simple comment -->
+
+<!--
+	This is another comment.
+-->
+
+Paragraph two.
+
+<!-- one comment block -- -- with two comments -->
+
+The end.

+ 11 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, inline style.html

@@ -0,0 +1,11 @@
+<p>Just a <a href="/url/">URL</a>.</p>
+
+<p><a href="/url/" title="title">URL and title</a>.</p>
+
+<p><a href="/url/" title="title preceded by two spaces">URL and title</a>.</p>
+
+<p><a href="/url/" title="title preceded by a tab">URL and title</a>.</p>
+
+<p><a href="/url/" title="title has spaces afterward">URL and title</a>.</p>
+
+<p>[Empty]().</p>

+ 12 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, inline style.text

@@ -0,0 +1,12 @@
+Just a [URL](/url/).
+
+[URL and title](/url/ "title").
+
+[URL and title](/url/  "title preceded by two spaces").
+
+[URL and title](/url/	"title preceded by a tab").
+
+[URL and title](/url/ "title has spaces afterward"  ).
+
+
+[Empty]().

+ 52 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, reference style.html

@@ -0,0 +1,52 @@
+<p>Foo <a href="/url/" title="Title">bar</a>.</p>
+
+<p>Foo <a href="/url/" title="Title">bar</a>.</p>
+
+<p>Foo <a href="/url/" title="Title">bar</a>.</p>
+
+<p>With <a href="/url/">embedded [brackets]</a>.</p>
+
+<p>Indented <a href="/url">once</a>.</p>
+
+<p>Indented <a href="/url">twice</a>.</p>
+
+<p>Indented <a href="/url">thrice</a>.</p>
+
+<p>Indented [four][] times.</p>
+
+<pre><code>[four]: /url
+</code></pre>
+
+<hr>
+
+<p><a href="foo">this</a> should work</p>
+
+<p>So should <a href="foo">this</a>.</p>
+
+<p>And <a href="foo">this</a>.</p>
+
+<p>And <a href="foo">this</a>.</p>
+
+<p>And <a href="foo">this</a>.</p>
+
+<p>But not [that] [].</p>
+
+<p>Nor [that][].</p>
+
+<p>Nor [that].</p>
+
+<p>[Something in brackets like <a href="foo">this</a> should work]</p>
+
+<p>[Same with <a href="foo">this</a>.]</p>
+
+<p>In this case, <a href="/somethingelse/">this</a> points to something else.</p>
+
+<p>Backslashing should suppress [this] and [this].</p>
+
+<hr>
+
+<p>Here's one where the <a href="/url/">link
+breaks</a> across lines.</p>
+
+<p>Here's another where the <a href="/url/">link
+breaks</a> across lines, but with a line-ending space.</p>

+ 71 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, reference style.text

@@ -0,0 +1,71 @@
+Foo [bar] [1].
+
+Foo [bar][1].
+
+Foo [bar]
+[1].
+
+[1]: /url/  "Title"
+
+
+With [embedded [brackets]] [b].
+
+
+Indented [once][].
+
+Indented [twice][].
+
+Indented [thrice][].
+
+Indented [four][] times.
+
+ [once]: /url
+
+  [twice]: /url
+
+   [thrice]: /url
+
+    [four]: /url
+
+
+[b]: /url/
+
+* * *
+
+[this] [this] should work
+
+So should [this][this].
+
+And [this] [].
+
+And [this][].
+
+And [this].
+
+But not [that] [].
+
+Nor [that][].
+
+Nor [that].
+
+[Something in brackets like [this][] should work]
+
+[Same with [this].]
+
+In this case, [this](/somethingelse/) points to something else.
+
+Backslashing should suppress \[this] and [this\].
+
+[this]: foo
+
+
+* * *
+
+Here's one where the [link
+breaks] across lines.
+
+Here's another where the [link 
+breaks] across lines, but with a line-ending space.
+
+
+[link breaks]: /url/

+ 9 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, shortcut references.html

@@ -0,0 +1,9 @@
+<p>This is the <a href="/simple">simple case</a>.</p>
+
+<p>This one has a <a href="/foo">line
+break</a>.</p>
+
+<p>This one has a <a href="/foo">line
+break</a> with a line-ending space.</p>
+
+<p><a href="/that">this</a> and the <a href="/other">other</a></p>

+ 20 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Links, shortcut references.text

@@ -0,0 +1,20 @@
+This is the [simple case].
+
+[simple case]: /simple
+
+
+
+This one has a [line
+break].
+
+This one has a [line 
+break] with a line-ending space.
+
+[line break]: /foo
+
+
+[this] [that] and the [other]
+
+[this]: /this
+[that]: /that
+[other]: /other

+ 3 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Literal quotes in titles.html

@@ -0,0 +1,3 @@
+<p>Foo <a href="/url/" title="Title with &quot;quotes&quot; inside">bar</a>.</p>
+
+<p>Foo <a href="/url/" title="Title with &quot;quotes&quot; inside">bar</a>.</p>

+ 7 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Literal quotes in titles.text

@@ -0,0 +1,7 @@
+Foo [bar][].
+
+Foo [bar](/url/ "Title with "quotes" inside").
+
+
+  [bar]: /url/ "Title with "quotes" inside"
+

+ 314 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Basics.html

@@ -0,0 +1,314 @@
+<h1>Markdown: Basics</h1>
+
+<ul id="ProjectSubmenu">
+    <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
+    <li><a class="selected" title="Markdown Basics">Basics</a></li>
+    <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li>
+    <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
+    <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
+</ul>
+
+<h2>Getting the Gist of Markdown's Formatting Syntax</h2>
+
+<p>This page offers a brief overview of what it's like to use Markdown.
+The <a href="/projects/markdown/syntax" title="Markdown Syntax">syntax page</a> provides complete, detailed documentation for
+every feature, but Markdown should be very easy to pick up simply by
+looking at a few examples of it in action. The examples on this page
+are written in a before/after style, showing example syntax and the
+HTML output produced by Markdown.</p>
+
+<p>It's also helpful to simply try Markdown out; the <a href="/projects/markdown/dingus" title="Markdown Dingus">Dingus</a> is a
+web application that allows you type your own Markdown-formatted text
+and translate it to XHTML.</p>
+
+<p><strong>Note:</strong> This document is itself written using Markdown; you
+can <a href="/projects/markdown/basics.text">see the source for it by adding '.text' to the URL</a>.</p>
+
+<h2>Paragraphs, Headers, Blockquotes</h2>
+
+<p>A paragraph is simply one or more consecutive lines of text, separated
+by one or more blank lines. (A blank line is any line that looks like a
+blank line -- a line containing nothing spaces or tabs is considered
+blank.) Normal paragraphs should not be intended with spaces or tabs.</p>
+
+<p>Markdown offers two styles of headers: <em>Setext</em> and <em>atx</em>.
+Setext-style headers for <code>&lt;h1&gt;</code> and <code>&lt;h2&gt;</code> are created by
+&quot;underlining&quot; with equal signs (<code>=</code>) and hyphens (<code>-</code>), respectively.
+To create an atx-style header, you put 1-6 hash marks (<code>#</code>) at the
+beginning of the line -- the number of hashes equals the resulting
+HTML header level.</p>
+
+<p>Blockquotes are indicated using email-style '<code>&gt;</code>' angle brackets.</p>
+
+<p>Markdown:</p>
+
+<pre><code>A First Level Header
+====================
+
+A Second Level Header
+---------------------
+
+Now is the time for all good men to come to
+the aid of their country. This is just a
+regular paragraph.
+
+The quick brown fox jumped over the lazy
+dog's back.
+
+### Header 3
+
+&gt; This is a blockquote.
+&gt; 
+&gt; This is the second paragraph in the blockquote.
+&gt;
+&gt; ## This is an H2 in a blockquote
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;h1&gt;A First Level Header&lt;/h1&gt;
+
+&lt;h2&gt;A Second Level Header&lt;/h2&gt;
+
+&lt;p&gt;Now is the time for all good men to come to
+the aid of their country. This is just a
+regular paragraph.&lt;/p&gt;
+
+&lt;p&gt;The quick brown fox jumped over the lazy
+dog's back.&lt;/p&gt;
+
+&lt;h3&gt;Header 3&lt;/h3&gt;
+
+&lt;blockquote&gt;
+    &lt;p&gt;This is a blockquote.&lt;/p&gt;
+
+    &lt;p&gt;This is the second paragraph in the blockquote.&lt;/p&gt;
+
+    &lt;h2&gt;This is an H2 in a blockquote&lt;/h2&gt;
+&lt;/blockquote&gt;
+</code></pre>
+
+<h3>Phrase Emphasis</h3>
+
+<p>Markdown uses asterisks and underscores to indicate spans of emphasis.</p>
+
+<p>Markdown:</p>
+
+<pre><code>Some of these words *are emphasized*.
+Some of these words _are emphasized also_.
+
+Use two asterisks for **strong emphasis**.
+Or, if you prefer, __use two underscores instead__.
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;Some of these words &lt;em&gt;are emphasized&lt;/em&gt;.
+Some of these words &lt;em&gt;are emphasized also&lt;/em&gt;.&lt;/p&gt;
+
+&lt;p&gt;Use two asterisks for &lt;strong&gt;strong emphasis&lt;/strong&gt;.
+Or, if you prefer, &lt;strong&gt;use two underscores instead&lt;/strong&gt;.&lt;/p&gt;
+</code></pre>
+
+<h2>Lists</h2>
+
+<p>Unordered (bulleted) lists use asterisks, pluses, and hyphens (<code>*</code>,
+<code>+</code>, and <code>-</code>) as list markers. These three markers are
+interchangable; this:</p>
+
+<pre><code>*   Candy.
+*   Gum.
+*   Booze.
+</code></pre>
+
+<p>this:</p>
+
+<pre><code>+   Candy.
++   Gum.
++   Booze.
+</code></pre>
+
+<p>and this:</p>
+
+<pre><code>-   Candy.
+-   Gum.
+-   Booze.
+</code></pre>
+
+<p>all produce the same output:</p>
+
+<pre><code>&lt;ul&gt;
+&lt;li&gt;Candy.&lt;/li&gt;
+&lt;li&gt;Gum.&lt;/li&gt;
+&lt;li&gt;Booze.&lt;/li&gt;
+&lt;/ul&gt;
+</code></pre>
+
+<p>Ordered (numbered) lists use regular numbers, followed by periods, as
+list markers:</p>
+
+<pre><code>1.  Red
+2.  Green
+3.  Blue
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;ol&gt;
+&lt;li&gt;Red&lt;/li&gt;
+&lt;li&gt;Green&lt;/li&gt;
+&lt;li&gt;Blue&lt;/li&gt;
+&lt;/ol&gt;
+</code></pre>
+
+<p>If you put blank lines between items, you'll get <code>&lt;p&gt;</code> tags for the
+list item text. You can create multi-paragraph list items by indenting
+the paragraphs by 4 spaces or 1 tab:</p>
+
+<pre><code>*   A list item.
+
+    With multiple paragraphs.
+
+*   Another item in the list.
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;ul&gt;
+&lt;li&gt;&lt;p&gt;A list item.&lt;/p&gt;
+&lt;p&gt;With multiple paragraphs.&lt;/p&gt;&lt;/li&gt;
+&lt;li&gt;&lt;p&gt;Another item in the list.&lt;/p&gt;&lt;/li&gt;
+&lt;/ul&gt;
+</code></pre>
+
+<h3>Links</h3>
+
+<p>Markdown supports two styles for creating links: <em>inline</em> and
+<em>reference</em>. With both styles, you use square brackets to delimit the
+text you want to turn into a link.</p>
+
+<p>Inline-style links use parentheses immediately after the link text.
+For example:</p>
+
+<pre><code>This is an [example link](http://example.com/).
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;This is an &lt;a href=&quot;http://example.com/&quot;&gt;
+example link&lt;/a&gt;.&lt;/p&gt;
+</code></pre>
+
+<p>Optionally, you may include a title attribute in the parentheses:</p>
+
+<pre><code>This is an [example link](http://example.com/ &quot;With a Title&quot;).
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;This is an &lt;a href=&quot;http://example.com/&quot; title=&quot;With a Title&quot;&gt;
+example link&lt;/a&gt;.&lt;/p&gt;
+</code></pre>
+
+<p>Reference-style links allow you to refer to your links by names, which
+you define elsewhere in your document:</p>
+
+<pre><code>I get 10 times more traffic from [Google][1] than from
+[Yahoo][2] or [MSN][3].
+
+[1]: http://google.com/        &quot;Google&quot;
+[2]: http://search.yahoo.com/  &quot;Yahoo Search&quot;
+[3]: http://search.msn.com/    &quot;MSN Search&quot;
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;I get 10 times more traffic from &lt;a href=&quot;http://google.com/&quot;
+title=&quot;Google&quot;&gt;Google&lt;/a&gt; than from &lt;a href=&quot;http://search.yahoo.com/&quot;
+title=&quot;Yahoo Search&quot;&gt;Yahoo&lt;/a&gt; or &lt;a href=&quot;http://search.msn.com/&quot;
+title=&quot;MSN Search&quot;&gt;MSN&lt;/a&gt;.&lt;/p&gt;
+</code></pre>
+
+<p>The title attribute is optional. Link names may contain letters,
+numbers and spaces, but are <em>not</em> case sensitive:</p>
+
+<pre><code>I start my morning with a cup of coffee and
+[The New York Times][NY Times].
+
+[ny times]: http://www.nytimes.com/
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;I start my morning with a cup of coffee and
+&lt;a href=&quot;http://www.nytimes.com/&quot;&gt;The New York Times&lt;/a&gt;.&lt;/p&gt;
+</code></pre>
+
+<h3>Images</h3>
+
+<p>Image syntax is very much like link syntax.</p>
+
+<p>Inline (titles are optional):</p>
+
+<pre><code>![alt text](/path/to/img.jpg &quot;Title&quot;)
+</code></pre>
+
+<p>Reference-style:</p>
+
+<pre><code>![alt text][id]
+
+[id]: /path/to/img.jpg &quot;Title&quot;
+</code></pre>
+
+<p>Both of the above examples produce the same output:</p>
+
+<pre><code>&lt;img src=&quot;/path/to/img.jpg&quot; alt=&quot;alt text&quot; title=&quot;Title&quot; /&gt;
+</code></pre>
+
+<h3>Code</h3>
+
+<p>In a regular paragraph, you can create code span by wrapping text in
+backtick quotes. Any ampersands (<code>&amp;</code>) and angle brackets (<code>&lt;</code> or
+<code>&gt;</code>) will automatically be translated into HTML entities. This makes
+it easy to use Markdown to write about HTML example code:</p>
+
+<pre><code>I strongly recommend against using any `&lt;blink&gt;` tags.
+
+I wish SmartyPants used named entities like `&amp;mdash;`
+instead of decimal-encoded entites like `&amp;#8212;`.
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;I strongly recommend against using any
+&lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
+
+&lt;p&gt;I wish SmartyPants used named entities like
+&lt;code&gt;&amp;amp;mdash;&lt;/code&gt; instead of decimal-encoded
+entites like &lt;code&gt;&amp;amp;#8212;&lt;/code&gt;.&lt;/p&gt;
+</code></pre>
+
+<p>To specify an entire block of pre-formatted code, indent every line of
+the block by 4 spaces or 1 tab. Just like with code spans, <code>&amp;</code>, <code>&lt;</code>,
+and <code>&gt;</code> characters will be escaped automatically.</p>
+
+<p>Markdown:</p>
+
+<pre><code>If you want your page to validate under XHTML 1.0 Strict,
+you've got to put paragraph tags in your blockquotes:
+
+    &lt;blockquote&gt;
+        &lt;p&gt;For example.&lt;/p&gt;
+    &lt;/blockquote&gt;
+</code></pre>
+
+<p>Output:</p>
+
+<pre><code>&lt;p&gt;If you want your page to validate under XHTML 1.0 Strict,
+you've got to put paragraph tags in your blockquotes:&lt;/p&gt;
+
+&lt;pre&gt;&lt;code&gt;&amp;lt;blockquote&amp;gt;
+    &amp;lt;p&amp;gt;For example.&amp;lt;/p&amp;gt;
+&amp;lt;/blockquote&amp;gt;
+&lt;/code&gt;&lt;/pre&gt;
+</code></pre>

+ 306 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Basics.text

@@ -0,0 +1,306 @@
+Markdown: Basics
+================
+
+<ul id="ProjectSubmenu">
+    <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
+    <li><a class="selected" title="Markdown Basics">Basics</a></li>
+    <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li>
+    <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
+    <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
+</ul>
+
+
+Getting the Gist of Markdown's Formatting Syntax
+------------------------------------------------
+
+This page offers a brief overview of what it's like to use Markdown.
+The [syntax page] [s] provides complete, detailed documentation for
+every feature, but Markdown should be very easy to pick up simply by
+looking at a few examples of it in action. The examples on this page
+are written in a before/after style, showing example syntax and the
+HTML output produced by Markdown.
+
+It's also helpful to simply try Markdown out; the [Dingus] [d] is a
+web application that allows you type your own Markdown-formatted text
+and translate it to XHTML.
+
+**Note:** This document is itself written using Markdown; you
+can [see the source for it by adding '.text' to the URL] [src].
+
+  [s]: /projects/markdown/syntax  "Markdown Syntax"
+  [d]: /projects/markdown/dingus  "Markdown Dingus"
+  [src]: /projects/markdown/basics.text
+
+
+## Paragraphs, Headers, Blockquotes ##
+
+A paragraph is simply one or more consecutive lines of text, separated
+by one or more blank lines. (A blank line is any line that looks like a
+blank line -- a line containing nothing spaces or tabs is considered
+blank.) Normal paragraphs should not be intended with spaces or tabs.
+
+Markdown offers two styles of headers: *Setext* and *atx*.
+Setext-style headers for `<h1>` and `<h2>` are created by
+"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
+To create an atx-style header, you put 1-6 hash marks (`#`) at the
+beginning of the line -- the number of hashes equals the resulting
+HTML header level.
+
+Blockquotes are indicated using email-style '`>`' angle brackets.
+
+Markdown:
+
+    A First Level Header
+    ====================
+    
+    A Second Level Header
+    ---------------------
+
+    Now is the time for all good men to come to
+    the aid of their country. This is just a
+    regular paragraph.
+
+    The quick brown fox jumped over the lazy
+    dog's back.
+    
+    ### Header 3
+
+    > This is a blockquote.
+    > 
+    > This is the second paragraph in the blockquote.
+    >
+    > ## This is an H2 in a blockquote
+
+
+Output:
+
+    <h1>A First Level Header</h1>
+    
+    <h2>A Second Level Header</h2>
+    
+    <p>Now is the time for all good men to come to
+    the aid of their country. This is just a
+    regular paragraph.</p>
+    
+    <p>The quick brown fox jumped over the lazy
+    dog's back.</p>
+    
+    <h3>Header 3</h3>
+    
+    <blockquote>
+        <p>This is a blockquote.</p>
+        
+        <p>This is the second paragraph in the blockquote.</p>
+        
+        <h2>This is an H2 in a blockquote</h2>
+    </blockquote>
+
+
+
+### Phrase Emphasis ###
+
+Markdown uses asterisks and underscores to indicate spans of emphasis.
+
+Markdown:
+
+    Some of these words *are emphasized*.
+    Some of these words _are emphasized also_.
+    
+    Use two asterisks for **strong emphasis**.
+    Or, if you prefer, __use two underscores instead__.
+
+Output:
+
+    <p>Some of these words <em>are emphasized</em>.
+    Some of these words <em>are emphasized also</em>.</p>
+    
+    <p>Use two asterisks for <strong>strong emphasis</strong>.
+    Or, if you prefer, <strong>use two underscores instead</strong>.</p>
+   
+
+
+## Lists ##
+
+Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
+`+`, and `-`) as list markers. These three markers are
+interchangable; this:
+
+    *   Candy.
+    *   Gum.
+    *   Booze.
+
+this:
+
+    +   Candy.
+    +   Gum.
+    +   Booze.
+
+and this:
+
+    -   Candy.
+    -   Gum.
+    -   Booze.
+
+all produce the same output:
+
+    <ul>
+    <li>Candy.</li>
+    <li>Gum.</li>
+    <li>Booze.</li>
+    </ul>
+
+Ordered (numbered) lists use regular numbers, followed by periods, as
+list markers:
+
+    1.  Red
+    2.  Green
+    3.  Blue
+
+Output:
+
+    <ol>
+    <li>Red</li>
+    <li>Green</li>
+    <li>Blue</li>
+    </ol>
+
+If you put blank lines between items, you'll get `<p>` tags for the
+list item text. You can create multi-paragraph list items by indenting
+the paragraphs by 4 spaces or 1 tab:
+
+    *   A list item.
+    
+        With multiple paragraphs.
+
+    *   Another item in the list.
+
+Output:
+
+    <ul>
+    <li><p>A list item.</p>
+    <p>With multiple paragraphs.</p></li>
+    <li><p>Another item in the list.</p></li>
+    </ul>
+    
+
+
+### Links ###
+
+Markdown supports two styles for creating links: *inline* and
+*reference*. With both styles, you use square brackets to delimit the
+text you want to turn into a link.
+
+Inline-style links use parentheses immediately after the link text.
+For example:
+
+    This is an [example link](http://example.com/).
+
+Output:
+
+    <p>This is an <a href="http://example.com/">
+    example link</a>.</p>
+
+Optionally, you may include a title attribute in the parentheses:
+
+    This is an [example link](http://example.com/ "With a Title").
+
+Output:
+
+    <p>This is an <a href="http://example.com/" title="With a Title">
+    example link</a>.</p>
+
+Reference-style links allow you to refer to your links by names, which
+you define elsewhere in your document:
+
+    I get 10 times more traffic from [Google][1] than from
+    [Yahoo][2] or [MSN][3].
+
+    [1]: http://google.com/        "Google"
+    [2]: http://search.yahoo.com/  "Yahoo Search"
+    [3]: http://search.msn.com/    "MSN Search"
+
+Output:
+
+    <p>I get 10 times more traffic from <a href="http://google.com/"
+    title="Google">Google</a> than from <a href="http://search.yahoo.com/"
+    title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
+    title="MSN Search">MSN</a>.</p>
+
+The title attribute is optional. Link names may contain letters,
+numbers and spaces, but are *not* case sensitive:
+
+    I start my morning with a cup of coffee and
+    [The New York Times][NY Times].
+
+    [ny times]: http://www.nytimes.com/
+
+Output:
+
+    <p>I start my morning with a cup of coffee and
+    <a href="http://www.nytimes.com/">The New York Times</a>.</p>
+
+
+### Images ###
+
+Image syntax is very much like link syntax.
+
+Inline (titles are optional):
+
+    ![alt text](/path/to/img.jpg "Title")
+
+Reference-style:
+
+    ![alt text][id]
+
+    [id]: /path/to/img.jpg "Title"
+
+Both of the above examples produce the same output:
+
+    <img src="/path/to/img.jpg" alt="alt text" title="Title" />
+
+
+
+### Code ###
+
+In a regular paragraph, you can create code span by wrapping text in
+backtick quotes. Any ampersands (`&`) and angle brackets (`<` or
+`>`) will automatically be translated into HTML entities. This makes
+it easy to use Markdown to write about HTML example code:
+
+    I strongly recommend against using any `<blink>` tags.
+
+    I wish SmartyPants used named entities like `&mdash;`
+    instead of decimal-encoded entites like `&#8212;`.
+
+Output:
+
+    <p>I strongly recommend against using any
+    <code>&lt;blink&gt;</code> tags.</p>
+    
+    <p>I wish SmartyPants used named entities like
+    <code>&amp;mdash;</code> instead of decimal-encoded
+    entites like <code>&amp;#8212;</code>.</p>
+
+
+To specify an entire block of pre-formatted code, indent every line of
+the block by 4 spaces or 1 tab. Just like with code spans, `&`, `<`,
+and `>` characters will be escaped automatically.
+
+Markdown:
+
+    If you want your page to validate under XHTML 1.0 Strict,
+    you've got to put paragraph tags in your blockquotes:
+
+        <blockquote>
+            <p>For example.</p>
+        </blockquote>
+
+Output:
+
+    <p>If you want your page to validate under XHTML 1.0 Strict,
+    you've got to put paragraph tags in your blockquotes:</p>
+    
+    <pre><code>&lt;blockquote&gt;
+        &lt;p&gt;For example.&lt;/p&gt;
+    &lt;/blockquote&gt;
+    </code></pre>

+ 946 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Syntax.html

@@ -0,0 +1,946 @@
+<h1>Markdown: Syntax</h1>
+
+<ul id="ProjectSubmenu">
+    <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
+    <li><a href="/projects/markdown/basics" title="Markdown Basics">Basics</a></li>
+    <li><a class="selected" title="Markdown Syntax Documentation">Syntax</a></li>
+    <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
+    <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
+</ul>
+
+<ul>
+<li><a href="#overview">Overview</a>
+
+<ul>
+<li><a href="#philosophy">Philosophy</a></li>
+<li><a href="#html">Inline HTML</a></li>
+<li><a href="#autoescape">Automatic Escaping for Special Characters</a></li>
+</ul></li>
+<li><a href="#block">Block Elements</a>
+
+<ul>
+<li><a href="#p">Paragraphs and Line Breaks</a></li>
+<li><a href="#header">Headers</a></li>
+<li><a href="#blockquote">Blockquotes</a></li>
+<li><a href="#list">Lists</a></li>
+<li><a href="#precode">Code Blocks</a></li>
+<li><a href="#hr">Horizontal Rules</a></li>
+</ul></li>
+<li><a href="#span">Span Elements</a>
+
+<ul>
+<li><a href="#link">Links</a></li>
+<li><a href="#em">Emphasis</a></li>
+<li><a href="#code">Code</a></li>
+<li><a href="#img">Images</a></li>
+</ul></li>
+<li><a href="#misc">Miscellaneous</a>
+
+<ul>
+<li><a href="#backslash">Backslash Escapes</a></li>
+<li><a href="#autolink">Automatic Links</a></li>
+</ul></li>
+</ul>
+
+<p><strong>Note:</strong> This document is itself written using Markdown; you
+can <a href="/projects/markdown/syntax.text">see the source for it by adding '.text' to the URL</a>.</p>
+
+<hr>
+
+<h2 id="overview">Overview</h2>
+
+<h3 id="philosophy">Philosophy</h3>
+
+<p>Markdown is intended to be as easy-to-read and easy-to-write as is feasible.</p>
+
+<p>Readability, however, is emphasized above all else. A Markdown-formatted
+document should be publishable as-is, as plain text, without looking
+like it's been marked up with tags or formatting instructions. While
+Markdown's syntax has been influenced by several existing text-to-HTML
+filters -- including <a href="http://docutils.sourceforge.net/mirror/setext.html">Setext</a>, <a href="http://www.aaronsw.com/2002/atx/">atx</a>, <a href="http://textism.com/tools/textile/">Textile</a>, <a href="http://docutils.sourceforge.net/rst.html">reStructuredText</a>,
+<a href="http://www.triptico.com/software/grutatxt.html">Grutatext</a>, and <a href="http://ettext.taint.org/doc/">EtText</a> -- the single biggest source of
+inspiration for Markdown's syntax is the format of plain text email.</p>
+
+<p>To this end, Markdown's syntax is comprised entirely of punctuation
+characters, which punctuation characters have been carefully chosen so
+as to look like what they mean. E.g., asterisks around a word actually
+look like *emphasis*. Markdown lists look like, well, lists. Even
+blockquotes look like quoted passages of text, assuming you've ever
+used email.</p>
+
+<h3 id="html">Inline HTML</h3>
+
+<p>Markdown's syntax is intended for one purpose: to be used as a
+format for <em>writing</em> for the web.</p>
+
+<p>Markdown is not a replacement for HTML, or even close to it. Its
+syntax is very small, corresponding only to a very small subset of
+HTML tags. The idea is <em>not</em> to create a syntax that makes it easier
+to insert HTML tags. In my opinion, HTML tags are already easy to
+insert. The idea for Markdown is to make it easy to read, write, and
+edit prose. HTML is a <em>publishing</em> format; Markdown is a <em>writing</em>
+format. Thus, Markdown's formatting syntax only addresses issues that
+can be conveyed in plain text.</p>
+
+<p>For any markup that is not covered by Markdown's syntax, you simply
+use HTML itself. There's no need to preface it or delimit it to
+indicate that you're switching from Markdown to HTML; you just use
+the tags.</p>
+
+<p>The only restrictions are that block-level HTML elements -- e.g. <code>&lt;div&gt;</code>,
+<code>&lt;table&gt;</code>, <code>&lt;pre&gt;</code>, <code>&lt;p&gt;</code>, etc. -- must be separated from surrounding
+content by blank lines, and the start and end tags of the block should
+not be indented with tabs or spaces. Markdown is smart enough not
+to add extra (unwanted) <code>&lt;p&gt;</code> tags around HTML block-level tags.</p>
+
+<p>For example, to add an HTML table to a Markdown article:</p>
+
+<pre><code>This is a regular paragraph.
+
+&lt;table&gt;
+    &lt;tr&gt;
+        &lt;td&gt;Foo&lt;/td&gt;
+    &lt;/tr&gt;
+&lt;/table&gt;
+
+This is another regular paragraph.
+</code></pre>
+
+<p>Note that Markdown formatting syntax is not processed within block-level
+HTML tags. E.g., you can't use Markdown-style <code>*emphasis*</code> inside an
+HTML block.</p>
+
+<p>Span-level HTML tags -- e.g. <code>&lt;span&gt;</code>, <code>&lt;cite&gt;</code>, or <code>&lt;del&gt;</code> -- can be
+used anywhere in a Markdown paragraph, list item, or header. If you
+want, you can even use HTML tags instead of Markdown formatting; e.g. if
+you'd prefer to use HTML <code>&lt;a&gt;</code> or <code>&lt;img&gt;</code> tags instead of Markdown's
+link or image syntax, go right ahead.</p>
+
+<p>Unlike block-level HTML tags, Markdown syntax <em>is</em> processed within
+span-level tags.</p>
+
+<h3 id="autoescape">Automatic Escaping for Special Characters</h3>
+
+<p>In HTML, there are two characters that demand special treatment: <code>&lt;</code>
+and <code>&amp;</code>. Left angle brackets are used to start tags; ampersands are
+used to denote HTML entities. If you want to use them as literal
+characters, you must escape them as entities, e.g. <code>&amp;lt;</code>, and
+<code>&amp;amp;</code>.</p>
+
+<p>Ampersands in particular are bedeviling for web writers. If you want to
+write about 'AT&amp;T', you need to write '<code>AT&amp;amp;T</code>'. You even need to
+escape ampersands within URLs. Thus, if you want to link to:</p>
+
+<pre><code>http://images.google.com/images?num=30&amp;q=larry+bird
+</code></pre>
+
+<p>you need to encode the URL as:</p>
+
+<pre><code>http://images.google.com/images?num=30&amp;amp;q=larry+bird
+</code></pre>
+
+<p>in your anchor tag <code>href</code> attribute. Needless to say, this is easy to
+forget, and is probably the single most common source of HTML validation
+errors in otherwise well-marked-up web sites.</p>
+
+<p>Markdown allows you to use these characters naturally, taking care of
+all the necessary escaping for you. If you use an ampersand as part of
+an HTML entity, it remains unchanged; otherwise it will be translated
+into <code>&amp;amp;</code>.</p>
+
+<p>So, if you want to include a copyright symbol in your article, you can write:</p>
+
+<pre><code>&amp;copy;
+</code></pre>
+
+<p>and Markdown will leave it alone. But if you write:</p>
+
+<pre><code>AT&amp;T
+</code></pre>
+
+<p>Markdown will translate it to:</p>
+
+<pre><code>AT&amp;amp;T
+</code></pre>
+
+<p>Similarly, because Markdown supports <a href="#html">inline HTML</a>, if you use
+angle brackets as delimiters for HTML tags, Markdown will treat them as
+such. But if you write:</p>
+
+<pre><code>4 &lt; 5
+</code></pre>
+
+<p>Markdown will translate it to:</p>
+
+<pre><code>4 &amp;lt; 5
+</code></pre>
+
+<p>However, inside Markdown code spans and blocks, angle brackets and
+ampersands are <em>always</em> encoded automatically. This makes it easy to use
+Markdown to write about HTML code. (As opposed to raw HTML, which is a
+terrible format for writing about HTML syntax, because every single <code>&lt;</code>
+and <code>&amp;</code> in your example code needs to be escaped.)</p>
+
+<hr>
+
+<h2 id="block">Block Elements</h2>
+
+<h3 id="p">Paragraphs and Line Breaks</h3>
+
+<p>A paragraph is simply one or more consecutive lines of text, separated
+by one or more blank lines. (A blank line is any line that looks like a
+blank line -- a line containing nothing but spaces or tabs is considered
+blank.) Normal paragraphs should not be intended with spaces or tabs.</p>
+
+<p>The implication of the &quot;one or more consecutive lines of text&quot; rule is
+that Markdown supports &quot;hard-wrapped&quot; text paragraphs. This differs
+significantly from most other text-to-HTML formatters (including Movable
+Type's &quot;Convert Line Breaks&quot; option) which translate every line break
+character in a paragraph into a <code>&lt;br /&gt;</code> tag.</p>
+
+<p>When you <em>do</em> want to insert a <code>&lt;br /&gt;</code> break tag using Markdown, you
+end a line with two or more spaces, then type return.</p>
+
+<p>Yes, this takes a tad more effort to create a <code>&lt;br /&gt;</code>, but a simplistic
+&quot;every line break is a <code>&lt;br /&gt;</code>&quot; rule wouldn't work for Markdown.
+Markdown's email-style <a href="#blockquote">blockquoting</a> and multi-paragraph <a href="#list">list items</a>
+work best -- and look better -- when you format them with hard breaks.</p>
+
+<h3 id="header">Headers</h3>
+
+<p>Markdown supports two styles of headers, <a href="http://docutils.sourceforge.net/mirror/setext.html">Setext</a> and <a href="http://www.aaronsw.com/2002/atx/">atx</a>.</p>
+
+<p>Setext-style headers are &quot;underlined&quot; using equal signs (for first-level
+headers) and dashes (for second-level headers). For example:</p>
+
+<pre><code>This is an H1
+=============
+
+This is an H2
+-------------
+</code></pre>
+
+<p>Any number of underlining <code>=</code>'s or <code>-</code>'s will work.</p>
+
+<p>Atx-style headers use 1-6 hash characters at the start of the line,
+corresponding to header levels 1-6. For example:</p>
+
+<pre><code># This is an H1
+
+## This is an H2
+
+###### This is an H6
+</code></pre>
+
+<p>Optionally, you may &quot;close&quot; atx-style headers. This is purely
+cosmetic -- you can use this if you think it looks better. The
+closing hashes don't even need to match the number of hashes
+used to open the header. (The number of opening hashes
+determines the header level.) :</p>
+
+<pre><code># This is an H1 #
+
+## This is an H2 ##
+
+### This is an H3 ######
+</code></pre>
+
+<h3 id="blockquote">Blockquotes</h3>
+
+<p>Markdown uses email-style <code>&gt;</code> characters for blockquoting. If you're
+familiar with quoting passages of text in an email message, then you
+know how to create a blockquote in Markdown. It looks best if you hard
+wrap the text and put a <code>&gt;</code> before every line:</p>
+
+<pre><code>&gt; This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
+&gt; consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
+&gt; Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
+&gt; 
+&gt; Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
+&gt; id sem consectetuer libero luctus adipiscing.
+</code></pre>
+
+<p>Markdown allows you to be lazy and only put the <code>&gt;</code> before the first
+line of a hard-wrapped paragraph:</p>
+
+<pre><code>&gt; This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
+consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
+Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
+
+&gt; Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
+id sem consectetuer libero luctus adipiscing.
+</code></pre>
+
+<p>Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by
+adding additional levels of <code>&gt;</code>:</p>
+
+<pre><code>&gt; This is the first level of quoting.
+&gt;
+&gt; &gt; This is nested blockquote.
+&gt;
+&gt; Back to the first level.
+</code></pre>
+
+<p>Blockquotes can contain other Markdown elements, including headers, lists,
+and code blocks:</p>
+
+<pre><code>&gt; ## This is a header.
+&gt; 
+&gt; 1.   This is the first list item.
+&gt; 2.   This is the second list item.
+&gt; 
+&gt; Here's some example code:
+&gt; 
+&gt;     return shell_exec(&quot;echo $input | $markdown_script&quot;);
+</code></pre>
+
+<p>Any decent text editor should make email-style quoting easy. For
+example, with BBEdit, you can make a selection and choose Increase
+Quote Level from the Text menu.</p>
+
+<h3 id="list">Lists</h3>
+
+<p>Markdown supports ordered (numbered) and unordered (bulleted) lists.</p>
+
+<p>Unordered lists use asterisks, pluses, and hyphens -- interchangably
+-- as list markers:</p>
+
+<pre><code>*   Red
+*   Green
+*   Blue
+</code></pre>
+
+<p>is equivalent to:</p>
+
+<pre><code>+   Red
++   Green
++   Blue
+</code></pre>
+
+<p>and:</p>
+
+<pre><code>-   Red
+-   Green
+-   Blue
+</code></pre>
+
+<p>Ordered lists use numbers followed by periods:</p>
+
+<pre><code>1.  Bird
+2.  McHale
+3.  Parish
+</code></pre>
+
+<p>It's important to note that the actual numbers you use to mark the
+list have no effect on the HTML output Markdown produces. The HTML
+Markdown produces from the above list is:</p>
+
+<pre><code>&lt;ol&gt;
+&lt;li&gt;Bird&lt;/li&gt;
+&lt;li&gt;McHale&lt;/li&gt;
+&lt;li&gt;Parish&lt;/li&gt;
+&lt;/ol&gt;
+</code></pre>
+
+<p>If you instead wrote the list in Markdown like this:</p>
+
+<pre><code>1.  Bird
+1.  McHale
+1.  Parish
+</code></pre>
+
+<p>or even:</p>
+
+<pre><code>3. Bird
+1. McHale
+8. Parish
+</code></pre>
+
+<p>you'd get the exact same HTML output. The point is, if you want to,
+you can use ordinal numbers in your ordered Markdown lists, so that
+the numbers in your source match the numbers in your published HTML.
+But if you want to be lazy, you don't have to.</p>
+
+<p>If you do use lazy list numbering, however, you should still start the
+list with the number 1. At some point in the future, Markdown may support
+starting ordered lists at an arbitrary number.</p>
+
+<p>List markers typically start at the left margin, but may be indented by
+up to three spaces. List markers must be followed by one or more spaces
+or a tab.</p>
+
+<p>To make lists look nice, you can wrap items with hanging indents:</p>
+
+<pre><code>*   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
+    Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
+    viverra nec, fringilla in, laoreet vitae, risus.
+*   Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
+    Suspendisse id sem consectetuer libero luctus adipiscing.
+</code></pre>
+
+<p>But if you want to be lazy, you don't have to:</p>
+
+<pre><code>*   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
+Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
+viverra nec, fringilla in, laoreet vitae, risus.
+*   Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
+Suspendisse id sem consectetuer libero luctus adipiscing.
+</code></pre>
+
+<p>If list items are separated by blank lines, Markdown will wrap the
+items in <code>&lt;p&gt;</code> tags in the HTML output. For example, this input:</p>
+
+<pre><code>*   Bird
+*   Magic
+</code></pre>
+
+<p>will turn into:</p>
+
+<pre><code>&lt;ul&gt;
+&lt;li&gt;Bird&lt;/li&gt;
+&lt;li&gt;Magic&lt;/li&gt;
+&lt;/ul&gt;
+</code></pre>
+
+<p>But this:</p>
+
+<pre><code>*   Bird
+
+*   Magic
+</code></pre>
+
+<p>will turn into:</p>
+
+<pre><code>&lt;ul&gt;
+&lt;li&gt;&lt;p&gt;Bird&lt;/p&gt;&lt;/li&gt;
+&lt;li&gt;&lt;p&gt;Magic&lt;/p&gt;&lt;/li&gt;
+&lt;/ul&gt;
+</code></pre>
+
+<p>List items may consist of multiple paragraphs. Each subsequent
+paragraph in a list item must be intended by either 4 spaces
+or one tab:</p>
+
+<pre><code>1.  This is a list item with two paragraphs. Lorem ipsum dolor
+    sit amet, consectetuer adipiscing elit. Aliquam hendrerit
+    mi posuere lectus.
+
+    Vestibulum enim wisi, viverra nec, fringilla in, laoreet
+    vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
+    sit amet velit.
+
+2.  Suspendisse id sem consectetuer libero luctus adipiscing.
+</code></pre>
+
+<p>It looks nice if you indent every line of the subsequent
+paragraphs, but here again, Markdown will allow you to be
+lazy:</p>
+
+<pre><code>*   This is a list item with two paragraphs.
+
+    This is the second paragraph in the list item. You're
+only required to indent the first line. Lorem ipsum dolor
+sit amet, consectetuer adipiscing elit.
+
+*   Another item in the same list.
+</code></pre>
+
+<p>To put a blockquote within a list item, the blockquote's <code>&gt;</code>
+delimiters need to be indented:</p>
+
+<pre><code>*   A list item with a blockquote:
+
+    &gt; This is a blockquote
+    &gt; inside a list item.
+</code></pre>
+
+<p>To put a code block within a list item, the code block needs
+to be indented <em>twice</em> -- 8 spaces or two tabs:</p>
+
+<pre><code>*   A list item with a code block:
+
+        &lt;code goes here&gt;
+</code></pre>
+
+<p>It's worth noting that it's possible to trigger an ordered list by
+accident, by writing something like this:</p>
+
+<pre><code>1986. What a great season.
+</code></pre>
+
+<p>In other words, a <em>number-period-space</em> sequence at the beginning of a
+line. To avoid this, you can backslash-escape the period:</p>
+
+<pre><code>1986\. What a great season.
+</code></pre>
+
+<h3 id="precode">Code Blocks</h3>
+
+<p>Pre-formatted code blocks are used for writing about programming or
+markup source code. Rather than forming normal paragraphs, the lines
+of a code block are interpreted literally. Markdown wraps a code block
+in both <code>&lt;pre&gt;</code> and <code>&lt;code&gt;</code> tags.</p>
+
+<p>To produce a code block in Markdown, simply indent every line of the
+block by at least 4 spaces or 1 tab. For example, given this input:</p>
+
+<pre><code>This is a normal paragraph:
+
+    This is a code block.
+</code></pre>
+
+<p>Markdown will generate:</p>
+
+<pre><code>&lt;p&gt;This is a normal paragraph:&lt;/p&gt;
+
+&lt;pre&gt;&lt;code&gt;This is a code block.
+&lt;/code&gt;&lt;/pre&gt;
+</code></pre>
+
+<p>One level of indentation -- 4 spaces or 1 tab -- is removed from each
+line of the code block. For example, this:</p>
+
+<pre><code>Here is an example of AppleScript:
+
+    tell application &quot;Foo&quot;
+        beep
+    end tell
+</code></pre>
+
+<p>will turn into:</p>
+
+<pre><code>&lt;p&gt;Here is an example of AppleScript:&lt;/p&gt;
+
+&lt;pre&gt;&lt;code&gt;tell application &quot;Foo&quot;
+    beep
+end tell
+&lt;/code&gt;&lt;/pre&gt;
+</code></pre>
+
+<p>A code block continues until it reaches a line that is not indented
+(or the end of the article).</p>
+
+<p>Within a code block, ampersands (<code>&amp;</code>) and angle brackets (<code>&lt;</code> and <code>&gt;</code>)
+are automatically converted into HTML entities. This makes it very
+easy to include example HTML source code using Markdown -- just paste
+it and indent it, and Markdown will handle the hassle of encoding the
+ampersands and angle brackets. For example, this:</p>
+
+<pre><code>    &lt;div class=&quot;footer&quot;&gt;
+        &amp;copy; 2004 Foo Corporation
+    &lt;/div&gt;
+</code></pre>
+
+<p>will turn into:</p>
+
+<pre><code>&lt;pre&gt;&lt;code&gt;&amp;lt;div class=&quot;footer&quot;&amp;gt;
+    &amp;amp;copy; 2004 Foo Corporation
+&amp;lt;/div&amp;gt;
+&lt;/code&gt;&lt;/pre&gt;
+</code></pre>
+
+<p>Regular Markdown syntax is not processed within code blocks. E.g.,
+asterisks are just literal asterisks within a code block. This means
+it's also easy to use Markdown to write about Markdown's own syntax.</p>
+
+<h3 id="hr">Horizontal Rules</h3>
+
+<p>You can produce a horizontal rule tag (<code>&lt;hr /&gt;</code>) by placing three or
+more hyphens, asterisks, or underscores on a line by themselves. If you
+wish, you may use spaces between the hyphens or asterisks. Each of the
+following lines will produce a horizontal rule:</p>
+
+<pre><code>* * *
+
+***
+
+*****
+
+- - -
+
+---------------------------------------
+
+_ _ _
+</code></pre>
+
+<hr>
+
+<h2 id="span">Span Elements</h2>
+
+<h3 id="link">Links</h3>
+
+<p>Markdown supports two style of links: <em>inline</em> and <em>reference</em>.</p>
+
+<p>In both styles, the link text is delimited by [square brackets].</p>
+
+<p>To create an inline link, use a set of regular parentheses immediately
+after the link text's closing square bracket. Inside the parentheses,
+put the URL where you want the link to point, along with an <em>optional</em>
+title for the link, surrounded in quotes. For example:</p>
+
+<pre><code>This is [an example](http://example.com/ &quot;Title&quot;) inline link.
+
+[This link](http://example.net/) has no title attribute.
+</code></pre>
+
+<p>Will produce:</p>
+
+<pre><code>&lt;p&gt;This is &lt;a href=&quot;http://example.com/&quot; title=&quot;Title&quot;&gt;
+an example&lt;/a&gt; inline link.&lt;/p&gt;
+
+&lt;p&gt;&lt;a href=&quot;http://example.net/&quot;&gt;This link&lt;/a&gt; has no
+title attribute.&lt;/p&gt;
+</code></pre>
+
+<p>If you're referring to a local resource on the same server, you can
+use relative paths:</p>
+
+<pre><code>See my [About](/about/) page for details.
+</code></pre>
+
+<p>Reference-style links use a second set of square brackets, inside
+which you place a label of your choosing to identify the link:</p>
+
+<pre><code>This is [an example][id] reference-style link.
+</code></pre>
+
+<p>You can optionally use a space to separate the sets of brackets:</p>
+
+<pre><code>This is [an example] [id] reference-style link.
+</code></pre>
+
+<p>Then, anywhere in the document, you define your link label like this,
+on a line by itself:</p>
+
+<pre><code>[id]: http://example.com/  &quot;Optional Title Here&quot;
+</code></pre>
+
+<p>That is:</p>
+
+<ul>
+<li>Square brackets containing the link identifier (optionally
+indented from the left margin using up to three spaces);</li>
+<li>followed by a colon;</li>
+<li>followed by one or more spaces (or tabs);</li>
+<li>followed by the URL for the link;</li>
+<li>optionally followed by a title attribute for the link, enclosed
+in double or single quotes.</li>
+</ul>
+
+<p>The link URL may, optionally, be surrounded by angle brackets:</p>
+
+<pre><code>[id]: &lt;http://example.com/&gt;  &quot;Optional Title Here&quot;
+</code></pre>
+
+<p>You can put the title attribute on the next line and use extra spaces
+or tabs for padding, which tends to look better with longer URLs:</p>
+
+<pre><code>[id]: http://example.com/longish/path/to/resource/here
+    &quot;Optional Title Here&quot;
+</code></pre>
+
+<p>Link definitions are only used for creating links during Markdown
+processing, and are stripped from your document in the HTML output.</p>
+
+<p>Link definition names may constist of letters, numbers, spaces, and punctuation -- but they are <em>not</em> case sensitive. E.g. these two links:</p>
+
+<pre><code>[link text][a]
+[link text][A]
+</code></pre>
+
+<p>are equivalent.</p>
+
+<p>The <em>implicit link name</em> shortcut allows you to omit the name of the
+link, in which case the link text itself is used as the name.
+Just use an empty set of square brackets -- e.g., to link the word
+&quot;Google&quot; to the google.com web site, you could simply write:</p>
+
+<pre><code>[Google][]
+</code></pre>
+
+<p>And then define the link:</p>
+
+<pre><code>[Google]: http://google.com/
+</code></pre>
+
+<p>Because link names may contain spaces, this shortcut even works for
+multiple words in the link text:</p>
+
+<pre><code>Visit [Daring Fireball][] for more information.
+</code></pre>
+
+<p>And then define the link:</p>
+
+<pre><code>[Daring Fireball]: http://daringfireball.net/
+</code></pre>
+
+<p>Link definitions can be placed anywhere in your Markdown document. I
+tend to put them immediately after each paragraph in which they're
+used, but if you want, you can put them all at the end of your
+document, sort of like footnotes.</p>
+
+<p>Here's an example of reference links in action:</p>
+
+<pre><code>I get 10 times more traffic from [Google] [1] than from
+[Yahoo] [2] or [MSN] [3].
+
+  [1]: http://google.com/        &quot;Google&quot;
+  [2]: http://search.yahoo.com/  &quot;Yahoo Search&quot;
+  [3]: http://search.msn.com/    &quot;MSN Search&quot;
+</code></pre>
+
+<p>Using the implicit link name shortcut, you could instead write:</p>
+
+<pre><code>I get 10 times more traffic from [Google][] than from
+[Yahoo][] or [MSN][].
+
+  [google]: http://google.com/        &quot;Google&quot;
+  [yahoo]:  http://search.yahoo.com/  &quot;Yahoo Search&quot;
+  [msn]:    http://search.msn.com/    &quot;MSN Search&quot;
+</code></pre>
+
+<p>Both of the above examples will produce the following HTML output:</p>
+
+<pre><code>&lt;p&gt;I get 10 times more traffic from &lt;a href=&quot;http://google.com/&quot;
+title=&quot;Google&quot;&gt;Google&lt;/a&gt; than from
+&lt;a href=&quot;http://search.yahoo.com/&quot; title=&quot;Yahoo Search&quot;&gt;Yahoo&lt;/a&gt;
+or &lt;a href=&quot;http://search.msn.com/&quot; title=&quot;MSN Search&quot;&gt;MSN&lt;/a&gt;.&lt;/p&gt;
+</code></pre>
+
+<p>For comparison, here is the same paragraph written using
+Markdown's inline link style:</p>
+
+<pre><code>I get 10 times more traffic from [Google](http://google.com/ &quot;Google&quot;)
+than from [Yahoo](http://search.yahoo.com/ &quot;Yahoo Search&quot;) or
+[MSN](http://search.msn.com/ &quot;MSN Search&quot;).
+</code></pre>
+
+<p>The point of reference-style links is not that they're easier to
+write. The point is that with reference-style links, your document
+source is vastly more readable. Compare the above examples: using
+reference-style links, the paragraph itself is only 81 characters
+long; with inline-style links, it's 176 characters; and as raw HTML,
+it's 234 characters. In the raw HTML, there's more markup than there
+is text.</p>
+
+<p>With Markdown's reference-style links, a source document much more
+closely resembles the final output, as rendered in a browser. By
+allowing you to move the markup-related metadata out of the paragraph,
+you can add links without interrupting the narrative flow of your
+prose.</p>
+
+<h3 id="em">Emphasis</h3>
+
+<p>Markdown treats asterisks (<code>*</code>) and underscores (<code>_</code>) as indicators of
+emphasis. Text wrapped with one <code>*</code> or <code>_</code> will be wrapped with an
+HTML <code>&lt;em&gt;</code> tag; double <code>*</code>'s or <code>_</code>'s will be wrapped with an HTML
+<code>&lt;strong&gt;</code> tag. E.g., this input:</p>
+
+<pre><code>*single asterisks*
+
+_single underscores_
+
+**double asterisks**
+
+__double underscores__
+</code></pre>
+
+<p>will produce:</p>
+
+<pre><code>&lt;em&gt;single asterisks&lt;/em&gt;
+
+&lt;em&gt;single underscores&lt;/em&gt;
+
+&lt;strong&gt;double asterisks&lt;/strong&gt;
+
+&lt;strong&gt;double underscores&lt;/strong&gt;
+</code></pre>
+
+<p>You can use whichever style you prefer; the lone restriction is that
+the same character must be used to open and close an emphasis span.</p>
+
+<p>Emphasis can be used in the middle of a word:</p>
+
+<pre><code>un*fucking*believable
+</code></pre>
+
+<p>But if you surround an <code>*</code> or <code>_</code> with spaces, it'll be treated as a
+literal asterisk or underscore.</p>
+
+<p>To produce a literal asterisk or underscore at a position where it
+would otherwise be used as an emphasis delimiter, you can backslash
+escape it:</p>
+
+<pre><code>\*this text is surrounded by literal asterisks\*
+</code></pre>
+
+<h3 id="code">Code</h3>
+
+<p>To indicate a span of code, wrap it with backtick quotes (<code>`</code>).
+Unlike a pre-formatted code block, a code span indicates code within a
+normal paragraph. For example:</p>
+
+<pre><code>Use the `printf()` function.
+</code></pre>
+
+<p>will produce:</p>
+
+<pre><code>&lt;p&gt;Use the &lt;code&gt;printf()&lt;/code&gt; function.&lt;/p&gt;
+</code></pre>
+
+<p>To include a literal backtick character within a code span, you can use
+multiple backticks as the opening and closing delimiters:</p>
+
+<pre><code>``There is a literal backtick (`) here.``
+</code></pre>
+
+<p>which will produce this:</p>
+
+<pre><code>&lt;p&gt;&lt;code&gt;There is a literal backtick (`) here.&lt;/code&gt;&lt;/p&gt;
+</code></pre>
+
+<p>The backtick delimiters surrounding a code span may include spaces --
+one after the opening, one before the closing. This allows you to place
+literal backtick characters at the beginning or end of a code span:</p>
+
+<pre><code>A single backtick in a code span: `` ` ``
+
+A backtick-delimited string in a code span: `` `foo` ``
+</code></pre>
+
+<p>will produce:</p>
+
+<pre><code>&lt;p&gt;A single backtick in a code span: &lt;code&gt;`&lt;/code&gt;&lt;/p&gt;
+
+&lt;p&gt;A backtick-delimited string in a code span: &lt;code&gt;`foo`&lt;/code&gt;&lt;/p&gt;
+</code></pre>
+
+<p>With a code span, ampersands and angle brackets are encoded as HTML
+entities automatically, which makes it easy to include example HTML
+tags. Markdown will turn this:</p>
+
+<pre><code>Please don't use any `&lt;blink&gt;` tags.
+</code></pre>
+
+<p>into:</p>
+
+<pre><code>&lt;p&gt;Please don't use any &lt;code&gt;&amp;lt;blink&amp;gt;&lt;/code&gt; tags.&lt;/p&gt;
+</code></pre>
+
+<p>You can write this:</p>
+
+<pre><code>`&amp;#8212;` is the decimal-encoded equivalent of `&amp;mdash;`.
+</code></pre>
+
+<p>to produce:</p>
+
+<pre><code>&lt;p&gt;&lt;code&gt;&amp;amp;#8212;&lt;/code&gt; is the decimal-encoded
+equivalent of &lt;code&gt;&amp;amp;mdash;&lt;/code&gt;.&lt;/p&gt;
+</code></pre>
+
+<h3 id="img">Images</h3>
+
+<p>Admittedly, it's fairly difficult to devise a &quot;natural&quot; syntax for
+placing images into a plain text document format.</p>
+
+<p>Markdown uses an image syntax that is intended to resemble the syntax
+for links, allowing for two styles: <em>inline</em> and <em>reference</em>.</p>
+
+<p>Inline image syntax looks like this:</p>
+
+<pre><code>![Alt text](/path/to/img.jpg)
+
+![Alt text](/path/to/img.jpg &quot;Optional title&quot;)
+</code></pre>
+
+<p>That is:</p>
+
+<ul>
+<li>An exclamation mark: <code>!</code>;</li>
+<li>followed by a set of square brackets, containing the <code>alt</code>
+attribute text for the image;</li>
+<li>followed by a set of parentheses, containing the URL or path to
+the image, and an optional <code>title</code> attribute enclosed in double
+or single quotes.</li>
+</ul>
+
+<p>Reference-style image syntax looks like this:</p>
+
+<pre><code>![Alt text][id]
+</code></pre>
+
+<p>Where &quot;id&quot; is the name of a defined image reference. Image references
+are defined using syntax identical to link references:</p>
+
+<pre><code>[id]: url/to/image  &quot;Optional title attribute&quot;
+</code></pre>
+
+<p>As of this writing, Markdown has no syntax for specifying the
+dimensions of an image; if this is important to you, you can simply
+use regular HTML <code>&lt;img&gt;</code> tags.</p>
+
+<hr>
+
+<h2 id="misc">Miscellaneous</h2>
+
+<h3 id="autolink">Automatic Links</h3>
+
+<p>Markdown supports a shortcut style for creating &quot;automatic&quot; links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:</p>
+
+<pre><code>&lt;http://example.com/&gt;
+</code></pre>
+
+<p>Markdown will turn this into:</p>
+
+<pre><code>&lt;a href=&quot;http://example.com/&quot;&gt;http://example.com/&lt;/a&gt;
+</code></pre>
+
+<p>Automatic links for email addresses work similarly, except that
+Markdown will also perform a bit of randomized decimal and hex
+entity-encoding to help obscure your address from address-harvesting
+spambots. For example, Markdown will turn this:</p>
+
+<pre><code>&lt;address@example.com&gt;
+</code></pre>
+
+<p>into something like this:</p>
+
+<pre><code>&lt;a href=&quot;&amp;#x6D;&amp;#x61;i&amp;#x6C;&amp;#x74;&amp;#x6F;:&amp;#x61;&amp;#x64;&amp;#x64;&amp;#x72;&amp;#x65;
+&amp;#115;&amp;#115;&amp;#64;&amp;#101;&amp;#120;&amp;#x61;&amp;#109;&amp;#x70;&amp;#x6C;e&amp;#x2E;&amp;#99;&amp;#111;
+&amp;#109;&quot;&gt;&amp;#x61;&amp;#x64;&amp;#x64;&amp;#x72;&amp;#x65;&amp;#115;&amp;#115;&amp;#64;&amp;#101;&amp;#120;&amp;#x61;
+&amp;#109;&amp;#x70;&amp;#x6C;e&amp;#x2E;&amp;#99;&amp;#111;&amp;#109;&lt;/a&gt;
+</code></pre>
+
+<p>which will render in a browser as a clickable link to &quot;address@example.com&quot;.</p>
+
+<p>(This sort of entity-encoding trick will indeed fool many, if not
+most, address-harvesting bots, but it definitely won't fool all of
+them. It's better than nothing, but an address published in this way
+will probably eventually start receiving spam.)</p>
+
+<h3 id="backslash">Backslash Escapes</h3>
+
+<p>Markdown allows you to use backslash escapes to generate literal
+characters which would otherwise have special meaning in Markdown's
+formatting syntax. For example, if you wanted to surround a word with
+literal asterisks (instead of an HTML <code>&lt;em&gt;</code> tag), you can backslashes
+before the asterisks, like this:</p>
+
+<pre><code>\*literal asterisks\*
+</code></pre>
+
+<p>Markdown provides backslash escapes for the following characters:</p>
+
+<pre><code>\   backslash
+`   backtick
+*   asterisk
+_   underscore
+{}  curly braces
+[]  square brackets
+()  parentheses
+#   hash mark
++   plus sign
+-   minus sign (hyphen)
+.   dot
+!   exclamation mark
+</code></pre>

+ 888 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Markdown Documentation - Syntax.text

@@ -0,0 +1,888 @@
+Markdown: Syntax
+================
+
+<ul id="ProjectSubmenu">
+    <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
+    <li><a href="/projects/markdown/basics" title="Markdown Basics">Basics</a></li>
+    <li><a class="selected" title="Markdown Syntax Documentation">Syntax</a></li>
+    <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
+    <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
+</ul>
+
+
+*   [Overview](#overview)
+    *   [Philosophy](#philosophy)
+    *   [Inline HTML](#html)
+    *   [Automatic Escaping for Special Characters](#autoescape)
+*   [Block Elements](#block)
+    *   [Paragraphs and Line Breaks](#p)
+    *   [Headers](#header)
+    *   [Blockquotes](#blockquote)
+    *   [Lists](#list)
+    *   [Code Blocks](#precode)
+    *   [Horizontal Rules](#hr)
+*   [Span Elements](#span)
+    *   [Links](#link)
+    *   [Emphasis](#em)
+    *   [Code](#code)
+    *   [Images](#img)
+*   [Miscellaneous](#misc)
+    *   [Backslash Escapes](#backslash)
+    *   [Automatic Links](#autolink)
+
+
+**Note:** This document is itself written using Markdown; you
+can [see the source for it by adding '.text' to the URL][src].
+
+  [src]: /projects/markdown/syntax.text
+
+* * *
+
+<h2 id="overview">Overview</h2>
+
+<h3 id="philosophy">Philosophy</h3>
+
+Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
+
+Readability, however, is emphasized above all else. A Markdown-formatted
+document should be publishable as-is, as plain text, without looking
+like it's been marked up with tags or formatting instructions. While
+Markdown's syntax has been influenced by several existing text-to-HTML
+filters -- including [Setext] [1], [atx] [2], [Textile] [3], [reStructuredText] [4],
+[Grutatext] [5], and [EtText] [6] -- the single biggest source of
+inspiration for Markdown's syntax is the format of plain text email.
+
+  [1]: http://docutils.sourceforge.net/mirror/setext.html
+  [2]: http://www.aaronsw.com/2002/atx/
+  [3]: http://textism.com/tools/textile/
+  [4]: http://docutils.sourceforge.net/rst.html
+  [5]: http://www.triptico.com/software/grutatxt.html
+  [6]: http://ettext.taint.org/doc/
+
+To this end, Markdown's syntax is comprised entirely of punctuation
+characters, which punctuation characters have been carefully chosen so
+as to look like what they mean. E.g., asterisks around a word actually
+look like \*emphasis\*. Markdown lists look like, well, lists. Even
+blockquotes look like quoted passages of text, assuming you've ever
+used email.
+
+
+
+<h3 id="html">Inline HTML</h3>
+
+Markdown's syntax is intended for one purpose: to be used as a
+format for *writing* for the web.
+
+Markdown is not a replacement for HTML, or even close to it. Its
+syntax is very small, corresponding only to a very small subset of
+HTML tags. The idea is *not* to create a syntax that makes it easier
+to insert HTML tags. In my opinion, HTML tags are already easy to
+insert. The idea for Markdown is to make it easy to read, write, and
+edit prose. HTML is a *publishing* format; Markdown is a *writing*
+format. Thus, Markdown's formatting syntax only addresses issues that
+can be conveyed in plain text.
+
+For any markup that is not covered by Markdown's syntax, you simply
+use HTML itself. There's no need to preface it or delimit it to
+indicate that you're switching from Markdown to HTML; you just use
+the tags.
+
+The only restrictions are that block-level HTML elements -- e.g. `<div>`,
+`<table>`, `<pre>`, `<p>`, etc. -- must be separated from surrounding
+content by blank lines, and the start and end tags of the block should
+not be indented with tabs or spaces. Markdown is smart enough not
+to add extra (unwanted) `<p>` tags around HTML block-level tags.
+
+For example, to add an HTML table to a Markdown article:
+
+    This is a regular paragraph.
+
+    <table>
+        <tr>
+            <td>Foo</td>
+        </tr>
+    </table>
+
+    This is another regular paragraph.
+
+Note that Markdown formatting syntax is not processed within block-level
+HTML tags. E.g., you can't use Markdown-style `*emphasis*` inside an
+HTML block.
+
+Span-level HTML tags -- e.g. `<span>`, `<cite>`, or `<del>` -- can be
+used anywhere in a Markdown paragraph, list item, or header. If you
+want, you can even use HTML tags instead of Markdown formatting; e.g. if
+you'd prefer to use HTML `<a>` or `<img>` tags instead of Markdown's
+link or image syntax, go right ahead.
+
+Unlike block-level HTML tags, Markdown syntax *is* processed within
+span-level tags.
+
+
+<h3 id="autoescape">Automatic Escaping for Special Characters</h3>
+
+In HTML, there are two characters that demand special treatment: `<`
+and `&`. Left angle brackets are used to start tags; ampersands are
+used to denote HTML entities. If you want to use them as literal
+characters, you must escape them as entities, e.g. `&lt;`, and
+`&amp;`.
+
+Ampersands in particular are bedeviling for web writers. If you want to
+write about 'AT&T', you need to write '`AT&amp;T`'. You even need to
+escape ampersands within URLs. Thus, if you want to link to:
+
+    http://images.google.com/images?num=30&q=larry+bird
+
+you need to encode the URL as:
+
+    http://images.google.com/images?num=30&amp;q=larry+bird
+
+in your anchor tag `href` attribute. Needless to say, this is easy to
+forget, and is probably the single most common source of HTML validation
+errors in otherwise well-marked-up web sites.
+
+Markdown allows you to use these characters naturally, taking care of
+all the necessary escaping for you. If you use an ampersand as part of
+an HTML entity, it remains unchanged; otherwise it will be translated
+into `&amp;`.
+
+So, if you want to include a copyright symbol in your article, you can write:
+
+    &copy;
+
+and Markdown will leave it alone. But if you write:
+
+    AT&T
+
+Markdown will translate it to:
+
+    AT&amp;T
+
+Similarly, because Markdown supports [inline HTML](#html), if you use
+angle brackets as delimiters for HTML tags, Markdown will treat them as
+such. But if you write:
+
+    4 < 5
+
+Markdown will translate it to:
+
+    4 &lt; 5
+
+However, inside Markdown code spans and blocks, angle brackets and
+ampersands are *always* encoded automatically. This makes it easy to use
+Markdown to write about HTML code. (As opposed to raw HTML, which is a
+terrible format for writing about HTML syntax, because every single `<`
+and `&` in your example code needs to be escaped.)
+
+
+* * *
+
+
+<h2 id="block">Block Elements</h2>
+
+
+<h3 id="p">Paragraphs and Line Breaks</h3>
+
+A paragraph is simply one or more consecutive lines of text, separated
+by one or more blank lines. (A blank line is any line that looks like a
+blank line -- a line containing nothing but spaces or tabs is considered
+blank.) Normal paragraphs should not be intended with spaces or tabs.
+
+The implication of the "one or more consecutive lines of text" rule is
+that Markdown supports "hard-wrapped" text paragraphs. This differs
+significantly from most other text-to-HTML formatters (including Movable
+Type's "Convert Line Breaks" option) which translate every line break
+character in a paragraph into a `<br />` tag.
+
+When you *do* want to insert a `<br />` break tag using Markdown, you
+end a line with two or more spaces, then type return.
+
+Yes, this takes a tad more effort to create a `<br />`, but a simplistic
+"every line break is a `<br />`" rule wouldn't work for Markdown.
+Markdown's email-style [blockquoting][bq] and multi-paragraph [list items][l]
+work best -- and look better -- when you format them with hard breaks.
+
+  [bq]: #blockquote
+  [l]:  #list
+
+
+
+<h3 id="header">Headers</h3>
+
+Markdown supports two styles of headers, [Setext] [1] and [atx] [2].
+
+Setext-style headers are "underlined" using equal signs (for first-level
+headers) and dashes (for second-level headers). For example:
+
+    This is an H1
+    =============
+
+    This is an H2
+    -------------
+
+Any number of underlining `=`'s or `-`'s will work.
+
+Atx-style headers use 1-6 hash characters at the start of the line,
+corresponding to header levels 1-6. For example:
+
+    # This is an H1
+
+    ## This is an H2
+
+    ###### This is an H6
+
+Optionally, you may "close" atx-style headers. This is purely
+cosmetic -- you can use this if you think it looks better. The
+closing hashes don't even need to match the number of hashes
+used to open the header. (The number of opening hashes
+determines the header level.) :
+
+    # This is an H1 #
+
+    ## This is an H2 ##
+
+    ### This is an H3 ######
+
+
+<h3 id="blockquote">Blockquotes</h3>
+
+Markdown uses email-style `>` characters for blockquoting. If you're
+familiar with quoting passages of text in an email message, then you
+know how to create a blockquote in Markdown. It looks best if you hard
+wrap the text and put a `>` before every line:
+
+    > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
+    > consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
+    > Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
+    > 
+    > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
+    > id sem consectetuer libero luctus adipiscing.
+
+Markdown allows you to be lazy and only put the `>` before the first
+line of a hard-wrapped paragraph:
+
+    > This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
+    consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
+    Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
+
+    > Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
+    id sem consectetuer libero luctus adipiscing.
+
+Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by
+adding additional levels of `>`:
+
+    > This is the first level of quoting.
+    >
+    > > This is nested blockquote.
+    >
+    > Back to the first level.
+
+Blockquotes can contain other Markdown elements, including headers, lists,
+and code blocks:
+
+	> ## This is a header.
+	> 
+	> 1.   This is the first list item.
+	> 2.   This is the second list item.
+	> 
+	> Here's some example code:
+	> 
+	>     return shell_exec("echo $input | $markdown_script");
+
+Any decent text editor should make email-style quoting easy. For
+example, with BBEdit, you can make a selection and choose Increase
+Quote Level from the Text menu.
+
+
+<h3 id="list">Lists</h3>
+
+Markdown supports ordered (numbered) and unordered (bulleted) lists.
+
+Unordered lists use asterisks, pluses, and hyphens -- interchangably
+-- as list markers:
+
+    *   Red
+    *   Green
+    *   Blue
+
+is equivalent to:
+
+    +   Red
+    +   Green
+    +   Blue
+
+and:
+
+    -   Red
+    -   Green
+    -   Blue
+
+Ordered lists use numbers followed by periods:
+
+    1.  Bird
+    2.  McHale
+    3.  Parish
+
+It's important to note that the actual numbers you use to mark the
+list have no effect on the HTML output Markdown produces. The HTML
+Markdown produces from the above list is:
+
+    <ol>
+    <li>Bird</li>
+    <li>McHale</li>
+    <li>Parish</li>
+    </ol>
+
+If you instead wrote the list in Markdown like this:
+
+    1.  Bird
+    1.  McHale
+    1.  Parish
+
+or even:
+
+    3. Bird
+    1. McHale
+    8. Parish
+
+you'd get the exact same HTML output. The point is, if you want to,
+you can use ordinal numbers in your ordered Markdown lists, so that
+the numbers in your source match the numbers in your published HTML.
+But if you want to be lazy, you don't have to.
+
+If you do use lazy list numbering, however, you should still start the
+list with the number 1. At some point in the future, Markdown may support
+starting ordered lists at an arbitrary number.
+
+List markers typically start at the left margin, but may be indented by
+up to three spaces. List markers must be followed by one or more spaces
+or a tab.
+
+To make lists look nice, you can wrap items with hanging indents:
+
+    *   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
+        Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
+        viverra nec, fringilla in, laoreet vitae, risus.
+    *   Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
+        Suspendisse id sem consectetuer libero luctus adipiscing.
+
+But if you want to be lazy, you don't have to:
+
+    *   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
+    Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
+    viverra nec, fringilla in, laoreet vitae, risus.
+    *   Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
+    Suspendisse id sem consectetuer libero luctus adipiscing.
+
+If list items are separated by blank lines, Markdown will wrap the
+items in `<p>` tags in the HTML output. For example, this input:
+
+    *   Bird
+    *   Magic
+
+will turn into:
+
+    <ul>
+    <li>Bird</li>
+    <li>Magic</li>
+    </ul>
+
+But this:
+
+    *   Bird
+
+    *   Magic
+
+will turn into:
+
+    <ul>
+    <li><p>Bird</p></li>
+    <li><p>Magic</p></li>
+    </ul>
+
+List items may consist of multiple paragraphs. Each subsequent
+paragraph in a list item must be intended by either 4 spaces
+or one tab:
+
+    1.  This is a list item with two paragraphs. Lorem ipsum dolor
+        sit amet, consectetuer adipiscing elit. Aliquam hendrerit
+        mi posuere lectus.
+
+        Vestibulum enim wisi, viverra nec, fringilla in, laoreet
+        vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
+        sit amet velit.
+
+    2.  Suspendisse id sem consectetuer libero luctus adipiscing.
+
+It looks nice if you indent every line of the subsequent
+paragraphs, but here again, Markdown will allow you to be
+lazy:
+
+    *   This is a list item with two paragraphs.
+
+        This is the second paragraph in the list item. You're
+    only required to indent the first line. Lorem ipsum dolor
+    sit amet, consectetuer adipiscing elit.
+
+    *   Another item in the same list.
+
+To put a blockquote within a list item, the blockquote's `>`
+delimiters need to be indented:
+
+    *   A list item with a blockquote:
+
+        > This is a blockquote
+        > inside a list item.
+
+To put a code block within a list item, the code block needs
+to be indented *twice* -- 8 spaces or two tabs:
+
+    *   A list item with a code block:
+
+            <code goes here>
+
+
+It's worth noting that it's possible to trigger an ordered list by
+accident, by writing something like this:
+
+    1986. What a great season.
+
+In other words, a *number-period-space* sequence at the beginning of a
+line. To avoid this, you can backslash-escape the period:
+
+    1986\. What a great season.
+
+
+
+<h3 id="precode">Code Blocks</h3>
+
+Pre-formatted code blocks are used for writing about programming or
+markup source code. Rather than forming normal paragraphs, the lines
+of a code block are interpreted literally. Markdown wraps a code block
+in both `<pre>` and `<code>` tags.
+
+To produce a code block in Markdown, simply indent every line of the
+block by at least 4 spaces or 1 tab. For example, given this input:
+
+    This is a normal paragraph:
+
+        This is a code block.
+
+Markdown will generate:
+
+    <p>This is a normal paragraph:</p>
+
+    <pre><code>This is a code block.
+    </code></pre>
+
+One level of indentation -- 4 spaces or 1 tab -- is removed from each
+line of the code block. For example, this:
+
+    Here is an example of AppleScript:
+
+        tell application "Foo"
+            beep
+        end tell
+
+will turn into:
+
+    <p>Here is an example of AppleScript:</p>
+
+    <pre><code>tell application "Foo"
+        beep
+    end tell
+    </code></pre>
+
+A code block continues until it reaches a line that is not indented
+(or the end of the article).
+
+Within a code block, ampersands (`&`) and angle brackets (`<` and `>`)
+are automatically converted into HTML entities. This makes it very
+easy to include example HTML source code using Markdown -- just paste
+it and indent it, and Markdown will handle the hassle of encoding the
+ampersands and angle brackets. For example, this:
+
+        <div class="footer">
+            &copy; 2004 Foo Corporation
+        </div>
+
+will turn into:
+
+    <pre><code>&lt;div class="footer"&gt;
+        &amp;copy; 2004 Foo Corporation
+    &lt;/div&gt;
+    </code></pre>
+
+Regular Markdown syntax is not processed within code blocks. E.g.,
+asterisks are just literal asterisks within a code block. This means
+it's also easy to use Markdown to write about Markdown's own syntax.
+
+
+
+<h3 id="hr">Horizontal Rules</h3>
+
+You can produce a horizontal rule tag (`<hr />`) by placing three or
+more hyphens, asterisks, or underscores on a line by themselves. If you
+wish, you may use spaces between the hyphens or asterisks. Each of the
+following lines will produce a horizontal rule:
+
+    * * *
+
+    ***
+
+    *****
+	
+    - - -
+
+    ---------------------------------------
+
+	_ _ _
+
+
+* * *
+
+<h2 id="span">Span Elements</h2>
+
+<h3 id="link">Links</h3>
+
+Markdown supports two style of links: *inline* and *reference*.
+
+In both styles, the link text is delimited by [square brackets].
+
+To create an inline link, use a set of regular parentheses immediately
+after the link text's closing square bracket. Inside the parentheses,
+put the URL where you want the link to point, along with an *optional*
+title for the link, surrounded in quotes. For example:
+
+    This is [an example](http://example.com/ "Title") inline link.
+
+    [This link](http://example.net/) has no title attribute.
+
+Will produce:
+
+    <p>This is <a href="http://example.com/" title="Title">
+    an example</a> inline link.</p>
+
+    <p><a href="http://example.net/">This link</a> has no
+    title attribute.</p>
+
+If you're referring to a local resource on the same server, you can
+use relative paths:
+
+    See my [About](/about/) page for details.
+
+Reference-style links use a second set of square brackets, inside
+which you place a label of your choosing to identify the link:
+
+    This is [an example][id] reference-style link.
+
+You can optionally use a space to separate the sets of brackets:
+
+    This is [an example] [id] reference-style link.
+
+Then, anywhere in the document, you define your link label like this,
+on a line by itself:
+
+    [id]: http://example.com/  "Optional Title Here"
+
+That is:
+
+*   Square brackets containing the link identifier (optionally
+    indented from the left margin using up to three spaces);
+*   followed by a colon;
+*   followed by one or more spaces (or tabs);
+*   followed by the URL for the link;
+*   optionally followed by a title attribute for the link, enclosed
+    in double or single quotes.
+
+The link URL may, optionally, be surrounded by angle brackets:
+
+    [id]: <http://example.com/>  "Optional Title Here"
+
+You can put the title attribute on the next line and use extra spaces
+or tabs for padding, which tends to look better with longer URLs:
+
+    [id]: http://example.com/longish/path/to/resource/here
+        "Optional Title Here"
+
+Link definitions are only used for creating links during Markdown
+processing, and are stripped from your document in the HTML output.
+
+Link definition names may constist of letters, numbers, spaces, and punctuation -- but they are *not* case sensitive. E.g. these two links:
+
+	[link text][a]
+	[link text][A]
+
+are equivalent.
+
+The *implicit link name* shortcut allows you to omit the name of the
+link, in which case the link text itself is used as the name.
+Just use an empty set of square brackets -- e.g., to link the word
+"Google" to the google.com web site, you could simply write:
+
+	[Google][]
+
+And then define the link:
+
+	[Google]: http://google.com/
+
+Because link names may contain spaces, this shortcut even works for
+multiple words in the link text:
+
+	Visit [Daring Fireball][] for more information.
+
+And then define the link:
+	
+	[Daring Fireball]: http://daringfireball.net/
+
+Link definitions can be placed anywhere in your Markdown document. I
+tend to put them immediately after each paragraph in which they're
+used, but if you want, you can put them all at the end of your
+document, sort of like footnotes.
+
+Here's an example of reference links in action:
+
+    I get 10 times more traffic from [Google] [1] than from
+    [Yahoo] [2] or [MSN] [3].
+
+      [1]: http://google.com/        "Google"
+      [2]: http://search.yahoo.com/  "Yahoo Search"
+      [3]: http://search.msn.com/    "MSN Search"
+
+Using the implicit link name shortcut, you could instead write:
+
+    I get 10 times more traffic from [Google][] than from
+    [Yahoo][] or [MSN][].
+
+      [google]: http://google.com/        "Google"
+      [yahoo]:  http://search.yahoo.com/  "Yahoo Search"
+      [msn]:    http://search.msn.com/    "MSN Search"
+
+Both of the above examples will produce the following HTML output:
+
+    <p>I get 10 times more traffic from <a href="http://google.com/"
+    title="Google">Google</a> than from
+    <a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a>
+    or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>
+
+For comparison, here is the same paragraph written using
+Markdown's inline link style:
+
+    I get 10 times more traffic from [Google](http://google.com/ "Google")
+    than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
+    [MSN](http://search.msn.com/ "MSN Search").
+
+The point of reference-style links is not that they're easier to
+write. The point is that with reference-style links, your document
+source is vastly more readable. Compare the above examples: using
+reference-style links, the paragraph itself is only 81 characters
+long; with inline-style links, it's 176 characters; and as raw HTML,
+it's 234 characters. In the raw HTML, there's more markup than there
+is text.
+
+With Markdown's reference-style links, a source document much more
+closely resembles the final output, as rendered in a browser. By
+allowing you to move the markup-related metadata out of the paragraph,
+you can add links without interrupting the narrative flow of your
+prose.
+
+
+<h3 id="em">Emphasis</h3>
+
+Markdown treats asterisks (`*`) and underscores (`_`) as indicators of
+emphasis. Text wrapped with one `*` or `_` will be wrapped with an
+HTML `<em>` tag; double `*`'s or `_`'s will be wrapped with an HTML
+`<strong>` tag. E.g., this input:
+
+    *single asterisks*
+
+    _single underscores_
+
+    **double asterisks**
+
+    __double underscores__
+
+will produce:
+
+    <em>single asterisks</em>
+
+    <em>single underscores</em>
+
+    <strong>double asterisks</strong>
+
+    <strong>double underscores</strong>
+
+You can use whichever style you prefer; the lone restriction is that
+the same character must be used to open and close an emphasis span.
+
+Emphasis can be used in the middle of a word:
+
+    un*fucking*believable
+
+But if you surround an `*` or `_` with spaces, it'll be treated as a
+literal asterisk or underscore.
+
+To produce a literal asterisk or underscore at a position where it
+would otherwise be used as an emphasis delimiter, you can backslash
+escape it:
+
+    \*this text is surrounded by literal asterisks\*
+
+
+
+<h3 id="code">Code</h3>
+
+To indicate a span of code, wrap it with backtick quotes (`` ` ``).
+Unlike a pre-formatted code block, a code span indicates code within a
+normal paragraph. For example:
+
+    Use the `printf()` function.
+
+will produce:
+
+    <p>Use the <code>printf()</code> function.</p>
+
+To include a literal backtick character within a code span, you can use
+multiple backticks as the opening and closing delimiters:
+
+    ``There is a literal backtick (`) here.``
+
+which will produce this:
+
+    <p><code>There is a literal backtick (`) here.</code></p>
+
+The backtick delimiters surrounding a code span may include spaces --
+one after the opening, one before the closing. This allows you to place
+literal backtick characters at the beginning or end of a code span:
+
+	A single backtick in a code span: `` ` ``
+	
+	A backtick-delimited string in a code span: `` `foo` ``
+
+will produce:
+
+	<p>A single backtick in a code span: <code>`</code></p>
+	
+	<p>A backtick-delimited string in a code span: <code>`foo`</code></p>
+
+With a code span, ampersands and angle brackets are encoded as HTML
+entities automatically, which makes it easy to include example HTML
+tags. Markdown will turn this:
+
+    Please don't use any `<blink>` tags.
+
+into:
+
+    <p>Please don't use any <code>&lt;blink&gt;</code> tags.</p>
+
+You can write this:
+
+    `&#8212;` is the decimal-encoded equivalent of `&mdash;`.
+
+to produce:
+
+    <p><code>&amp;#8212;</code> is the decimal-encoded
+    equivalent of <code>&amp;mdash;</code>.</p>
+
+
+
+<h3 id="img">Images</h3>
+
+Admittedly, it's fairly difficult to devise a "natural" syntax for
+placing images into a plain text document format.
+
+Markdown uses an image syntax that is intended to resemble the syntax
+for links, allowing for two styles: *inline* and *reference*.
+
+Inline image syntax looks like this:
+
+    ![Alt text](/path/to/img.jpg)
+
+    ![Alt text](/path/to/img.jpg "Optional title")
+
+That is:
+
+*   An exclamation mark: `!`;
+*   followed by a set of square brackets, containing the `alt`
+    attribute text for the image;
+*   followed by a set of parentheses, containing the URL or path to
+    the image, and an optional `title` attribute enclosed in double
+    or single quotes.
+
+Reference-style image syntax looks like this:
+
+    ![Alt text][id]
+
+Where "id" is the name of a defined image reference. Image references
+are defined using syntax identical to link references:
+
+    [id]: url/to/image  "Optional title attribute"
+
+As of this writing, Markdown has no syntax for specifying the
+dimensions of an image; if this is important to you, you can simply
+use regular HTML `<img>` tags.
+
+
+* * *
+
+
+<h2 id="misc">Miscellaneous</h2>
+
+<h3 id="autolink">Automatic Links</h3>
+
+Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:
+
+    <http://example.com/>
+    
+Markdown will turn this into:
+
+    <a href="http://example.com/">http://example.com/</a>
+
+Automatic links for email addresses work similarly, except that
+Markdown will also perform a bit of randomized decimal and hex
+entity-encoding to help obscure your address from address-harvesting
+spambots. For example, Markdown will turn this:
+
+    <address@example.com>
+
+into something like this:
+
+    <a href="&#x6D;&#x61;i&#x6C;&#x74;&#x6F;:&#x61;&#x64;&#x64;&#x72;&#x65;
+    &#115;&#115;&#64;&#101;&#120;&#x61;&#109;&#x70;&#x6C;e&#x2E;&#99;&#111;
+    &#109;">&#x61;&#x64;&#x64;&#x72;&#x65;&#115;&#115;&#64;&#101;&#120;&#x61;
+    &#109;&#x70;&#x6C;e&#x2E;&#99;&#111;&#109;</a>
+
+which will render in a browser as a clickable link to "address@example.com".
+
+(This sort of entity-encoding trick will indeed fool many, if not
+most, address-harvesting bots, but it definitely won't fool all of
+them. It's better than nothing, but an address published in this way
+will probably eventually start receiving spam.)
+
+
+
+<h3 id="backslash">Backslash Escapes</h3>
+
+Markdown allows you to use backslash escapes to generate literal
+characters which would otherwise have special meaning in Markdown's
+formatting syntax. For example, if you wanted to surround a word with
+literal asterisks (instead of an HTML `<em>` tag), you can backslashes
+before the asterisks, like this:
+
+    \*literal asterisks\*
+
+Markdown provides backslash escapes for the following characters:
+
+    \   backslash
+    `   backtick
+    *   asterisk
+    _   underscore
+    {}  curly braces
+    []  square brackets
+    ()  parentheses
+    #   hash mark
+	+	plus sign
+	-	minus sign (hyphen)
+    .   dot
+    !   exclamation mark
+

+ 9 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Nested blockquotes.html

@@ -0,0 +1,9 @@
+<blockquote>
+<p>foo</p>
+
+<blockquote>
+<p>bar</p>
+</blockquote>
+
+<p>foo</p>
+</blockquote>

+ 5 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Nested blockquotes.text

@@ -0,0 +1,5 @@
+> foo
+>
+> > bar
+>
+> foo

+ 166 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Ordered and unordered lists.html

@@ -0,0 +1,166 @@
+<h2>Unordered</h2>
+
+<p>Asterisks tight:</p>
+
+<ul>
+<li>asterisk 1</li>
+<li>asterisk 2</li>
+<li>asterisk 3</li>
+</ul>
+
+<p>Asterisks loose:</p>
+
+<ul>
+<li><p>asterisk 1</p></li>
+
+<li><p>asterisk 2</p></li>
+
+<li><p>asterisk 3</p></li>
+</ul>
+
+<hr>
+
+<p>Pluses tight:</p>
+
+<ul>
+<li>Plus 1</li>
+<li>Plus 2</li>
+<li>Plus 3</li>
+</ul>
+
+<p>Pluses loose:</p>
+
+<ul>
+<li><p>Plus 1</p></li>
+
+<li><p>Plus 2</p></li>
+
+<li><p>Plus 3</p></li>
+</ul>
+
+<hr>
+
+<p>Minuses tight:</p>
+
+<ul>
+<li>Minus 1</li>
+<li>Minus 2</li>
+<li>Minus 3</li>
+</ul>
+
+<p>Minuses loose:</p>
+
+<ul>
+<li><p>Minus 1</p></li>
+
+<li><p>Minus 2</p></li>
+
+<li><p>Minus 3</p></li>
+</ul>
+
+<h2>Ordered</h2>
+
+<p>Tight:</p>
+
+<ol>
+<li>First</li>
+<li>Second</li>
+<li>Third</li>
+</ol>
+
+<p>and:</p>
+
+<ol>
+<li>One</li>
+<li>Two</li>
+<li>Three</li>
+</ol>
+
+<p>Loose using tabs:</p>
+
+<ol>
+<li><p>First</p></li>
+
+<li><p>Second</p></li>
+
+<li><p>Third</p></li>
+</ol>
+
+<p>and using spaces:</p>
+
+<ol>
+<li><p>One</p></li>
+
+<li><p>Two</p></li>
+
+<li><p>Three</p></li>
+</ol>
+
+<p>Multiple paragraphs:</p>
+
+<ol>
+<li><p>Item 1, graf one.</p>
+
+<p>Item 2. graf two. The quick brown fox jumped over the lazy dog's
+back.</p></li>
+
+<li><p>Item 2.</p></li>
+
+<li><p>Item 3.</p></li>
+</ol>
+
+<h2>Nested</h2>
+
+<ul>
+<li>Tab
+
+<ul>
+<li>Tab
+
+<ul>
+<li>Tab</li>
+</ul></li>
+</ul></li>
+</ul>
+
+<p>Here's another:</p>
+
+<ol>
+<li>First</li>
+<li>Second:
+
+<ul>
+<li>Fee</li>
+<li>Fie</li>
+<li>Foe</li>
+</ul></li>
+<li>Third</li>
+</ol>
+
+<p>Same thing but with paragraphs:</p>
+
+<ol>
+<li><p>First</p></li>
+
+<li><p>Second:</p>
+
+<ul>
+<li>Fee</li>
+<li>Fie</li>
+<li>Foe</li>
+</ul></li>
+
+<li><p>Third</p></li>
+</ol>
+
+<p>This was an error in Markdown 1.0.1:</p>
+
+<ul>
+<li><p>this</p>
+
+<ul>
+<li>sub</li>
+</ul>
+
+<p>that</p></li>
+</ul>

+ 131 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Ordered and unordered lists.text

@@ -0,0 +1,131 @@
+## Unordered
+
+Asterisks tight:
+
+*	asterisk 1
+*	asterisk 2
+*	asterisk 3
+
+
+Asterisks loose:
+
+*	asterisk 1
+
+*	asterisk 2
+
+*	asterisk 3
+
+* * *
+
+Pluses tight:
+
++	Plus 1
++	Plus 2
++	Plus 3
+
+
+Pluses loose:
+
++	Plus 1
+
++	Plus 2
+
++	Plus 3
+
+* * *
+
+
+Minuses tight:
+
+-	Minus 1
+-	Minus 2
+-	Minus 3
+
+
+Minuses loose:
+
+-	Minus 1
+
+-	Minus 2
+
+-	Minus 3
+
+
+## Ordered
+
+Tight:
+
+1.	First
+2.	Second
+3.	Third
+
+and:
+
+1. One
+2. Two
+3. Three
+
+
+Loose using tabs:
+
+1.	First
+
+2.	Second
+
+3.	Third
+
+and using spaces:
+
+1. One
+
+2. Two
+
+3. Three
+
+Multiple paragraphs:
+
+1.	Item 1, graf one.
+
+	Item 2. graf two. The quick brown fox jumped over the lazy dog's
+	back.
+	
+2.	Item 2.
+
+3.	Item 3.
+
+
+
+## Nested
+
+*	Tab
+	*	Tab
+		*	Tab
+
+Here's another:
+
+1. First
+2. Second:
+	* Fee
+	* Fie
+	* Foe
+3. Third
+
+Same thing but with paragraphs:
+
+1. First
+
+2. Second:
+	* Fee
+	* Fie
+	* Foe
+
+3. Third
+
+
+This was an error in Markdown 1.0.1:
+
+*	this
+
+	*	sub
+
+	that

+ 7 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Strong and em together.html

@@ -0,0 +1,7 @@
+<p><strong><em>This is strong and em.</em></strong></p>
+
+<p>So is <strong><em>this</em></strong> word.</p>
+
+<p><strong><em>This is strong and em.</em></strong></p>
+
+<p>So is <strong><em>this</em></strong> word.</p>

+ 7 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Strong and em together.text

@@ -0,0 +1,7 @@
+***This is strong and em.***
+
+So is ***this*** word.
+
+___This is strong and em.___
+
+So is ___this___ word.

+ 26 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tabs.html

@@ -0,0 +1,26 @@
+<ul>
+<li><p>this is a list item
+indented with tabs</p></li>
+
+<li><p>this is a list item
+indented with spaces</p></li>
+</ul>
+
+<p>Code:</p>
+
+<pre><code>this code block is indented by one tab
+</code></pre>
+
+<p>And:</p>
+
+<pre><code>    this code block is indented by two tabs
+</code></pre>
+
+<p>And:</p>
+
+<pre><code>+   this is an example list item
+    indented with tabs
+
++   this is an example list item
+    indented with spaces
+</code></pre>

+ 21 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tabs.text

@@ -0,0 +1,21 @@
++	this is a list item
+	indented with tabs
+
++   this is a list item
+    indented with spaces
+
+Code:
+
+	this code block is indented by one tab
+
+And:
+
+		this code block is indented by two tabs
+
+And:
+
+	+	this is an example list item
+		indented with tabs
+	
+	+   this is an example list item
+	    indented with spaces

+ 9 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tidyness.html

@@ -0,0 +1,9 @@
+<blockquote>
+<p>A list within a blockquote:</p>
+
+<ul>
+<li>asterisk 1</li>
+<li>asterisk 2</li>
+<li>asterisk 3</li>
+</ul>
+</blockquote>

+ 5 - 0
Godeps/_workspace/src/github.com/russross/blackfriday/testdata/Tidyness.text

@@ -0,0 +1,5 @@
+> A list within a blockquote:
+> 
+> *	asterisk 1
+> *	asterisk 2
+> *	asterisk 3

+ 10 - 0
Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/.travis.yml

@@ -0,0 +1,10 @@
+language: go
+go:
+  - 1.5
+install:
+  - go get golang.org/x/tools/cmd/vet
+script:
+  - go get -t -v ./...
+  - diff -u <(echo -n) <(gofmt -d -s .)
+  - go tool vet .
+  - go test -v -race ./...

+ 19 - 0
Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/LICENSE

@@ -0,0 +1,19 @@
+Copyright (c) 2015 Dmitri Shuralyov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 31 - 0
Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/README.md

@@ -0,0 +1,31 @@
+# sanitized_anchor_name [![Build Status](https://travis-ci.org/shurcooL/sanitized_anchor_name.svg?branch=master)](https://travis-ci.org/shurcooL/sanitized_anchor_name) [![GoDoc](https://godoc.org/github.com/shurcooL/sanitized_anchor_name?status.svg)](https://godoc.org/github.com/shurcooL/sanitized_anchor_name)
+
+Package sanitized_anchor_name provides a func to create sanitized anchor names.
+
+Its logic can be reused by multiple packages to create interoperable anchor names and links to those anchors.
+
+At this time, it does not try to ensure that generated anchor names are unique, that responsibility falls on the caller.
+
+Installation
+------------
+
+```bash
+go get -u github.com/shurcooL/sanitized_anchor_name
+```
+
+Example
+-------
+
+```Go
+anchorName := sanitized_anchor_name.Create("This is a header")
+
+fmt.Println(anchorName)
+
+// Output:
+// this-is-a-header
+```
+
+License
+-------
+
+- [MIT License](LICENSE)

+ 29 - 0
Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main.go

@@ -0,0 +1,29 @@
+// Package sanitized_anchor_name provides a func to create sanitized anchor names.
+//
+// Its logic can be reused by multiple packages to create interoperable anchor names
+// and links to those anchors.
+//
+// At this time, it does not try to ensure that generated anchor names
+// are unique, that responsibility falls on the caller.
+package sanitized_anchor_name
+
+import "unicode"
+
+// Create returns a sanitized anchor name for the given text.
+func Create(text string) string {
+	var anchorName []rune
+	var futureDash = false
+	for _, r := range []rune(text) {
+		switch {
+		case unicode.IsLetter(r) || unicode.IsNumber(r):
+			if futureDash && len(anchorName) > 0 {
+				anchorName = append(anchorName, '-')
+			}
+			futureDash = false
+			anchorName = append(anchorName, unicode.ToLower(r))
+		default:
+			futureDash = true
+		}
+	}
+	return string(anchorName)
+}

+ 35 - 0
Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name/main_test.go

@@ -0,0 +1,35 @@
+package sanitized_anchor_name_test
+
+import (
+	"fmt"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/shurcooL/sanitized_anchor_name"
+)
+
+func ExampleCreate() {
+	anchorName := sanitized_anchor_name.Create("This is a header")
+
+	fmt.Println(anchorName)
+
+	// Output:
+	// this-is-a-header
+}
+
+func ExampleCreate2() {
+	fmt.Println(sanitized_anchor_name.Create("This is a header"))
+	fmt.Println(sanitized_anchor_name.Create("This is also          a header"))
+	fmt.Println(sanitized_anchor_name.Create("main.go"))
+	fmt.Println(sanitized_anchor_name.Create("Article 123"))
+	fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?"))
+	fmt.Printf("%q\n", sanitized_anchor_name.Create("        "))
+	fmt.Println(sanitized_anchor_name.Create("Hello, 世界"))
+
+	// Output:
+	// this-is-a-header
+	// this-is-also-a-header
+	// main-go
+	// article-123
+	// let-s-try-this-shall-we
+	// ""
+	// hello-世界
+}

+ 24 - 0
Godeps/_workspace/src/github.com/spf13/cobra/.gitignore

@@ -0,0 +1,24 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+
+cobra.test

+ 3 - 0
Godeps/_workspace/src/github.com/spf13/cobra/.mailmap

@@ -0,0 +1,3 @@
+Steve Francia <steve.francia@gmail.com>
+Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
+Fabiano Franz <ffranz@redhat.com>                   <contact@fabianofranz.com>

+ 9 - 0
Godeps/_workspace/src/github.com/spf13/cobra/.travis.yml

@@ -0,0 +1,9 @@
+language: go
+go:
+  - 1.3.3
+  - 1.4.2
+  - 1.5.1
+  - tip
+script:
+  - go test -v ./...
+  - go build

+ 174 - 0
Godeps/_workspace/src/github.com/spf13/cobra/LICENSE.txt

@@ -0,0 +1,174 @@
+                                Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.

+ 869 - 0
Godeps/_workspace/src/github.com/spf13/cobra/README.md

@@ -0,0 +1,869 @@
+![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
+
+Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
+
+Many of the most widely used Go projects are built using Cobra including:
+
+* [Kubernetes](http://kubernetes.io/)
+* [Hugo](http://gohugo.io)
+* [rkt](https://github.com/coreos/rkt)
+* [Docker (distribution)](https://github.com/docker/distribution)
+* [OpenShift](https://www.openshift.com/)
+* [Delve](https://github.com/derekparker/delve)
+* [GopherJS](http://www.gopherjs.org/)
+* [CockroachDB](http://www.cockroachlabs.com/)
+* [Bleve](http://www.blevesearch.com/)
+* [ProjectAtomic (enterprise)](http://www.projectatomic.io/)
+* [Parse (CLI)](https://parse.com/)
+
+
+[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra) 
+[![CircleCI status](https://circleci.com/gh/spf13/cobra.png?circle-token=:circle-token "CircleCI status")](https://circleci.com/gh/spf13/cobra)
+
+![cobra](https://cloud.githubusercontent.com/assets/173412/10911369/84832a8e-8212-11e5-9f82-cc96660a4794.gif)
+
+# Overview
+
+Cobra is a library providing a simple interface to create powerful modern CLI
+interfaces similar to git & go tools.
+
+Cobra is also an application that will generate your application scaffolding to rapidly
+develop a Cobra-based application.
+
+Cobra provides:
+* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
+* Fully POSIX-compliant flags (including short & long versions)
+* Nested subcommands
+* Global, local and cascading flags
+* Easy generation of applications & commands with `cobra create appname` & `cobra add cmdname`
+* Intelligent suggestions (`app srver`... did you mean `app server`?)
+* Automatic help generation for commands and flags
+* Automatic detailed help for `app help [command]`
+* Automatic help flag recognition of `-h`, `--help`, etc.
+* Automatically generated bash autocomplete for your application
+* Automatically generated man pages for your application
+* Command aliases so you can change things without breaking them
+* The flexibilty to define your own help, usage, etc.
+* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
+
+Cobra has an exceptionally clean interface and simple design without needless
+constructors or initialization methods.
+
+Applications built with Cobra commands are designed to be as user-friendly as
+possible. Flags can be placed before or after the command (as long as a
+confusing space isn’t provided). Both short and long flags can be used. A
+command need not even be fully typed.  Help is automatically generated and
+available for the application or for a specific command using either the help
+command or the `--help` flag.
+
+# Concepts
+
+Cobra is built on a structure of commands, arguments & flags.
+
+**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
+
+The best applications will read like sentences when used. Users will know how
+to use the application because they will natively understand how to use it.
+
+The pattern to follow is 
+`APPNAME VERB NOUN --ADJECTIVE.`
+    or
+`APPNAME COMMAND ARG --FLAG`
+
+A few good real world examples may better illustrate this point.
+
+In the following example, 'server' is a command, and 'port' is a flag:
+
+    > hugo serve --port=1313
+
+In this command we are telling Git to clone the url bare.
+
+    > git clone URL --bare
+
+## Commands
+
+Command is the central point of the application. Each interaction that
+the application supports will be contained in a Command. A command can
+have children commands and optionally run an action.
+
+In the example above, 'server' is the command.
+
+A Command has the following structure:
+
+```go
+type Command struct {
+    Use string // The one-line usage message.
+    Short string // The short description shown in the 'help' output.
+    Long string // The long message shown in the 'help <this-command>' output.
+    Run func(cmd *Command, args []string) // Run runs the command.
+}
+```
+
+## Flags
+
+A Flag is a way to modify the behavior of a command. Cobra supports
+fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
+A Cobra command can define flags that persist through to children commands
+and flags that are only available to that command.
+
+In the example above, 'port' is the flag.
+
+Flag functionality is provided by the [pflag
+library](https://github.com/ogier/pflag), a fork of the flag standard library
+which maintains the same interface while adding POSIX compliance.
+
+## Usage
+
+Cobra works by creating a set of commands and then organizing them into a tree.
+The tree defines the structure of the application.
+
+Once each command is defined with its corresponding flags, then the
+tree is assigned to the commander which is finally executed.
+
+# Installing
+Using Cobra is easy. First, use `go get` to install the latest version
+of the library. This command will install the `cobra` generator executible
+along with the library:
+
+    > go get -v github.com/spf13/cobra/cobra
+
+Next, include Cobra in your application:
+
+```go
+import "github.com/spf13/cobra"
+```
+
+# Getting Started
+
+While you are welcome to provide your own organization, typically a Cobra based
+application will follow the following organizational structure.
+
+```
+  ▾ appName/
+    ▾ cmd/
+        add.go
+        your.go
+        commands.go
+        here.go
+      main.go
+```
+
+In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
+
+```go
+package main
+
+import "{pathToYourApp}/cmd"
+
+func main() {
+	if err := cmd.RootCmd.Execute(); err != nil {
+		fmt.Println(err)
+		os.Exit(-1)
+	}
+}
+```
+
+## Using the Cobra Generator
+
+Cobra provides its own program that will create your application and add any
+commands you want. It's the easiest way to incorporate Cobra into your application.
+
+### cobra init
+
+The `cobra init [yourApp]` command will create your initial application code
+for you. It is a very powerful application that will populate your program with
+the right structure so you can immediately enjoy all the benefits of Cobra. It
+will also automatically apply the license you specify to your application.
+
+Cobra init is pretty smart. You can provide it a full path, or simply a path
+similar to what is expected in the import.
+
+```
+cobra init github.com/spf13/newAppName
+```
+
+### cobra add
+
+Once an application is initialized Cobra can create additional commands for you.
+Let's say you created an app and you wanted the following commands for it:
+
+* app serve
+* app config
+* app config create
+
+In your project directory (where your main.go file is) you would run the following:
+
+```
+cobra add serve
+cobra add config
+cobra add create -p 'configCmd'
+```
+
+Once you have run these four commands you would have an app structure that would look like:
+
+```
+  ▾ app/
+    ▾ cmd/
+        serve.go
+        config.go
+        create.go
+      main.go
+```
+
+at this point you can run `go run main.go` and it would run your app. `go run
+main.go serve`, `go run main.go config`, `go run main.go config create` along
+with `go run main.go help serve`, etc would all work.
+
+Obviously you haven't added your own code to these yet, the commands are ready
+for you to give them their tasks. Have fun.
+
+### Configuring the cobra generator
+
+The cobra generator will be easier to use if you provide a simple configuration
+file which will help you eliminate providing a bunch of repeated information in
+flags over and over.
+
+an example ~/.cobra.yaml file:
+
+```yaml
+author: Steve Francia <spf@spf13.com>
+license: MIT
+```
+
+## Manually implementing Cobra
+
+To manually implement cobra you need to create a bare main.go file and a RootCmd file.
+You will optionally provide additional commands as you see fit.
+
+### Create the root command
+
+The root command represents your binary itself.
+
+
+#### Manually create rootCmd
+
+Cobra doesn't require any special constructors. Simply create your commands.
+
+Ideally you place this in app/cmd/root.go:
+
+```go
+var RootCmd = &cobra.Command{
+	Use:   "hugo",
+	Short: "Hugo is a very fast static site generator",
+	Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at http://hugo.spf13.com`,
+	Run: func(cmd *cobra.Command, args []string) {
+		// Do Stuff Here
+	},
+}
+```
+
+You will additionally define flags and handle configuration in your init() function.
+
+for example cmd/root.go:
+
+```go
+func init() {
+	cobra.OnInitialize(initConfig)
+	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
+	RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
+	RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
+	RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
+	viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
+	viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+}
+```
+
+### Create your main.go
+
+With the root command you need to have your main function execute it.
+Execute should be run on the root for clarity, though it can be called on any command.
+
+In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
+
+```go
+package main
+
+import "{pathToYourApp}/cmd"
+
+func main() {
+	if err := cmd.RootCmd.Execute(); err != nil {
+		fmt.Println(err)
+		os.Exit(-1)
+	}
+}
+```
+
+
+### Create additional commands
+
+Additional commands can be defined and typically are each given their own file
+inside of the cmd/ directory.
+
+If you wanted to create a version command you would create cmd/version.go and
+populate it with the following:
+
+```go
+package cmd
+
+import (
+	"github.com/spf13/cobra"
+)
+
+func init() {
+	RootCmd.AddCommand(versionCmd)
+}
+
+var versionCmd = &cobra.Command{
+	Use:   "version",
+	Short: "Print the version number of Hugo",
+	Long:  `All software has versions. This is Hugo's`,
+	Run: func(cmd *cobra.Command, args []string) {
+		fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
+	},
+}
+```
+
+### Attach command to its parent 
+
+
+If you notice in the above example we attach the command to its parent. In
+this case the parent is the rootCmd. In this example we are attaching it to the
+root, but commands can be attached at any level.
+
+```go
+RootCmd.AddCommand(versionCmd)
+```
+
+### Remove a command from its parent
+
+Removing a command is not a common action in simple programs, but it allows 3rd
+parties to customize an existing command tree.
+
+In this example, we remove the existing `VersionCmd` command of an existing
+root command, and we replace it with our own version:
+
+```go
+mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
+mainlib.RootCmd.AddCommand(versionCmd)
+```
+
+## Working with Flags
+
+Flags provide modifiers to control how the action command operates.
+
+### Assign flags to a command
+
+Since the flags are defined and used in different locations, we need to
+define a variable outside with the correct scope to assign the flag to
+work with.
+
+```go
+var Verbose bool
+var Source string
+```
+
+There are two different approaches to assign a flag.
+
+### Persistent Flags
+
+A flag can be 'persistent' meaning that this flag will be available to the
+command it's assigned to as well as every command under that command. For
+global flags, assign a flag as a persistent flag on the root.
+
+```go
+RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
+```
+
+### Local Flags
+
+A flag can also be assigned locally which will only apply to that specific command.
+
+```go
+RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
+```
+
+
+## Example
+
+In the example below, we have defined three commands. Two are at the top level
+and one (cmdTimes) is a child of one of the top commands. In this case the root
+is not executable meaning that a subcommand is required. This is accomplished
+by not providing a 'Run' for the 'rootCmd'.
+
+We have only defined one flag for a single command.
+
+More documentation about flags is available at https://github.com/spf13/pflag
+
+```go
+package main
+
+import (
+	"fmt"
+	"strings"
+
+	"github.com/spf13/cobra"
+)
+
+func main() {
+
+	var echoTimes int
+
+	var cmdPrint = &cobra.Command{
+		Use:   "print [string to print]",
+		Short: "Print anything to the screen",
+		Long: `print is for printing anything back to the screen.
+            For many years people have printed back to the screen.
+            `,
+		Run: func(cmd *cobra.Command, args []string) {
+			fmt.Println("Print: " + strings.Join(args, " "))
+		},
+	}
+
+	var cmdEcho = &cobra.Command{
+		Use:   "echo [string to echo]",
+		Short: "Echo anything to the screen",
+		Long: `echo is for echoing anything back.
+            Echo works a lot like print, except it has a child command.
+            `,
+		Run: func(cmd *cobra.Command, args []string) {
+			fmt.Println("Print: " + strings.Join(args, " "))
+		},
+	}
+
+	var cmdTimes = &cobra.Command{
+		Use:   "times [# times] [string to echo]",
+		Short: "Echo anything to the screen more times",
+		Long: `echo things multiple times back to the user by providing
+            a count and a string.`,
+		Run: func(cmd *cobra.Command, args []string) {
+			for i := 0; i < echoTimes; i++ {
+				fmt.Println("Echo: " + strings.Join(args, " "))
+			}
+		},
+	}
+
+	cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
+
+	var rootCmd = &cobra.Command{Use: "app"}
+	rootCmd.AddCommand(cmdPrint, cmdEcho)
+	cmdEcho.AddCommand(cmdTimes)
+	rootCmd.Execute()
+}
+```
+
+For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
+
+## The Help Command
+
+Cobra automatically adds a help command to your application when you have subcommands.
+This will be called when a user runs 'app help'. Additionally, help will also
+support all other commands as input. Say, for instance, you have a command called
+'create' without any additional configuration; Cobra will work when 'app help
+create' is called.  Every command will automatically have the '--help' flag added.
+
+### Example
+
+The following output is automatically generated by Cobra. Nothing beyond the
+command and flag definitions are needed.
+
+    > hugo help
+    
+    hugo is the main command, used to build your Hugo site.
+    
+    Hugo is a Fast and Flexible Static Site Generator
+    built with love by spf13 and friends in Go.
+    
+    Complete documentation is available at http://gohugo.io/.
+    
+    Usage:
+      hugo [flags]
+      hugo [command]
+    
+    Available Commands:
+      server          Hugo runs its own webserver to render the files
+      version         Print the version number of Hugo
+      config          Print the site configuration
+      check           Check content in the source directory
+      benchmark       Benchmark hugo by building a site a number of times.
+      convert         Convert your content to different formats
+      new             Create new content for your site
+      list            Listing out various types of content
+      undraft         Undraft changes the content's draft status from 'True' to 'False'
+      genautocomplete Generate shell autocompletion script for Hugo
+      gendoc          Generate Markdown documentation for the Hugo CLI.
+      genman          Generate man page for Hugo
+      import          Import your site from others.
+    
+    Flags:
+      -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
+      -D, --buildDrafts[=false]: include content marked as draft
+      -F, --buildFuture[=false]: include content with publishdate in the future
+          --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
+          --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
+          --config="": config file (default is path/config.yaml|json|toml)
+      -d, --destination="": filesystem path to write files to
+          --disableRSS[=false]: Do not build RSS files
+          --disableSitemap[=false]: Do not build Sitemap file
+          --editor="": edit new content with this editor, if provided
+          --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
+          --log[=false]: Enable Logging
+          --logFile="": Log File path (if set, logging enabled automatically)
+          --noTimes[=false]: Don't sync modification time of files
+          --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
+          --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
+      -s, --source="": filesystem path to read files relative from
+          --stepAnalysis[=false]: display memory and timing of different steps of the program
+      -t, --theme="": theme to use (located in /themes/THEMENAME/)
+          --uglyURLs[=false]: if true, use /filename.html instead of /filename/
+      -v, --verbose[=false]: verbose output
+          --verboseLog[=false]: verbose logging
+      -w, --watch[=false]: watch filesystem for changes and recreate as needed
+    
+    Use "hugo [command] --help" for more information about a command.
+
+
+Help is just a command like any other. There is no special logic or behavior
+around it. In fact, you can provide your own if you want.
+
+### Defining your own help
+
+You can provide your own Help command or you own template for the default command to use.
+
+The default help command is
+
+```go
+func (c *Command) initHelp() {
+	if c.helpCommand == nil {
+		c.helpCommand = &Command{
+			Use:   "help [command]",
+			Short: "Help about any command",
+			Long: `Help provides help for any command in the application.
+        Simply type ` + c.Name() + ` help [path to command] for full details.`,
+			Run: c.HelpFunc(),
+		}
+	}
+	c.AddCommand(c.helpCommand)
+}
+```
+
+You can provide your own command, function or template through the following methods:
+
+```go
+command.SetHelpCommand(cmd *Command)
+
+command.SetHelpFunc(f func(*Command, []string))
+
+command.SetHelpTemplate(s string)
+```
+
+The latter two will also apply to any children commands.
+
+## Usage
+
+When the user provides an invalid flag or invalid command, Cobra responds by
+showing the user the 'usage'.
+
+### Example
+You may recognize this from the help above. That's because the default help
+embeds the usage as part of its output.
+
+    Usage:
+      hugo [flags]
+      hugo [command]
+    
+    Available Commands:
+      server          Hugo runs its own webserver to render the files
+      version         Print the version number of Hugo
+      config          Print the site configuration
+      check           Check content in the source directory
+      benchmark       Benchmark hugo by building a site a number of times.
+      convert         Convert your content to different formats
+      new             Create new content for your site
+      list            Listing out various types of content
+      undraft         Undraft changes the content's draft status from 'True' to 'False'
+      genautocomplete Generate shell autocompletion script for Hugo
+      gendoc          Generate Markdown documentation for the Hugo CLI.
+      genman          Generate man page for Hugo
+      import          Import your site from others.
+    
+    Flags:
+      -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
+      -D, --buildDrafts[=false]: include content marked as draft
+      -F, --buildFuture[=false]: include content with publishdate in the future
+          --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
+          --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
+          --config="": config file (default is path/config.yaml|json|toml)
+      -d, --destination="": filesystem path to write files to
+          --disableRSS[=false]: Do not build RSS files
+          --disableSitemap[=false]: Do not build Sitemap file
+          --editor="": edit new content with this editor, if provided
+          --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
+          --log[=false]: Enable Logging
+          --logFile="": Log File path (if set, logging enabled automatically)
+          --noTimes[=false]: Don't sync modification time of files
+          --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
+          --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
+      -s, --source="": filesystem path to read files relative from
+          --stepAnalysis[=false]: display memory and timing of different steps of the program
+      -t, --theme="": theme to use (located in /themes/THEMENAME/)
+          --uglyURLs[=false]: if true, use /filename.html instead of /filename/
+      -v, --verbose[=false]: verbose output
+          --verboseLog[=false]: verbose logging
+      -w, --watch[=false]: watch filesystem for changes and recreate as needed
+
+### Defining your own usage
+You can provide your own usage function or template for Cobra to use.
+
+The default usage function is:
+
+```go
+return func(c *Command) error {
+	err := tmpl(c.Out(), c.UsageTemplate(), c)
+	return err
+}
+```
+
+Like help, the function and template are overridable through public methods:
+
+```go
+command.SetUsageFunc(f func(*Command) error)
+
+command.SetUsageTemplate(s string)
+```
+
+## PreRun or PostRun Hooks
+
+It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`.  The `Persistent*Run` functions will be inherrited by children if they do not declare their own.  These function are run in the following order:
+
+- `PersistentPreRun`
+- `PreRun`
+- `Run`
+- `PostRun`
+- `PersistentPostRun`
+
+An example of two commands which use all of these features is below.  When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
+
+```go
+package main
+
+import (
+	"fmt"
+
+	"github.com/spf13/cobra"
+)
+
+func main() {
+
+	var rootCmd = &cobra.Command{
+		Use:   "root [sub]",
+		Short: "My root command",
+		PersistentPreRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
+		},
+		PreRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
+		},
+		Run: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside rootCmd Run with args: %v\n", args)
+		},
+		PostRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
+		},
+		PersistentPostRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
+		},
+	}
+
+	var subCmd = &cobra.Command{
+		Use:   "sub [no options!]",
+		Short: "My subcommand",
+		PreRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
+		},
+		Run: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside subCmd Run with args: %v\n", args)
+		},
+		PostRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
+		},
+		PersistentPostRun: func(cmd *cobra.Command, args []string) {
+			fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
+		},
+	}
+
+	rootCmd.AddCommand(subCmd)
+
+	rootCmd.SetArgs([]string{""})
+	_ = rootCmd.Execute()
+	fmt.Print("\n")
+	rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
+	_ = rootCmd.Execute()
+}
+```
+
+
+## Alternative Error Handling
+
+Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is:
+
+* PersistentPreRunE
+* PreRunE
+* RunE
+* PostRunE
+* PersistentPostRunE
+
+**Example Usage using RunE:**
+
+```go
+package main
+
+import (
+	"errors"
+	"log"
+
+	"github.com/spf13/cobra"
+)
+
+func main() {
+	var rootCmd = &cobra.Command{
+		Use:   "hugo",
+		Short: "Hugo is a very fast static site generator",
+		Long: `A Fast and Flexible Static Site Generator built with
+                love by spf13 and friends in Go.
+                Complete documentation is available at http://hugo.spf13.com`,
+		RunE: func(cmd *cobra.Command, args []string) error {
+			// Do Stuff Here
+			return errors.New("some random error")
+		},
+	}
+
+	if err := rootCmd.Execute(); err != nil {
+		log.Fatal(err)
+	}
+}
+```
+
+## Suggestions when "unknown command" happens
+
+Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
+
+```
+$ hugo srever
+Error: unknown command "srever" for "hugo"
+
+Did you mean this?
+        server
+
+Run 'hugo --help' for usage.
+```
+
+Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
+
+If you need to disable suggestions or tweak the string distance in your command, use:
+
+```go
+command.DisableSuggestions = true
+```
+
+or
+
+```go
+command.SuggestionsMinimumDistance = 1
+```
+
+You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:
+
+```
+$ kubectl remove
+Error: unknown command "remove" for "kubectl"
+
+Did you mean this?
+        delete
+
+Run 'kubectl help' for usage.
+```
+
+## Generating Markdown-formatted documentation for your command
+
+Cobra can generate a Markdown-formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md).
+
+## Generating man pages for your command
+
+Cobra can generate a man page based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Man Docs](man_docs.md).
+
+## Generating bash completions for your command
+
+Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible.  Read more about it in [Bash Completions](bash_completions.md).
+
+## Debugging
+
+Cobra provides a ‘DebugFlags’ method on a command which, when called, will print
+out everything Cobra knows about the flags for each command.
+
+### Example
+
+```go
+command.DebugFlags()
+```
+
+## Release Notes
+* **0.9.0** June 17, 2014
+  * flags can appears anywhere in the args (provided they are unambiguous)
+  * --help prints usage screen for app or command
+  * Prefix matching for commands
+  * Cleaner looking help and usage output
+  * Extensive test suite
+* **0.8.0** Nov 5, 2013
+  * Reworked interface to remove commander completely
+  * Command now primary structure
+  * No initialization needed
+  * Usage & Help templates & functions definable at any level
+  * Updated Readme
+* **0.7.0** Sept 24, 2013
+  * Needs more eyes
+  * Test suite
+  * Support for automatic error messages
+  * Support for help command
+  * Support for printing to any io.Writer instead of os.Stderr
+  * Support for persistent flags which cascade down tree
+  * Ready for integration into Hugo
+* **0.1.0** Sept 3, 2013
+  * Implement first draft
+
+## Extensions
+
+Libraries for extending Cobra:
+
+* [cmdns](https://github.com/gosuri/cmdns): Enables name spacing a command's immediate children. It provides an alternative way to structure subcommands, similar to `heroku apps:create` and `ovrclk clusters:launch`.
+
+## ToDo
+* Launch proper documentation site
+
+## Contributing
+
+1. Fork it
+2. Create your feature branch (`git checkout -b my-new-feature`)
+3. Commit your changes (`git commit -am 'Add some feature'`)
+4. Push to the branch (`git push origin my-new-feature`)
+5. Create new Pull Request
+
+## Contributors
+
+Names in no particular order:
+
+* [spf13](https://github.com/spf13), 
+[eparis](https://github.com/eparis), 
+[bep](https://github.com/bep), and many more!
+
+## License
+
+Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
+
+
+[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

+ 425 - 0
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.go

@@ -0,0 +1,425 @@
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"sort"
+	"strings"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/pflag"
+)
+
+const (
+	BashCompFilenameExt     = "cobra_annotation_bash_completion_filename_extentions"
+	BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
+	BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
+)
+
+func preamble(out *bytes.Buffer) {
+	fmt.Fprintf(out, `#!/bin/bash
+
+__debug()
+{
+    if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
+        echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
+    fi
+}
+
+# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
+# _init_completion. This is a very minimal version of that function.
+__my_init_completion()
+{
+    COMPREPLY=()
+    _get_comp_words_by_ref cur prev words cword
+}
+
+__index_of_word()
+{
+    local w word=$1
+    shift
+    index=0
+    for w in "$@"; do
+        [[ $w = "$word" ]] && return
+        index=$((index+1))
+    done
+    index=-1
+}
+
+__contains_word()
+{
+    local w word=$1; shift
+    for w in "$@"; do
+        [[ $w = "$word" ]] && return
+    done
+    return 1
+}
+
+__handle_reply()
+{
+    __debug "${FUNCNAME}"
+    case $cur in
+        -*)
+            if [[ $(type -t compopt) = "builtin" ]]; then
+                compopt -o nospace
+            fi
+            local allflags
+            if [ ${#must_have_one_flag[@]} -ne 0 ]; then
+                allflags=("${must_have_one_flag[@]}")
+            else
+                allflags=("${flags[*]} ${two_word_flags[*]}")
+            fi
+            COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
+            if [[ $(type -t compopt) = "builtin" ]]; then
+                [[ $COMPREPLY == *= ]] || compopt +o nospace
+            fi
+            return 0;
+            ;;
+    esac
+
+    # check if we are handling a flag with special work handling
+    local index
+    __index_of_word "${prev}" "${flags_with_completion[@]}"
+    if [[ ${index} -ge 0 ]]; then
+        ${flags_completion[${index}]}
+        return
+    fi
+
+    # we are parsing a flag and don't have a special handler, no completion
+    if [[ ${cur} != "${words[cword]}" ]]; then
+        return
+    fi
+
+    local completions
+    if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
+        completions=("${must_have_one_flag[@]}")
+    elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
+        completions=("${must_have_one_noun[@]}")
+    else
+        completions=("${commands[@]}")
+    fi
+    COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
+
+    if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
+        declare -F __custom_func >/dev/null && __custom_func
+    fi
+}
+
+# The arguments should be in the form "ext1|ext2|extn"
+__handle_filename_extension_flag()
+{
+    local ext="$1"
+    _filedir "@(${ext})"
+}
+
+__handle_subdirs_in_dir_flag()
+{
+    local dir="$1"
+    pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1
+}
+
+__handle_flag()
+{
+    __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
+
+    # if a command required a flag, and we found it, unset must_have_one_flag()
+    local flagname=${words[c]}
+    # if the word contained an =
+    if [[ ${words[c]} == *"="* ]]; then
+        flagname=${flagname%%=*} # strip everything after the =
+        flagname="${flagname}=" # but put the = back
+    fi
+    __debug "${FUNCNAME}: looking for ${flagname}"
+    if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
+        must_have_one_flag=()
+    fi
+
+    # skip the argument to a two word flag
+    if __contains_word "${words[c]}" "${two_word_flags[@]}"; then
+        c=$((c+1))
+        # if we are looking for a flags value, don't show commands
+        if [[ $c -eq $cword ]]; then
+            commands=()
+        fi
+    fi
+
+    # skip the flag itself
+    c=$((c+1))
+
+}
+
+__handle_noun()
+{
+    __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
+
+    if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
+        must_have_one_noun=()
+    fi
+
+    nouns+=("${words[c]}")
+    c=$((c+1))
+}
+
+__handle_command()
+{
+    __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
+
+    local next_command
+    if [[ -n ${last_command} ]]; then
+        next_command="_${last_command}_${words[c]}"
+    else
+        next_command="_${words[c]}"
+    fi
+    c=$((c+1))
+    __debug "${FUNCNAME}: looking for ${next_command}"
+    declare -F $next_command >/dev/null && $next_command
+}
+
+__handle_word()
+{
+    if [[ $c -ge $cword ]]; then
+        __handle_reply
+        return
+    fi
+    __debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
+    if [[ "${words[c]}" == -* ]]; then
+        __handle_flag
+    elif __contains_word "${words[c]}" "${commands[@]}"; then
+        __handle_command
+    else
+        __handle_noun
+    fi
+    __handle_word
+}
+
+`)
+}
+
+func postscript(out *bytes.Buffer, name string) {
+	fmt.Fprintf(out, "__start_%s()\n", name)
+	fmt.Fprintf(out, `{
+    local cur prev words cword
+    if declare -F _init_completion >/dev/null 2>&1; then
+        _init_completion -s || return
+    else
+        __my_init_completion || return
+    fi
+
+    local c=0
+    local flags=()
+    local two_word_flags=()
+    local flags_with_completion=()
+    local flags_completion=()
+    local commands=("%s")
+    local must_have_one_flag=()
+    local must_have_one_noun=()
+    local last_command
+    local nouns=()
+
+    __handle_word
+}
+
+`, name)
+	fmt.Fprintf(out, `if [[ $(type -t compopt) = "builtin" ]]; then
+    complete -F __start_%s %s
+else
+    complete -o nospace -F __start_%s %s
+fi
+
+`, name, name, name, name)
+	fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n")
+}
+
+func writeCommands(cmd *Command, out *bytes.Buffer) {
+	fmt.Fprintf(out, "    commands=()\n")
+	for _, c := range cmd.Commands() {
+		if !c.IsAvailableCommand() || c == cmd.helpCommand {
+			continue
+		}
+		fmt.Fprintf(out, "    commands+=(%q)\n", c.Name())
+	}
+	fmt.Fprintf(out, "\n")
+}
+
+func writeFlagHandler(name string, annotations map[string][]string, out *bytes.Buffer) {
+	for key, value := range annotations {
+		switch key {
+		case BashCompFilenameExt:
+			fmt.Fprintf(out, "    flags_with_completion+=(%q)\n", name)
+
+			if len(value) > 0 {
+				ext := "__handle_filename_extension_flag " + strings.Join(value, "|")
+				fmt.Fprintf(out, "    flags_completion+=(%q)\n", ext)
+			} else {
+				ext := "_filedir"
+				fmt.Fprintf(out, "    flags_completion+=(%q)\n", ext)
+			}
+		case BashCompSubdirsInDir:
+			fmt.Fprintf(out, "    flags_with_completion+=(%q)\n", name)
+
+			if len(value) == 1 {
+				ext := "__handle_subdirs_in_dir_flag " + value[0]
+				fmt.Fprintf(out, "    flags_completion+=(%q)\n", ext)
+			} else {
+				ext := "_filedir -d"
+				fmt.Fprintf(out, "    flags_completion+=(%q)\n", ext)
+			}
+		}
+	}
+}
+
+func writeShortFlag(flag *pflag.Flag, out *bytes.Buffer) {
+	b := (flag.Value.Type() == "bool")
+	name := flag.Shorthand
+	format := "    "
+	if !b {
+		format += "two_word_"
+	}
+	format += "flags+=(\"-%s\")\n"
+	fmt.Fprintf(out, format, name)
+	writeFlagHandler("-"+name, flag.Annotations, out)
+}
+
+func writeFlag(flag *pflag.Flag, out *bytes.Buffer) {
+	b := (flag.Value.Type() == "bool")
+	name := flag.Name
+	format := "    flags+=(\"--%s"
+	if !b {
+		format += "="
+	}
+	format += "\")\n"
+	fmt.Fprintf(out, format, name)
+	writeFlagHandler("--"+name, flag.Annotations, out)
+}
+
+func writeFlags(cmd *Command, out *bytes.Buffer) {
+	fmt.Fprintf(out, `    flags=()
+    two_word_flags=()
+    flags_with_completion=()
+    flags_completion=()
+
+`)
+	cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
+		writeFlag(flag, out)
+		if len(flag.Shorthand) > 0 {
+			writeShortFlag(flag, out)
+		}
+	})
+	cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
+		writeFlag(flag, out)
+		if len(flag.Shorthand) > 0 {
+			writeShortFlag(flag, out)
+		}
+	})
+
+	fmt.Fprintf(out, "\n")
+}
+
+func writeRequiredFlag(cmd *Command, out *bytes.Buffer) {
+	fmt.Fprintf(out, "    must_have_one_flag=()\n")
+	flags := cmd.NonInheritedFlags()
+	flags.VisitAll(func(flag *pflag.Flag) {
+		for key := range flag.Annotations {
+			switch key {
+			case BashCompOneRequiredFlag:
+				format := "    must_have_one_flag+=(\"--%s"
+				b := (flag.Value.Type() == "bool")
+				if !b {
+					format += "="
+				}
+				format += "\")\n"
+				fmt.Fprintf(out, format, flag.Name)
+
+				if len(flag.Shorthand) > 0 {
+					fmt.Fprintf(out, "    must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)
+				}
+			}
+		}
+	})
+}
+
+func writeRequiredNoun(cmd *Command, out *bytes.Buffer) {
+	fmt.Fprintf(out, "    must_have_one_noun=()\n")
+	sort.Sort(sort.StringSlice(cmd.ValidArgs))
+	for _, value := range cmd.ValidArgs {
+		fmt.Fprintf(out, "    must_have_one_noun+=(%q)\n", value)
+	}
+}
+
+func gen(cmd *Command, out *bytes.Buffer) {
+	for _, c := range cmd.Commands() {
+		if !c.IsAvailableCommand() || c == cmd.helpCommand {
+			continue
+		}
+		gen(c, out)
+	}
+	commandName := cmd.CommandPath()
+	commandName = strings.Replace(commandName, " ", "_", -1)
+	fmt.Fprintf(out, "_%s()\n{\n", commandName)
+	fmt.Fprintf(out, "    last_command=%q\n", commandName)
+	writeCommands(cmd, out)
+	writeFlags(cmd, out)
+	writeRequiredFlag(cmd, out)
+	writeRequiredNoun(cmd, out)
+	fmt.Fprintf(out, "}\n\n")
+}
+
+func (cmd *Command) GenBashCompletion(out *bytes.Buffer) {
+	preamble(out)
+	if len(cmd.BashCompletionFunction) > 0 {
+		fmt.Fprintf(out, "%s\n", cmd.BashCompletionFunction)
+	}
+	gen(cmd, out)
+	postscript(out, cmd.Name())
+}
+
+func (cmd *Command) GenBashCompletionFile(filename string) error {
+	out := new(bytes.Buffer)
+
+	cmd.GenBashCompletion(out)
+
+	outFile, err := os.Create(filename)
+	if err != nil {
+		return err
+	}
+	defer outFile.Close()
+
+	_, err = outFile.Write(out.Bytes())
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag, if it exists.
+func (cmd *Command) MarkFlagRequired(name string) error {
+	return MarkFlagRequired(cmd.Flags(), name)
+}
+
+// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag, if it exists.
+func (cmd *Command) MarkPersistentFlagRequired(name string) error {
+	return MarkFlagRequired(cmd.PersistentFlags(), name)
+}
+
+// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag in the flag set, if it exists.
+func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
+	return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
+}
+
+// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
+// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
+func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error {
+	return MarkFlagFilename(cmd.Flags(), name, extensions...)
+}
+
+// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists.
+// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
+func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
+	return MarkFlagFilename(cmd.PersistentFlags(), name, extensions...)
+}
+
+// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag in the flag set, if it exists.
+// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
+func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
+	return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
+}

+ 149 - 0
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.md

@@ -0,0 +1,149 @@
+# Generating Bash Completions For Your Own cobra.Command
+
+Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
+
+```go
+package main
+
+import (
+        "io/ioutil"
+        "os"
+
+        "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
+)
+
+func main() {
+        kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
+        kubectl.GenBashCompletionFile("out.sh")
+}
+```
+
+That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
+
+## Creating your own custom functions
+
+Some more actual code that works in kubernetes:
+
+```bash
+const (
+        bash_completion_func = `__kubectl_parse_get()
+{
+    local kubectl_output out
+    if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
+        out=($(echo "${kubectl_output}" | awk '{print $1}'))
+        COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
+    fi
+}
+
+__kubectl_get_resource()
+{
+    if [[ ${#nouns[@]} -eq 0 ]]; then
+        return 1
+    fi
+    __kubectl_parse_get ${nouns[${#nouns[@]} -1]}
+    if [[ $? -eq 0 ]]; then
+        return 0
+    fi
+}
+
+__custom_func() {
+    case ${last_command} in
+        kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
+            __kubectl_get_resource
+            return
+            ;;
+        *)
+            ;;
+    esac
+}
+`)
+```
+
+And then I set that in my command definition:
+
+```go
+cmds := &cobra.Command{
+	Use:   "kubectl",
+	Short: "kubectl controls the Kubernetes cluster manager",
+	Long: `kubectl controls the Kubernetes cluster manager.
+
+Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
+	Run: runHelp,
+	BashCompletionFunction: bash_completion_func,
+}
+```
+
+The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__custom_func()` to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`.  `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`.  So it will call `__kubectl_parse_get pod`.  `__kubectl_parse_get` will actually call out to kubernetes and get any pods.  It will then set `COMPREPLY` to valid pods!
+
+## Have the completions code complete your 'nouns'
+
+In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
+
+```go
+validArgs []string = { "pods", "nodes", "services", "replicationControllers" }
+
+cmd := &cobra.Command{
+	Use:     "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
+	Short:   "Display one or many resources",
+	Long:    get_long,
+	Example: get_example,
+	Run: func(cmd *cobra.Command, args []string) {
+		err := RunGet(f, out, cmd, args)
+		util.CheckErr(err)
+	},
+	ValidArgs: validArgs,
+}
+```
+
+Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
+
+```bash
+# kubectl get [tab][tab]
+nodes                 pods                    replicationControllers  services
+```
+
+## Mark flags as required
+
+Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab].  Marking a flag as 'Required' is incredibly easy.
+
+```go
+cmd.MarkFlagRequired("pod")
+cmd.MarkFlagRequired("container")
+```
+
+and you'll get something like
+
+```bash
+# kubectl exec [tab][tab][tab]
+-c            --container=  -p            --pod=  
+```
+
+# Specify valid filename extensions for flags that take a filename
+
+In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
+
+```go
+	annotations := []string{"json", "yaml", "yml"}
+	annotation := make(map[string][]string)
+	annotation[cobra.BashCompFilenameExt] = annotations
+
+	flag := &pflag.Flag{
+		Name:        "filename",
+		Shorthand:   "f",
+		Usage:       usage,
+		Value:       value,
+		DefValue:    value.String(),
+		Annotations: annotation,
+	}
+	cmd.Flags().AddFlag(flag)
+```
+
+Now when you run a command with this filename flag you'll get something like
+
+```bash
+# kubectl create -f 
+test/                         example/                      rpmbuild/
+hello.yml                     test.json
+```
+
+So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.

+ 94 - 0
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go

@@ -0,0 +1,94 @@
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"strings"
+	"testing"
+)
+
+var _ = fmt.Println
+var _ = os.Stderr
+
+func checkOmit(t *testing.T, found, unexpected string) {
+	if strings.Contains(found, unexpected) {
+		t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
+	}
+}
+
+func check(t *testing.T, found, expected string) {
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+}
+
+// World worst custom function, just keep telling you to enter hello!
+const (
+	bash_completion_func = `__custom_func() {
+COMPREPLY=( "hello" )
+}
+`
+)
+
+func TestBashCompletions(t *testing.T) {
+	c := initializeWithRootCmd()
+	cmdEcho.AddCommand(cmdTimes)
+	c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated)
+
+	// custom completion function
+	c.BashCompletionFunction = bash_completion_func
+
+	// required flag
+	c.MarkFlagRequired("introot")
+
+	// valid nouns
+	validArgs := []string{"pods", "nodes", "services", "replicationControllers"}
+	c.ValidArgs = validArgs
+
+	// filename
+	var flagval string
+	c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")
+	c.MarkFlagFilename("filename", "json", "yaml", "yml")
+
+	// persistent filename
+	var flagvalPersistent string
+	c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename")
+	c.MarkPersistentFlagFilename("persistent-filename")
+	c.MarkPersistentFlagRequired("persistent-filename")
+
+	// filename extensions
+	var flagvalExt string
+	c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)")
+	c.MarkFlagFilename("filename-ext")
+
+	// subdirectories in a given directory
+	var flagvalTheme string
+	c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)")
+	c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
+
+	out := new(bytes.Buffer)
+	c.GenBashCompletion(out)
+	str := out.String()
+
+	check(t, str, "_cobra-test")
+	check(t, str, "_cobra-test_echo")
+	check(t, str, "_cobra-test_echo_times")
+	check(t, str, "_cobra-test_print")
+
+	// check for required flags
+	check(t, str, `must_have_one_flag+=("--introot=")`)
+	check(t, str, `must_have_one_flag+=("--persistent-filename=")`)
+	// check for custom completion function
+	check(t, str, `COMPREPLY=( "hello" )`)
+	// check for required nouns
+	check(t, str, `must_have_one_noun+=("pods")`)
+	// check for filename extension flags
+	check(t, str, `flags_completion+=("_filedir")`)
+	// check for filename extension flags
+	check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)
+	// check for subdirs_in_dir flags
+	check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)
+
+	checkOmit(t, str, cmdDeprecated.Name())
+}

+ 170 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra.go

@@ -0,0 +1,170 @@
+// Copyright © 2013 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Commands similar to git, go tools and other modern CLI tools
+// inspired by go, go-Commander, gh and subcommand
+
+package cobra
+
+import (
+	"fmt"
+	"io"
+	"reflect"
+	"strconv"
+	"strings"
+	"text/template"
+	"unicode"
+)
+
+var templateFuncs template.FuncMap = template.FuncMap{
+	"trim":           strings.TrimSpace,
+	"trimRightSpace": trimRightSpace,
+	"rpad":           rpad,
+	"gt":             Gt,
+	"eq":             Eq,
+}
+
+var initializers []func()
+
+// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
+// Set this to true to enable it
+var EnablePrefixMatching bool = false
+
+// enables an information splash screen on Windows if the CLI is started from explorer.exe.
+var EnableWindowsMouseTrap bool = true
+
+var MousetrapHelpText string = `This is a command line tool
+
+You need to open cmd.exe and run it from there.
+`
+
+//AddTemplateFunc adds a template function that's available to Usage and Help
+//template generation.
+func AddTemplateFunc(name string, tmplFunc interface{}) {
+	templateFuncs[name] = tmplFunc
+}
+
+//AddTemplateFuncs adds multiple template functions availalble to Usage and
+//Help template generation.
+func AddTemplateFuncs(tmplFuncs template.FuncMap) {
+	for k, v := range tmplFuncs {
+		templateFuncs[k] = v
+	}
+}
+
+//OnInitialize takes a series of func() arguments and appends them to a slice of func().
+func OnInitialize(y ...func()) {
+	for _, x := range y {
+		initializers = append(initializers, x)
+	}
+}
+
+//Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
+//Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
+//ints and then compared.
+func Gt(a interface{}, b interface{}) bool {
+	var left, right int64
+	av := reflect.ValueOf(a)
+
+	switch av.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+		left = int64(av.Len())
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		left = av.Int()
+	case reflect.String:
+		left, _ = strconv.ParseInt(av.String(), 10, 64)
+	}
+
+	bv := reflect.ValueOf(b)
+
+	switch bv.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+		right = int64(bv.Len())
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		right = bv.Int()
+	case reflect.String:
+		right, _ = strconv.ParseInt(bv.String(), 10, 64)
+	}
+
+	return left > right
+}
+
+//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
+func Eq(a interface{}, b interface{}) bool {
+	av := reflect.ValueOf(a)
+	bv := reflect.ValueOf(b)
+
+	switch av.Kind() {
+	case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
+		panic("Eq called on unsupported type")
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		return av.Int() == bv.Int()
+	case reflect.String:
+		return av.String() == bv.String()
+	}
+	return false
+}
+
+func trimRightSpace(s string) string {
+	return strings.TrimRightFunc(s, unicode.IsSpace)
+}
+
+//rpad adds padding to the right of a string
+func rpad(s string, padding int) string {
+	template := fmt.Sprintf("%%-%ds", padding)
+	return fmt.Sprintf(template, s)
+}
+
+// tmpl executes the given template text on data, writing the result to w.
+func tmpl(w io.Writer, text string, data interface{}) error {
+	t := template.New("top")
+	t.Funcs(templateFuncs)
+	template.Must(t.Parse(text))
+	return t.Execute(w, data)
+}
+
+// ld compares two strings and returns the levenshtein distance between them
+func ld(s, t string, ignoreCase bool) int {
+	if ignoreCase {
+		s = strings.ToLower(s)
+		t = strings.ToLower(t)
+	}
+	d := make([][]int, len(s)+1)
+	for i := range d {
+		d[i] = make([]int, len(t)+1)
+	}
+	for i := range d {
+		d[i][0] = i
+	}
+	for j := range d[0] {
+		d[0][j] = j
+	}
+	for j := 1; j <= len(t); j++ {
+		for i := 1; i <= len(s); i++ {
+			if s[i-1] == t[j-1] {
+				d[i][j] = d[i-1][j-1]
+			} else {
+				min := d[i-1][j]
+				if d[i][j-1] < min {
+					min = d[i][j-1]
+				}
+				if d[i-1][j-1] < min {
+					min = d[i-1][j-1]
+				}
+				d[i][j] = min + 1
+			}
+		}
+
+	}
+	return d[len(s)][len(t)]
+}

+ 128 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/add.go

@@ -0,0 +1,128 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cmd
+
+import (
+	"fmt"
+	"path/filepath"
+	"strings"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+func init() {
+	RootCmd.AddCommand(addCmd)
+}
+
+var pName string
+
+// initialize Command
+var addCmd = &cobra.Command{
+	Use:     "add [command name]",
+	Aliases: []string{"command"},
+	Short:   "Add a command to a Cobra Application",
+	Long: `Add (cobra add) will create a new command, with a license and
+the appropriate structure for a Cobra-based CLI application,
+and register it to its parent (default RootCmd).
+
+If you want your command to be public, pass in the command name
+with an initial uppercase letter.
+
+Example: cobra add server  -> resulting in a new cmd/server.go
+  `,
+
+	Run: func(cmd *cobra.Command, args []string) {
+		if len(args) != 1 {
+			er("add needs a name for the command")
+		}
+		guessProjectPath()
+		createCmdFile(args[0])
+	},
+}
+
+func init() {
+	addCmd.Flags().StringVarP(&pName, "parent", "p", "RootCmd", "name of parent command for this command")
+}
+
+func parentName() string {
+	if !strings.HasSuffix(strings.ToLower(pName), "cmd") {
+		return pName + "Cmd"
+	}
+
+	return pName
+}
+
+func createCmdFile(cmdName string) {
+	lic := getLicense()
+
+	template := `{{ comment .copyright }}
+{{ comment .license }}
+
+package cmd
+
+import (
+	"fmt"
+
+	"github.com/spf13/cobra"
+)
+
+// {{.cmdName}}Cmd represents the {{.cmdName}} command
+var {{ .cmdName }}Cmd = &cobra.Command{
+	Use:   "{{ .cmdName }}",
+	Short: "A brief description of your command",
+	Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples
+and usage of using your command. For example:
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.` + "`" + `,
+	Run: func(cmd *cobra.Command, args []string) {
+		// TODO: Work your own magic here
+		fmt.Println("{{ .cmdName }} called")
+	},
+}
+
+func init() {
+	{{ .parentName }}.AddCommand({{ .cmdName }}Cmd)
+
+	// Here you will define your flags and configuration settings.
+
+	// Cobra supports Persistent Flags which will work for this command
+	// and all subcommands, e.g.:
+	// {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo")
+
+	// Cobra supports local flags which will only run when this command
+	// is called directly, e.g.:
+	// {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
+
+}
+`
+
+	var data map[string]interface{}
+	data = make(map[string]interface{})
+
+	data["copyright"] = copyrightLine()
+	data["license"] = lic.Header
+	data["appName"] = projectName()
+	data["viper"] = viper.GetBool("useViper")
+	data["parentName"] = parentName()
+	data["cmdName"] = cmdName
+
+	err := writeTemplateToFile(filepath.Join(ProjectPath(), guessCmdDir()), cmdName+".go", template, data)
+	if err != nil {
+		er(err)
+	}
+	fmt.Println(cmdName, "created at", filepath.Join(ProjectPath(), guessCmdDir(), cmdName+".go"))
+}

+ 347 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers.go

@@ -0,0 +1,347 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cmd
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"strings"
+	"text/template"
+	"time"
+
+	"github.com/spf13/viper"
+)
+
+// var BaseDir = ""
+// var AppName = ""
+// var CommandDir = ""
+
+var funcMap template.FuncMap
+var projectPath = ""
+var inputPath = ""
+var projectBase = ""
+
+// for testing only
+var testWd = ""
+
+var cmdDirs = []string{"cmd", "cmds", "command", "commands"}
+
+func init() {
+	funcMap = template.FuncMap{
+		"comment": commentifyString,
+	}
+}
+
+func er(msg interface{}) {
+	fmt.Println("Error:", msg)
+	os.Exit(-1)
+}
+
+// Check if a file or directory exists.
+func exists(path string) (bool, error) {
+	_, err := os.Stat(path)
+	if err == nil {
+		return true, nil
+	}
+	if os.IsNotExist(err) {
+		return false, nil
+	}
+	return false, err
+}
+
+func ProjectPath() string {
+	if projectPath == "" {
+		guessProjectPath()
+	}
+
+	return projectPath
+}
+
+// wrapper of the os package so we can test better
+func getWd() (string, error) {
+	if testWd == "" {
+		return os.Getwd()
+	}
+	return testWd, nil
+}
+
+func guessCmdDir() string {
+	guessProjectPath()
+	if b, _ := isEmpty(projectPath); b {
+		return "cmd"
+	}
+
+	files, _ := filepath.Glob(projectPath + string(os.PathSeparator) + "c*")
+	for _, f := range files {
+		for _, c := range cmdDirs {
+			if f == c {
+				return c
+			}
+		}
+	}
+
+	return "cmd"
+}
+
+func guessImportPath() string {
+	guessProjectPath()
+
+	if !strings.HasPrefix(projectPath, getSrcPath()) {
+		er("Cobra only supports project within $GOPATH")
+	}
+
+	return filepath.Clean(strings.TrimPrefix(projectPath, getSrcPath()))
+}
+
+func getSrcPath() string {
+	return filepath.Join(os.Getenv("GOPATH"), "src") + string(os.PathSeparator)
+}
+
+func projectName() string {
+	return filepath.Base(ProjectPath())
+}
+
+func guessProjectPath() {
+	// if no path is provided... assume CWD.
+	if inputPath == "" {
+		x, err := getWd()
+		if err != nil {
+			er(err)
+		}
+
+		// inspect CWD
+		base := filepath.Base(x)
+
+		// if we are in the cmd directory.. back up
+		for _, c := range cmdDirs {
+			if base == c {
+				projectPath = filepath.Dir(x)
+				return
+			}
+		}
+
+		if projectPath == "" {
+			projectPath = filepath.Clean(x)
+			return
+		}
+	}
+
+	srcPath := getSrcPath()
+	// if provided, inspect for logical locations
+	if strings.ContainsRune(inputPath, os.PathSeparator) {
+		if filepath.IsAbs(inputPath) {
+			// if Absolute, use it
+			projectPath = filepath.Clean(inputPath)
+			return
+		}
+		// If not absolute but contains slashes,
+		// assuming it means create it from $GOPATH
+		count := strings.Count(inputPath, string(os.PathSeparator))
+
+		switch count {
+		// If only one directory deep, assume "github.com"
+		case 1:
+			projectPath = filepath.Join(srcPath, "github.com", inputPath)
+			return
+		case 2:
+			projectPath = filepath.Join(srcPath, inputPath)
+			return
+		default:
+			er("Unknown directory")
+		}
+	} else {
+		// hardest case.. just a word.
+		if projectBase == "" {
+			x, err := getWd()
+			if err == nil {
+				projectPath = filepath.Join(x, inputPath)
+				return
+			}
+			er(err)
+		} else {
+			projectPath = filepath.Join(srcPath, projectBase, inputPath)
+			return
+		}
+	}
+}
+
+// isEmpty checks if a given path is empty.
+func isEmpty(path string) (bool, error) {
+	if b, _ := exists(path); !b {
+		return false, fmt.Errorf("%q path does not exist", path)
+	}
+	fi, err := os.Stat(path)
+	if err != nil {
+		return false, err
+	}
+	if fi.IsDir() {
+		f, err := os.Open(path)
+		// FIX: Resource leak - f.close() should be called here by defer or is missed
+		// if the err != nil branch is taken.
+		defer f.Close()
+		if err != nil {
+			return false, err
+		}
+		list, err := f.Readdir(-1)
+		// f.Close() - see bug fix above
+		return len(list) == 0, nil
+	}
+	return fi.Size() == 0, nil
+}
+
+// isDir checks if a given path is a directory.
+func isDir(path string) (bool, error) {
+	fi, err := os.Stat(path)
+	if err != nil {
+		return false, err
+	}
+	return fi.IsDir(), nil
+}
+
+// dirExists checks if a path exists and is a directory.
+func dirExists(path string) (bool, error) {
+	fi, err := os.Stat(path)
+	if err == nil && fi.IsDir() {
+		return true, nil
+	}
+	if os.IsNotExist(err) {
+		return false, nil
+	}
+	return false, err
+}
+
+func writeTemplateToFile(path string, file string, template string, data interface{}) error {
+	filename := filepath.Join(path, file)
+
+	r, err := templateToReader(template, data)
+
+	if err != nil {
+		return err
+	}
+
+	err = safeWriteToDisk(filename, r)
+
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+func writeStringToFile(path, file, text string) error {
+	filename := filepath.Join(path, file)
+
+	r := strings.NewReader(text)
+	err := safeWriteToDisk(filename, r)
+
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+func templateToReader(tpl string, data interface{}) (io.Reader, error) {
+	tmpl := template.New("")
+	tmpl.Funcs(funcMap)
+	tmpl, err := tmpl.Parse(tpl)
+
+	if err != nil {
+		return nil, err
+	}
+	buf := new(bytes.Buffer)
+	err = tmpl.Execute(buf, data)
+
+	return buf, err
+}
+
+// Same as WriteToDisk but checks to see if file/directory already exists.
+func safeWriteToDisk(inpath string, r io.Reader) (err error) {
+	dir, _ := filepath.Split(inpath)
+	ospath := filepath.FromSlash(dir)
+
+	if ospath != "" {
+		err = os.MkdirAll(ospath, 0777) // rwx, rw, r
+		if err != nil {
+			return
+		}
+	}
+
+	ex, err := exists(inpath)
+	if err != nil {
+		return
+	}
+	if ex {
+		return fmt.Errorf("%v already exists", inpath)
+	}
+
+	file, err := os.Create(inpath)
+	if err != nil {
+		return
+	}
+	defer file.Close()
+
+	_, err = io.Copy(file, r)
+	return
+}
+
+func getLicense() License {
+	l := whichLicense()
+	if l != "" {
+		if x, ok := Licenses[l]; ok {
+			return x
+		}
+	}
+
+	return Licenses["apache"]
+}
+
+func whichLicense() string {
+	// if explicitly flagged, use that
+	if userLicense != "" {
+		return matchLicense(userLicense)
+	}
+
+	// if already present in the project, use that
+	// TODO: Inspect project for existing license
+
+	// default to viper's setting
+
+	return matchLicense(viper.GetString("license"))
+}
+
+func copyrightLine() string {
+	author := viper.GetString("author")
+	year := time.Now().Format("2006")
+
+	return "Copyright © " + year + " " + author
+}
+
+func commentifyString(in string) string {
+	var newlines []string
+	lines := strings.Split(in, "\n")
+	for _, x := range lines {
+		if !strings.HasPrefix(x, "//") {
+			if x != "" {
+				newlines = append(newlines, "// "+x)
+			} else {
+				newlines = append(newlines, "//")
+			}
+		} else {
+			newlines = append(newlines, x)
+		}
+	}
+	return strings.Join(newlines, "\n")
+}

+ 39 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/helpers_test.go

@@ -0,0 +1,39 @@
+package cmd
+
+import (
+	"fmt"
+	"os"
+	"testing"
+)
+
+var _ = fmt.Println
+var _ = os.Stderr
+
+func checkGuess(t *testing.T, wd, input, expected string) {
+	testWd = wd
+	inputPath = input
+	guessProjectPath()
+
+	if projectPath != expected {
+		t.Errorf("Unexpected Project Path. \n Got: %q\nExpected: %q\n", projectPath, expected)
+	}
+
+	reset()
+}
+
+func reset() {
+	testWd = ""
+	inputPath = ""
+	projectPath = ""
+}
+
+func TestProjectPath(t *testing.T) {
+	checkGuess(t, "", "github.com/spf13/hugo", getSrcPath()+"github.com/spf13/hugo")
+	checkGuess(t, "", "spf13/hugo", getSrcPath()+"github.com/spf13/hugo")
+	checkGuess(t, "", "/bar/foo", "/bar/foo")
+	checkGuess(t, "/bar/foo", "baz", "/bar/foo/baz")
+	checkGuess(t, "/bar/foo/cmd", "", "/bar/foo")
+	checkGuess(t, "/bar/foo/command", "", "/bar/foo")
+	checkGuess(t, "/bar/foo/commands", "", "/bar/foo")
+	checkGuess(t, "github.com/spf13/hugo/../hugo", "", "github.com/spf13/hugo")
+}

+ 226 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/init.go

@@ -0,0 +1,226 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cmd
+
+import (
+	"fmt"
+	"os"
+	"strings"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+func init() {
+	RootCmd.AddCommand(initCmd)
+}
+
+// initialize Command
+var initCmd = &cobra.Command{
+	Use:     "init [name]",
+	Aliases: []string{"initialize", "initalise", "create"},
+	Short:   "Initalize a Cobra Application",
+	Long: `Initialize (cobra init) will create a new application, with a license
+and the appropriate structure for a Cobra-based CLI application.
+
+  * If a name is provided, it will be created in the current directory;
+  * If no name is provided, the current directory will be assumed;
+  * If a relative path is provided, it will be created inside $GOPATH
+    (e.g. github.com/spf13/hugo);
+  * If an absolute path is provided, it will be created;
+  * If the directory already exists but is empty, it will be used.
+
+Init will not use an exiting directory with contents.`,
+
+	Run: func(cmd *cobra.Command, args []string) {
+		switch len(args) {
+		case 0:
+			inputPath = ""
+
+		case 1:
+			inputPath = args[0]
+
+		default:
+			er("init doesn't support more than 1 parameter")
+		}
+		guessProjectPath()
+		initalizePath(projectPath)
+	},
+}
+
+func initalizePath(path string) {
+	b, err := exists(path)
+	if err != nil {
+		er(err)
+	}
+
+	if !b { // If path doesn't yet exist, create it
+		err := os.MkdirAll(path, os.ModePerm)
+		if err != nil {
+			er(err)
+		}
+	} else { // If path exists and is not empty don't use it
+		empty, err := exists(path)
+		if err != nil {
+			er(err)
+		}
+		if !empty {
+			er("Cobra will not create a new project in a non empty directory")
+		}
+	}
+	// We have a directory and it's empty.. Time to initialize it.
+
+	createLicenseFile()
+	createMainFile()
+	createRootCmdFile()
+}
+
+func createLicenseFile() {
+	lic := getLicense()
+
+	template := lic.Text
+
+	var data map[string]interface{}
+	data = make(map[string]interface{})
+
+	// Try to remove the email address, if any
+	data["copyright"] = strings.Split(copyrightLine(), " <")[0]
+
+	err := writeTemplateToFile(ProjectPath(), "LICENSE", template, data)
+	_ = err
+	// if err != nil {
+	// 	er(err)
+	// }
+}
+
+func createMainFile() {
+	lic := getLicense()
+
+	template := `{{ comment .copyright }}
+{{ comment .license }}
+
+package main
+
+import "{{ .importpath }}"
+
+func main() {
+	cmd.Execute()
+}
+`
+	var data map[string]interface{}
+	data = make(map[string]interface{})
+
+	data["copyright"] = copyrightLine()
+	data["license"] = lic.Header
+	data["importpath"] = guessImportPath() + "/" + guessCmdDir()
+
+	err := writeTemplateToFile(ProjectPath(), "main.go", template, data)
+	_ = err
+	// if err != nil {
+	// 	er(err)
+	// }
+}
+
+func createRootCmdFile() {
+	lic := getLicense()
+
+	template := `{{ comment .copyright }}
+{{ comment .license }}
+
+package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/spf13/cobra"
+{{ if .viper }}	"github.com/spf13/viper"
+{{ end }})
+{{if .viper}}
+var cfgFile string
+{{ end }}
+// This represents the base command when called without any subcommands
+var RootCmd = &cobra.Command{
+	Use:   "{{ .appName }}",
+	Short: "A brief description of your application",
+	Long: ` + "`" + `A longer description that spans multiple lines and likely contains
+examples and usage of using your application. For example:
+
+Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.` + "`" + `,
+// Uncomment the following line if your bare application
+// has an action associated with it:
+//	Run: func(cmd *cobra.Command, args []string) { },
+}
+
+// Execute adds all child commands to the root command sets flags appropriately.
+// This is called by main.main(). It only needs to happen once to the rootCmd.
+func Execute() {
+	if err := RootCmd.Execute(); err != nil {
+		fmt.Println(err)
+		os.Exit(-1)
+	}
+}
+
+func init() {
+{{ if .viper }}	cobra.OnInitialize(initConfig)
+
+{{ end }}	// Here you will define your flags and configuration settings.
+	// Cobra supports Persistent Flags, which, if defined here,
+	// will be global for your application.
+{{ if .viper }}
+	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)")
+{{ else }}
+	// RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)")
+{{ end }}	// Cobra also supports local flags, which will only run
+	// when this action is called directly.
+	RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
+}
+{{ if .viper }}
+// initConfig reads in config file and ENV variables if set.
+func initConfig() {
+	if cfgFile != "" { // enable ability to specify config file via flag
+		viper.SetConfigFile(cfgFile)
+	}
+
+	viper.SetConfigName(".{{ .appName }}") // name of config file (without extension)
+	viper.AddConfigPath("$HOME")  // adding home directory as first search path
+	viper.AutomaticEnv()          // read in environment variables that match
+
+	// If a config file is found, read it in.
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}
+{{ end }}`
+
+	var data map[string]interface{}
+	data = make(map[string]interface{})
+
+	data["copyright"] = copyrightLine()
+	data["license"] = lic.Header
+	data["appName"] = projectName()
+	data["viper"] = viper.GetBool("useViper")
+
+	err := writeTemplateToFile(ProjectPath()+string(os.PathSeparator)+guessCmdDir(), "root.go", template, data)
+	if err != nil {
+		er(err)
+	}
+
+	fmt.Println("Your Cobra application is ready at")
+	fmt.Println(ProjectPath())
+	fmt.Println("Give it a try by going there and running `go run main.go`")
+	fmt.Println("Add commands to it by running `cobra add [cmdname]`")
+}

+ 1133 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/licenses.go

@@ -0,0 +1,1133 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Parts inspired by https://github.com/ryanuber/go-license
+
+package cmd
+
+import "strings"
+
+//Licenses contains all possible licenses a user can chose from
+var Licenses map[string]License
+
+//License represents a software license agreement, containing the Name of
+// the license, its possible matches (on the command line as given to cobra)
+// the header to be used with each file on the file's creating, and the text
+// of the license
+type License struct {
+	Name            string   // The type of license in use
+	PossibleMatches []string // Similar names to guess
+	Text            string   // License text data
+	Header          string   // License header for source files
+}
+
+// given a license name (in), try to match the license indicated
+func matchLicense(in string) string {
+	for key, lic := range Licenses {
+		for _, match := range lic.PossibleMatches {
+			if strings.EqualFold(in, match) {
+				return key
+			}
+		}
+	}
+	return ""
+}
+
+func init() {
+	Licenses = make(map[string]License)
+
+	Licenses["apache"] = License{
+		Name:            "Apache 2.0",
+		PossibleMatches: []string{"apache", "apache20", "apache 2.0", "apache2.0", "apache-2.0"},
+		Header: `
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.`,
+		Text: `
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+`,
+	}
+
+	Licenses["mit"] = License{
+		Name:            "Mit",
+		PossibleMatches: []string{"mit"},
+		Header: `
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.`,
+		Text: `The MIT License (MIT)
+
+{{ .copyright }}
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+`,
+	}
+
+	Licenses["bsd"] = License{
+		Name:            "NewBSD",
+		PossibleMatches: []string{"bsd", "newbsd", "3 clause bsd"},
+		Header: `
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+   this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.`,
+		Text: `{{ .copyright }}
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+   this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+`,
+	}
+
+	Licenses["freebsd"] = License{
+		Name:            "Simplified BSD License",
+		PossibleMatches: []string{"freebsd", "simpbsd", "simple bsd", "2 clause bsd"},
+		Header: `
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+   this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.`,
+		Text: `{{ .copyright }}
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice,
+   this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+`,
+	}
+
+	Licenses["gpl3"] = License{
+		Name:            "GNU General Public License 3.0",
+		PossibleMatches: []string{"gpl3", "gpl", "gnu gpl3", "gnu gpl"},
+		Header: `{{ .copyright }}
+
+ This file is part of {{ .appName }}.
+
+ {{ .appName }} is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ {{ .appName }} is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with {{ .appName }}. If not, see <http://www.gnu.org/licenses/>.
+	   `,
+		Text: `                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type 'show c' for details.
+
+The hypothetical commands 'show w' and 'show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+`,
+	}
+
+	// Licenses["apache20"] = License{
+	// 	Name:            "Apache 2.0",
+	// 	PossibleMatches: []string{"apache", "apache20", ""},
+	//   Header: `
+	//   `,
+	// 	Text: `
+	//   `,
+	// }
+}

+ 84 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd/root.go

@@ -0,0 +1,84 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cmd
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
+	"github.com/spf13/viper"
+)
+
+var cfgFile string
+var userLicense string
+
+// This represents the base command when called without any subcommands
+var RootCmd = &cobra.Command{
+	Use:   "cobra",
+	Short: "A generator for Cobra based Applications",
+	Long: `Cobra is a CLI library for Go that empowers applications.
+This application is a tool to generate the needed files
+to quickly create a Cobra application.`,
+}
+
+//Execute adds all child commands to the root command sets flags appropriately.
+func Execute() {
+	if err := RootCmd.Execute(); err != nil {
+		fmt.Println(err)
+		os.Exit(-1)
+	}
+}
+
+func init() {
+	cobra.OnInitialize(initConfig)
+	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
+	RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/")
+	RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
+	RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
+	RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
+	viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
+	viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
+	viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
+	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
+	viper.SetDefault("license", "apache")
+	viper.SetDefault("licenseText", `
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+`)
+}
+
+// Read in config file and ENV variables if set.
+func initConfig() {
+	if cfgFile != "" { // enable ability to specify config file via flag
+		viper.SetConfigFile(cfgFile)
+	}
+
+	viper.SetConfigName(".cobra") // name of config file (without extension)
+	viper.AddConfigPath("$HOME")  // adding home directory as first search path
+	viper.AutomaticEnv()          // read in environment variables that match
+
+	// If a config file is found, read it in.
+	if err := viper.ReadInConfig(); err == nil {
+		fmt.Println("Using config file:", viper.ConfigFileUsed())
+	}
+}

+ 20 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra/main.go

@@ -0,0 +1,20 @@
+// Copyright © 2015 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package main
+
+import "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra/cobra/cmd"
+
+func main() {
+	cmd.Execute()
+}

+ 1163 - 0
Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go

@@ -0,0 +1,1163 @@
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"reflect"
+	"runtime"
+	"strings"
+	"testing"
+	"text/template"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/pflag"
+)
+
+var _ = fmt.Println
+var _ = os.Stderr
+
+var tp, te, tt, t1, tr []string
+var rootPersPre, echoPre, echoPersPre, timesPersPre []string
+var flagb1, flagb2, flagb3, flagbr, flagbp bool
+var flags1, flags2a, flags2b, flags3, outs string
+var flagi1, flagi2, flagi3, flagir int
+var globalFlag1 bool
+var flagEcho, rootcalled bool
+var versionUsed int
+
+const strtwoParentHelp = "help message for parent flag strtwo"
+const strtwoChildHelp = "help message for child flag strtwo"
+
+var cmdHidden = &Command{
+	Use:   "hide [secret string to print]",
+	Short: "Print anything to screen (if command is known)",
+	Long:  `an absolutely utterly useless command for testing.`,
+	Run: func(cmd *Command, args []string) {
+		outs = "hidden"
+	},
+	Hidden: true,
+}
+
+var cmdPrint = &Command{
+	Use:   "print [string to print]",
+	Short: "Print anything to the screen",
+	Long:  `an absolutely utterly useless command for testing.`,
+	Run: func(cmd *Command, args []string) {
+		tp = args
+	},
+}
+
+var cmdEcho = &Command{
+	Use:     "echo [string to echo]",
+	Aliases: []string{"say"},
+	Short:   "Echo anything to the screen",
+	Long:    `an utterly useless command for testing.`,
+	Example: "Just run cobra-test echo",
+	PersistentPreRun: func(cmd *Command, args []string) {
+		echoPersPre = args
+	},
+	PreRun: func(cmd *Command, args []string) {
+		echoPre = args
+	},
+	Run: func(cmd *Command, args []string) {
+		te = args
+	},
+}
+
+var cmdEchoSub = &Command{
+	Use:   "echosub [string to print]",
+	Short: "second sub command for echo",
+	Long:  `an absolutely utterly useless command for testing gendocs!.`,
+	Run: func(cmd *Command, args []string) {
+	},
+}
+
+var cmdDeprecated = &Command{
+	Use:        "deprecated [can't do anything here]",
+	Short:      "A command which is deprecated",
+	Long:       `an absolutely utterly useless command for testing deprecation!.`,
+	Deprecated: "Please use echo instead",
+	Run: func(cmd *Command, args []string) {
+	},
+}
+
+var cmdTimes = &Command{
+	Use:        "times [# times] [string to echo]",
+	SuggestFor: []string{"counts"},
+	Short:      "Echo anything to the screen more times",
+	Long:       `a slightly useless command for testing.`,
+	PersistentPreRun: func(cmd *Command, args []string) {
+		timesPersPre = args
+	},
+	Run: func(cmd *Command, args []string) {
+		tt = args
+	},
+}
+
+var cmdRootNoRun = &Command{
+	Use:   "cobra-test",
+	Short: "The root can run its own function",
+	Long:  "The root description for help",
+	PersistentPreRun: func(cmd *Command, args []string) {
+		rootPersPre = args
+	},
+}
+
+var cmdRootSameName = &Command{
+	Use:   "print",
+	Short: "Root with the same name as a subcommand",
+	Long:  "The root description for help",
+}
+
+var cmdRootWithRun = &Command{
+	Use:   "cobra-test",
+	Short: "The root can run its own function",
+	Long:  "The root description for help",
+	Run: func(cmd *Command, args []string) {
+		tr = args
+		rootcalled = true
+	},
+}
+
+var cmdSubNoRun = &Command{
+	Use:   "subnorun",
+	Short: "A subcommand without a Run function",
+	Long:  "A long output about a subcommand without a Run function",
+}
+
+var cmdVersion1 = &Command{
+	Use:   "version",
+	Short: "Print the version number",
+	Long:  `First version of the version command`,
+	Run: func(cmd *Command, args []string) {
+		versionUsed = 1
+	},
+}
+
+var cmdVersion2 = &Command{
+	Use:   "version",
+	Short: "Print the version number",
+	Long:  `Second version of the version command`,
+	Run: func(cmd *Command, args []string) {
+		versionUsed = 2
+	},
+}
+
+func flagInit() {
+	cmdEcho.ResetFlags()
+	cmdPrint.ResetFlags()
+	cmdTimes.ResetFlags()
+	cmdRootNoRun.ResetFlags()
+	cmdRootSameName.ResetFlags()
+	cmdRootWithRun.ResetFlags()
+	cmdSubNoRun.ResetFlags()
+	cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
+	cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
+	cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
+	cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
+	cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
+	cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
+	cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
+	cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
+	cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
+	cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
+	cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
+	cmdVersion1.ResetFlags()
+	cmdVersion2.ResetFlags()
+}
+
+func commandInit() {
+	cmdEcho.ResetCommands()
+	cmdPrint.ResetCommands()
+	cmdTimes.ResetCommands()
+	cmdRootNoRun.ResetCommands()
+	cmdRootSameName.ResetCommands()
+	cmdRootWithRun.ResetCommands()
+	cmdSubNoRun.ResetCommands()
+}
+
+func initialize() *Command {
+	tt, tp, te = nil, nil, nil
+	rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
+
+	var c = cmdRootNoRun
+	flagInit()
+	commandInit()
+	return c
+}
+
+func initializeWithSameName() *Command {
+	tt, tp, te = nil, nil, nil
+	rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
+	var c = cmdRootSameName
+	flagInit()
+	commandInit()
+	return c
+}
+
+func initializeWithRootCmd() *Command {
+	cmdRootWithRun.ResetCommands()
+	tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false
+	flagInit()
+	cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
+	cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
+	commandInit()
+	return cmdRootWithRun
+}
+
+type resulter struct {
+	Error   error
+	Output  string
+	Command *Command
+}
+
+func fullSetupTest(input string) resulter {
+	c := initializeWithRootCmd()
+
+	return fullTester(c, input)
+}
+
+func noRRSetupTestSilenced(input string) resulter {
+	c := initialize()
+	c.SilenceErrors = true
+	c.SilenceUsage = true
+	return fullTester(c, input)
+}
+
+func noRRSetupTest(input string) resulter {
+	c := initialize()
+
+	return fullTester(c, input)
+}
+
+func rootOnlySetupTest(input string) resulter {
+	c := initializeWithRootCmd()
+
+	return simpleTester(c, input)
+}
+
+func simpleTester(c *Command, input string) resulter {
+	buf := new(bytes.Buffer)
+	// Testing flag with invalid input
+	c.SetOutput(buf)
+	c.SetArgs(strings.Split(input, " "))
+
+	err := c.Execute()
+	output := buf.String()
+
+	return resulter{err, output, c}
+}
+
+func simpleTesterC(c *Command, input string) resulter {
+	buf := new(bytes.Buffer)
+	// Testing flag with invalid input
+	c.SetOutput(buf)
+	c.SetArgs(strings.Split(input, " "))
+
+	cmd, err := c.ExecuteC()
+	output := buf.String()
+
+	return resulter{err, output, cmd}
+}
+
+func fullTester(c *Command, input string) resulter {
+	buf := new(bytes.Buffer)
+	// Testing flag with invalid input
+	c.SetOutput(buf)
+	cmdEcho.AddCommand(cmdTimes)
+	c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated)
+	c.SetArgs(strings.Split(input, " "))
+
+	err := c.Execute()
+	output := buf.String()
+
+	return resulter{err, output, c}
+}
+
+func logErr(t *testing.T, found, expected string) {
+	out := new(bytes.Buffer)
+
+	_, _, line, ok := runtime.Caller(2)
+	if ok {
+		fmt.Fprintf(out, "Line: %d ", line)
+	}
+	fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	t.Errorf(out.String())
+}
+
+func checkStringContains(t *testing.T, found, expected string) {
+	if !strings.Contains(found, expected) {
+		logErr(t, found, expected)
+	}
+}
+
+func checkResultContains(t *testing.T, x resulter, check string) {
+	checkStringContains(t, x.Output, check)
+}
+
+func checkStringOmits(t *testing.T, found, expected string) {
+	if strings.Contains(found, expected) {
+		logErr(t, found, expected)
+	}
+}
+
+func checkResultOmits(t *testing.T, x resulter, check string) {
+	checkStringOmits(t, x.Output, check)
+}
+
+func checkOutputContains(t *testing.T, c *Command, check string) {
+	buf := new(bytes.Buffer)
+	c.SetOutput(buf)
+	c.Execute()
+
+	if !strings.Contains(buf.String(), check) {
+		logErr(t, buf.String(), check)
+	}
+}
+
+func TestSingleCommand(t *testing.T) {
+	noRRSetupTest("print one two")
+
+	if te != nil || tt != nil {
+		t.Error("Wrong command called")
+	}
+	if tp == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tp, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+}
+
+func TestChildCommand(t *testing.T) {
+	noRRSetupTest("echo times one two")
+
+	if te != nil || tp != nil {
+		t.Error("Wrong command called")
+	}
+	if tt == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tt, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+}
+
+func TestCommandAlias(t *testing.T) {
+	noRRSetupTest("say times one two")
+
+	if te != nil || tp != nil {
+		t.Error("Wrong command called")
+	}
+	if tt == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tt, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+}
+
+func TestPrefixMatching(t *testing.T) {
+	EnablePrefixMatching = true
+	noRRSetupTest("ech times one two")
+
+	if te != nil || tp != nil {
+		t.Error("Wrong command called")
+	}
+	if tt == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tt, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+
+	EnablePrefixMatching = false
+}
+
+func TestNoPrefixMatching(t *testing.T) {
+	EnablePrefixMatching = false
+
+	noRRSetupTest("ech times one two")
+
+	if !(tt == nil && te == nil && tp == nil) {
+		t.Error("Wrong command called")
+	}
+}
+
+func TestAliasPrefixMatching(t *testing.T) {
+	EnablePrefixMatching = true
+	noRRSetupTest("sa times one two")
+
+	if te != nil || tp != nil {
+		t.Error("Wrong command called")
+	}
+	if tt == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tt, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+	EnablePrefixMatching = false
+}
+
+func TestChildSameName(t *testing.T) {
+	c := initializeWithSameName()
+	c.AddCommand(cmdPrint, cmdEcho)
+	c.SetArgs(strings.Split("print one two", " "))
+	c.Execute()
+
+	if te != nil || tt != nil {
+		t.Error("Wrong command called")
+	}
+	if tp == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tp, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+}
+
+func TestGrandChildSameName(t *testing.T) {
+	c := initializeWithSameName()
+	cmdTimes.AddCommand(cmdPrint)
+	c.AddCommand(cmdTimes)
+	c.SetArgs(strings.Split("times print one two", " "))
+	c.Execute()
+
+	if te != nil || tt != nil {
+		t.Error("Wrong command called")
+	}
+	if tp == nil {
+		t.Error("Wrong command called")
+	}
+	if strings.Join(tp, " ") != "one two" {
+		t.Error("Command didn't parse correctly")
+	}
+}
+
+func TestFlagLong(t *testing.T) {
+	noRRSetupTest("echo --intone=13 something -- here")
+
+	if cmdEcho.ArgsLenAtDash() != 1 {
+		t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())
+	}
+	if strings.Join(te, " ") != "something here" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", te)
+	}
+	if flagi1 != 13 {
+		t.Errorf("int flag didn't get correct value, had %d", flagi1)
+	}
+	if flagi2 != 234 {
+		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
+	}
+}
+
+func TestFlagShort(t *testing.T) {
+	noRRSetupTest("echo -i13 -- something here")
+
+	if cmdEcho.ArgsLenAtDash() != 0 {
+		t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())
+	}
+	if strings.Join(te, " ") != "something here" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", te)
+	}
+	if flagi1 != 13 {
+		t.Errorf("int flag didn't get correct value, had %d", flagi1)
+	}
+	if flagi2 != 234 {
+		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
+	}
+
+	noRRSetupTest("echo -i 13 something here")
+
+	if strings.Join(te, " ") != "something here" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", te)
+	}
+	if flagi1 != 13 {
+		t.Errorf("int flag didn't get correct value, had %d", flagi1)
+	}
+	if flagi2 != 234 {
+		t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
+	}
+
+	noRRSetupTest("print -i99 one two")
+
+	if strings.Join(tp, " ") != "one two" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", tp)
+	}
+	if flagi3 != 99 {
+		t.Errorf("int flag didn't get correct value, had %d", flagi3)
+	}
+	if flagi1 != 123 {
+		t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2)
+	}
+}
+
+func TestChildCommandFlags(t *testing.T) {
+	noRRSetupTest("echo times -j 99 one two")
+
+	if strings.Join(tt, " ") != "one two" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", tt)
+	}
+
+	// Testing with flag that shouldn't be persistent
+	r := noRRSetupTest("echo times -j 99 -i77 one two")
+
+	if r.Error == nil {
+		t.Errorf("invalid flag should generate error")
+	}
+
+	if !strings.Contains(r.Error.Error(), "unknown shorthand") {
+		t.Errorf("Wrong error message displayed, \n %s", r.Error)
+	}
+
+	if flagi2 != 99 {
+		t.Errorf("flag value should be 99, %d given", flagi2)
+	}
+
+	if flagi1 != 123 {
+		t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)
+	}
+
+	// Testing with flag only existing on child
+	r = noRRSetupTest("echo -j 99 -i77 one two")
+
+	if r.Error == nil {
+		t.Errorf("invalid flag should generate error")
+	}
+	if !strings.Contains(r.Error.Error(), "unknown shorthand flag") {
+		t.Errorf("Wrong error message displayed, \n %s", r.Error)
+	}
+
+	// Testing with persistent flag overwritten by child
+	noRRSetupTest("echo times --strtwo=child one two")
+
+	if flags2b != "child" {
+		t.Errorf("flag value should be child, %s given", flags2b)
+	}
+
+	if flags2a != "two" {
+		t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)
+	}
+
+	// Testing flag with invalid input
+	r = noRRSetupTest("echo -i10E")
+
+	if r.Error == nil {
+		t.Errorf("invalid input should generate error")
+	}
+	if !strings.Contains(r.Error.Error(), "invalid argument \"10E\" for i10E") {
+		t.Errorf("Wrong error message displayed, \n %s", r.Error)
+	}
+}
+
+func TestTrailingCommandFlags(t *testing.T) {
+	x := fullSetupTest("echo two -x")
+
+	if x.Error == nil {
+		t.Errorf("invalid flag should generate error")
+	}
+}
+
+func TestInvalidSubcommandFlags(t *testing.T) {
+	cmd := initializeWithRootCmd()
+	cmd.AddCommand(cmdTimes)
+
+	result := simpleTester(cmd, "times --inttwo=2 --badflag=bar")
+	// given that we are not checking here result.Error we check for
+	// stock usage message
+	checkResultContains(t, result, "cobra-test times [# times]")
+	if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") {
+		t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")
+	}
+
+}
+
+func TestSubcommandExecuteC(t *testing.T) {
+	cmd := initializeWithRootCmd()
+	double := &Command{
+		Use: "double message",
+		Run: func(c *Command, args []string) {
+			msg := strings.Join(args, " ")
+			c.Println(msg, msg)
+		},
+	}
+
+	echo := &Command{
+		Use: "echo message",
+		Run: func(c *Command, args []string) {
+			msg := strings.Join(args, " ")
+			c.Println(msg, msg)
+		},
+	}
+
+	cmd.AddCommand(double, echo)
+
+	result := simpleTesterC(cmd, "double hello world")
+	checkResultContains(t, result, "hello world hello world")
+
+	if result.Command.Name() != "double" {
+		t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())
+	}
+
+	result = simpleTesterC(cmd, "echo msg to be echoed")
+	checkResultContains(t, result, "msg to be echoed")
+
+	if result.Command.Name() != "echo" {
+		t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())
+	}
+}
+
+func TestSubcommandArgEvaluation(t *testing.T) {
+	cmd := initializeWithRootCmd()
+
+	first := &Command{
+		Use: "first",
+		Run: func(cmd *Command, args []string) {
+		},
+	}
+	cmd.AddCommand(first)
+
+	second := &Command{
+		Use: "second",
+		Run: func(cmd *Command, args []string) {
+			fmt.Fprintf(cmd.Out(), "%v", args)
+		},
+	}
+	first.AddCommand(second)
+
+	result := simpleTester(cmd, "first second first third")
+
+	expectedOutput := fmt.Sprintf("%v", []string{"first third"})
+	if result.Output != expectedOutput {
+		t.Errorf("exptected %v, got %v", expectedOutput, result.Output)
+	}
+}
+
+func TestPersistentFlags(t *testing.T) {
+	fullSetupTest("echo -s something -p more here")
+
+	// persistentFlag should act like normal flag on its own command
+	if strings.Join(te, " ") != "more here" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", te)
+	}
+	if flags1 != "something" {
+		t.Errorf("string flag didn't get correct value, had %v", flags1)
+	}
+	if !flagbp {
+		t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
+	}
+
+	// persistentFlag should act like normal flag on its own command
+	fullSetupTest("echo times -s again -c -p test here")
+
+	if strings.Join(tt, " ") != "test here" {
+		t.Errorf("flags didn't leave proper args remaining..%s given", tt)
+	}
+
+	if flags1 != "again" {
+		t.Errorf("string flag didn't get correct value, had %v", flags1)
+	}
+
+	if !flagb2 {
+		t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2)
+	}
+	if !flagbp {
+		t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
+	}
+}
+
+func TestHelpCommand(t *testing.T) {
+	x := fullSetupTest("help")
+	checkResultContains(t, x, cmdRootWithRun.Long)
+
+	x = fullSetupTest("help echo")
+	checkResultContains(t, x, cmdEcho.Long)
+
+	x = fullSetupTest("help echo times")
+	checkResultContains(t, x, cmdTimes.Long)
+}
+
+func TestChildCommandHelp(t *testing.T) {
+	c := noRRSetupTest("print --help")
+	checkResultContains(t, c, strtwoParentHelp)
+	r := noRRSetupTest("echo times --help")
+	checkResultContains(t, r, strtwoChildHelp)
+}
+
+func TestNonRunChildHelp(t *testing.T) {
+	x := noRRSetupTest("subnorun")
+	checkResultContains(t, x, cmdSubNoRun.Long)
+}
+
+func TestRunnableRootCommand(t *testing.T) {
+	x := fullSetupTest("")
+
+	if rootcalled != true {
+		t.Errorf("Root Function was not called\n out:%v", x.Error)
+	}
+}
+
+func TestVisitParents(t *testing.T) {
+	c := &Command{Use: "app"}
+	sub := &Command{Use: "sub"}
+	dsub := &Command{Use: "dsub"}
+	sub.AddCommand(dsub)
+	c.AddCommand(sub)
+	total := 0
+	add := func(x *Command) {
+		total++
+	}
+	sub.VisitParents(add)
+	if total != 1 {
+		t.Errorf("Should have visited 1 parent but visited %d", total)
+	}
+
+	total = 0
+	dsub.VisitParents(add)
+	if total != 2 {
+		t.Errorf("Should have visited 2 parent but visited %d", total)
+	}
+
+	total = 0
+	c.VisitParents(add)
+	if total != 0 {
+		t.Errorf("Should have not visited any parent but visited %d", total)
+	}
+}
+
+func TestRunnableRootCommandNilInput(t *testing.T) {
+	empty_arg := make([]string, 0)
+	c := initializeWithRootCmd()
+
+	buf := new(bytes.Buffer)
+	// Testing flag with invalid input
+	c.SetOutput(buf)
+	cmdEcho.AddCommand(cmdTimes)
+	c.AddCommand(cmdPrint, cmdEcho)
+	c.SetArgs(empty_arg)
+
+	err := c.Execute()
+	if err != nil {
+		t.Errorf("Execute() failed with %v", err)
+	}
+
+	if rootcalled != true {
+		t.Errorf("Root Function was not called")
+	}
+}
+
+func TestRunnableRootCommandEmptyInput(t *testing.T) {
+	args := make([]string, 3)
+	args[0] = ""
+	args[1] = "--introot=12"
+	args[2] = ""
+	c := initializeWithRootCmd()
+
+	buf := new(bytes.Buffer)
+	// Testing flag with invalid input
+	c.SetOutput(buf)
+	cmdEcho.AddCommand(cmdTimes)
+	c.AddCommand(cmdPrint, cmdEcho)
+	c.SetArgs(args)
+
+	c.Execute()
+
+	if rootcalled != true {
+		t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf)
+	}
+}
+
+func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
+	fullSetupTest("echo invalid-sub")
+
+	if te[0] != "invalid-sub" {
+		t.Errorf("Subcommand didn't work...")
+	}
+}
+
+func TestRootFlags(t *testing.T) {
+	fullSetupTest("-i 17 -b")
+
+	if flagbr != true {
+		t.Errorf("flag value should be true, %v given", flagbr)
+	}
+
+	if flagir != 17 {
+		t.Errorf("flag value should be 17, %d given", flagir)
+	}
+}
+
+func TestRootHelp(t *testing.T) {
+	x := fullSetupTest("--help")
+
+	checkResultContains(t, x, "Available Commands:")
+	checkResultContains(t, x, "for more information about a command")
+
+	if strings.Contains(x.Output, "unknown flag: --help") {
+		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
+	}
+
+	if strings.Contains(x.Output, cmdEcho.Use) {
+		t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
+	}
+
+	x = fullSetupTest("echo --help")
+
+	if strings.Contains(x.Output, cmdTimes.Use) {
+		t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
+	}
+
+	checkResultContains(t, x, "Available Commands:")
+	checkResultContains(t, x, "for more information about a command")
+
+	if strings.Contains(x.Output, "unknown flag: --help") {
+		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
+	}
+
+}
+
+func TestFlagAccess(t *testing.T) {
+	initialize()
+
+	local := cmdTimes.LocalFlags()
+	inherited := cmdTimes.InheritedFlags()
+
+	for _, f := range []string{"inttwo", "strtwo", "booltwo"} {
+		if local.Lookup(f) == nil {
+			t.Errorf("LocalFlags expected to contain %s, Got: nil", f)
+		}
+	}
+	if inherited.Lookup("strone") == nil {
+		t.Errorf("InheritedFlags expected to contain strone, Got: nil")
+	}
+	if inherited.Lookup("strtwo") != nil {
+		t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")
+
+	}
+}
+
+func TestNoNRunnableRootCommandNilInput(t *testing.T) {
+	args := make([]string, 0)
+	c := initialize()
+
+	buf := new(bytes.Buffer)
+	// Testing flag with invalid input
+	c.SetOutput(buf)
+	cmdEcho.AddCommand(cmdTimes)
+	c.AddCommand(cmdPrint, cmdEcho)
+	c.SetArgs(args)
+
+	c.Execute()
+
+	if !strings.Contains(buf.String(), cmdRootNoRun.Long) {
+		t.Errorf("Expected to get help output, Got: \n %s", buf)
+	}
+}
+
+func TestRootNoCommandHelp(t *testing.T) {
+	x := rootOnlySetupTest("--help")
+
+	checkResultOmits(t, x, "Available Commands:")
+	checkResultOmits(t, x, "for more information about a command")
+
+	if strings.Contains(x.Output, "unknown flag: --help") {
+		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
+	}
+
+	x = rootOnlySetupTest("echo --help")
+
+	checkResultOmits(t, x, "Available Commands:")
+	checkResultOmits(t, x, "for more information about a command")
+
+	if strings.Contains(x.Output, "unknown flag: --help") {
+		t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
+	}
+}
+
+func TestRootUnknownCommand(t *testing.T) {
+	r := noRRSetupTest("bogus")
+	s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"
+
+	if r.Output != s {
+		t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
+	}
+
+	r = noRRSetupTest("--strtwo=a bogus")
+	if r.Output != s {
+		t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
+	}
+}
+
+func TestRootUnknownCommandSilenced(t *testing.T) {
+	r := noRRSetupTestSilenced("bogus")
+	s := "Run 'cobra-test --help' for usage.\n"
+
+	if r.Output != "" {
+		t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", s, r.Output)
+	}
+
+	r = noRRSetupTestSilenced("--strtwo=a bogus")
+	if r.Output != "" {
+		t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", s, r.Output)
+	}
+}
+
+func TestRootSuggestions(t *testing.T) {
+	outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n"
+	outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"
+
+	cmd := initializeWithRootCmd()
+	cmd.AddCommand(cmdTimes)
+
+	tests := map[string]string{
+		"time":     "times",
+		"tiems":    "times",
+		"tims":     "times",
+		"timeS":    "times",
+		"rimes":    "times",
+		"ti":       "times",
+		"t":        "times",
+		"timely":   "times",
+		"ri":       "",
+		"timezone": "",
+		"foo":      "",
+		"counts":   "times",
+	}
+
+	for typo, suggestion := range tests {
+		for _, suggestionsDisabled := range []bool{false, true} {
+			cmd.DisableSuggestions = suggestionsDisabled
+			result := simpleTester(cmd, typo)
+			expected := ""
+			if len(suggestion) == 0 || suggestionsDisabled {
+				expected = fmt.Sprintf(outputWithoutSuggestions, typo)
+			} else {
+				expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion)
+			}
+			if result.Output != expected {
+				t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)
+			}
+		}
+	}
+}
+
+func TestFlagsBeforeCommand(t *testing.T) {
+	// short without space
+	x := fullSetupTest("-i10 echo")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
+	}
+
+	// short (int) with equals
+	// It appears that pflags doesn't support this...
+	// Commenting out until support can be added
+
+	//x = noRRSetupTest("echo -i=10")
+	//if x.Error != nil {
+	//t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
+	//}
+
+	// long with equals
+	x = noRRSetupTest("--intone=123 echo one two")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
+	}
+
+	// With parsing error properly reported
+	x = fullSetupTest("-i10E echo")
+	if !strings.Contains(x.Error.Error(), "invalid argument \"10E\" for i10E") {
+		t.Errorf("Wrong error message displayed, \n %s", x.Error)
+	}
+
+	//With quotes
+	x = fullSetupTest("-s=\"walking\" echo")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
+	}
+
+	//With quotes and space
+	x = fullSetupTest("-s=\"walking fast\" echo")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
+	}
+
+	//With inner quote
+	x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
+	}
+
+	//With quotes and space
+	x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
+	}
+
+}
+
+func TestRemoveCommand(t *testing.T) {
+	versionUsed = 0
+	c := initializeWithRootCmd()
+	c.AddCommand(cmdVersion1)
+	c.RemoveCommand(cmdVersion1)
+	x := fullTester(c, "version")
+	if x.Error == nil {
+		t.Errorf("Removed command should not have been called\n")
+		return
+	}
+}
+
+func TestCommandWithoutSubcommands(t *testing.T) {
+	c := initializeWithRootCmd()
+
+	x := simpleTester(c, "")
+	if x.Error != nil {
+		t.Errorf("Calling command without subcommands should not have error: %v", x.Error)
+		return
+	}
+}
+
+func TestCommandWithoutSubcommandsWithArg(t *testing.T) {
+	c := initializeWithRootCmd()
+	expectedArgs := []string{"arg"}
+
+	x := simpleTester(c, "arg")
+	if x.Error != nil {
+		t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error)
+		return
+	}
+	if !reflect.DeepEqual(expectedArgs, tr) {
+		t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr)
+		return
+	}
+}
+
+func TestReplaceCommandWithRemove(t *testing.T) {
+	versionUsed = 0
+	c := initializeWithRootCmd()
+	c.AddCommand(cmdVersion1)
+	c.RemoveCommand(cmdVersion1)
+	c.AddCommand(cmdVersion2)
+	x := fullTester(c, "version")
+	if x.Error != nil {
+		t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
+		return
+	}
+	if versionUsed == 1 {
+		t.Errorf("Removed command shouldn't be called\n")
+	}
+	if versionUsed != 2 {
+		t.Errorf("Replacing command should have been called but didn't\n")
+	}
+}
+
+func TestDeprecatedSub(t *testing.T) {
+	c := fullSetupTest("deprecated")
+
+	checkResultContains(t, c, cmdDeprecated.Deprecated)
+}
+
+func TestPreRun(t *testing.T) {
+	noRRSetupTest("echo one two")
+	if echoPre == nil || echoPersPre == nil {
+		t.Error("PreRun or PersistentPreRun not called")
+	}
+	if rootPersPre != nil || timesPersPre != nil {
+		t.Error("Wrong *Pre functions called!")
+	}
+
+	noRRSetupTest("echo times one two")
+	if timesPersPre == nil {
+		t.Error("PreRun or PersistentPreRun not called")
+	}
+	if echoPre != nil || echoPersPre != nil || rootPersPre != nil {
+		t.Error("Wrong *Pre functions called!")
+	}
+
+	noRRSetupTest("print one two")
+	if rootPersPre == nil {
+		t.Error("Parent PersistentPreRun not called but should not have been")
+	}
+	if echoPre != nil || echoPersPre != nil || timesPersPre != nil {
+		t.Error("Wrong *Pre functions called!")
+	}
+}
+
+// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last
+func TestPeristentPreRunPropagation(t *testing.T) {
+	rootCmd := initialize()
+
+	// First add the cmdEchoSub to cmdPrint
+	cmdPrint.AddCommand(cmdEchoSub)
+	// Now add cmdPrint to rootCmd
+	rootCmd.AddCommand(cmdPrint)
+
+	rootCmd.SetArgs(strings.Split("print echosub lala", " "))
+	rootCmd.Execute()
+
+	if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" {
+		t.Error("RootCmd PersistentPreRun not called but should have been")
+	}
+}
+
+func TestGlobalNormFuncPropagation(t *testing.T) {
+	normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
+		return pflag.NormalizedName(name)
+	}
+
+	rootCmd := initialize()
+	rootCmd.SetGlobalNormalizationFunc(normFunc)
+	if reflect.ValueOf(normFunc) != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()) {
+		t.Error("rootCmd seems to have a wrong normalization function")
+	}
+
+	// First add the cmdEchoSub to cmdPrint
+	cmdPrint.AddCommand(cmdEchoSub)
+	if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil {
+		t.Error("cmdPrint and cmdEchoSub should had no normalization functions")
+	}
+
+	// Now add cmdPrint to rootCmd
+	rootCmd.AddCommand(cmdPrint)
+	if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() ||
+		reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
+		t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")
+	}
+}
+
+func TestFlagOnPflagCommandLine(t *testing.T) {
+	flagName := "flagOnCommandLine"
+	pflag.CommandLine.String(flagName, "", "about my flag")
+	r := fullSetupTest("--help")
+
+	checkResultContains(t, r, flagName)
+}
+
+func TestAddTemplateFunctions(t *testing.T) {
+	AddTemplateFunc("t", func() bool { return true })
+	AddTemplateFuncs(template.FuncMap{
+		"f": func() bool { return false },
+		"h": func() string { return "Hello," },
+		"w": func() string { return "world." }})
+
+	const usage = "Hello, world."
+
+	c := &Command{}
+	c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
+
+	if us := c.UsageString(); us != usage {
+		t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us)
+	}
+}
+
+func TestUsageIsNotPrintedTwice(t *testing.T) {
+	var cmd = &Command{Use: "root"}
+	var sub = &Command{Use: "sub"}
+	cmd.AddCommand(sub)
+
+	r := simpleTester(cmd, "")
+	if strings.Count(r.Output, "Usage:") != 1 {
+		t.Error("Usage output is not printed exactly once")
+	}
+}

+ 1200 - 0
Godeps/_workspace/src/github.com/spf13/cobra/command.go

@@ -0,0 +1,1200 @@
+// Copyright © 2013 Steve Francia <spf@spf13.com>.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces.
+//In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code.
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"runtime"
+	"strings"
+	"time"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/inconshreveable/mousetrap"
+	flag "github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/pflag"
+)
+
+// Command is just that, a command for your application.
+// eg.  'go run' ... 'run' is the command. Cobra requires
+// you to define the usage and description as part of your command
+// definition to ensure usability.
+type Command struct {
+	// Name is the command name, usually the executable's name.
+	name string
+	// The one-line usage message.
+	Use string
+	// An array of aliases that can be used instead of the first word in Use.
+	Aliases []string
+	// An array of command names for which this command will be suggested - similar to aliases but only suggests.
+	SuggestFor []string
+	// The short description shown in the 'help' output.
+	Short string
+	// The long message shown in the 'help <this-command>' output.
+	Long string
+	// Examples of how to use the command
+	Example string
+	// List of all valid non-flag arguments, used for bash completions *TODO* actually validate these
+	ValidArgs []string
+	// Custom functions used by the bash autocompletion generator
+	BashCompletionFunction string
+	// Is this command deprecated and should print this string when used?
+	Deprecated string
+	// Is this command hidden and should NOT show up in the list of available commands?
+	Hidden bool
+	// Full set of flags
+	flags *flag.FlagSet
+	// Set of flags childrens of this command will inherit
+	pflags *flag.FlagSet
+	// Flags that are declared specifically by this command (not inherited).
+	lflags *flag.FlagSet
+	// SilenceErrors is an option to quiet errors down stream
+	SilenceErrors bool
+	// Silence Usage is an option to silence usage when an error occurs.
+	SilenceUsage bool
+	// The *Run functions are executed in the following order:
+	//   * PersistentPreRun()
+	//   * PreRun()
+	//   * Run()
+	//   * PostRun()
+	//   * PersistentPostRun()
+	// All functions get the same args, the arguments after the command name
+	// PersistentPreRun: children of this command will inherit and execute
+	PersistentPreRun func(cmd *Command, args []string)
+	// PersistentPreRunE: PersistentPreRun but returns an error
+	PersistentPreRunE func(cmd *Command, args []string) error
+	// PreRun: children of this command will not inherit.
+	PreRun func(cmd *Command, args []string)
+	// PreRunE: PreRun but returns an error
+	PreRunE func(cmd *Command, args []string) error
+	// Run: Typically the actual work function. Most commands will only implement this
+	Run func(cmd *Command, args []string)
+	// RunE: Run but returns an error
+	RunE func(cmd *Command, args []string) error
+	// PostRun: run after the Run command.
+	PostRun func(cmd *Command, args []string)
+	// PostRunE: PostRun but returns an error
+	PostRunE func(cmd *Command, args []string) error
+	// PersistentPostRun: children of this command will inherit and execute after PostRun
+	PersistentPostRun func(cmd *Command, args []string)
+	// PersistentPostRunE: PersistentPostRun but returns an error
+	PersistentPostRunE func(cmd *Command, args []string) error
+	// DisableAutoGenTag remove
+	DisableAutoGenTag bool
+	// Commands is the list of commands supported by this program.
+	commands []*Command
+	// Parent Command for this command
+	parent *Command
+	// max lengths of commands' string lengths for use in padding
+	commandsMaxUseLen         int
+	commandsMaxCommandPathLen int
+	commandsMaxNameLen        int
+
+	flagErrorBuf *bytes.Buffer
+
+	args          []string                 // actual args parsed from flags
+	output        *io.Writer               // nil means stderr; use Out() method instead
+	usageFunc     func(*Command) error     // Usage can be defined by application
+	usageTemplate string                   // Can be defined by Application
+	helpTemplate  string                   // Can be defined by Application
+	helpFunc      func(*Command, []string) // Help can be defined by application
+	helpCommand   *Command                 // The help command
+	// The global normalization function that we can use on every pFlag set and children commands
+	globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName
+
+	// Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages
+	DisableSuggestions bool
+	// If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
+	SuggestionsMinimumDistance int
+}
+
+// os.Args[1:] by default, if desired, can be overridden
+// particularly useful when testing.
+func (c *Command) SetArgs(a []string) {
+	c.args = a
+}
+
+func (c *Command) getOut(def io.Writer) io.Writer {
+	if c.output != nil {
+		return *c.output
+	}
+
+	if c.HasParent() {
+		return c.parent.Out()
+	} else {
+		return def
+	}
+}
+
+func (c *Command) Out() io.Writer {
+	return c.getOut(os.Stderr)
+}
+
+func (c *Command) getOutOrStdout() io.Writer {
+	return c.getOut(os.Stdout)
+}
+
+// SetOutput sets the destination for usage and error messages.
+// If output is nil, os.Stderr is used.
+func (c *Command) SetOutput(output io.Writer) {
+	c.output = &output
+}
+
+// Usage can be defined by application
+func (c *Command) SetUsageFunc(f func(*Command) error) {
+	c.usageFunc = f
+}
+
+// Can be defined by Application
+func (c *Command) SetUsageTemplate(s string) {
+	c.usageTemplate = s
+}
+
+// Can be defined by Application
+func (c *Command) SetHelpFunc(f func(*Command, []string)) {
+	c.helpFunc = f
+}
+
+func (c *Command) SetHelpCommand(cmd *Command) {
+	c.helpCommand = cmd
+}
+
+// Can be defined by Application
+func (c *Command) SetHelpTemplate(s string) {
+	c.helpTemplate = s
+}
+
+// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
+// The user should not have a cyclic dependency on commands.
+func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
+	c.Flags().SetNormalizeFunc(n)
+	c.PersistentFlags().SetNormalizeFunc(n)
+	c.globNormFunc = n
+
+	for _, command := range c.commands {
+		command.SetGlobalNormalizationFunc(n)
+	}
+}
+
+func (c *Command) UsageFunc() (f func(*Command) error) {
+	if c.usageFunc != nil {
+		return c.usageFunc
+	}
+
+	if c.HasParent() {
+		return c.parent.UsageFunc()
+	} else {
+		return func(c *Command) error {
+			err := tmpl(c.Out(), c.UsageTemplate(), c)
+			if err != nil {
+				fmt.Print(err)
+			}
+			return err
+		}
+	}
+}
+
+// HelpFunc returns either the function set by SetHelpFunc for this command
+// or a parent, or it returns a function which calls c.Help()
+func (c *Command) HelpFunc() func(*Command, []string) {
+	cmd := c
+	for cmd != nil {
+		if cmd.helpFunc != nil {
+			return cmd.helpFunc
+		}
+		cmd = cmd.parent
+	}
+	return func(*Command, []string) {
+		err := c.Help()
+		if err != nil {
+			c.Println(err)
+		}
+	}
+}
+
+var minUsagePadding int = 25
+
+func (c *Command) UsagePadding() int {
+	if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
+		return minUsagePadding
+	} else {
+		return c.parent.commandsMaxUseLen
+	}
+}
+
+var minCommandPathPadding int = 11
+
+//
+func (c *Command) CommandPathPadding() int {
+	if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
+		return minCommandPathPadding
+	} else {
+		return c.parent.commandsMaxCommandPathLen
+	}
+}
+
+var minNamePadding int = 11
+
+func (c *Command) NamePadding() int {
+	if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
+		return minNamePadding
+	} else {
+		return c.parent.commandsMaxNameLen
+	}
+}
+
+func (c *Command) UsageTemplate() string {
+	if c.usageTemplate != "" {
+		return c.usageTemplate
+	}
+
+	if c.HasParent() {
+		return c.parent.UsageTemplate()
+	} else {
+		return `Usage:{{if .Runnable}}
+  {{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}
+  {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
+
+Aliases:
+  {{.NameAndAliases}}
+{{end}}{{if .HasExample}}
+
+Examples:
+{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
+
+Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
+  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}
+
+Flags:
+{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}
+
+Global Flags:
+{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
+
+Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
+  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}
+
+Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
+`
+	}
+}
+
+func (c *Command) HelpTemplate() string {
+	if c.helpTemplate != "" {
+		return c.helpTemplate
+	}
+
+	if c.HasParent() {
+		return c.parent.HelpTemplate()
+	} else {
+		return `{{with or .Long .Short }}{{. | trim}}
+
+{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
+	}
+}
+
+// Really only used when casting a command to a commander
+func (c *Command) resetChildrensParents() {
+	for _, x := range c.commands {
+		x.parent = c
+	}
+}
+
+// Test if the named flag is a boolean flag.
+func isBooleanFlag(name string, f *flag.FlagSet) bool {
+	flag := f.Lookup(name)
+	if flag == nil {
+		return false
+	}
+	return flag.Value.Type() == "bool"
+}
+
+// Test if the named flag is a boolean flag.
+func isBooleanShortFlag(name string, f *flag.FlagSet) bool {
+	result := false
+	f.VisitAll(func(f *flag.Flag) {
+		if f.Shorthand == name && f.Value.Type() == "bool" {
+			result = true
+		}
+	})
+	return result
+}
+
+func stripFlags(args []string, c *Command) []string {
+	if len(args) < 1 {
+		return args
+	}
+	c.mergePersistentFlags()
+
+	commands := []string{}
+
+	inQuote := false
+	inFlag := false
+	for _, y := range args {
+		if !inQuote {
+			switch {
+			case strings.HasPrefix(y, "\""):
+				inQuote = true
+			case strings.Contains(y, "=\""):
+				inQuote = true
+			case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
+				// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
+				inFlag = !isBooleanFlag(y[2:], c.Flags())
+			case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):
+				inFlag = true
+			case inFlag:
+				inFlag = false
+			case y == "":
+				// strip empty commands, as the go tests expect this to be ok....
+			case !strings.HasPrefix(y, "-"):
+				commands = append(commands, y)
+				inFlag = false
+			}
+		}
+
+		if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") {
+			inQuote = false
+		}
+	}
+
+	return commands
+}
+
+// argsMinusFirstX removes only the first x from args.  Otherwise, commands that look like
+// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]).
+func argsMinusFirstX(args []string, x string) []string {
+	for i, y := range args {
+		if x == y {
+			ret := []string{}
+			ret = append(ret, args[:i]...)
+			ret = append(ret, args[i+1:]...)
+			return ret
+		}
+	}
+	return args
+}
+
+// find the target command given the args and command tree
+// Meant to be run on the highest node. Only searches down.
+func (c *Command) Find(args []string) (*Command, []string, error) {
+	if c == nil {
+		return nil, nil, fmt.Errorf("Called find() on a nil Command")
+	}
+
+	var innerfind func(*Command, []string) (*Command, []string)
+
+	innerfind = func(c *Command, innerArgs []string) (*Command, []string) {
+		argsWOflags := stripFlags(innerArgs, c)
+		if len(argsWOflags) == 0 {
+			return c, innerArgs
+		}
+		nextSubCmd := argsWOflags[0]
+		matches := make([]*Command, 0)
+		for _, cmd := range c.commands {
+			if cmd.Name() == nextSubCmd || cmd.HasAlias(nextSubCmd) { // exact name or alias match
+				return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd))
+			}
+			if EnablePrefixMatching {
+				if strings.HasPrefix(cmd.Name(), nextSubCmd) { // prefix match
+					matches = append(matches, cmd)
+				}
+				for _, x := range cmd.Aliases {
+					if strings.HasPrefix(x, nextSubCmd) {
+						matches = append(matches, cmd)
+					}
+				}
+			}
+		}
+
+		// only accept a single prefix match - multiple matches would be ambiguous
+		if len(matches) == 1 {
+			return innerfind(matches[0], argsMinusFirstX(innerArgs, argsWOflags[0]))
+		}
+
+		return c, innerArgs
+	}
+
+	commandFound, a := innerfind(c, args)
+	argsWOflags := stripFlags(a, commandFound)
+
+	// no subcommand, always take args
+	if !commandFound.HasSubCommands() {
+		return commandFound, a, nil
+	}
+
+	// root command with subcommands, do subcommand checking
+	if commandFound == c && len(argsWOflags) > 0 {
+		suggestionsString := ""
+		if !c.DisableSuggestions {
+			if c.SuggestionsMinimumDistance <= 0 {
+				c.SuggestionsMinimumDistance = 2
+			}
+			if suggestions := c.SuggestionsFor(argsWOflags[0]); len(suggestions) > 0 {
+				suggestionsString += "\n\nDid you mean this?\n"
+				for _, s := range suggestions {
+					suggestionsString += fmt.Sprintf("\t%v\n", s)
+				}
+			}
+		}
+		return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestionsString)
+	}
+
+	return commandFound, a, nil
+}
+
+func (c *Command) SuggestionsFor(typedName string) []string {
+	suggestions := []string{}
+	for _, cmd := range c.commands {
+		if cmd.IsAvailableCommand() {
+			levenshteinDistance := ld(typedName, cmd.Name(), true)
+			suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance
+			suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName))
+			if suggestByLevenshtein || suggestByPrefix {
+				suggestions = append(suggestions, cmd.Name())
+			}
+			for _, explicitSuggestion := range cmd.SuggestFor {
+				if strings.EqualFold(typedName, explicitSuggestion) {
+					suggestions = append(suggestions, cmd.Name())
+				}
+			}
+		}
+	}
+	return suggestions
+}
+
+func (c *Command) VisitParents(fn func(*Command)) {
+	var traverse func(*Command) *Command
+
+	traverse = func(x *Command) *Command {
+		if x != c {
+			fn(x)
+		}
+		if x.HasParent() {
+			return traverse(x.parent)
+		}
+		return x
+	}
+	traverse(c)
+}
+
+func (c *Command) Root() *Command {
+	var findRoot func(*Command) *Command
+
+	findRoot = func(x *Command) *Command {
+		if x.HasParent() {
+			return findRoot(x.parent)
+		}
+		return x
+	}
+
+	return findRoot(c)
+}
+
+// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
+// found during arg parsing. This allows your program to know which args were
+// before the -- and which came after. (Description from
+// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).
+func (c *Command) ArgsLenAtDash() int {
+	return c.Flags().ArgsLenAtDash()
+}
+
+func (c *Command) execute(a []string) (err error) {
+	if c == nil {
+		return fmt.Errorf("Called Execute() on a nil Command")
+	}
+
+	if len(c.Deprecated) > 0 {
+		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
+	}
+
+	// initialize help flag as the last point possible to allow for user
+	// overriding
+	c.initHelpFlag()
+
+	err = c.ParseFlags(a)
+	if err != nil {
+		return err
+	}
+	// If help is called, regardless of other flags, return we want help
+	// Also say we need help if the command isn't runnable.
+	helpVal, err := c.Flags().GetBool("help")
+	if err != nil {
+		// should be impossible to get here as we always declare a help
+		// flag in initHelpFlag()
+		c.Println("\"help\" flag declared as non-bool. Please correct your code")
+		return err
+	}
+	if helpVal || !c.Runnable() {
+		return flag.ErrHelp
+	}
+
+	c.preRun()
+	argWoFlags := c.Flags().Args()
+
+	for p := c; p != nil; p = p.Parent() {
+		if p.PersistentPreRunE != nil {
+			if err := p.PersistentPreRunE(c, argWoFlags); err != nil {
+				return err
+			}
+			break
+		} else if p.PersistentPreRun != nil {
+			p.PersistentPreRun(c, argWoFlags)
+			break
+		}
+	}
+	if c.PreRunE != nil {
+		if err := c.PreRunE(c, argWoFlags); err != nil {
+			return err
+		}
+	} else if c.PreRun != nil {
+		c.PreRun(c, argWoFlags)
+	}
+
+	if c.RunE != nil {
+		if err := c.RunE(c, argWoFlags); err != nil {
+			return err
+		}
+	} else {
+		c.Run(c, argWoFlags)
+	}
+	if c.PostRunE != nil {
+		if err := c.PostRunE(c, argWoFlags); err != nil {
+			return err
+		}
+	} else if c.PostRun != nil {
+		c.PostRun(c, argWoFlags)
+	}
+	for p := c; p != nil; p = p.Parent() {
+		if p.PersistentPostRunE != nil {
+			if err := p.PersistentPostRunE(c, argWoFlags); err != nil {
+				return err
+			}
+			break
+		} else if p.PersistentPostRun != nil {
+			p.PersistentPostRun(c, argWoFlags)
+			break
+		}
+	}
+
+	return nil
+}
+
+func (c *Command) preRun() {
+	for _, x := range initializers {
+		x()
+	}
+}
+
+func (c *Command) errorMsgFromParse() string {
+	s := c.flagErrorBuf.String()
+
+	x := strings.Split(s, "\n")
+
+	if len(x) > 0 {
+		return x[0]
+	} else {
+		return ""
+	}
+}
+
+// Call execute to use the args (os.Args[1:] by default)
+// and run through the command tree finding appropriate matches
+// for commands and then corresponding flags.
+func (c *Command) Execute() error {
+	_, err := c.ExecuteC()
+	return err
+}
+
+func (c *Command) ExecuteC() (cmd *Command, err error) {
+
+	// Regardless of what command execute is called on, run on Root only
+	if c.HasParent() {
+		return c.Root().ExecuteC()
+	}
+
+	if EnableWindowsMouseTrap && runtime.GOOS == "windows" {
+		if mousetrap.StartedByExplorer() {
+			c.Print(MousetrapHelpText)
+			time.Sleep(5 * time.Second)
+			os.Exit(1)
+		}
+	}
+
+	// initialize help as the last point possible to allow for user
+	// overriding
+	c.initHelpCmd()
+
+	var args []string
+
+	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
+	if len(c.args) == 0 && filepath.Base(os.Args[0]) != "cobra.test" {
+		args = os.Args[1:]
+	} else {
+		args = c.args
+	}
+
+	cmd, flags, err := c.Find(args)
+	if err != nil {
+		// If found parse to a subcommand and then failed, talk about the subcommand
+		if cmd != nil {
+			c = cmd
+		}
+		if !c.SilenceErrors {
+			c.Println("Error:", err.Error())
+			c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
+		}
+		return c, err
+	}
+	err = cmd.execute(flags)
+	if err != nil {
+		// If root command has SilentErrors flagged,
+		// all subcommands should respect it
+		if !cmd.SilenceErrors && !c.SilenceErrors {
+			if err == flag.ErrHelp {
+				cmd.HelpFunc()(cmd, args)
+				return cmd, nil
+			}
+			c.Println("Error:", err.Error())
+		}
+
+		// If root command has SilentUsage flagged,
+		// all subcommands should respect it
+		if !cmd.SilenceUsage && !c.SilenceUsage {
+			c.Println(cmd.UsageString())
+		}
+		return cmd, err
+	}
+	return cmd, nil
+}
+
+func (c *Command) initHelpFlag() {
+	if c.Flags().Lookup("help") == nil {
+		c.Flags().BoolP("help", "h", false, "help for "+c.Name())
+	}
+}
+
+func (c *Command) initHelpCmd() {
+	if c.helpCommand == nil {
+		if !c.HasSubCommands() {
+			return
+		}
+
+		c.helpCommand = &Command{
+			Use:   "help [command]",
+			Short: "Help about any command",
+			Long: `Help provides help for any command in the application.
+    Simply type ` + c.Name() + ` help [path to command] for full details.`,
+			PersistentPreRun:  func(cmd *Command, args []string) {},
+			PersistentPostRun: func(cmd *Command, args []string) {},
+
+			Run: func(c *Command, args []string) {
+				cmd, _, e := c.Root().Find(args)
+				if cmd == nil || e != nil {
+					c.Printf("Unknown help topic %#q.", args)
+					c.Root().Usage()
+				} else {
+					helpFunc := cmd.HelpFunc()
+					helpFunc(cmd, args)
+				}
+			},
+		}
+	}
+	c.AddCommand(c.helpCommand)
+}
+
+// Used for testing
+func (c *Command) ResetCommands() {
+	c.commands = nil
+	c.helpCommand = nil
+}
+
+//Commands returns a slice of child commands.
+func (c *Command) Commands() []*Command {
+	return c.commands
+}
+
+// AddCommand adds one or more commands to this parent command.
+func (c *Command) AddCommand(cmds ...*Command) {
+	for i, x := range cmds {
+		if cmds[i] == c {
+			panic("Command can't be a child of itself")
+		}
+		cmds[i].parent = c
+		// update max lengths
+		usageLen := len(x.Use)
+		if usageLen > c.commandsMaxUseLen {
+			c.commandsMaxUseLen = usageLen
+		}
+		commandPathLen := len(x.CommandPath())
+		if commandPathLen > c.commandsMaxCommandPathLen {
+			c.commandsMaxCommandPathLen = commandPathLen
+		}
+		nameLen := len(x.Name())
+		if nameLen > c.commandsMaxNameLen {
+			c.commandsMaxNameLen = nameLen
+		}
+		// If glabal normalization function exists, update all children
+		if c.globNormFunc != nil {
+			x.SetGlobalNormalizationFunc(c.globNormFunc)
+		}
+		c.commands = append(c.commands, x)
+	}
+}
+
+// AddCommand removes one or more commands from a parent command.
+func (c *Command) RemoveCommand(cmds ...*Command) {
+	commands := []*Command{}
+main:
+	for _, command := range c.commands {
+		for _, cmd := range cmds {
+			if command == cmd {
+				command.parent = nil
+				continue main
+			}
+		}
+		commands = append(commands, command)
+	}
+	c.commands = commands
+	// recompute all lengths
+	c.commandsMaxUseLen = 0
+	c.commandsMaxCommandPathLen = 0
+	c.commandsMaxNameLen = 0
+	for _, command := range c.commands {
+		usageLen := len(command.Use)
+		if usageLen > c.commandsMaxUseLen {
+			c.commandsMaxUseLen = usageLen
+		}
+		commandPathLen := len(command.CommandPath())
+		if commandPathLen > c.commandsMaxCommandPathLen {
+			c.commandsMaxCommandPathLen = commandPathLen
+		}
+		nameLen := len(command.Name())
+		if nameLen > c.commandsMaxNameLen {
+			c.commandsMaxNameLen = nameLen
+		}
+	}
+}
+
+// Convenience method to Print to the defined output
+func (c *Command) Print(i ...interface{}) {
+	fmt.Fprint(c.Out(), i...)
+}
+
+// Convenience method to Println to the defined output
+func (c *Command) Println(i ...interface{}) {
+	str := fmt.Sprintln(i...)
+	c.Print(str)
+}
+
+// Convenience method to Printf to the defined output
+func (c *Command) Printf(format string, i ...interface{}) {
+	str := fmt.Sprintf(format, i...)
+	c.Print(str)
+}
+
+// Output the usage for the command
+// Used when a user provides invalid input
+// Can be defined by user by overriding UsageFunc
+func (c *Command) Usage() error {
+	c.mergePersistentFlags()
+	err := c.UsageFunc()(c)
+	return err
+}
+
+// Output the help for the command
+// Used when a user calls help [command]
+// by the default HelpFunc in the commander
+func (c *Command) Help() error {
+	c.mergePersistentFlags()
+	err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)
+	return err
+}
+
+func (c *Command) UsageString() string {
+	tmpOutput := c.output
+	bb := new(bytes.Buffer)
+	c.SetOutput(bb)
+	c.Usage()
+	c.output = tmpOutput
+	return bb.String()
+}
+
+// CommandPath returns the full path to this command.
+func (c *Command) CommandPath() string {
+	str := c.Name()
+	x := c
+	for x.HasParent() {
+		str = x.parent.Name() + " " + str
+		x = x.parent
+	}
+	return str
+}
+
+//The full usage for a given command (including parents)
+func (c *Command) UseLine() string {
+	str := ""
+	if c.HasParent() {
+		str = c.parent.CommandPath() + " "
+	}
+	return str + c.Use
+}
+
+// For use in determining which flags have been assigned to which commands
+// and which persist
+func (c *Command) DebugFlags() {
+	c.Println("DebugFlags called on", c.Name())
+	var debugflags func(*Command)
+
+	debugflags = func(x *Command) {
+		if x.HasFlags() || x.HasPersistentFlags() {
+			c.Println(x.Name())
+		}
+		if x.HasFlags() {
+			x.flags.VisitAll(func(f *flag.Flag) {
+				if x.HasPersistentFlags() {
+					if x.persistentFlag(f.Name) == nil {
+						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")
+					} else {
+						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [LP]")
+					}
+				} else {
+					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [L]")
+				}
+			})
+		}
+		if x.HasPersistentFlags() {
+			x.pflags.VisitAll(func(f *flag.Flag) {
+				if x.HasFlags() {
+					if x.flags.Lookup(f.Name) == nil {
+						c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")
+					}
+				} else {
+					c.Println("  -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, "  [P]")
+				}
+			})
+		}
+		c.Println(x.flagErrorBuf)
+		if x.HasSubCommands() {
+			for _, y := range x.commands {
+				debugflags(y)
+			}
+		}
+	}
+
+	debugflags(c)
+}
+
+// Name returns the command's name: the first word in the use line.
+func (c *Command) Name() string {
+	if c.name != "" {
+		return c.name
+	}
+	name := c.Use
+	i := strings.Index(name, " ")
+	if i >= 0 {
+		name = name[:i]
+	}
+	return name
+}
+
+// Determine if a given string is an alias of the command.
+func (c *Command) HasAlias(s string) bool {
+	for _, a := range c.Aliases {
+		if a == s {
+			return true
+		}
+	}
+	return false
+}
+
+func (c *Command) NameAndAliases() string {
+	return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
+}
+
+func (c *Command) HasExample() bool {
+	return len(c.Example) > 0
+}
+
+// Determine if the command is itself runnable
+func (c *Command) Runnable() bool {
+	return c.Run != nil || c.RunE != nil
+}
+
+// Determine if the command has children commands
+func (c *Command) HasSubCommands() bool {
+	return len(c.commands) > 0
+}
+
+// IsAvailableCommand determines if a command is available as a non-help command
+// (this includes all non deprecated/hidden commands)
+func (c *Command) IsAvailableCommand() bool {
+	if len(c.Deprecated) != 0 || c.Hidden {
+		return false
+	}
+
+	if c.HasParent() && c.Parent().helpCommand == c {
+		return false
+	}
+
+	if c.Runnable() || c.HasAvailableSubCommands() {
+		return true
+	}
+
+	return false
+}
+
+// IsHelpCommand determines if a command is a 'help' command; a help command is
+// determined by the fact that it is NOT runnable/hidden/deprecated, and has no
+// sub commands that are runnable/hidden/deprecated
+func (c *Command) IsHelpCommand() bool {
+
+	// if a command is runnable, deprecated, or hidden it is not a 'help' command
+	if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
+		return false
+	}
+
+	// if any non-help sub commands are found, the command is not a 'help' command
+	for _, sub := range c.commands {
+		if !sub.IsHelpCommand() {
+			return false
+		}
+	}
+
+	// the command either has no sub commands, or no non-help sub commands
+	return true
+}
+
+// HasHelpSubCommands determines if a command has any avilable 'help' sub commands
+// that need to be shown in the usage/help default template under 'additional help
+// topics'
+func (c *Command) HasHelpSubCommands() bool {
+
+	// return true on the first found available 'help' sub command
+	for _, sub := range c.commands {
+		if sub.IsHelpCommand() {
+			return true
+		}
+	}
+
+	// the command either has no sub commands, or no available 'help' sub commands
+	return false
+}
+
+// HasAvailableSubCommands determines if a command has available sub commands that
+// need to be shown in the usage/help default template under 'available commands'
+func (c *Command) HasAvailableSubCommands() bool {
+
+	// return true on the first found available (non deprecated/help/hidden)
+	// sub command
+	for _, sub := range c.commands {
+		if sub.IsAvailableCommand() {
+			return true
+		}
+	}
+
+	// the command either has no sub comamnds, or no available (non deprecated/help/hidden)
+	// sub commands
+	return false
+}
+
+// Determine if the command is a child command
+func (c *Command) HasParent() bool {
+	return c.parent != nil
+}
+
+// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists
+func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
+	return c.globNormFunc
+}
+
+// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)
+func (c *Command) Flags() *flag.FlagSet {
+	if c.flags == nil {
+		c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.flags.SetOutput(c.flagErrorBuf)
+	}
+	return c.flags
+}
+
+// Get the local FlagSet specifically set in the current command
+func (c *Command) LocalFlags() *flag.FlagSet {
+	c.mergePersistentFlags()
+
+	local := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+	c.lflags.VisitAll(func(f *flag.Flag) {
+		local.AddFlag(f)
+	})
+	if !c.HasParent() {
+		flag.CommandLine.VisitAll(func(f *flag.Flag) {
+			if local.Lookup(f.Name) == nil {
+				local.AddFlag(f)
+			}
+		})
+	}
+	return local
+}
+
+// All Flags which were inherited from parents commands
+func (c *Command) InheritedFlags() *flag.FlagSet {
+	c.mergePersistentFlags()
+
+	inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+	local := c.LocalFlags()
+
+	var rmerge func(x *Command)
+
+	rmerge = func(x *Command) {
+		if x.HasPersistentFlags() {
+			x.PersistentFlags().VisitAll(func(f *flag.Flag) {
+				if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil {
+					inherited.AddFlag(f)
+				}
+			})
+		}
+		if x.HasParent() {
+			rmerge(x.parent)
+		}
+	}
+
+	if c.HasParent() {
+		rmerge(c.parent)
+	}
+
+	return inherited
+}
+
+// All Flags which were not inherited from parent commands
+func (c *Command) NonInheritedFlags() *flag.FlagSet {
+	return c.LocalFlags()
+}
+
+// Get the Persistent FlagSet specifically set in the current command
+func (c *Command) PersistentFlags() *flag.FlagSet {
+	if c.pflags == nil {
+		c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.pflags.SetOutput(c.flagErrorBuf)
+	}
+	return c.pflags
+}
+
+// For use in testing
+func (c *Command) ResetFlags() {
+	c.flagErrorBuf = new(bytes.Buffer)
+	c.flagErrorBuf.Reset()
+	c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+	c.flags.SetOutput(c.flagErrorBuf)
+	c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+	c.pflags.SetOutput(c.flagErrorBuf)
+}
+
+// Does the command contain any flags (local plus persistent from the entire structure)
+func (c *Command) HasFlags() bool {
+	return c.Flags().HasFlags()
+}
+
+// Does the command contain persistent flags
+func (c *Command) HasPersistentFlags() bool {
+	return c.PersistentFlags().HasFlags()
+}
+
+// Does the command has flags specifically declared locally
+func (c *Command) HasLocalFlags() bool {
+	return c.LocalFlags().HasFlags()
+}
+
+func (c *Command) HasInheritedFlags() bool {
+	return c.InheritedFlags().HasFlags()
+}
+
+// Climbs up the command tree looking for matching flag
+func (c *Command) Flag(name string) (flag *flag.Flag) {
+	flag = c.Flags().Lookup(name)
+
+	if flag == nil {
+		flag = c.persistentFlag(name)
+	}
+
+	return
+}
+
+// recursively find matching persistent flag
+func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
+	if c.HasPersistentFlags() {
+		flag = c.PersistentFlags().Lookup(name)
+	}
+
+	if flag == nil && c.HasParent() {
+		flag = c.parent.persistentFlag(name)
+	}
+	return
+}
+
+// Parses persistent flag tree & local flags
+func (c *Command) ParseFlags(args []string) (err error) {
+	c.mergePersistentFlags()
+	err = c.Flags().Parse(args)
+	return
+}
+
+func (c *Command) Parent() *Command {
+	return c.parent
+}
+
+func (c *Command) mergePersistentFlags() {
+	var rmerge func(x *Command)
+
+	// Save the set of local flags
+	if c.lflags == nil {
+		c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
+		if c.flagErrorBuf == nil {
+			c.flagErrorBuf = new(bytes.Buffer)
+		}
+		c.lflags.SetOutput(c.flagErrorBuf)
+		addtolocal := func(f *flag.Flag) {
+			c.lflags.AddFlag(f)
+		}
+		c.Flags().VisitAll(addtolocal)
+		c.PersistentFlags().VisitAll(addtolocal)
+	}
+	rmerge = func(x *Command) {
+		if !x.HasParent() {
+			flag.CommandLine.VisitAll(func(f *flag.Flag) {
+				if x.PersistentFlags().Lookup(f.Name) == nil {
+					x.PersistentFlags().AddFlag(f)
+				}
+			})
+		}
+		if x.HasPersistentFlags() {
+			x.PersistentFlags().VisitAll(func(f *flag.Flag) {
+				if c.Flags().Lookup(f.Name) == nil {
+					c.Flags().AddFlag(f)
+				}
+			})
+		}
+		if x.HasParent() {
+			rmerge(x.parent)
+		}
+	}
+
+	rmerge(c)
+}

+ 114 - 0
Godeps/_workspace/src/github.com/spf13/cobra/command_test.go

@@ -0,0 +1,114 @@
+package cobra
+
+import (
+	"reflect"
+	"testing"
+)
+
+// test to ensure hidden commands run as intended
+func TestHiddenCommandExecutes(t *testing.T) {
+
+	// ensure that outs does not already equal what the command will be setting it
+	// to, if it did this test would not actually be testing anything...
+	if outs == "hidden" {
+		t.Errorf("outs should NOT EQUAL hidden")
+	}
+
+	cmdHidden.Execute()
+
+	// upon running the command, the value of outs should now be 'hidden'
+	if outs != "hidden" {
+		t.Errorf("Hidden command failed to run!")
+	}
+}
+
+// test to ensure hidden commands do not show up in usage/help text
+func TestHiddenCommandIsHidden(t *testing.T) {
+	if cmdHidden.IsAvailableCommand() {
+		t.Errorf("Hidden command found!")
+	}
+}
+
+func TestStripFlags(t *testing.T) {
+	tests := []struct {
+		input  []string
+		output []string
+	}{
+		{
+			[]string{"foo", "bar"},
+			[]string{"foo", "bar"},
+		},
+		{
+			[]string{"foo", "--bar", "-b"},
+			[]string{"foo"},
+		},
+		{
+			[]string{"-b", "foo", "--bar", "bar"},
+			[]string{},
+		},
+		{
+			[]string{"-i10", "echo"},
+			[]string{"echo"},
+		},
+		{
+			[]string{"-i=10", "echo"},
+			[]string{"echo"},
+		},
+		{
+			[]string{"--int=100", "echo"},
+			[]string{"echo"},
+		},
+		{
+			[]string{"-ib", "echo", "-bfoo", "baz"},
+			[]string{"echo", "baz"},
+		},
+		{
+			[]string{"-i=baz", "bar", "-i", "foo", "blah"},
+			[]string{"bar", "blah"},
+		},
+		{
+			[]string{"--int=baz", "-bbar", "-i", "foo", "blah"},
+			[]string{"blah"},
+		},
+		{
+			[]string{"--cat", "bar", "-i", "foo", "blah"},
+			[]string{"bar", "blah"},
+		},
+		{
+			[]string{"-c", "bar", "-i", "foo", "blah"},
+			[]string{"bar", "blah"},
+		},
+		{
+			[]string{"--persist", "bar"},
+			[]string{"bar"},
+		},
+		{
+			[]string{"-p", "bar"},
+			[]string{"bar"},
+		},
+	}
+
+	cmdPrint := &Command{
+		Use:   "print [string to print]",
+		Short: "Print anything to the screen",
+		Long:  `an utterly useless command for testing.`,
+		Run: func(cmd *Command, args []string) {
+			tp = args
+		},
+	}
+
+	var flagi int
+	var flagstr string
+	var flagbool bool
+	cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")
+	cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")
+	cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")
+	cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")
+
+	for _, test := range tests {
+		output := stripFlags(test.input, cmdPrint)
+		if !reflect.DeepEqual(test.output, output) {
+			t.Errorf("expected: %v, got: %v", test.output, output)
+		}
+	}
+}

+ 34 - 0
Godeps/_workspace/src/github.com/spf13/cobra/doc_util.go

@@ -0,0 +1,34 @@
+// Copyright 2015 Red Hat Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cobra
+
+// Test to see if we have a reason to print See Also information in docs
+// Basically this is a test for a parent commend or a subcommand which is
+// both not deprecated and not the autogenerated help command.
+func (cmd *Command) hasSeeAlso() bool {
+	if cmd.HasParent() {
+		return true
+	}
+	children := cmd.Commands()
+	if len(children) == 0 {
+		return false
+	}
+	for _, c := range children {
+		if !c.IsAvailableCommand() || c == cmd.helpCommand {
+			continue
+		}
+		return true
+	}
+	return false
+}

+ 34 - 0
Godeps/_workspace/src/github.com/spf13/cobra/examples_test.go

@@ -0,0 +1,34 @@
+package cobra_test
+
+import (
+	"bytes"
+	"fmt"
+
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/cobra"
+)
+
+func ExampleCommand_GenManTree() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &cobra.GenManHeader{
+		Title:   "MINE",
+		Section: "3",
+	}
+	cmd.GenManTree(header, "/tmp")
+}
+
+func ExampleCommand_GenMan() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &cobra.GenManHeader{
+		Title:   "MINE",
+		Section: "3",
+	}
+	out := new(bytes.Buffer)
+	cmd.GenMan(header, out)
+	fmt.Print(out.String())
+}

+ 227 - 0
Godeps/_workspace/src/github.com/spf13/cobra/man_docs.go

@@ -0,0 +1,227 @@
+// Copyright 2015 Red Hat Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"sort"
+	"strings"
+	"time"
+
+	mangen "github.com/coreos/etcd/Godeps/_workspace/src/github.com/cpuguy83/go-md2man/md2man"
+	"github.com/coreos/etcd/Godeps/_workspace/src/github.com/spf13/pflag"
+)
+
+// GenManTree will call cmd.GenManTree(header, dir)
+func GenManTree(cmd *Command, header *GenManHeader, dir string) {
+	cmd.GenManTree(header, dir)
+}
+
+// GenManTree will generate a man page for this command and all decendants
+// in the directory given. The header may be nil. This function may not work
+// correctly if your command names have - in them. If you have `cmd` with two
+// subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third`
+// it is undefined which help output will be in the file `cmd-sub-third.1`.
+func (cmd *Command) GenManTree(header *GenManHeader, dir string) {
+	if header == nil {
+		header = &GenManHeader{}
+	}
+	for _, c := range cmd.Commands() {
+		if !c.IsAvailableCommand() || c == cmd.helpCommand {
+			continue
+		}
+		GenManTree(c, header, dir)
+	}
+	out := new(bytes.Buffer)
+
+	needToResetTitle := header.Title == ""
+
+	cmd.GenMan(header, out)
+
+	if needToResetTitle {
+		header.Title = ""
+	}
+
+	filename := cmd.CommandPath()
+	filename = dir + strings.Replace(filename, " ", "-", -1) + ".1"
+	outFile, err := os.Create(filename)
+	if err != nil {
+		fmt.Println(err)
+		os.Exit(1)
+	}
+	defer outFile.Close()
+	_, err = outFile.Write(out.Bytes())
+	if err != nil {
+		fmt.Println(err)
+		os.Exit(1)
+	}
+}
+
+// GenManHeader is a lot like the .TH header at the start of man pages. These
+// include the title, section, date, source, and manual. We will use the
+// current time if Date if unset and will use "Auto generated by spf13/cobra"
+// if the Source is unset.
+type GenManHeader struct {
+	Title   string
+	Section string
+	Date    *time.Time
+	date    string
+	Source  string
+	Manual  string
+}
+
+// GenMan will call cmd.GenMan(header, out)
+func GenMan(cmd *Command, header *GenManHeader, out *bytes.Buffer) {
+	cmd.GenMan(header, out)
+}
+
+// GenMan will generate a man page for the given command in the out buffer.
+// The header argument may be nil, however obviously out may not.
+func (cmd *Command) GenMan(header *GenManHeader, out *bytes.Buffer) {
+	if header == nil {
+		header = &GenManHeader{}
+	}
+	buf := genMarkdown(cmd, header)
+	final := mangen.Render(buf)
+	out.Write(final)
+}
+
+func fillHeader(header *GenManHeader, name string) {
+	if header.Title == "" {
+		header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
+	}
+	if header.Section == "" {
+		header.Section = "1"
+	}
+	if header.Date == nil {
+		now := time.Now()
+		header.Date = &now
+	}
+	header.date = (*header.Date).Format("Jan 2006")
+	if header.Source == "" {
+		header.Source = "Auto generated by spf13/cobra"
+	}
+}
+
+func manPreamble(out *bytes.Buffer, header *GenManHeader, name, short, long string) {
+	dashName := strings.Replace(name, " ", "-", -1)
+	fmt.Fprintf(out, `%% %s(%s)%s
+%% %s
+%% %s
+# NAME
+`, header.Title, header.Section, header.date, header.Source, header.Manual)
+	fmt.Fprintf(out, "%s \\- %s\n\n", dashName, short)
+	fmt.Fprintf(out, "# SYNOPSIS\n")
+	fmt.Fprintf(out, "**%s** [OPTIONS]\n\n", name)
+	fmt.Fprintf(out, "# DESCRIPTION\n")
+	fmt.Fprintf(out, "%s\n\n", long)
+}
+
+func manPrintFlags(out *bytes.Buffer, flags *pflag.FlagSet) {
+	flags.VisitAll(func(flag *pflag.Flag) {
+		if len(flag.Deprecated) > 0 || flag.Hidden {
+			return
+		}
+		format := ""
+		if len(flag.Shorthand) > 0 {
+			format = "**-%s**, **--%s**"
+		} else {
+			format = "%s**--%s**"
+		}
+		if len(flag.NoOptDefVal) > 0 {
+			format = format + "["
+		}
+		if flag.Value.Type() == "string" {
+			// put quotes on the value
+			format = format + "=%q"
+		} else {
+			format = format + "=%s"
+		}
+		if len(flag.NoOptDefVal) > 0 {
+			format = format + "]"
+		}
+		format = format + "\n\t%s\n\n"
+		fmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
+	})
+}
+
+func manPrintOptions(out *bytes.Buffer, command *Command) {
+	flags := command.NonInheritedFlags()
+	if flags.HasFlags() {
+		fmt.Fprintf(out, "# OPTIONS\n")
+		manPrintFlags(out, flags)
+		fmt.Fprintf(out, "\n")
+	}
+	flags = command.InheritedFlags()
+	if flags.HasFlags() {
+		fmt.Fprintf(out, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")
+		manPrintFlags(out, flags)
+		fmt.Fprintf(out, "\n")
+	}
+}
+
+func genMarkdown(cmd *Command, header *GenManHeader) []byte {
+	// something like `rootcmd subcmd1 subcmd2`
+	commandName := cmd.CommandPath()
+	// something like `rootcmd-subcmd1-subcmd2`
+	dashCommandName := strings.Replace(commandName, " ", "-", -1)
+
+	fillHeader(header, commandName)
+
+	buf := new(bytes.Buffer)
+
+	short := cmd.Short
+	long := cmd.Long
+	if len(long) == 0 {
+		long = short
+	}
+
+	manPreamble(buf, header, commandName, short, long)
+	manPrintOptions(buf, cmd)
+	if len(cmd.Example) > 0 {
+		fmt.Fprintf(buf, "# EXAMPLE\n")
+		fmt.Fprintf(buf, "```\n%s\n```\n", cmd.Example)
+	}
+	if cmd.hasSeeAlso() {
+		fmt.Fprintf(buf, "# SEE ALSO\n")
+		if cmd.HasParent() {
+			parentPath := cmd.Parent().CommandPath()
+			dashParentPath := strings.Replace(parentPath, " ", "-", -1)
+			fmt.Fprintf(buf, "**%s(%s)**", dashParentPath, header.Section)
+			cmd.VisitParents(func(c *Command) {
+				if c.DisableAutoGenTag {
+					cmd.DisableAutoGenTag = c.DisableAutoGenTag
+				}
+			})
+		}
+		children := cmd.Commands()
+		sort.Sort(byName(children))
+		for i, c := range children {
+			if !c.IsAvailableCommand() || c == cmd.helpCommand {
+				continue
+			}
+			if cmd.HasParent() || i > 0 {
+				fmt.Fprintf(buf, ", ")
+			}
+			fmt.Fprintf(buf, "**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
+		}
+		fmt.Fprintf(buf, "\n")
+	}
+	if !cmd.DisableAutoGenTag {
+		fmt.Fprintf(buf, "# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))
+	}
+	return buf.Bytes()
+}

+ 25 - 0
Godeps/_workspace/src/github.com/spf13/cobra/man_docs.md

@@ -0,0 +1,25 @@
+# Generating Man Pages For Your Own cobra.Command
+
+Generating man pages from a cobra command is incredibly easy. An example is as follows:
+
+```go
+package main
+
+import (
+	"github.com/spf13/cobra"
+)
+
+func main() {
+	cmd := &cobra.Command{
+		Use:   "test",
+		Short: "my test program",
+	}
+	header := &cobra.GenManHeader{
+		Title: "MINE",
+		Section: "3",
+	}
+	cmd.GenManTree(header, "/tmp")
+}
+```
+
+That will get you a man page `/tmp/test.1`

+ 94 - 0
Godeps/_workspace/src/github.com/spf13/cobra/man_docs_test.go

@@ -0,0 +1,94 @@
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"strings"
+	"testing"
+)
+
+var _ = fmt.Println
+var _ = os.Stderr
+
+func translate(in string) string {
+	return strings.Replace(in, "-", "\\-", -1)
+}
+
+func TestGenManDoc(t *testing.T) {
+	c := initializeWithRootCmd()
+	// Need two commands to run the command alphabetical sort
+	cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
+	c.AddCommand(cmdPrint, cmdEcho)
+	cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
+
+	out := new(bytes.Buffer)
+
+	header := &GenManHeader{
+		Title:   "Project",
+		Section: "2",
+	}
+	// We generate on a subcommand so we have both subcommands and parents
+	cmdEcho.GenMan(header, out)
+	found := out.String()
+
+	// Make sure parent has - in CommandPath() in SEE ALSO:
+	parentPath := cmdEcho.Parent().CommandPath()
+	dashParentPath := strings.Replace(parentPath, " ", "-", -1)
+	expected := translate(dashParentPath)
+	expected = expected + "(" + header.Section + ")"
+	checkStringContains(t, found, expected)
+
+	// Our description
+	expected = translate(cmdEcho.Name())
+	checkStringContains(t, found, expected)
+
+	// Better have our example
+	expected = translate(cmdEcho.Name())
+	checkStringContains(t, found, expected)
+
+	// A local flag
+	expected = "boolone"
+	checkStringContains(t, found, expected)
+
+	// persistent flag on parent
+	expected = "rootflag"
+	checkStringContains(t, found, expected)
+
+	// We better output info about our parent
+	expected = translate(cmdRootWithRun.Name())
+	checkStringContains(t, found, expected)
+
+	// And about subcommands
+	expected = translate(cmdEchoSub.Name())
+	checkStringContains(t, found, expected)
+
+	unexpected := translate(cmdDeprecated.Name())
+	checkStringOmits(t, found, unexpected)
+
+	// auto generated
+	expected = translate("Auto generated")
+	checkStringContains(t, found, expected)
+}
+
+func TestGenManNoGenTag(t *testing.T) {
+
+	c := initializeWithRootCmd()
+	// Need two commands to run the command alphabetical sort
+	cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
+	c.AddCommand(cmdPrint, cmdEcho)
+	cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
+	cmdEcho.DisableAutoGenTag = true
+	out := new(bytes.Buffer)
+
+	header := &GenManHeader{
+		Title:   "Project",
+		Section: "2",
+	}
+	// We generate on a subcommand so we have both subcommands and parents
+	cmdEcho.GenMan(header, out)
+	found := out.String()
+
+	unexpected := translate("#HISTORY")
+	checkStringOmits(t, found, unexpected)
+}

+ 162 - 0
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.go

@@ -0,0 +1,162 @@
+//Copyright 2015 Red Hat Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"sort"
+	"strings"
+	"time"
+)
+
+func printOptions(out *bytes.Buffer, cmd *Command, name string) {
+	flags := cmd.NonInheritedFlags()
+	flags.SetOutput(out)
+	if flags.HasFlags() {
+		fmt.Fprintf(out, "### Options\n\n```\n")
+		flags.PrintDefaults()
+		fmt.Fprintf(out, "```\n\n")
+	}
+
+	parentFlags := cmd.InheritedFlags()
+	parentFlags.SetOutput(out)
+	if parentFlags.HasFlags() {
+		fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n")
+		parentFlags.PrintDefaults()
+		fmt.Fprintf(out, "```\n\n")
+	}
+}
+
+type byName []*Command
+
+func (s byName) Len() int           { return len(s) }
+func (s byName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
+func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
+
+func GenMarkdown(cmd *Command, out *bytes.Buffer) {
+	cmd.GenMarkdown(out)
+}
+
+func (cmd *Command) GenMarkdown(out *bytes.Buffer) {
+	cmd.GenMarkdownCustom(out, func(s string) string { return s })
+}
+
+func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {
+	cmd.GenMarkdownCustom(out, linkHandler)
+}
+
+func (cmd *Command) GenMarkdownCustom(out *bytes.Buffer, linkHandler func(string) string) {
+	name := cmd.CommandPath()
+
+	short := cmd.Short
+	long := cmd.Long
+	if len(long) == 0 {
+		long = short
+	}
+
+	fmt.Fprintf(out, "## %s\n\n", name)
+	fmt.Fprintf(out, "%s\n\n", short)
+	fmt.Fprintf(out, "### Synopsis\n\n")
+	fmt.Fprintf(out, "\n%s\n\n", long)
+
+	if cmd.Runnable() {
+		fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())
+	}
+
+	if len(cmd.Example) > 0 {
+		fmt.Fprintf(out, "### Examples\n\n")
+		fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)
+	}
+
+	printOptions(out, cmd, name)
+	if cmd.hasSeeAlso() {
+		fmt.Fprintf(out, "### SEE ALSO\n")
+		if cmd.HasParent() {
+			parent := cmd.Parent()
+			pname := parent.CommandPath()
+			link := pname + ".md"
+			link = strings.Replace(link, " ", "_", -1)
+			fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)
+			cmd.VisitParents(func(c *Command) {
+				if c.DisableAutoGenTag {
+					cmd.DisableAutoGenTag = c.DisableAutoGenTag
+				}
+			})
+		}
+
+		children := cmd.Commands()
+		sort.Sort(byName(children))
+
+		for _, child := range children {
+			if !child.IsAvailableCommand() || child == cmd.helpCommand {
+				continue
+			}
+			cname := name + " " + child.Name()
+			link := cname + ".md"
+			link = strings.Replace(link, " ", "_", -1)
+			fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)
+		}
+		fmt.Fprintf(out, "\n")
+	}
+	if !cmd.DisableAutoGenTag {
+		fmt.Fprintf(out, "###### Auto generated by spf13/cobra on %s\n", time.Now().Format("2-Jan-2006"))
+	}
+}
+
+func GenMarkdownTree(cmd *Command, dir string) {
+	cmd.GenMarkdownTree(dir)
+}
+
+func (cmd *Command) GenMarkdownTree(dir string) {
+	identity := func(s string) string { return s }
+	emptyStr := func(s string) string { return "" }
+	cmd.GenMarkdownTreeCustom(dir, emptyStr, identity)
+}
+
+func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {
+	cmd.GenMarkdownTreeCustom(dir, filePrepender, linkHandler)
+}
+
+func (cmd *Command) GenMarkdownTreeCustom(dir string, filePrepender func(string) string, linkHandler func(string) string) {
+	for _, c := range cmd.Commands() {
+		if !c.IsAvailableCommand() || c == cmd.helpCommand {
+			continue
+		}
+		c.GenMarkdownTreeCustom(dir, filePrepender, linkHandler)
+	}
+	out := new(bytes.Buffer)
+
+	cmd.GenMarkdownCustom(out, linkHandler)
+
+	filename := cmd.CommandPath()
+	filename = dir + strings.Replace(filename, " ", "_", -1) + ".md"
+	outFile, err := os.Create(filename)
+	if err != nil {
+		fmt.Println(err)
+		os.Exit(1)
+	}
+	defer outFile.Close()
+	_, err = outFile.WriteString(filePrepender(filename))
+	if err != nil {
+		fmt.Println(err)
+		os.Exit(1)
+	}
+	_, err = outFile.Write(out.Bytes())
+	if err != nil {
+		fmt.Println(err)
+		os.Exit(1)
+	}
+}

+ 81 - 0
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.md

@@ -0,0 +1,81 @@
+# Generating Markdown Docs For Your Own cobra.Command
+
+## Generate markdown docs for the entire command tree
+
+This program can actually generate docs for the kubectl command in the kubernetes project
+
+```go
+package main
+
+import (
+	"io/ioutil"
+	"os"
+
+	"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
+	"github.com/spf13/cobra"
+)
+
+func main() {
+	kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
+	cobra.GenMarkdownTree(kubectl, "./")
+}
+```
+
+This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
+
+## Generate markdown docs for a single command
+
+You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`
+
+```go
+	out := new(bytes.Buffer)
+	cobra.GenMarkdown(cmd, out)
+```
+
+This will write the markdown doc for ONLY "cmd" into the out, buffer.
+
+## Customize the output
+
+Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:
+
+```go
+func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string) string) {
+    //...
+}
+```
+
+```go
+func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) {
+    //...
+}
+```
+
+The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
+
+```go
+const fmTemplate = `---
+date: %s
+title: "%s"
+slug: %s
+url: %s
+---
+`
+
+filePrepender := func(filename string) string {
+	now := time.Now().Format(time.RFC3339)
+	name := filepath.Base(filename)
+	base := strings.TrimSuffix(name, path.Ext(name))
+	url := "/commands/" + strings.ToLower(base) + "/"
+	return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
+}
+```
+
+The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
+
+```go
+linkHandler := func(name string) string {
+	base := strings.TrimSuffix(name, path.Ext(name))
+	return "/commands/" + strings.ToLower(base) + "/"
+}
+```
+ 

+ 84 - 0
Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go

@@ -0,0 +1,84 @@
+package cobra
+
+import (
+	"bytes"
+	"fmt"
+	"os"
+	"strings"
+	"testing"
+)
+
+var _ = fmt.Println
+var _ = os.Stderr
+
+func TestGenMdDoc(t *testing.T) {
+	c := initializeWithRootCmd()
+	// Need two commands to run the command alphabetical sort
+	cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
+	c.AddCommand(cmdPrint, cmdEcho)
+	cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
+
+	out := new(bytes.Buffer)
+
+	// We generate on s subcommand so we have both subcommands and parents
+	GenMarkdown(cmdEcho, out)
+	found := out.String()
+
+	// Our description
+	expected := cmdEcho.Long
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+
+	// Better have our example
+	expected = cmdEcho.Example
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+
+	// A local flag
+	expected = "boolone"
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+
+	// persistent flag on parent
+	expected = "rootflag"
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+
+	// We better output info about our parent
+	expected = cmdRootWithRun.Short
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+
+	// And about subcommands
+	expected = cmdEchoSub.Short
+	if !strings.Contains(found, expected) {
+		t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
+	}
+
+	unexpected := cmdDeprecated.Short
+	if strings.Contains(found, unexpected) {
+		t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
+	}
+}
+
+func TestGenMdNoTag(t *testing.T) {
+	c := initializeWithRootCmd()
+	// Need two commands to run the command alphabetical sort
+	cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
+	c.AddCommand(cmdPrint, cmdEcho)
+	c.DisableAutoGenTag = true
+	cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
+	out := new(bytes.Buffer)
+
+	GenMarkdown(c, out)
+	found := out.String()
+
+	unexpected := "Auto generated"
+	checkStringOmits(t, found, unexpected)
+
+}

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.