Merge branch 'maint'
[org-mode.git] / lisp / ox-md.el
blobaa509d62e0bf079106f58b03ecf2a873805691f2
1 ;;; ox-md.el --- Markdown Back-End for Org Export Engine
3 ;; Copyright (C) 2012-2014 Free Software Foundation, Inc.
5 ;; Author: Nicolas Goaziou <n.goaziou@gmail.com>
6 ;; Keywords: org, wp, markdown
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This library implements a Markdown back-end (vanilla flavor) for
26 ;; Org exporter, based on `html' back-end. See Org manual for more
27 ;; information.
29 ;;; Code:
31 (eval-when-compile (require 'cl))
32 (require 'ox-html)
33 (require 'ox-publish)
36 ;;; User-Configurable Variables
38 (defgroup org-export-md nil
39 "Options specific to Markdown export back-end."
40 :tag "Org Markdown"
41 :group 'org-export
42 :version "24.4"
43 :package-version '(Org . "8.0"))
45 (defcustom org-md-headline-style 'atx
46 "Style used to format headlines.
47 This variable can be set to either `atx' or `setext'."
48 :group 'org-export-md
49 :type '(choice
50 (const :tag "Use \"atx\" style" atx)
51 (const :tag "Use \"Setext\" style" setext)))
55 ;;; Define Back-End
57 (org-export-define-derived-backend 'md 'html
58 :export-block '("MD" "MARKDOWN")
59 :filters-alist '((:filter-parse-tree . org-md-separate-elements))
60 :menu-entry
61 '(?m "Export to Markdown"
62 ((?M "To temporary buffer"
63 (lambda (a s v b) (org-md-export-as-markdown a s v)))
64 (?m "To file" (lambda (a s v b) (org-md-export-to-markdown a s v)))
65 (?o "To file and open"
66 (lambda (a s v b)
67 (if a (org-md-export-to-markdown t s v)
68 (org-open-file (org-md-export-to-markdown nil s v)))))))
69 :translate-alist '((bold . org-md-bold)
70 (code . org-md-verbatim)
71 (comment . (lambda (&rest args) ""))
72 (comment-block . (lambda (&rest args) ""))
73 (example-block . org-md-example-block)
74 (fixed-width . org-md-example-block)
75 (footnote-definition . ignore)
76 (footnote-reference . ignore)
77 (headline . org-md-headline)
78 (horizontal-rule . org-md-horizontal-rule)
79 (inline-src-block . org-md-verbatim)
80 (inner-template . org-md-inner-template)
81 (italic . org-md-italic)
82 (item . org-md-item)
83 (keyword . org-md-keyword)
84 (line-break . org-md-line-break)
85 (link . org-md-link)
86 (node-property . org-md-node-property)
87 (paragraph . org-md-paragraph)
88 (plain-list . org-md-plain-list)
89 (plain-text . org-md-plain-text)
90 (property-drawer . org-md-property-drawer)
91 (quote-block . org-md-quote-block)
92 (section . org-md-section)
93 (src-block . org-md-example-block)
94 (template . org-md-template)
95 (verbatim . org-md-verbatim))
96 :options-alist '((:md-headline-style nil nil org-md-headline-style)))
99 ;;; Filters
101 (defun org-md-separate-elements (tree backend info)
102 "Fix blank lines between elements.
104 TREE is the parse tree being exported. BACKEND is the export
105 back-end used. INFO is a plist used as a communication channel.
107 Enforce a blank line between elements. There are three
108 exceptions to this rule:
110 1. Preserve blank lines between sibling items in a plain list,
112 2. Outside of plain lists, preserve blank lines between
113 a paragraph and a plain list,
115 3. In an item, remove any blank line before the very first
116 paragraph and the next sub-list.
118 Assume BACKEND is `md'."
119 (org-element-map tree (remq 'item org-element-all-elements)
120 (lambda (e)
121 (cond
122 ((not (and (eq (org-element-type e) 'paragraph)
123 (eq (org-element-type (org-export-get-next-element e info))
124 'plain-list)))
125 (org-element-put-property e :post-blank 1))
126 ((not (eq (org-element-type (org-element-property :parent e)) 'item)))
127 (t (org-element-put-property
128 e :post-blank (if (org-export-get-previous-element e info) 1 0))))))
129 ;; Return updated tree.
130 tree)
134 ;;; Transcode Functions
136 ;;;; Bold
138 (defun org-md-bold (bold contents info)
139 "Transcode BOLD object into Markdown format.
140 CONTENTS is the text within bold markup. INFO is a plist used as
141 a communication channel."
142 (format "**%s**" contents))
145 ;;;; Code and Verbatim
147 (defun org-md-verbatim (verbatim contents info)
148 "Transcode VERBATIM object into Markdown format.
149 CONTENTS is nil. INFO is a plist used as a communication
150 channel."
151 (let ((value (org-element-property :value verbatim)))
152 (format (cond ((not (string-match "`" value)) "`%s`")
153 ((or (string-match "\\``" value)
154 (string-match "`\\'" value))
155 "`` %s ``")
156 (t "``%s``"))
157 value)))
160 ;;;; Example Block and Src Block
162 (defun org-md-example-block (example-block contents info)
163 "Transcode EXAMPLE-BLOCK element into Markdown format.
164 CONTENTS is nil. INFO is a plist used as a communication
165 channel."
166 (replace-regexp-in-string
167 "^" " "
168 (org-remove-indentation
169 (org-export-format-code-default example-block info))))
172 ;;;; Headline
174 (defun org-md-headline (headline contents info)
175 "Transcode HEADLINE element into Markdown format.
176 CONTENTS is the headline contents. INFO is a plist used as
177 a communication channel."
178 (unless (org-element-property :footnote-section-p headline)
179 (let* ((level (org-export-get-relative-level headline info))
180 (title (org-export-data (org-element-property :title headline) info))
181 (todo (and (plist-get info :with-todo-keywords)
182 (let ((todo (org-element-property :todo-keyword
183 headline)))
184 (and todo (concat (org-export-data todo info) " ")))))
185 (tags (and (plist-get info :with-tags)
186 (let ((tag-list (org-export-get-tags headline info)))
187 (and tag-list
188 (format " :%s:"
189 (mapconcat 'identity tag-list ":"))))))
190 (priority
191 (and (plist-get info :with-priority)
192 (let ((char (org-element-property :priority headline)))
193 (and char (format "[#%c] " char)))))
194 (anchor
195 (when (plist-get info :with-toc)
196 (org-html--anchor
197 (or (org-element-property :CUSTOM_ID headline)
198 (concat "sec-"
199 (mapconcat 'number-to-string
200 (org-export-get-headline-number
201 headline info) "-")))
202 nil nil info)))
203 ;; Headline text without tags.
204 (heading (concat todo priority title))
205 (style (plist-get info :md-headline-style)))
206 (cond
207 ;; Cannot create a headline. Fall-back to a list.
208 ((or (org-export-low-level-p headline info)
209 (not (memq style '(atx setext)))
210 (and (eq style 'atx) (> level 6))
211 (and (eq style 'setext) (> level 2)))
212 (let ((bullet
213 (if (not (org-export-numbered-headline-p headline info)) "-"
214 (concat (number-to-string
215 (car (last (org-export-get-headline-number
216 headline info))))
217 "."))))
218 (concat bullet (make-string (- 4 (length bullet)) ? ) heading tags
219 "\n\n"
220 (and contents
221 (replace-regexp-in-string "^" " " contents)))))
222 ;; Use "Setext" style.
223 ((eq style 'setext)
224 (concat heading tags anchor "\n"
225 (make-string (length heading) (if (= level 1) ?= ?-))
226 "\n\n"
227 contents))
228 ;; Use "atx" style.
229 (t (concat (make-string level ?#) " " heading tags anchor "\n\n" contents))))))
232 ;;;; Horizontal Rule
234 (defun org-md-horizontal-rule (horizontal-rule contents info)
235 "Transcode HORIZONTAL-RULE element into Markdown format.
236 CONTENTS is the horizontal rule contents. INFO is a plist used
237 as a communication channel."
238 "---")
241 ;;;; Italic
243 (defun org-md-italic (italic contents info)
244 "Transcode ITALIC object into Markdown format.
245 CONTENTS is the text within italic markup. INFO is a plist used
246 as a communication channel."
247 (format "*%s*" contents))
250 ;;;; Item
252 (defun org-md-item (item contents info)
253 "Transcode ITEM element into Markdown format.
254 CONTENTS is the item contents. INFO is a plist used as
255 a communication channel."
256 (let* ((type (org-element-property :type (org-export-get-parent item)))
257 (struct (org-element-property :structure item))
258 (bullet (if (not (eq type 'ordered)) "-"
259 (concat (number-to-string
260 (car (last (org-list-get-item-number
261 (org-element-property :begin item)
262 struct
263 (org-list-prevs-alist struct)
264 (org-list-parents-alist struct)))))
265 "."))))
266 (concat bullet
267 (make-string (- 4 (length bullet)) ? )
268 (case (org-element-property :checkbox item)
269 (on "[X] ")
270 (trans "[-] ")
271 (off "[ ] "))
272 (let ((tag (org-element-property :tag item)))
273 (and tag (format "**%s:** "(org-export-data tag info))))
274 (and contents
275 (org-trim (replace-regexp-in-string "^" " " contents))))))
279 ;;;; Keyword
281 (defun org-md-keyword (keyword contents info)
282 "Transcode a KEYWORD element into Markdown format.
283 CONTENTS is nil. INFO is a plist used as a communication
284 channel."
285 (if (member (org-element-property :key keyword) '("MARKDOWN" "MD"))
286 (org-element-property :value keyword)
287 (org-export-with-backend 'html keyword contents info)))
290 ;;;; Line Break
292 (defun org-md-line-break (line-break contents info)
293 "Transcode LINE-BREAK object into Markdown format.
294 CONTENTS is nil. INFO is a plist used as a communication
295 channel."
296 " \n")
299 ;;;; Link
301 (defun org-md-link (link contents info)
302 "Transcode LINE-BREAK object into Markdown format.
303 CONTENTS is the link's description. INFO is a plist used as
304 a communication channel."
305 (let ((link-org-files-as-md
306 (function
307 (lambda (raw-path)
308 ;; Treat links to `file.org' as links to `file.md'.
309 (if (string= ".org" (downcase (file-name-extension raw-path ".")))
310 (concat (file-name-sans-extension raw-path) ".md")
311 raw-path))))
312 (type (org-element-property :type link)))
313 (cond ((member type '("custom-id" "id"))
314 (let ((destination (org-export-resolve-id-link link info)))
315 (if (stringp destination) ; External file.
316 (let ((path (funcall link-org-files-as-md destination)))
317 (if (not contents) (format "<%s>" path)
318 (format "[%s](%s)" contents path)))
319 (concat
320 (and contents (concat contents " "))
321 (format "(%s)"
322 (format (org-export-translate "See section %s" :html info)
323 (mapconcat 'number-to-string
324 (org-export-get-headline-number
325 destination info)
326 ".")))))))
327 ((org-export-inline-image-p link org-html-inline-image-rules)
328 (let ((path (let ((raw-path (org-element-property :path link)))
329 (if (not (file-name-absolute-p raw-path)) raw-path
330 (expand-file-name raw-path))))
331 (caption (org-export-data
332 (org-export-get-caption
333 (org-export-get-parent-element link)) info)))
334 (format "![img](%s)"
335 (if (not (org-string-nw-p caption)) path
336 (format "%s \"%s\"" path caption)))))
337 ((string= type "coderef")
338 (let ((ref (org-element-property :path link)))
339 (format (org-export-get-coderef-format ref contents)
340 (org-export-resolve-coderef ref info))))
341 ((equal type "radio") contents)
342 ((equal type "fuzzy")
343 (let ((destination (org-export-resolve-fuzzy-link link info)))
344 (if (org-string-nw-p contents) contents
345 (when destination
346 (let ((number (org-export-get-ordinal destination info)))
347 (when number
348 (if (atom number) (number-to-string number)
349 (mapconcat 'number-to-string number "."))))))))
350 (t (let* ((raw-path (org-element-property :path link))
351 (path
352 (cond
353 ((member type '("http" "https" "ftp"))
354 (concat type ":" raw-path))
355 ((string= type "file")
356 (let ((path (funcall link-org-files-as-md raw-path)))
357 (if (not (file-name-absolute-p path)) path
358 ;; If file path is absolute, prepend it
359 ;; with "file:" component.
360 (concat "file:" path))))
361 (t raw-path))))
362 (if (not contents) (format "<%s>" path)
363 (format "[%s](%s)" contents path)))))))
366 ;;;; Node Property
368 (defun org-md-node-property (node-property contents info)
369 "Transcode a NODE-PROPERTY element into Markdown syntax.
370 CONTENTS is nil. INFO is a plist holding contextual
371 information."
372 (format "%s:%s"
373 (org-element-property :key node-property)
374 (let ((value (org-element-property :value node-property)))
375 (if value (concat " " value) ""))))
378 ;;;; Paragraph
380 (defun org-md-paragraph (paragraph contents info)
381 "Transcode PARAGRAPH element into Markdown format.
382 CONTENTS is the paragraph contents. INFO is a plist used as
383 a communication channel."
384 (let ((first-object (car (org-element-contents paragraph))))
385 ;; If paragraph starts with a #, protect it.
386 (if (and (stringp first-object) (string-match "\\`#" first-object))
387 (replace-regexp-in-string "\\`#" "\\#" contents nil t)
388 contents)))
391 ;;;; Plain List
393 (defun org-md-plain-list (plain-list contents info)
394 "Transcode PLAIN-LIST element into Markdown format.
395 CONTENTS is the plain-list contents. INFO is a plist used as
396 a communication channel."
397 contents)
400 ;;;; Plain Text
402 (defun org-md-plain-text (text info)
403 "Transcode a TEXT string into Markdown format.
404 TEXT is the string to transcode. INFO is a plist holding
405 contextual information."
406 (when (plist-get info :with-smart-quotes)
407 (setq text (org-export-activate-smart-quotes text :html info)))
408 ;; Protect ambiguous #. This will protect # at the beginning of
409 ;; a line, but not at the beginning of a paragraph. See
410 ;; `org-md-paragraph'.
411 (setq text (replace-regexp-in-string "\n#" "\n\\\\#" text))
412 ;; Protect ambiguous !
413 (setq text (replace-regexp-in-string "\\(!\\)\\[" "\\\\!" text nil nil 1))
414 ;; Protect `, *, _ and \
415 (setq text (replace-regexp-in-string "[`*_\\]" "\\\\\\&" text))
416 ;; Handle special strings, if required.
417 (when (plist-get info :with-special-strings)
418 (setq text (org-html-convert-special-strings text)))
419 ;; Handle break preservation, if required.
420 (when (plist-get info :preserve-breaks)
421 (setq text (replace-regexp-in-string "[ \t]*\n" " \n" text)))
422 ;; Return value.
423 text)
426 ;;;; Property Drawer
428 (defun org-md-property-drawer (property-drawer contents info)
429 "Transcode a PROPERTY-DRAWER element into Markdown format.
430 CONTENTS holds the contents of the drawer. INFO is a plist
431 holding contextual information."
432 (and (org-string-nw-p contents)
433 (replace-regexp-in-string "^" " " contents)))
436 ;;;; Quote Block
438 (defun org-md-quote-block (quote-block contents info)
439 "Transcode QUOTE-BLOCK element into Markdown format.
440 CONTENTS is the quote-block contents. INFO is a plist used as
441 a communication channel."
442 (replace-regexp-in-string
443 "^" "> "
444 (replace-regexp-in-string "\n\\'" "" contents)))
447 ;;;; Section
449 (defun org-md-section (section contents info)
450 "Transcode SECTION element into Markdown format.
451 CONTENTS is the section contents. INFO is a plist used as
452 a communication channel."
453 contents)
456 ;;;; Template
458 (defun org-md-inner-template (contents info)
459 "Return body of document after converting it to Markdown syntax.
460 CONTENTS is the transcoded contents string. INFO is a plist
461 holding export options."
462 ;; Make sure CONTENTS is separated from table of contents and
463 ;; footnotes with at least a blank line.
464 (org-trim (org-html-inner-template (concat "\n" contents "\n") info)))
466 (defun org-md-template (contents info)
467 "Return complete document string after Markdown conversion.
468 CONTENTS is the transcoded contents string. INFO is a plist used
469 as a communication channel."
470 contents)
474 ;;; Interactive function
476 ;;;###autoload
477 (defun org-md-export-as-markdown (&optional async subtreep visible-only)
478 "Export current buffer to a Markdown buffer.
480 If narrowing is active in the current buffer, only export its
481 narrowed part.
483 If a region is active, export that region.
485 A non-nil optional argument ASYNC means the process should happen
486 asynchronously. The resulting buffer should be accessible
487 through the `org-export-stack' interface.
489 When optional argument SUBTREEP is non-nil, export the sub-tree
490 at point, extracting information from the headline properties
491 first.
493 When optional argument VISIBLE-ONLY is non-nil, don't export
494 contents of hidden elements.
496 Export is done in a buffer named \"*Org MD Export*\", which will
497 be displayed when `org-export-show-temporary-export-buffer' is
498 non-nil."
499 (interactive)
500 (org-export-to-buffer 'md "*Org MD Export*"
501 async subtreep visible-only nil nil (lambda () (text-mode))))
503 ;;;###autoload
504 (defun org-md-convert-region-to-md ()
505 "Assume the current region has org-mode syntax, and convert it to Markdown.
506 This can be used in any buffer. For example, you can write an
507 itemized list in org-mode syntax in a Markdown buffer and use
508 this command to convert it."
509 (interactive)
510 (org-export-replace-region-by 'md))
513 ;;;###autoload
514 (defun org-md-export-to-markdown (&optional async subtreep visible-only)
515 "Export current buffer to a Markdown file.
517 If narrowing is active in the current buffer, only export its
518 narrowed part.
520 If a region is active, export that region.
522 A non-nil optional argument ASYNC means the process should happen
523 asynchronously. The resulting file should be accessible through
524 the `org-export-stack' interface.
526 When optional argument SUBTREEP is non-nil, export the sub-tree
527 at point, extracting information from the headline properties
528 first.
530 When optional argument VISIBLE-ONLY is non-nil, don't export
531 contents of hidden elements.
533 Return output file's name."
534 (interactive)
535 (let ((outfile (org-export-output-file-name ".md" subtreep)))
536 (org-export-to-file 'md outfile async subtreep visible-only)))
538 ;;;###autoload
539 (defun org-md-publish-to-md (plist filename pub-dir)
540 "Publish an org file to Markdown.
542 FILENAME is the filename of the Org file to be published. PLIST
543 is the property list for the given project. PUB-DIR is the
544 publishing directory.
546 Return output file name."
547 (org-publish-org-to 'md filename ".md" plist pub-dir))
549 (provide 'ox-md)
551 ;; Local variables:
552 ;; generated-autoload-file: "org-loaddefs.el"
553 ;; End:
555 ;;; ox-md.el ends here