Merge branch 'maint'
[org-mode.git] / lisp / ox-md.el
blobf3fdedc49144a1a3e4095a45a4c61b73d63c696c
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 (export-block . org-md-export-block)
75 (fixed-width . org-md-example-block)
76 (footnote-definition . ignore)
77 (footnote-reference . ignore)
78 (headline . org-md-headline)
79 (horizontal-rule . org-md-horizontal-rule)
80 (inline-src-block . org-md-verbatim)
81 (inner-template . org-md-inner-template)
82 (italic . org-md-italic)
83 (item . org-md-item)
84 (keyword . org-md-keyword)
85 (line-break . org-md-line-break)
86 (link . org-md-link)
87 (node-property . org-md-node-property)
88 (paragraph . org-md-paragraph)
89 (plain-list . org-md-plain-list)
90 (plain-text . org-md-plain-text)
91 (property-drawer . org-md-property-drawer)
92 (quote-block . org-md-quote-block)
93 (section . org-md-section)
94 (src-block . org-md-example-block)
95 (template . org-md-template)
96 (verbatim . org-md-verbatim))
97 :options-alist '((:md-headline-style nil nil org-md-headline-style)))
100 ;;; Filters
102 (defun org-md-separate-elements (tree backend info)
103 "Fix blank lines between elements.
105 TREE is the parse tree being exported. BACKEND is the export
106 back-end used. INFO is a plist used as a communication channel.
108 Enforce a blank line between elements. There are two exceptions
109 to this rule:
111 1. Preserve blank lines between sibling items in a plain list,
113 2. In an item, remove any blank line before the very first
114 paragraph and the next sub-list.
116 Assume BACKEND is `md'."
117 (org-element-map tree (remq 'item org-element-all-elements)
118 (lambda (e)
119 (org-element-put-property
120 e :post-blank
121 (if (and (eq (org-element-type e) 'paragraph)
122 (eq (org-element-type (org-element-property :parent e)) 'item)
123 (eq (org-element-type (org-export-get-next-element e info))
124 'plain-list)
125 (not (org-export-get-previous-element e info)))
127 1))))
128 ;; Return updated tree.
129 tree)
133 ;;; Transcode Functions
135 ;;;; Bold
137 (defun org-md-bold (bold contents info)
138 "Transcode BOLD object into Markdown format.
139 CONTENTS is the text within bold markup. INFO is a plist used as
140 a communication channel."
141 (format "**%s**" contents))
144 ;;;; Code and Verbatim
146 (defun org-md-verbatim (verbatim contents info)
147 "Transcode VERBATIM object into Markdown format.
148 CONTENTS is nil. INFO is a plist used as a communication
149 channel."
150 (let ((value (org-element-property :value verbatim)))
151 (format (cond ((not (string-match "`" value)) "`%s`")
152 ((or (string-match "\\``" value)
153 (string-match "`\\'" value))
154 "`` %s ``")
155 (t "``%s``"))
156 value)))
159 ;;;; Example Block, Src Block and export Block
161 (defun org-md-example-block (example-block contents info)
162 "Transcode EXAMPLE-BLOCK element into Markdown format.
163 CONTENTS is nil. INFO is a plist used as a communication
164 channel."
165 (replace-regexp-in-string
166 "^" " "
167 (org-remove-indentation
168 (org-export-format-code-default example-block info))))
170 (defun org-md-export-block (export-block contents info)
171 "Transcode a EXPORT-BLOCK element from Org to Markdown.
172 CONTENTS is nil. INFO is a plist holding contextual information."
173 (if (member (org-element-property :type export-block) '("MARKDOWN" "MD"))
174 (org-remove-indentation (org-element-property :value export-block))
175 ;; Also include HTML export blocks.
176 (org-export-with-backend 'html export-block contents info)))
179 ;;;; Headline
181 (defun org-md-headline (headline contents info)
182 "Transcode HEADLINE element into Markdown format.
183 CONTENTS is the headline contents. INFO is a plist used as
184 a communication channel."
185 (unless (org-element-property :footnote-section-p headline)
186 (let* ((level (org-export-get-relative-level headline info))
187 (title (org-export-data (org-element-property :title headline) info))
188 (todo (and (plist-get info :with-todo-keywords)
189 (let ((todo (org-element-property :todo-keyword
190 headline)))
191 (and todo (concat (org-export-data todo info) " ")))))
192 (tags (and (plist-get info :with-tags)
193 (let ((tag-list (org-export-get-tags headline info)))
194 (and tag-list
195 (format " :%s:"
196 (mapconcat 'identity tag-list ":"))))))
197 (priority
198 (and (plist-get info :with-priority)
199 (let ((char (org-element-property :priority headline)))
200 (and char (format "[#%c] " char)))))
201 (anchor
202 (when (plist-get info :with-toc)
203 (org-html--anchor
204 (or (org-element-property :CUSTOM_ID headline)
205 (org-export-get-headline-id headline info))
206 nil nil info)))
207 ;; Headline text without tags.
208 (heading (concat todo priority title))
209 (style (plist-get info :md-headline-style)))
210 (cond
211 ;; Cannot create a headline. Fall-back to a list.
212 ((or (org-export-low-level-p headline info)
213 (not (memq style '(atx setext)))
214 (and (eq style 'atx) (> level 6))
215 (and (eq style 'setext) (> level 2)))
216 (let ((bullet
217 (if (not (org-export-numbered-headline-p headline info)) "-"
218 (concat (number-to-string
219 (car (last (org-export-get-headline-number
220 headline info))))
221 "."))))
222 (concat bullet (make-string (- 4 (length bullet)) ? ) heading tags
223 "\n\n"
224 (and contents
225 (replace-regexp-in-string "^" " " contents)))))
226 ;; Use "Setext" style.
227 ((eq style 'setext)
228 (concat heading tags anchor "\n"
229 (make-string (length heading) (if (= level 1) ?= ?-))
230 "\n\n"
231 contents))
232 ;; Use "atx" style.
233 (t (concat (make-string level ?#) " " heading tags anchor "\n\n" contents))))))
236 ;;;; Horizontal Rule
238 (defun org-md-horizontal-rule (horizontal-rule contents info)
239 "Transcode HORIZONTAL-RULE element into Markdown format.
240 CONTENTS is the horizontal rule contents. INFO is a plist used
241 as a communication channel."
242 "---")
245 ;;;; Italic
247 (defun org-md-italic (italic contents info)
248 "Transcode ITALIC object into Markdown format.
249 CONTENTS is the text within italic markup. INFO is a plist used
250 as a communication channel."
251 (format "*%s*" contents))
254 ;;;; Item
256 (defun org-md-item (item contents info)
257 "Transcode ITEM element into Markdown format.
258 CONTENTS is the item contents. INFO is a plist used as
259 a communication channel."
260 (let* ((type (org-element-property :type (org-export-get-parent item)))
261 (struct (org-element-property :structure item))
262 (bullet (if (not (eq type 'ordered)) "-"
263 (concat (number-to-string
264 (car (last (org-list-get-item-number
265 (org-element-property :begin item)
266 struct
267 (org-list-prevs-alist struct)
268 (org-list-parents-alist struct)))))
269 "."))))
270 (concat bullet
271 (make-string (- 4 (length bullet)) ? )
272 (case (org-element-property :checkbox item)
273 (on "[X] ")
274 (trans "[-] ")
275 (off "[ ] "))
276 (let ((tag (org-element-property :tag item)))
277 (and tag (format "**%s:** "(org-export-data tag info))))
278 (and contents
279 (org-trim (replace-regexp-in-string "^" " " contents))))))
283 ;;;; Keyword
285 (defun org-md-keyword (keyword contents info)
286 "Transcode a KEYWORD element into Markdown format.
287 CONTENTS is nil. INFO is a plist used as a communication
288 channel."
289 (if (member (org-element-property :key keyword) '("MARKDOWN" "MD"))
290 (org-element-property :value keyword)
291 (org-export-with-backend 'html keyword contents info)))
294 ;;;; Line Break
296 (defun org-md-line-break (line-break contents info)
297 "Transcode LINE-BREAK object into Markdown format.
298 CONTENTS is nil. INFO is a plist used as a communication
299 channel."
300 " \n")
303 ;;;; Link
305 (defun org-md-link (link contents info)
306 "Transcode LINE-BREAK object into Markdown format.
307 CONTENTS is the link's description. INFO is a plist used as
308 a communication channel."
309 (let ((link-org-files-as-md
310 (function
311 (lambda (raw-path)
312 ;; Treat links to `file.org' as links to `file.md'.
313 (if (string= ".org" (downcase (file-name-extension raw-path ".")))
314 (concat (file-name-sans-extension raw-path) ".md")
315 raw-path))))
316 (type (org-element-property :type link)))
317 (cond
318 ((member type '("custom-id" "id"))
319 (let ((destination (org-export-resolve-id-link link info)))
320 (if (stringp destination) ; External file.
321 (let ((path (funcall link-org-files-as-md destination)))
322 (if (not contents) (format "<%s>" path)
323 (format "[%s](%s)" contents path)))
324 (concat
325 (and contents (concat contents " "))
326 (format "(%s)"
327 (format (org-export-translate "See section %s" :html info)
328 (if (org-export-numbered-headline-p destination info)
329 (mapconcat #'number-to-string
330 (org-export-get-headline-number
331 destination info)
332 ".")
333 (org-export-data
334 (org-element-property :title destination) info))))))))
335 ((org-export-inline-image-p link org-html-inline-image-rules)
336 (let ((path (let ((raw-path (org-element-property :path link)))
337 (if (not (file-name-absolute-p raw-path)) raw-path
338 (expand-file-name raw-path))))
339 (caption (org-export-data
340 (org-export-get-caption
341 (org-export-get-parent-element link)) info)))
342 (format "![img](%s)"
343 (if (not (org-string-nw-p caption)) path
344 (format "%s \"%s\"" path caption)))))
345 ((string= type "coderef")
346 (let ((ref (org-element-property :path link)))
347 (format (org-export-get-coderef-format ref contents)
348 (org-export-resolve-coderef ref info))))
349 ((equal type "radio") contents)
350 ((equal type "fuzzy")
351 (let ((destination (org-export-resolve-fuzzy-link link info)))
352 (if (org-string-nw-p contents) contents
353 (when destination
354 (let ((number (org-export-get-ordinal destination info)))
355 (if number
356 (if (atom number) (number-to-string number)
357 (mapconcat #'number-to-string number "."))
358 ;; Unnumbered headline.
359 (and (eq 'headline (org-element-type destination))
360 ;; BUG: shouldn't headlines have a form like [ref](name) in md?
361 (org-export-data
362 (org-element-property :title destination) info))))))))
363 ;; Link type is handled by a special function.
364 ((let ((protocol (nth 2 (assoc type org-link-protocols))))
365 (and (functionp protocol)
366 (funcall protocol
367 (org-link-unescape (org-element-property :path link))
368 contents
369 'md))))
370 (t (let* ((raw-path (org-element-property :path link))
371 (path
372 (cond
373 ((member type '("http" "https" "ftp"))
374 (concat type ":" raw-path))
375 ((string= type "file")
376 (let ((path (funcall link-org-files-as-md raw-path)))
377 (if (not (file-name-absolute-p path)) path
378 ;; If file path is absolute, prepend it
379 ;; with "file:" component.
380 (concat "file:" path))))
381 (t raw-path))))
382 (if (not contents) (format "<%s>" path)
383 (format "[%s](%s)" contents path)))))))
386 ;;;; Node Property
388 (defun org-md-node-property (node-property contents info)
389 "Transcode a NODE-PROPERTY element into Markdown syntax.
390 CONTENTS is nil. INFO is a plist holding contextual
391 information."
392 (format "%s:%s"
393 (org-element-property :key node-property)
394 (let ((value (org-element-property :value node-property)))
395 (if value (concat " " value) ""))))
398 ;;;; Paragraph
400 (defun org-md-paragraph (paragraph contents info)
401 "Transcode PARAGRAPH element into Markdown format.
402 CONTENTS is the paragraph contents. INFO is a plist used as
403 a communication channel."
404 (let ((first-object (car (org-element-contents paragraph))))
405 ;; If paragraph starts with a #, protect it.
406 (if (and (stringp first-object) (string-match "\\`#" first-object))
407 (replace-regexp-in-string "\\`#" "\\#" contents nil t)
408 contents)))
411 ;;;; Plain List
413 (defun org-md-plain-list (plain-list contents info)
414 "Transcode PLAIN-LIST element into Markdown format.
415 CONTENTS is the plain-list contents. INFO is a plist used as
416 a communication channel."
417 contents)
420 ;;;; Plain Text
422 (defun org-md-plain-text (text info)
423 "Transcode a TEXT string into Markdown format.
424 TEXT is the string to transcode. INFO is a plist holding
425 contextual information."
426 (when (plist-get info :with-smart-quotes)
427 (setq text (org-export-activate-smart-quotes text :html info)))
428 ;; Protect ambiguous #. This will protect # at the beginning of
429 ;; a line, but not at the beginning of a paragraph. See
430 ;; `org-md-paragraph'.
431 (setq text (replace-regexp-in-string "\n#" "\n\\\\#" text))
432 ;; Protect ambiguous !
433 (setq text (replace-regexp-in-string "\\(!\\)\\[" "\\\\!" text nil nil 1))
434 ;; Protect `, *, _ and \
435 (setq text (replace-regexp-in-string "[`*_\\]" "\\\\\\&" text))
436 ;; Handle special strings, if required.
437 (when (plist-get info :with-special-strings)
438 (setq text (org-html-convert-special-strings text)))
439 ;; Handle break preservation, if required.
440 (when (plist-get info :preserve-breaks)
441 (setq text (replace-regexp-in-string "[ \t]*\n" " \n" text)))
442 ;; Return value.
443 text)
446 ;;;; Property Drawer
448 (defun org-md-property-drawer (property-drawer contents info)
449 "Transcode a PROPERTY-DRAWER element into Markdown format.
450 CONTENTS holds the contents of the drawer. INFO is a plist
451 holding contextual information."
452 (and (org-string-nw-p contents)
453 (replace-regexp-in-string "^" " " contents)))
456 ;;;; Quote Block
458 (defun org-md-quote-block (quote-block contents info)
459 "Transcode QUOTE-BLOCK element into Markdown format.
460 CONTENTS is the quote-block contents. INFO is a plist used as
461 a communication channel."
462 (replace-regexp-in-string
463 "^" "> "
464 (replace-regexp-in-string "\n\\'" "" contents)))
467 ;;;; Section
469 (defun org-md-section (section contents info)
470 "Transcode SECTION element into Markdown format.
471 CONTENTS is the section contents. INFO is a plist used as
472 a communication channel."
473 contents)
476 ;;;; Template
478 (defun org-md-inner-template (contents info)
479 "Return body of document after converting it to Markdown syntax.
480 CONTENTS is the transcoded contents string. INFO is a plist
481 holding export options."
482 ;; Make sure CONTENTS is separated from table of contents and
483 ;; footnotes with at least a blank line.
484 (org-trim (org-html-inner-template (concat "\n" contents "\n") info)))
486 (defun org-md-template (contents info)
487 "Return complete document string after Markdown conversion.
488 CONTENTS is the transcoded contents string. INFO is a plist used
489 as a communication channel."
490 contents)
494 ;;; Interactive function
496 ;;;###autoload
497 (defun org-md-export-as-markdown (&optional async subtreep visible-only)
498 "Export current buffer to a Markdown buffer.
500 If narrowing is active in the current buffer, only export its
501 narrowed part.
503 If a region is active, export that region.
505 A non-nil optional argument ASYNC means the process should happen
506 asynchronously. The resulting buffer should be accessible
507 through the `org-export-stack' interface.
509 When optional argument SUBTREEP is non-nil, export the sub-tree
510 at point, extracting information from the headline properties
511 first.
513 When optional argument VISIBLE-ONLY is non-nil, don't export
514 contents of hidden elements.
516 Export is done in a buffer named \"*Org MD Export*\", which will
517 be displayed when `org-export-show-temporary-export-buffer' is
518 non-nil."
519 (interactive)
520 (org-export-to-buffer 'md "*Org MD Export*"
521 async subtreep visible-only nil nil (lambda () (text-mode))))
523 ;;;###autoload
524 (defun org-md-convert-region-to-md ()
525 "Assume the current region has org-mode syntax, and convert it to Markdown.
526 This can be used in any buffer. For example, you can write an
527 itemized list in org-mode syntax in a Markdown buffer and use
528 this command to convert it."
529 (interactive)
530 (org-export-replace-region-by 'md))
533 ;;;###autoload
534 (defun org-md-export-to-markdown (&optional async subtreep visible-only)
535 "Export current buffer to a Markdown file.
537 If narrowing is active in the current buffer, only export its
538 narrowed part.
540 If a region is active, export that region.
542 A non-nil optional argument ASYNC means the process should happen
543 asynchronously. The resulting file should be accessible through
544 the `org-export-stack' interface.
546 When optional argument SUBTREEP is non-nil, export the sub-tree
547 at point, extracting information from the headline properties
548 first.
550 When optional argument VISIBLE-ONLY is non-nil, don't export
551 contents of hidden elements.
553 Return output file's name."
554 (interactive)
555 (let ((outfile (org-export-output-file-name ".md" subtreep)))
556 (org-export-to-file 'md outfile async subtreep visible-only)))
558 ;;;###autoload
559 (defun org-md-publish-to-md (plist filename pub-dir)
560 "Publish an org file to Markdown.
562 FILENAME is the filename of the Org file to be published. PLIST
563 is the property list for the given project. PUB-DIR is the
564 publishing directory.
566 Return output file name."
567 (org-publish-org-to 'md filename ".md" plist pub-dir))
569 (provide 'ox-md)
571 ;; Local variables:
572 ;; generated-autoload-file: "org-loaddefs.el"
573 ;; End:
575 ;;; ox-md.el ends here