Beispiel #1
0
func MakeSummary(post Mapper, lines int, topCtx mustache.Context) string {
	content := post["_content"].(*DocContent).Source
	r := bufio.NewReader(bytes.NewBufferString(content))
	dst := ""
	for lines > 0 {
		line, _ := r.ReadString('\n')
		dst += line
		lines--
		if lines == 0 {
			for "" != strings.Trim(line, "\r\n\t ") {
				line, _ = r.ReadString('\n')
				dst += line
			}
		}
	}
	str, err := mustache.RenderString(dst, topCtx)
	if err != nil {
		log.Println("BAD Mustache after Summary cut!")
		str, err = mustache.RenderString(dst, topCtx)
		if err != nil {
			log.Println("BAD Mustache Summary?", err)
			str = post["_content"].(*DocContent).Main
		}
	}
	mdParser := markdown.NewParser(&markdown.Extensions{Smart: true})
	buf := bytes.NewBuffer(nil)
	mdParser.Markdown(bytes.NewBufferString(str), markdown.ToHTML(buf))
	return buf.String()
}
Beispiel #2
0
func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
	body := r.FormValue("body")

	// save markdown source
	p := &page.Page{Title: title, Body: []byte(body)}
	err := page.Save(pageSrcLocation, p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// save html
	mdParser := markdown.NewParser(&markdown.Extensions{Smart: true})
	mdBody := bytes.NewBuffer(nil)

	mdParser.Markdown(strings.NewReader(body), markdown.ToHTML(mdBody))
	p = &page.Page{Title: title, Body: []byte(mdBody.String())}
	err = page.Save(pageLocation, p)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/view/"+title, http.StatusFound)
}
Beispiel #3
0
func main() {
	var opt markdown.Extensions
	flag.BoolVar(&opt.Notes, "notes", false, "turn on footnote syntax")
	flag.BoolVar(&opt.Smart, "smart", false, "turn on smart quotes, dashes, and ellipses")
	flag.BoolVar(&opt.Dlists, "dlists", false, "support definitions lists")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [FILE]\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()

	r := os.Stdin
	if flag.NArg() > 0 {
		f, err := os.Open(flag.Arg(0))
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		r = f
	}

	p := markdown.NewParser(&opt)

	startPProf()
	defer stopPProf()

	w := bufio.NewWriter(os.Stdout)
	p.Markdown(r, markdown.ToHTML(w))
	w.Flush()
}
Beispiel #4
0
func GetWikiMarkup(data []byte) []byte {
	output := bytes.NewBuffer(nil)
	reader := bytes.NewBuffer(data)

	parser.Markdown(reader, markdown.ToHTML(output))
	return output.Bytes()
}
Beispiel #5
0
func (wc *webConverter) markdownToHtml(content string) string {
	var mparser = markdown.NewParser(nil)
	stringBuffer := strings.NewReader(content)
	bufferReader := new(bytes.Buffer)
	mparser.Markdown(stringBuffer, markdown.ToHTML(bufferReader))
	return bufferReader.String()
}
Beispiel #6
0
func markdownFormat(text string) string {
	p := markdown.NewParser(&markdown.Extensions{Smart: true})
	// w := bufio.NewWriter(os.Stdout)
	buffer := bytes.NewBufferString("")
	p.Markdown(strings.NewReader(text), markdown.ToHTML(buffer))
	return buffer.String()
}
Beispiel #7
0
func RenderMarkdown(md string) string {
	htmlbuf := bytes.NewBufferString("")
	p := markdown.NewParser(&markdown.Extensions{Smart: true, FilterHTML: false})
	w := bufio.NewWriter(htmlbuf)
	p.Markdown(bytes.NewBufferString(md), markdown.ToHTML(w))
	w.Flush()
	return htmlbuf.String()
}
Beispiel #8
0
func fromMarkdown(src string) string {
	// Dance for the markdown library:
	body := []byte(src)
	bodyReader := bytes.NewReader(body)
	markup := new(bytes.Buffer)
	p := markdown.NewParser(&markdown.Extensions{Smart: true, Notes: true})
	p.Markdown(bodyReader, markdown.ToHTML(markup))
	return markup.String()
}
Beispiel #9
0
// tmplMarkdown formats a given string using markdown
func tmplMarkdown(t string) template.HTML {
	p := markdown.NewParser(&markdown.Extensions{Smart: true})

	inbuf := bytes.NewBufferString(t)
	outbuf := bytes.NewBufferString("")
	p.Markdown(inbuf, markdown.ToHTML(outbuf))

	return template.HTML(outbuf.String())
}
Beispiel #10
0
// 把Markdown文本转换为HTML
func Markdown2html(strMarkdown string) (html string) {
	p := markdown.NewParser(&markdown.Extensions{Smart: true})
	var buf bytes.Buffer
	w := bufio.NewWriter(&buf)
	r := bytes.NewBufferString(strMarkdown)
	p.Markdown(r, markdown.ToHTML(w))
	w.Flush()
	html = string(buf.Bytes())
	return
}
Beispiel #11
0
func (*mdFilter) filter(input []byte) bytes.Buffer {
	p := markdown.NewParser(&markdown.Extensions{Smart: true})
	var buf bytes.Buffer
	buf.WriteString(`<html><header><style type="text/css">`)
	buf.WriteString(CSS)
	buf.WriteString("</style></header><body>")
	p.Markdown(bytes.NewReader(input), markdown.ToHTML(&buf))
	buf.WriteString("</body></html>")
	return buf
}
Beispiel #12
0
func MarkdownToHtml(content string) (str string) {
	defer func() {
		e := recover()
		if e != nil {
			log.Println(e)
		}
	}()
	mdParser := markdown.NewParser(&markdown.Extensions{Smart: true})
	buf := bytes.NewBuffer(nil)
	mdParser.Markdown(bytes.NewBufferString(content), markdown.ToHTML(buf))
	str = buf.String()
	return
}
Beispiel #13
0
Datei: main.go Projekt: itang/_my
func main() {
	p := markdown.NewParser(&markdown.Extensions{Smart: true})

	file, _ := os.Open("test.md")
	outfile, _ := os.Create("test_out.html")
	defer file.Close()
	defer outfile.Close()

	in := bufio.NewReader(file)
	out := bufio.NewWriter(outfile)
	p.Markdown(in, markdown.ToHTML(out))
	out.Flush()
}
Beispiel #14
0
// converts posts's BodyMarkdown to HTML (BodyHTML) if post does not already have HTML
func toHTML(posts []*Post) {
	parser := markdown.NewParser(&markdown.Extensions{Smart: true})
	for _, post := range posts {
		if post.BodyHTML == "" {
			log.Printf("\"%s\": Converting Markdown to HTML\n", post.Slug)
			html := new(bytes.Buffer)
			parser.Markdown(strings.NewReader(post.BodyMarkdown), markdown.ToHTML(html))
			post.BodyHTML = html.String()
		} else {
			log.Printf("\"%s\": HTML already exists, not using Markdown\n", post.Slug)
		}
	}
}
Beispiel #15
0
func PrapreMainContent(id string, content string, ctx mustache.Context) (string, error) {
	mdParser := markdown.NewParser(&markdown.Extensions{Smart: true})
	str, err := mustache.RenderString(content, ctx)
	if err != nil {
		return str, err
	}
	if strings.HasSuffix(id, ".md") || strings.HasSuffix(id, ".markdown") {
		//log.Println("R: MD : " + id)
		buf := bytes.NewBuffer(nil)
		mdParser.Markdown(bytes.NewBufferString(str), markdown.ToHTML(buf))
		str = buf.String()
	}
	return str, nil
}
Beispiel #16
0
func ReadmeHandler(res http.ResponseWriter, req *http.Request) {
	parser := markdown.NewParser(&markdown.Extensions{Smart: true})
	file, err := os.Open("README.md")
	if err != nil {
		fmt.Fprintln(res, err)
	} else {
		w := bufio.NewWriter(res)
		w.WriteString("<html>")
		w.WriteString(`<head><link href="http://kevinburke.bitbucket.org/markdowncss/markdown.css" rel="stylesheet"></link></head>`)
		w.WriteString(`<body><a href="https://github.com/janne/gometrics"><img style="position: absolute; top: 0; right: 30px; border: 0;" src="https://github.com/jamesflorentino/fork-ribbons/raw/master/ribbons/red-white.png" alt="Fork me on GitHub"></a>`)
		parser.Markdown(file, markdown.ToHTML(w))
		w.WriteString("</body></html>")
		w.Flush()
	}
}
Beispiel #17
0
func Main() error {
	template, err := ioutil.ReadFile("template.html")
	if err != nil {
		return err
	}

	reader := bufio.NewReader(os.Stdin)

	var title string

	for {
		line, err := reader.ReadString('\n')
		if err != nil {
			return err
		}

		if strings.HasPrefix(line, "===") {
			break
		} else {
			title = line[:len(line)-1]
		}
	}

	md, err := ioutil.ReadAll(reader)
	if err != nil {
		return err
	}

	result := bytes.NewBuffer(nil)

	p := markdown.NewParser(nil)
	p.Markdown(bytes.NewReader(md), markdown.ToHTML(result))

	filtered, err := AfterFilter(result.Bytes())
	if err != nil {
		return err
	}

	template = bytes.Replace(template, []byte("{TITLE}"), []byte(title), -1)
	template = bytes.Replace(template, []byte("{CONTENT}"), filtered, -1)
	template = bytes.Replace(template, []byte("{NAME}"), []byte(os.Args[1]), -1)

	if _, err := os.Stdout.Write(template); err != nil {
		return err
	}

	return nil
}
Beispiel #18
0
// loadPage loads the markdown for a page from templates/title.markdown, and
// converts it to HTML, returning a new Page with
// Page.Title = title string
// Page.Body = new html
func loadPage(title string) (*Page, error) {
	// get markdown for page specified
	filename := "templates/" + title + ".markdown"
	markdown_file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer markdown_file.Close()

	// parse markdown into Page.Body
	var html_buf bytes.Buffer
	parser := markdown.NewParser(&markdown.Extensions{Smart: true})
	parser.Markdown(markdown_file, markdown.ToHTML(&html_buf))

	return &Page{Title: title, Body: html_buf.Bytes()}, nil
}
Beispiel #19
0
func (f *fetcher) retrieveContent(path string, extension string) (string, error) {
	u := dropbox.Uri{
		Root: "sandbox" + path,
	}

	file, _, err := dropbox.GetFile(f.Session, u, nil)
	if err != nil {
		return "", err
	}

	// Markdown check
	if extension == "md" {
		p := markdown.NewParser(&markdown.Extensions{Smart: true})
		buf := new(bytes.Buffer)
		p.Markdown(bytes.NewReader(file), markdown.ToHTML(buf))
		return buf.String(), nil
	} else {
		return string(file), nil
	}

}
Beispiel #20
0
func LoadPost(post Post) (postData PostData) {
	// Read metadata
	metadata, err := ioutil.ReadFile(post.metadataPath)
	if err != nil {
		log.Fatal(err)
	}

	// Load params into a map
	var params map[string]interface{}
	err = json.Unmarshal(metadata, &params)
	if err != nil {
		log.Fatal(err)
	}

	// Read content file
	content, err := ioutil.ReadFile(post.contentPath)
	if err != nil {
		log.Fatal(err)
	}

	// Parse Markdown
	var b bytes.Buffer

	parser := markdown.NewParser(&markdown.Extensions{Smart: true})
	parser.Markdown(bytes.NewReader(content), markdown.ToHTML(&b))

	processedContent := b.String()

	// Populate postData
	postData.Title = params["title"].(string)
	postData.Date, err = time.Parse(time.RFC3339, params["date"].(string))
	postData.Params = params
	postData.Content = processedContent
	if err != nil {
		log.Fatal(err)
	}

	return
}
Beispiel #21
0
func main() {
	// Args
	path := os.Args[1]
	port := ":8080"
	if len(os.Args) > 2 {
		port = ":" + os.Args[2]
	}

	// Open Markdown File
	mkd_file, err := os.Open(path)
	if err != nil {
		log.Fatal("Open File Error: ", err.Error())
	}
	defer mkd_file.Close()

	// Markdown Parser
	p := markdown.NewParser(nil)
	var markdown_buf bytes.Buffer
	p.Markdown(mkd_file, markdown.ToHTML(&markdown_buf))

	// Launch the HTTP server
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`
		<head><style>
a {
	color              : #666;
	outline            : 0;
	text-decoration    : none;
	transition         : color .5s ease 0s;
	-moz-transition    : color .5s ease 0s;
	-webkit-transition : color .5s ease 0s;
}
a:hover {
	font-style : italic;
}
strong {
	font-weight : bold;
}
hr {
	border : 1px solid black;
	margin : 30px 0;
}
::selection {
	background : #c4c4c4;
	color      : black;
}
::-moz-selection {
	background : #777;
	color      : black;
}
body {
	font-family : sans-serif;
	background  : black;
	color       : #ddd;
	width       : 77%;
	max-width   : 666px;
	padding     : 0px 20px 30px 0;
	font-size   : 17px;
}
h1, h2, h3 {
	font-weight : bold;
	margin-top  : 30px;
}
h1 {
	font-size : 1.8em;
}
h2 {
	font-size : 1.4em;
}
h3 {
	font-size  : 1em;
	margin-top : 20px;
}
p {
	margin : 16px 0;
}
a:hover {
	color : white;
}
em {
	font-style : italic;
}
code {
	font-size     : 13px;
	color         : #888;
	background    : black;
	padding       : 3px;
	border        : 1px solid #171717;
	border-top    : 1px solid #111111;
	border-bottom : 1px solid #222222;
	box-shadow    : 0 0 3px #070707;
}
pre, p code {
	display               : block;
	font-size             : 13px;
	color                 : #888;
	background            : black;
	padding               : 10px;
	margin                : 10px 0;
	overflow-x            : hidden;
	white-space           : pre;
	border                : 1px solid #171717;
	border-top            : 1px solid #111111;
	border-bottom         : 1px solid #222222;
	border-radius         : 3px;
	-moz-border-radius    : 3px;
	-webkit-border-radius : 3px;
	box-shadow            : inset 10px 0 30px #0A0A0A;
	                      , inset 30px 0 100px #070707;
}
pre code {
	border     : 0;
	box-shadow : 0;
}
pre:hover, p code:hover {
	overflow-x : scroll;
}
pre code {
	padding    : 0;
	border     : 0;
	background : none;
}
blockquote {
	padding    : 10px 10px 10px 15px;
	background : #070707;
	color      : #777;
	font-size  : 16px;
}
blockquote a {
	text-decoration : underline;
}
ul {
	margin : 8px 0 4px 0;
}
li {
	margin           : 0 0 8px 20px;
	padding-left     : 4px;
	list-style-image : url(http://sadasant.com/images/whitebullets.png);
}
img {
	max-width : 77%;
	border    : 1px solid #111;
}
		</style></head>
		<body>`))
		w.Write(markdown_buf.Bytes())
		w.Write([]byte("</body>"))
	})

	// Serving the doc
	server := &http.Server{
		Addr: port,
	}
	listener, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatal(err.Error())
	}
	go server.Serve(listener)

	// Surf the url
	url := "http://localhost" + port
	println("Listening on: " + url + "/")
	cmd := exec.Command("surf", url)
	if err = cmd.Run(); err != nil {
		log.Fatal(err.Error())
	}

	// Bye bye!
	listener.Close()
}
Beispiel #22
0
func getFuncs() template.FuncMap {
	return template.FuncMap{
		"eq": func(a, b interface{}) bool {
			return a == b
		},
		"ne": func(a, b interface{}) bool {
			return a != b
		},
		"contains": func(a string, arr []string) bool {
			for _, e := range arr {
				if e == a {
					return true
				}
			}
			return false
		},
		"odd": func(a int) bool {
			return math.Mod(float64(a), 2) != 0
		},
		"even": func(a int) bool {
			return math.Mod(float64(a), 2) == 0
		},
		"inc": func(a int) int {
			return a + 1
		},
		"json": func(o interface{}) string {
			str, err := json.Marshal(o)
			if err != nil {
				return ""
			}
			return string(str)
		},
		"_": func(messageId string) string {
			return gettext.Gettext(messageId)
		},
		"_f": func(messageId string, args ...interface{}) string {
			return gettext.Sprintf(gettext.Gettext(messageId), args...)
		},
		"defferelementwith": func(element data.Element, messages []data.Message, messageIndex int) bool {
			logger.Debug(element)
			if messageIndex == 0 {
				return element.StrVal != ""
			}
			for _, e := range messages[messageIndex-1].Elements {
				if e.ElementType.Id == element.ElementType.Id {
					return e.StrVal != element.StrVal
				}
			}
			return true
		},
		"haserror": func(errors map[string]string, elementType data.ElementType) bool {
			if len(errors) == 0 {
				return false
			}
			_, exists := errors[fmt.Sprintf("field%d", elementType.Id)]
			return exists
		},
		"geterror": func(errors map[string]string, elementType data.ElementType) string {
			if len(errors) == 0 {
				return ""
			}
			error, _ := errors[fmt.Sprintf("field%d", elementType.Id)]
			return error
		},
		"getvalue": func(elementType data.ElementType, params url.Values, elements []data.Element) string {
			fieldName := fmt.Sprintf("field%d", elementType.Id)
			if _, ok := params[fieldName]; ok {
				return params.Get(fieldName)
			} else {
				for _, e := range elements {
					if e.ElementType.Id == elementType.Id {
						return e.StrVal
					}
				}
			}
			return ""
		},
		"getvalues": func(elementType data.ElementType, params url.Values, elements []data.Element) []string {
			fieldName := fmt.Sprintf("field%d", elementType.Id)
			if _, ok := params[fieldName]; ok {
				return params[fieldName]
			} else {
				for _, e := range elements {
					if e.ElementType.Id == elementType.Id {
						return strings.Split(e.StrVal, "\t")
					}
				}
			}
			return []string{""}
		},
		"markdown": func(content interface{}) template.HTML {
			str := html.EscapeString(content.(string))
			p := markdown.NewParser(&markdown.Extensions{Smart: true})
			buf := bytes.NewBufferString("")
			w := bufio.NewWriter(buf)
			p.Markdown(bufio.NewReader(bytes.NewBufferString(str)), markdown.ToHTML(w))
			w.Flush()
			return template.HTML(buf.String())
		},
	}
}
Beispiel #23
0
	baseUrl    *url.URL
	fmap       = template.FuncMap{
		"url_for": func(path string) string {
			return baseUrl.String() + path
		},
		"first_line": func(s string) string {
			sl := strings.Split(s, "\n")
			return sl[0]
		},
		"get_token": func(session *sessions.Session) interface{} {
			return session.Values["token"]
		},
		"gen_markdown": func(s string) template.HTML {
			var buf bytes.Buffer
			p := markdown.NewParser(nil)
			p.Markdown(bytes.NewBufferString(s), markdown.ToHTML(&buf))

			return template.HTML(buf.String())
		},
	}
	tmpl = template.Must(template.New("tmpl").Funcs(fmap).ParseGlob("templates/*.html"))
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	env := os.Getenv("ISUCON_ENV")
	if env == "" {
		env = "local"
	}
	config := loadConfig("../config/" + env + ".json")
Beispiel #24
0
/**
  Given a article.MetaData object containing some paths and stuff,
  does appropriate transformations to construct the HTML form.
*/
func WriteHtmlFile(sys System, md *article.MetaData) {
	// TODO(rjkroege): it is silly to re-open these files when I
	// have had them open before them. And to re-read chunks of
	// them when I have already done so. But this is easier. And
	// it probably doesn't matter given that most files don't need
	// to be regenerated.

	// Handle  failures in the library.
	defer func() {
		if r := recover(); r != nil {
			fmt.Println(md.Name, "WriteHtmlFile, failed", r)
		}
	}()

	fd, err := sys.OpenFileForReading(md.Name)
	defer fd.Close()
	if err != nil {
		fmt.Print(err)
		return
	}

	modtime, serr := sys.ModTime(md.FormattedName())
	// This might be suspect?
	if serr != nil || modtime.Before(md.DateFromStat) {
		// TODO(rjkroege): if the md file is not as new as the HTML file,
		// skip all of this work.
		// fmt.Println("processing " + md.Name)
		ofd, werr := sys.OpenFileForWriting(md.FormattedName())
		defer ofd.Close()
		if werr != nil {
			fmt.Print("WriteHtmlFile:OpenFileForWriting", werr, "\n")
			return
		}

		// TODO(rjkroege): using a byte slice might be faster?
		// learn to improve perf on Go.
		body := ""
		rd := bufio.NewReader(io.Reader(fd))

		// Trim the metadata here.
		if md.HadMetaData {
			for {
				line, rerr := rd.ReadString('\n')
				if rerr != nil {
					fmt.Print("WriteHtmlFile:ReadString ", werr, "\n")
					return
				}
				if line == "\n" {
					break
				}
			}
		}

		// TODO(rjkroege): don't read the file into memory.
		// Read errors will wipe out previously generated output. Do I care?
		for {
			line, rerr := rd.ReadString('\n')
			if rerr == io.EOF {
				break
			} else if rerr != nil {
				fmt.Print("WriteHtmlFile: read error ", rerr, "\n")
				return
			}
			body += line
		}

		w := bufio.NewWriter(ofd)
		defer w.Flush()

		// Header with substitutions
		headerTemplate.Execute(w, md)

		// Convert the markdown file into a HTML
		p := markdown.NewParser(&markdown.Extensions{Smart: true})
		p.Markdown(strings.NewReader(body), markdown.ToHTML(w))

		// Footer with substitutions
		footerTemplate.Execute(w, md)
		// fmt.Println("done " + md.Name)
	}
}
Beispiel #25
0
	// 创建主页面
	main_view = layout.Copy()
	main_view.Div("left", article_list)
	main_view.Div("right", kview.New("show.kt", utils))

	// 创建编辑页面
	edit_view = layout.Copy()
	edit_view.Div("left", article_list)
	edit_view.Div("right", kview.New("edit.kt"))
}

var (
	mde = markdown.Extensions{
		Smart:        true,
		Dlists:       true,
		FilterHTML:   true,
		FilterStyles: true,
	}
	utils = map[string]interface{}{
		"markdown": func(txt string) []byte {
			p := markdown.NewParser(&mde)
			var buf bytes.Buffer
			w := bufio.NewWriter(&buf)
			r := bytes.NewBufferString(txt)
			p.Markdown(r, markdown.ToHTML(w))
			w.Flush()
			return buf.Bytes()
		},
	}
)