1 ;;; markdown-mode.el --- Major mode to edit Markdown files in Emacs
3 ;; Copyright (C) 2007, 2008, 2009, 2010, 2011 Jason R. Blevins
4 ;; Copyright (C) 2007, 2009 Edward O'Connor <ted@oconnor.cx>
5 ;; Copyright (C) 2007 Conal Elliott <conal@conal.net>
6 ;; Copyright (C) 2008 Greg Bognar <greg_bognar@hms.harvard.edu>
7 ;; Copyright (C) 2008 Dmitry Dzhus <mail@sphinx.net.ru>
8 ;; Copyright (C) 2008 Bryan Kyle <bryan.kyle@gmail.com>
9 ;; Copyright (C) 2008 Ben Voui <intrigeri@boum.org>
10 ;; Copyright (C) 2009 Ankit Solanki <ankit.solanki@gmail.com>
11 ;; Copyright (C) 2009 Hilko Bengen <bengen@debian.org>
12 ;; Copyright (C) 2009 Peter Williams <pezra@barelyenough.org>
13 ;; Copyright (C) 2010 George Ogata <george.ogata@gmail.com>
14 ;; Copyright (C) 2011 Eric Merritt <ericbmerritt@gmail.com>
15 ;; Copyright (C) 2011 Philippe Ivaldi <pivaldi@sfr.fr>
18 ;; Keywords: Markdown major mode
19 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
20 ;; URL: http://jblevins.org/projects/markdown-mode/
22 ;; This file is not part of GNU Emacs.
24 ;; This program is free software; you can redistribute it and/or modify
25 ;; it under the terms of the GNU General Public License as published by
26 ;; the Free Software Foundation; either version 2, or (at your option)
29 ;; This program is distributed in the hope that it will be useful,
30 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
31 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 ;; GNU General Public License for more details.
34 ;; You should have received a copy of the GNU General Public License
35 ;; along with this program; if not, write to the Free Software
36 ;; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
40 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
41 ;; text files in GNU Emacs. markdown-mode is free software, licensed
44 ;; [Markdown]: http://daringfireball.net/projects/markdown/
46 ;; The latest stable version is markdown-mode 1.7, released on October 1, 2009:
48 ;; * [markdown-mode.el][]
50 ;; * [Release notes][]
52 ;; markdown-mode is also available in the Debian
53 ;; [emacs-goodies-el](http://packages.debian.org/emacs-goodies-el)
54 ;; package (beginning with revision 27.0-1) and the OpenBSD
55 ;; [textproc/markdown-mode](http://pkgsrc.se/textproc/markdown-mode) package.
57 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
58 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20080604-001.png
59 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-7
61 ;; The latest development version can be downloaded directly
62 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
63 ;; (browsable and clonable) Git repository at
64 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
65 ;; including the full project history, can be cloned via the Git protocol
68 ;; git clone git://jblevins.org/git/markdown-mode.git
70 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
74 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
75 ;; 19 and XEmacs 19, which provides a uniform interface for creating
76 ;; menus in GNU Emacs and XEmacs.
80 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
81 ;; the following lines to your `.emacs` file to associate markdown-mode
82 ;; with `.text` files:
84 ;; (autoload 'markdown-mode "markdown-mode.el"
85 ;; "Major mode for editing Markdown files" t)
86 ;; (setq auto-mode-alist
87 ;; (cons '("\\.text" . markdown-mode) auto-mode-alist))
89 ;; There is no consensus on an official file extension so change `.text` to
90 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
94 ;; Although no configuration is *necessary* there are a few things
95 ;; that can be customized. The `M-x customize-mode` command
96 ;; provides an interface to all of the possible customizations:
98 ;; * `markdown-command' - the command used to run Markdown (default:
99 ;; `markdown'). This variable may be customized to pass
100 ;; command-line options to your Markdown processor of choice, but
101 ;; this command must accept input from `stdin`. If it does not, a
102 ;; simple wrapper script can be used to write `stdin` to a file
103 ;; and then pass that file to your Markdown interpreter. Ideally,
104 ;; this command will produce an XHTML fragment around which
105 ;; markdown-mode will wrap a header and footer (which can be
106 ;; further customized). However, it attempts to detect whether
107 ;; the command produces standalone XHTML output (via
108 ;; `markdown-xhtml-standalone-regexp'), in which case no header
109 ;; and footer content will be added.
111 ;; * `markdown-hr-length' - the length of horizontal rules
114 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
115 ;; underscores for bold instead of two asterisks (default: `nil').
117 ;; * `markdown-italic-underscore' - set to a non-nil value to use
118 ;; underscores for italic instead of asterisks (default: `nil').
120 ;; * `markdown-indent-function' - the function to use for automatic
121 ;; indentation (default: `markdown-indent-line').
123 ;; * `markdown-indent-on-enter' - set to a non-nil value to
124 ;; automatically indent new lines when the enter key is pressed
127 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
128 ;; to automatically open a linked document in a new buffer if the
129 ;; cursor is an wiki link
132 ;; * `markdown-uri-types' - a list of protocols for URIs that
133 ;; `markdown-mode' should highlight.
135 ;; * `markdown-enable-math' - syntax highlighting for
136 ;; LaTeX fragments (default: `nil').
138 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
140 ;; * `markdown-xhtml-header-content' - additional content to include
141 ;; in the XHTML <head> block.
143 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
144 ;; indicates whether the output of `markdown-command' is standalone
145 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
146 ;; this is not matched, we assume this output is a fragment and add
147 ;; our own header and footer.
149 ;; Additionally, the faces used for syntax highlighting can be modified to
150 ;; your liking by issuing `M-x customize-group RET markdown-faces`
151 ;; or by using the "Markdown Faces" link at the bottom of the mode
152 ;; customization screen.
156 ;; Keybindings are grouped by prefixes based on their function. For
157 ;; example, commands dealing with headers begin with `C-c C-t`. The
158 ;; primary commands in each group will are described below. You can
159 ;; obtain a list of all keybindings by pressing `C-c C-h`.
161 ;; * Anchors: `C-c C-a`
163 ;; `C-c C-a l` inserts inline links of the form `[text](url)`. If
164 ;; there is an active region, text in the region is used for the
165 ;; link text. `C-c C-a w` acts similarly for wiki links of the
166 ;; form `[[WikiLink]]`.
168 ;; * Commands: `C-c C-c`
170 ;; `C-c C-c m` will run Markdown on the current buffer and preview
171 ;; the output in another buffer while `C-c C-c p` runs Markdown on
172 ;; the current buffer and previews the output in a browser.
173 ;; `C-c C-c e` will run Markdown on the current buffer and save
174 ;; the result in the file `basename.html`, where `basename` is the
175 ;; name of the Markdown file with the extension removed. **This
176 ;; file will be overwritten without notice.** Press `C-c C-c v`
177 ;; to view the exported file in a browser.
179 ;; `C-c C-c c` will check for undefined references. If there are
180 ;; any, a small buffer will open with a list of undefined
181 ;; references and the line numbers on which they appear. In Emacs
182 ;; 22 and greater, selecting a reference from this list and
183 ;; pressing `RET` will insert an empty reference definition at the
184 ;; end of the buffer. Similarly, selecting the line number will
185 ;; jump to the corresponding line.
187 ;; * Images: `C-c C-i`
189 ;; `C-c C-i i` inserts an image, using the active region (if any)
192 ;; * Physical styles: `C-c C-p`
194 ;; These commands all act on text in the active region, if any,
195 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
196 ;; the selected text bold, `C-c C-p f` formats the region as
197 ;; fixed-width text, and `C-c C-p i` is used for italic text.
199 ;; * Logical styles: `C-c C-s`
201 ;; These commands all act on text in the active region, if any,
202 ;; and insert empty markup fragments otherwise. Logical styles
203 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
204 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong (`C-c
207 ;; * Headers: `C-c C-t`
209 ;; All header commands use text in the active region, if any, as
210 ;; the header text. To insert an atx or hash style level-n
211 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
212 ;; top-level setext or underline style header press `C-c C-t t`
213 ;; (mnemonic: title) and for a second-level underline-style header
214 ;; press `C-c C-t s` (mnemonic: section).
218 ;; `C-c -` inserts a horizontal rule.
220 ;; Many of the commands described above behave differently depending on
221 ;; whether Transient Mark mode is enabled or not. When it makes sense,
222 ;; if Transient Mark mode is on and a region is active, the command
223 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
224 ;; bold). For users who prefer to work outside of Transient Mark mode,
225 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
227 ;; When applicable, commands that specifically act on the region even
228 ;; outside of Transient Mark mode have the same keybinding as the with
229 ;; the exception of an additional `C-` prefix. For example,
230 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
231 ;; the region in Transient Mark mode while `markdown-blockquote-region'
232 ;; is bound to `C-c C-s C-b` and always applies to the region (when
235 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
236 ;; visibility cycling for atx- or hash-style headers. There are two
237 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
238 ;; the table of contents view (headers only), outline view (top-level
239 ;; headers only), and the full document view. Pressing `TAB` while the
240 ;; point is at a header will cycle through levels of visibility for the
241 ;; subtree: completely folded, visible children, and fully visible.
242 ;; Note that mixing hash and underline style headers will give undesired
247 ;; Besides supporting the basic Markdown syntax, markdown-mode also
248 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
249 ;; links may be followed automatically by hitting the enter key when
250 ;; your curser is on a wiki link or by hitting `C-c C-f`. The
251 ;; autofollowing on enter key may be controlled with the
252 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
253 ;; `M-n` to quickly jump to the previous and next wiki links,
256 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
257 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
258 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
259 ;; You can do this either by using `M-x customize-group markdown`
260 ;; or by placing the following in your `.emacs` file:
262 ;; (defun markdown-custom ()
263 ;; "markdown-mode-hook"
264 ;; (setq markdown-command "markdown | smartypants"))
265 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
267 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
269 ;; Experimental syntax highlighting for mathematical expressions written
270 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
271 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
272 ;; either via customize or by placing `(setq markdown-enable-itex t)`
273 ;; in `.emacs`, and restarting Emacs.
275 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
276 ;; mode, `gfm-mode', is also available. The GitHub implementation of
277 ;; differs slightly from standard Markdown. Most importantly, newlines are
278 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
279 ;; `auto-fill-mode' and turns on `longlines-mode'.
283 ;; markdown-mode has benefited greatly from the efforts of the
286 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
287 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
288 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
289 ;; GitHub Flavored Markdown mode (`gfm-mode').
290 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
291 ;; `markdown' with an active region.
292 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
293 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
294 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
295 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
296 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
297 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
298 ;; compatibility and custom CSS.
299 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
300 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
301 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
302 ;; * Joost Kremers <j.kremers@em.uni-frankfurt.de> for bug reports
303 ;; regarding indentation.
304 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
306 ;; * George Ogata <george.ogata@gmail.com> for fixing several
307 ;; byte-compilation warnings.
308 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
309 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
310 ;; customizations and XHTML export.
314 ;; Although markdown-mode is developed and tested primarily using
315 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
318 ;; markdown-mode's syntax highlighting is accomplished using the
319 ;; search-based fontification features of Emacs through a series of
320 ;; regular expressions. Unfortunately, Emacs has trouble highlighting
321 ;; multi-line constructs using regular expressions and this creates
322 ;; several syntax-highlighting quirks such as mistaking indented
323 ;; lists for preformatted text, etc. Making markdown-mode's syntax
324 ;; highlighting more robust through the use of matching functions
325 ;; or syntactic font lock is a high-priority item for future work.
327 ;; If you find any bugs not mentioned here, please construct a test
328 ;; case and/or a patch and email me at <jrblevin@sdf.org>.
332 ;; markdown-mode was written and is maintained by Jason Blevins. The
333 ;; first version was released on May 24, 2007.
335 ;; * 2007-05-24: Version 1.1
336 ;; * 2007-05-25: Version 1.2
337 ;; * 2007-06-05: [Version 1.3][]
338 ;; * 2007-06-29: Version 1.4
339 ;; * 2008-05-24: [Version 1.5][]
340 ;; * 2008-06-04: [Version 1.6][]
341 ;; * 2009-10-01: [Version 1.7][]
343 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
344 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
345 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
346 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
354 ;;; Constants =================================================================
356 (defconst markdown-mode-version
"1.7-dev"
357 "Markdown mode version number.")
359 (defconst markdown-output-buffer-name
"*markdown-output*"
360 "Name of temporary buffer for markdown command output.")
362 ;;; Customizable variables ====================================================
364 (defvar markdown-mode-hook nil
365 "Hook runs when Markdown mode is loaded.")
367 (defgroup markdown nil
368 "Major mode for editing text files in Markdown format."
371 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
373 (defcustom markdown-command
"markdown"
374 "Command to run markdown."
378 (defcustom markdown-hr-length
5
379 "Length of horizonal rules."
383 (defcustom markdown-bold-underscore nil
384 "Use two underscores for bold instead of two asterisks."
388 (defcustom markdown-italic-underscore nil
389 "Use underscores for italic instead of asterisks."
393 (defcustom markdown-indent-function
'markdown-indent-line
394 "Function to use to indent."
398 (defcustom markdown-indent-on-enter t
399 "Automatically indent new lines when enter key is pressed."
403 (defcustom markdown-follow-wiki-link-on-enter t
404 "Follow wiki link at point (if any) when the enter key is pressed."
408 (defcustom markdown-uri-types
409 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
410 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
411 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
412 "Link types for syntax highlighting of URIs."
416 (defcustom markdown-enable-math nil
417 "Syntax highlighting for inline LaTeX expressions.
418 This will not take effect until Emacs is restarted."
422 (defcustom markdown-css-path
""
423 "URL of CSS file to link to in the output XHTML."
427 (defcustom markdown-xhtml-header-content
""
428 "Additional content to include in the XHTML <head> block."
432 (defcustom markdown-xhtml-standalone-regexp
433 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
434 "Regexp indicating whether `markdown-command' output is standalone XHTML."
438 ;;; Font lock =================================================================
442 (defvar markdown-italic-face
'markdown-italic-face
443 "Face name to use for italic text.")
445 (defvar markdown-bold-face
'markdown-bold-face
446 "Face name to use for bold text.")
448 (defvar markdown-header-face
'markdown-header-face
449 "Face name to use as a base for headers.")
451 (defvar markdown-header-face-1
'markdown-header-face-1
452 "Face name to use for level-1 headers.")
454 (defvar markdown-header-face-2
'markdown-header-face-2
455 "Face name to use for level-2 headers.")
457 (defvar markdown-header-face-3
'markdown-header-face-3
458 "Face name to use for level-3 headers.")
460 (defvar markdown-header-face-4
'markdown-header-face-4
461 "Face name to use for level-4 headers.")
463 (defvar markdown-header-face-5
'markdown-header-face-5
464 "Face name to use for level-5 headers.")
466 (defvar markdown-header-face-6
'markdown-header-face-6
467 "Face name to use for level-6 headers.")
469 (defvar markdown-inline-code-face
'markdown-inline-code-face
470 "Face name to use for inline code.")
472 (defvar markdown-list-face
'markdown-list-face
473 "Face name to use for list markers.")
475 (defvar markdown-blockquote-face
'markdown-blockquote-face
476 "Face name to use for blockquote.")
478 (defvar markdown-pre-face
'markdown-pre-face
479 "Face name to use for preformatted text.")
481 (defvar markdown-link-face
'markdown-link-face
482 "Face name to use for links.")
484 (defvar markdown-missing-link-face
'markdown-missing-link-face
485 "Face name to use for links where the linked file does not exist.")
487 (defvar markdown-reference-face
'markdown-reference-face
488 "Face name to use for reference.")
490 (defvar markdown-url-face
'markdown-url-face
491 "Face name to use for URLs.")
493 (defvar markdown-link-title-face
'markdown-link-title-face
494 "Face name to use for reference link titles.")
496 (defvar markdown-comment-face
'markdown-comment-face
497 "Face name to use for HTML comments.")
499 (defvar markdown-math-face
'markdown-math-face
500 "Face name to use for LaTeX expressions.")
502 (defgroup markdown-faces nil
503 "Faces used in Markdown Mode"
507 (defface markdown-italic-face
508 '((t :inherit font-lock-variable-name-face
:italic t
))
509 "Face for italic text."
510 :group
'markdown-faces
)
512 (defface markdown-bold-face
513 '((t :inherit font-lock-variable-name-face
:bold t
))
514 "Face for bold text."
515 :group
'markdown-faces
)
517 (defface markdown-header-face
518 '((t :inherit font-lock-function-name-face
:weight bold
))
519 "Base face for headers."
520 :group
'markdown-faces
)
522 (defface markdown-header-face-1
523 '((t :inherit markdown-header-face
))
524 "Face for level-1 headers."
525 :group
'markdown-faces
)
527 (defface markdown-header-face-2
528 '((t :inherit markdown-header-face
))
529 "Face for level-2 headers."
530 :group
'markdown-faces
)
532 (defface markdown-header-face-3
533 '((t :inherit markdown-header-face
))
534 "Face for level-3 headers."
535 :group
'markdown-faces
)
537 (defface markdown-header-face-4
538 '((t :inherit markdown-header-face
))
539 "Face for level-4 headers."
540 :group
'markdown-faces
)
542 (defface markdown-header-face-5
543 '((t :inherit markdown-header-face
))
544 "Face for level-5 headers."
545 :group
'markdown-faces
)
547 (defface markdown-header-face-6
548 '((t :inherit markdown-header-face
))
549 "Face for level-6 headers."
550 :group
'markdown-faces
)
552 (defface markdown-inline-code-face
553 '((t :inherit font-lock-constant-face
))
554 "Face for inline code."
555 :group
'markdown-faces
)
557 (defface markdown-list-face
558 '((t :inherit font-lock-builtin-face
))
559 "Face for list item markers."
560 :group
'markdown-faces
)
562 (defface markdown-blockquote-face
563 '((t :inherit font-lock-doc-face
))
564 "Face for blockquote sections."
565 :group
'markdown-faces
)
567 (defface markdown-pre-face
568 '((t :inherit font-lock-constant-face
))
569 "Face for preformatted text."
570 :group
'markdown-faces
)
572 (defface markdown-link-face
573 '((t :inherit font-lock-keyword-face
))
575 :group
'markdown-faces
)
577 (defface markdown-missing-link-face
578 '((t :inherit font-lock-warning-face
))
579 "Face for missing links."
580 :group
'markdown-faces
)
582 (defface markdown-reference-face
583 '((t :inherit font-lock-type-face
))
584 "Face for link references."
585 :group
'markdown-faces
)
587 (defface markdown-url-face
588 '((t :inherit font-lock-string-face
))
590 :group
'markdown-faces
)
592 (defface markdown-link-title-face
593 '((t :inherit font-lock-comment-face
))
594 "Face for reference link titles."
595 :group
'markdown-faces
)
597 (defface markdown-comment-face
598 '((t :inherit font-lock-comment-face
))
599 "Face for HTML comments."
600 :group
'markdown-faces
)
602 (defface markdown-math-face
603 '((t :inherit font-lock-string-face
))
604 "Face for LaTeX expressions."
605 :group
'markdown-faces
)
607 (defconst markdown-regex-link-inline
608 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
609 "Regular expression for a [text](file) or an image link ![text](file).")
611 (defconst markdown-regex-link-reference
612 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
613 "Regular expression for a reference link [text][id].")
615 (defconst markdown-regex-reference-definition
616 "^ \\{0,3\\}\\(\\[.+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
617 "Regular expression for a link definition [id]: ...")
619 (defconst markdown-regex-header-1-atx
620 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
621 "Regular expression for level 1 atx-style (hash mark) headers.")
623 (defconst markdown-regex-header-2-atx
624 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
625 "Regular expression for level 2 atx-style (hash mark) headers.")
627 (defconst markdown-regex-header-3-atx
628 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
629 "Regular expression for level 3 atx-style (hash mark) headers.")
631 (defconst markdown-regex-header-4-atx
632 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
633 "Regular expression for level 4 atx-style (hash mark) headers.")
635 (defconst markdown-regex-header-5-atx
636 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
637 "Regular expression for level 5 atx-style (hash mark) headers.")
639 (defconst markdown-regex-header-6-atx
640 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
641 "Regular expression for level 6 atx-style (hash mark) headers.")
643 (defconst markdown-regex-header-1-setext
644 "^\\(.*\\)\n\\(===+\\)$"
645 "Regular expression for level 1 setext-style (underline) headers.")
647 (defconst markdown-regex-header-2-setext
648 "^\\(.*\\)\n\\(---+\\)$"
649 "Regular expression for level 2 setext-style (underline) headers.")
651 (defconst markdown-regex-hr
652 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
653 "Regular expression for matching Markdown horizontal rules.")
655 (defconst markdown-regex-code
656 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ].*?[^ \\]\\)\\3\\)"
657 "Regular expression for matching inline code fragments.")
659 (defconst markdown-regex-pre
661 "Regular expression for matching preformatted text sections.")
663 (defconst markdown-regex-list
664 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
665 "Regular expression for matching list markers.")
667 (defconst markdown-regex-bold
668 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n\\)*?[^\\ ]\\3\\)"
669 "Regular expression for matching bold text.")
671 (defconst markdown-regex-italic
672 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n\\)*?[^\\ ]\\3\\)\\)"
673 "Regular expression for matching italic text.")
675 (defconst markdown-regex-blockquote
677 "Regular expression for matching blockquote lines.")
679 (defconst markdown-regex-line-break
681 "Regular expression for matching line breaks.")
683 (defconst markdown-regex-wiki-link
684 "\\[\\[\\([^]]+\\)\\]\\]"
685 "Regular expression for matching wiki links.")
687 (defconst markdown-regex-uri
689 "\\(" (mapconcat 'identity markdown-uri-types
"\\|")
690 "\\):[^]\t\n\r<>,;() ]+")
691 "Regular expression for matching inline URIs.")
693 (defconst markdown-regex-angle-uri
696 (mapconcat 'identity markdown-uri-types
"\\|")
697 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
698 "Regular expression for matching inline URIs in angle brackets.")
700 (defconst markdown-regex-email
701 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
702 "Regular expression for matching inline email addresses.")
704 (defconst markdown-regex-latex-expression
705 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
706 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
708 (defconst markdown-regex-latex-display
709 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
710 "Regular expression for itex \[..\] display mode expressions.")
712 (defconst markdown-regex-list-indent
713 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
714 "Regular expression for matching indentation of list items.")
716 (defvar markdown-mode-font-lock-keywords-basic
718 '(markdown-match-comments 0 markdown-comment-face t t
)
719 '(markdown-match-pre-blocks 0 markdown-pre-face t t
)
720 (cons markdown-regex-code
'(2 markdown-inline-code-face
))
721 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
722 (cons markdown-regex-header-1-setext
'markdown-header-face-1
)
723 (cons markdown-regex-header-2-setext
'markdown-header-face-2
)
724 (cons markdown-regex-header-1-atx
'markdown-header-face-1
)
725 (cons markdown-regex-header-2-atx
'markdown-header-face-2
)
726 (cons markdown-regex-header-3-atx
'markdown-header-face-3
)
727 (cons markdown-regex-header-4-atx
'markdown-header-face-4
)
728 (cons markdown-regex-header-5-atx
'markdown-header-face-5
)
729 (cons markdown-regex-header-6-atx
'markdown-header-face-6
)
730 (cons markdown-regex-hr
'markdown-header-face
)
731 (cons markdown-regex-list
'markdown-list-face
)
732 (cons markdown-regex-link-inline
733 '((1 markdown-link-face t
)
734 (2 markdown-url-face t
)))
735 (cons markdown-regex-link-reference
736 '((1 markdown-link-face t
)
737 (2 markdown-reference-face t
)))
738 (cons markdown-regex-reference-definition
739 '((1 markdown-reference-face t
)
740 (2 markdown-url-face t
)
741 (3 markdown-link-title-face t
)))
742 (cons markdown-regex-bold
'(2 markdown-bold-face
))
743 (cons markdown-regex-italic
'(2 markdown-italic-face
))
744 (cons markdown-regex-angle-uri
'markdown-link-face
)
745 (cons markdown-regex-uri
'markdown-link-face
)
746 (cons markdown-regex-email
'markdown-link-face
)
748 "Syntax highlighting for Markdown files.")
750 (defconst markdown-mode-font-lock-keywords-latex
752 ;; Math mode $..$ or $$..$$
753 (cons markdown-regex-latex-expression
'(2 markdown-math-face
))
754 ;; Display mode equations with brackets: \[ \]
755 (cons markdown-regex-latex-display
'markdown-math-face
)
756 ;; Equation reference (eq:foo)
757 (cons "(eq:\\w+)" 'markdown-reference-face
)
758 ;; Equation reference \eqref{foo}
759 (cons "\\\\eqref{\\w+}" 'markdown-reference-face
))
760 "Syntax highlighting for LaTeX fragments.")
762 (defvar markdown-mode-font-lock-keywords
764 (if markdown-enable-math
765 markdown-mode-font-lock-keywords-latex
)
766 markdown-mode-font-lock-keywords-basic
)
767 "Default highlighting expressions for Markdown mode.")
771 ;;; Markdown parsing functions ================================================
773 (defun markdown-cur-line-blank-p ()
774 "Return t if the current line is blank and nil otherwise."
777 (re-search-forward "^\\s *$" (point-at-eol) t
)))
779 (defun markdown-prev-line-blank-p ()
780 "Return t if the previous line is blank and nil otherwise.
781 If we are at the first line, then consider the previous line to be blank."
783 (if (= (point-at-bol) (point-min))
786 (markdown-cur-line-blank-p))))
788 (defun markdown-prev-line-indent-p ()
789 "Return t if the previous line is indented and nil otherwise."
792 (goto-char (point-at-bol))
793 (if (re-search-forward "^\\s " (point-at-eol) t
) t
)))
795 (defun markdown-cur-line-indent ()
796 "Return the number of leading whitespace characters in the current line."
798 (goto-char (point-at-bol))
799 (re-search-forward "^\\s +" (point-at-eol) t
)
802 (defun markdown-prev-line-indent ()
803 "Return the number of leading whitespace characters in the previous line."
806 (markdown-cur-line-indent)))
808 (defun markdown-cur-non-list-indent ()
809 "Return the number of leading whitespace characters in the current line."
812 (when (re-search-forward markdown-regex-list-indent
(point-at-eol) t
)
815 (defun markdown-prev-non-list-indent ()
816 "Return position of the first non-list-marker on the previous line."
819 (markdown-cur-non-list-indent)))
821 (defun markdown-beginning-of-block-p ()
822 "Return non-nil if the point is at the beginning of a block."
823 (and (eq (point) (point-at-bol))
824 (markdown-prev-line-blank-p)
825 (not (markdown-cur-line-blank-p))))
827 (defun markdown-next-block ()
828 "Move the point to the start of the next block."
831 (while (and (not (markdown-prev-line-blank-p))
832 (not (eq (point) (point-max))))
835 (defun markdown-previous-block ()
836 "Move the point to the start of the previous block."
839 (while (and (not (markdown-prev-line-blank-p))
840 (not (eq (point) (point-min))))
843 (defun markdown-end-of-block ()
844 "Move the point to the end of the current block."
846 (if (markdown-cur-line-blank-p)
848 (when (and (not (equal (point) (point-max))))
849 (markdown-next-block)
850 (while (and (markdown-prev-line-blank-p)
851 (not (equal (point) (point-min)))
852 (not (equal (point) (point-max))))
854 (if (not (equal (point-at-eol) (point-max)))
858 ; From html-helper-mode
859 (defun markdown-match-comments (last)
860 "Match HTML comments from the point to LAST."
861 (cond ((search-forward "<!--" last t
)
864 (cond ((search-forward-regexp "--[ \t]*>" last t
)
865 (set-match-data (list beg
(point)))
870 (defun markdown-match-pre-blocks (last)
871 "Match Markdown pre blocks from point to LAST.
872 A region matches as if it is indented at least four spaces
873 relative to the nearest previous block of lesser non-list-marker
876 (let (cur-begin cur-end cur-indent prev-indent prev-begin prev-end
877 prev-list stop match
)
879 ;; Move to the first full block in the region
880 (unless (markdown-beginning-of-block-p)
881 (markdown-next-block))
882 (setq cur-begin
(point))
883 (setq cur-indent
(markdown-cur-line-indent))
884 (markdown-end-of-block)
885 (setq cur-end
(point))
888 (while (and (<= cur-end last
) (not stop
) (not match
))
889 ;; Move to the nearest preceding block of lesser (non-marker) indentation
890 (setq prev-indent
(+ cur-indent
1))
891 (setq prev-begin nil
)
892 (goto-char cur-begin
)
893 (while (and (>= prev-indent cur-indent
)
895 (eq prev-indent cur-indent
)))
896 (not (equal (point) (point-min))))
897 (markdown-previous-block)
898 (setq prev-begin
(point))
899 (setq prev-list
(markdown-cur-non-list-indent))
901 (setq prev-indent prev-list
)
902 (setq prev-indent
(markdown-cur-line-indent)))
903 (markdown-end-of-block)
904 (setq prev-end
(point))
905 (goto-char prev-begin
))
907 ;; If the loop didn't execute
909 (setq prev-indent
0))
911 ;; Compare with prev-indent minus its remainder mod 4
912 (setq prev-indent
(- prev-indent
(mod prev-indent
4)))
914 ;; Set match data and return t if we have a match
915 (if (>= cur-indent
(+ prev-indent
4))
919 (set-match-data (list cur-begin cur-end
))
920 ;; Leave point at end of block
924 ;; Move to the next block
926 (markdown-next-block)
927 (setq cur-begin
(point))
928 (setq cur-indent
(markdown-cur-line-indent))
929 (markdown-end-of-block)
931 (if (equal (point) cur-end
)
933 (setq cur-end
(point))))
936 (defun markdown-font-lock-extend-region ()
938 (goto-char font-lock-beg
)
939 (let ((found (re-search-backward "\n" nil t
)))
941 (goto-char font-lock-end
)
942 (when (re-search-forward "\n" nil t
)
944 (setq font-lock-end
(point)))
945 (setq font-lock-beg found
)))))
949 ;;; Syntax Table ==============================================================
951 (defvar markdown-mode-syntax-table
952 (let ((markdown-mode-syntax-table (make-syntax-table)))
953 (modify-syntax-entry ?
\" "w" markdown-mode-syntax-table
)
954 markdown-mode-syntax-table
)
955 "Syntax table for `markdown-mode'.")
959 ;;; Element Insertion =========================================================
961 (defun markdown-wrap-or-insert (s1 s2
)
962 "Insert the strings S1 and S2.
963 If Transient Mark mode is on and a region is active, wrap the strings S1
964 and S2 around the region."
965 (if (and transient-mark-mode mark-active
)
966 (let ((a (region-beginning)) (b (region-end)))
969 (goto-char (+ b
(length s1
)))
973 (defun markdown-insert-hr ()
974 "Insert a horizonal rule."
977 (dotimes (count (- markdown-hr-length
1) hr
) ; Count to n - 1
978 (setq hr
(concat "* " hr
))) ; Build HR string
979 (setq hr
(concat hr
"*\n")) ; Add the n-th *
982 (defun markdown-insert-bold ()
983 "Insert markup for a bold word or phrase.
984 If Transient Mark mode is on and a region is active, it is made bold."
986 (if markdown-bold-underscore
987 (markdown-wrap-or-insert "__" "__")
988 (markdown-wrap-or-insert "**" "**"))
991 (defun markdown-insert-italic ()
992 "Insert markup for an italic word or phrase.
993 If Transient Mark mode is on and a region is active, it is made italic."
995 (if markdown-italic-underscore
996 (markdown-wrap-or-insert "_" "_")
997 (markdown-wrap-or-insert "*" "*"))
1000 (defun markdown-insert-code ()
1001 "Insert markup for an inline code fragment.
1002 If Transient Mark mode is on and a region is active, it is marked
1005 (markdown-wrap-or-insert "`" "`")
1008 (defun markdown-insert-link ()
1009 "Insert an inline link of the form []().
1010 If Transient Mark mode is on and a region is active, it is used
1013 (markdown-wrap-or-insert "[" "]")
1017 (defun markdown-insert-wiki-link ()
1018 "Insert a wiki link of the form [[WikiLink]].
1019 If Transient Mark mode is on and a region is active, it is used
1022 (markdown-wrap-or-insert "[[" "]]")
1025 (defun markdown-insert-image ()
1026 "Insert an inline image tag of the form ![]().
1027 If Transient Mark mode is on and a region is active, it is used
1028 as the alt text of the image."
1030 (markdown-wrap-or-insert "![" "]")
1034 (defun markdown-insert-header-1 ()
1035 "Insert a first level atx-style (hash mark) header.
1036 If Transient Mark mode is on and a region is active, it is used
1037 as the header text."
1039 (markdown-insert-header 1))
1041 (defun markdown-insert-header-2 ()
1042 "Insert a second level atx-style (hash mark) header.
1043 If Transient Mark mode is on and a region is active, it is used
1044 as the header text."
1046 (markdown-insert-header 2))
1048 (defun markdown-insert-header-3 ()
1049 "Insert a third level atx-style (hash mark) header.
1050 If Transient Mark mode is on and a region is active, it is used
1051 as the header text."
1053 (markdown-insert-header 3))
1055 (defun markdown-insert-header-4 ()
1056 "Insert a fourth level atx-style (hash mark) header.
1057 If Transient Mark mode is on and a region is active, it is used
1058 as the header text."
1060 (markdown-insert-header 4))
1062 (defun markdown-insert-header-5 ()
1063 "Insert a fifth level atx-style (hash mark) header.
1064 If Transient Mark mode is on and a region is active, it is used
1065 as the header text."
1067 (markdown-insert-header 5))
1069 (defun markdown-insert-header-6 ()
1070 "Insert a sixth level atx-style (hash mark) header.
1071 If Transient Mark mode is on and a region is active, it is used
1072 as the header text."
1074 (markdown-insert-header 6))
1076 (defun markdown-insert-header (n)
1077 "Insert an atx-style (hash mark) header.
1078 With no prefix argument, insert a level-1 header. With prefix N,
1079 insert a level-N header. If Transient Mark mode is on and the
1080 region is active, it is used as the header text."
1082 (unless n
; Test to see if n is defined
1083 (setq n
1)) ; Default to level 1 header
1084 (let (hdr hdrl hdrr
)
1085 (dotimes (count n hdr
)
1086 (setq hdr
(concat "#" hdr
))) ; Build a hash mark header string
1087 (setq hdrl
(concat hdr
" "))
1088 (setq hdrr
(concat " " hdr
))
1089 (markdown-wrap-or-insert hdrl hdrr
))
1090 (backward-char (+ 1 n
)))
1092 (defun markdown-insert-title ()
1093 "Insert a setext-style (underline) first level header.
1094 If Transient Mark mode is on and a region is active, it is used
1095 as the header text."
1097 (if (and transient-mark-mode mark-active
)
1098 (let ((a (region-beginning))
1103 (dotimes (count len hdr
)
1104 (setq hdr
(concat "=" hdr
))) ; Build a === title underline
1106 (insert "\n" hdr
"\n"))
1107 (insert "\n==========\n")
1108 (backward-char 12)))
1110 (defun markdown-insert-section ()
1111 "Insert a setext-style (underline) second level header.
1112 If Transient Mark mode is on and a region is active, it is used
1113 as the header text."
1115 (if (and transient-mark-mode mark-active
)
1116 (let ((a (region-beginning))
1121 (dotimes (count len hdr
)
1122 (setq hdr
(concat "-" hdr
))) ; Build a --- section underline
1124 (insert "\n" hdr
"\n"))
1125 (insert "\n----------\n")
1126 (backward-char 12)))
1128 (defun markdown-insert-blockquote ()
1129 "Start a blockquote section (or blockquote the region).
1130 If Transient Mark mode is on and a region is active, it is used as
1131 the blockquote text."
1133 (if (and (boundp 'transient-mark-mode
) transient-mark-mode mark-active
)
1134 (markdown-blockquote-region (region-beginning) (region-end))
1137 (defun markdown-block-region (beg end prefix
)
1138 "Format the region using a block prefix.
1139 Arguments BEG and END specify the beginning and end of the
1140 region.The characters PREFIX will appear at the beginning
1145 ; Ensure that there is a leading blank line
1147 (while (not (looking-back "\n\n" 2))
1149 (setq endpos
(+ 1 endpos
)))
1150 ; Insert blockquote characters
1151 (move-to-left-margin)
1152 (while (< (point-at-bol) endpos
)
1154 (setq endpos
(+ (length prefix
) endpos
))
1156 ; Move back before any blank lines at the end
1158 (while (looking-back "\n" 1)
1160 ; Ensure one blank line at the end
1161 (while (not (looking-at "\n\n"))
1163 (backward-char))))))
1165 (defun markdown-blockquote-region (beg end
)
1166 "Blockquote the region.
1167 Arguments BEG and END specify the beginning and end of the region."
1169 (markdown-block-region beg end
"> "))
1171 (defun markdown-insert-pre ()
1172 "Start a preformatted section (or apply to the region).
1173 If Transient Mark mode is on and a region is active, it is marked
1174 as preformatted text."
1176 (if (and (boundp 'transient-mark-mode
) transient-mark-mode mark-active
)
1177 (markdown-pre-region (region-beginning) (region-end))
1180 (defun markdown-pre-region (beg end
)
1181 "Format the region as preformatted text.
1182 Arguments BEG and END specify the beginning and end of the region."
1184 (markdown-block-region beg end
" "))
1186 ;;; Indentation ====================================================================
1188 (defun markdown-indent-find-next-position (cur-pos positions
)
1189 "Return the position after the index of CUR-POS in POSITIONS."
1190 (while (and positions
1191 (not (equal cur-pos
(car positions
))))
1192 (setq positions
(cdr positions
)))
1193 (or (cadr positions
) 0))
1195 (defun markdown-indent-line ()
1196 "Indent the current line using some heuristics."
1198 (if (markdown-prev-line-indent-p)
1199 ;; If the current column is any of the positions, remove all
1200 ;; of the positions up-to and including the current column
1202 (markdown-indent-find-next-position
1203 (current-column) (markdown-calc-indents)))))
1205 (defun markdown-calc-indents ()
1206 "Return a list of indentation columns to cycle through."
1212 ;; Previous line indent
1213 (setq prev-line-pos
(markdown-prev-line-indent))
1214 (setq positions
(cons prev-line-pos positions
))
1216 ;; Previous non-list-marker indent
1217 (setq pos
(markdown-prev-non-list-indent))
1219 (setq positions
(cons pos positions
)))
1221 ;; Indentation of the previous line + tab-width
1224 (setq positions
(cons (+ prev-line-pos tab-width
) positions
)))
1226 (setq positions
(cons tab-width positions
))))
1228 ;; Indentation of the previous line - tab-width
1229 (if (and prev-line-pos
1230 (> prev-line-pos tab-width
))
1231 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
1233 ;; Indentation of preceeding list item
1238 (while (not (equal (point) (point-min)))
1240 (goto-char (point-at-bol))
1241 (when (re-search-forward markdown-regex-list-indent
(point-at-eol) t
)
1242 (throw 'break
(length (match-string 1)))))
1244 (if (and pos
(not (eq pos prev-line-pos
)))
1245 (setq positions
(cons pos positions
)))
1248 (setq positions
(cons 0 (reverse positions
)))
1252 (defun markdown-do-normal-return ()
1253 "Insert a newline and optionally indent the next line."
1255 (if markdown-indent-on-enter
1256 (funcall indent-line-function
)))
1258 (defun markdown-enter-key ()
1259 "Handle RET according to context.
1260 If there is a wiki link at the point, follow it unless
1261 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1262 it in the usual way."
1264 (if (and markdown-follow-wiki-link-on-enter
(markdown-wiki-link-p))
1265 (markdown-follow-wiki-link-at-point)
1266 (markdown-do-normal-return)))
1270 ;;; Keymap ====================================================================
1272 (defvar markdown-mode-map
1273 (let ((map (make-keymap)))
1274 ;; Element insertion
1275 (define-key map
"\C-c\C-al" 'markdown-insert-link
)
1276 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
1277 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
1278 (define-key map
"\C-c\C-t1" 'markdown-insert-header-1
)
1279 (define-key map
"\C-c\C-t2" 'markdown-insert-header-2
)
1280 (define-key map
"\C-c\C-t3" 'markdown-insert-header-3
)
1281 (define-key map
"\C-c\C-t4" 'markdown-insert-header-4
)
1282 (define-key map
"\C-c\C-t5" 'markdown-insert-header-5
)
1283 (define-key map
"\C-c\C-t6" 'markdown-insert-header-6
)
1284 (define-key map
"\C-c\C-pb" 'markdown-insert-bold
)
1285 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
1286 (define-key map
"\C-c\C-pi" 'markdown-insert-italic
)
1287 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
1288 (define-key map
"\C-c\C-pf" 'markdown-insert-code
)
1289 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
1290 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
1291 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
1292 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
1293 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
1294 (define-key map
"\C-c-" 'markdown-insert-hr
)
1295 (define-key map
"\C-c\C-tt" 'markdown-insert-title
)
1296 (define-key map
"\C-c\C-ts" 'markdown-insert-section
)
1297 ;; WikiLink Following
1298 (define-key map
"\C-c\C-f" 'markdown-follow-wiki-link-at-point
)
1299 (define-key map
"\M-n" 'markdown-next-wiki-link
)
1300 (define-key map
"\M-p" 'markdown-previous-wiki-link
)
1302 (define-key map
"\C-m" 'markdown-enter-key
)
1303 ;; Visibility cycling
1304 (define-key map
(kbd "<tab>") 'markdown-cycle
)
1305 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
1306 ;; Markdown functions
1307 (define-key map
"\C-c\C-cm" 'markdown
)
1308 (define-key map
"\C-c\C-cp" 'markdown-preview
)
1309 (define-key map
"\C-c\C-ce" 'markdown-export
)
1310 (define-key map
"\C-c\C-cv" 'markdown-export-and-view
)
1312 (define-key map
"\C-c\C-cc" 'markdown-check-refs
)
1314 "Keymap for Markdown major mode.")
1316 ;;; Menu ==================================================================
1318 (easy-menu-define markdown-mode-menu markdown-mode-map
1319 "Menu for Markdown mode"
1322 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
1323 ["Cycle global visibility" markdown-shifttab
])
1325 ["Compile" markdown
]
1326 ["Preview" markdown-preview
]
1327 ["Export" markdown-export
]
1328 ["Export & View" markdown-export-and-view
]
1331 ["Insert Title" markdown-insert-title
]
1332 ["Insert Section" markdown-insert-section
])
1334 ["First level" markdown-insert-header-1
]
1335 ["Second level" markdown-insert-header-2
]
1336 ["Third level" markdown-insert-header-3
]
1337 ["Fourth level" markdown-insert-header-4
]
1338 ["Fifth level" markdown-insert-header-5
]
1339 ["Sixth level" markdown-insert-header-6
])
1341 ["Bold" markdown-insert-bold
]
1342 ["Italic" markdown-insert-italic
]
1343 ["Blockquote" markdown-insert-blockquote
]
1344 ["Preformatted" markdown-insert-pre
]
1345 ["Code" markdown-insert-code
]
1347 ["Insert inline link" markdown-insert-link
]
1348 ["Insert image" markdown-insert-image
]
1349 ["Insert horizontal rule" markdown-insert-hr
]
1351 ["Check references" markdown-check-refs
]
1353 ["Version" markdown-show-version
]
1358 ;;; References ================================================================
1360 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
1362 (defconst markdown-refcheck-buffer
1363 "*Undefined references for %BUFFER%*"
1364 "Pattern for name of buffer for listing undefined references.
1365 The string %BUFFER% will be replaced by the corresponding
1366 `markdown-mode' buffer name.")
1368 (defun markdown-has-reference-definition (reference)
1369 "Find out whether Markdown REFERENCE is defined.
1371 REFERENCE should include the square brackets, like [this]."
1372 (let ((reference (downcase reference
)))
1374 (goto-char (point-min))
1376 (while (re-search-forward markdown-regex-reference-definition nil t
)
1377 (when (string= reference
(downcase (match-string-no-properties 1)))
1378 (throw 'found t
)))))))
1380 (defun markdown-get-undefined-refs ()
1381 "Return a list of undefined Markdown references.
1383 Result is an alist of pairs (reference . occurencies), where
1384 occurencies is itself another alist of pairs (label .
1387 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
1388 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
1389 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
1392 (goto-char (point-min))
1394 (re-search-forward markdown-regex-link-reference nil t
)
1395 (let* ((label (match-string-no-properties 1))
1396 (reference (match-string-no-properties 2))
1397 (target (downcase (if (string= reference
"[]") label reference
))))
1398 (unless (markdown-has-reference-definition target
)
1399 (let ((entry (assoc target missing
)))
1401 (add-to-list 'missing
(cons target
1402 (list (cons label
(markdown-line-number-at-pos)))) t
)
1404 (append (cdr entry
) (list (cons label
(markdown-line-number-at-pos))))))))))
1407 (defun markdown-add-missing-ref-definition (ref buffer
&optional recheck
)
1408 "Add blank REF definition to the end of BUFFER.
1410 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
1412 When RECHECK is non-nil, BUFFER gets rechecked for undefined
1413 references so that REF disappears from the list of those links."
1414 (with-current-buffer buffer
1415 (when (not (eq major-mode
'markdown-mode
))
1416 (error "Not available in current mode"))
1417 (goto-char (point-max))
1418 (indent-new-comment-line)
1419 (insert (concat ref
": ")))
1420 (switch-to-buffer-other-window buffer
)
1421 (goto-char (point-max))
1423 (markdown-check-refs t
)))
1425 ;; Button which adds an empty Markdown reference definition to the end
1426 ;; of buffer specified as its 'target-buffer property. Reference name
1427 ;; is button's label
1428 (when (>= emacs-major-version
22)
1429 (define-button-type 'markdown-ref-button
1430 'help-echo
"Push to create an empty reference definition"
1433 (markdown-add-missing-ref-definition
1434 (button-label b
) (button-get b
'target-buffer
) t
))))
1436 ;; Button jumping to line in buffer specified as its 'target-buffer
1437 ;; property. Line number is button's 'line property.
1438 (when (>= emacs-major-version
22)
1439 (define-button-type 'goto-line-button
1440 'help-echo
"Push to go to this line"
1443 (message (button-get b
'buffer
))
1444 (switch-to-buffer-other-window (button-get b
'target-buffer
))
1445 ;; use call-interactively to silence compiler
1446 (call-interactively 'goto-line
(button-get b
'target-line
)))))
1448 (defun markdown-check-refs (&optional silent
)
1449 "Show all undefined Markdown references in current `markdown-mode' buffer.
1451 If SILENT is non-nil, do not message anything when no undefined
1454 Links which have empty reference definitions are considered to be
1457 (when (not (eq major-mode
'markdown-mode
))
1458 (error "Not available in current mode"))
1459 (let ((oldbuf (current-buffer))
1460 (refs (markdown-get-undefined-refs))
1461 (refbuf (get-buffer-create (replace-regexp-in-string
1462 "%BUFFER%" (buffer-name)
1463 markdown-refcheck-buffer t
))))
1467 (message "No undefined references found"))
1468 (kill-buffer refbuf
))
1469 (with-current-buffer refbuf
1471 (View-exit-and-edit))
1473 (insert "Following references lack definitions:")
1476 (let ((button-label (format "%s" (car ref
))))
1477 (if (>= emacs-major-version
22)
1478 ;; Create a reference button in Emacs 22
1479 (insert-text-button button-label
1480 :type
'markdown-ref-button
1481 'target-buffer oldbuf
)
1482 ;; Insert reference as text in Emacs < 22
1483 (insert button-label
)))
1485 (dolist (occurency (cdr ref
))
1486 (let ((line (cdr occurency
)))
1487 (if (>= emacs-major-version
22)
1488 ;; Create a line number button in Emacs 22
1489 (insert-button (number-to-string line
)
1490 :type
'goto-line-button
1491 'target-buffer oldbuf
1493 ;; Insert line number as text in Emacs < 22
1494 (insert (number-to-string line
)))
1495 (insert " "))) (delete-char -
1)
1498 (view-buffer-other-window refbuf
)
1499 (goto-char (point-min))
1500 (forward-line 2)))))
1502 ;;; Outline ===================================================================
1504 ;; The following visibility cycling code was taken from org-mode
1505 ;; by Carsten Dominik and adapted for markdown-mode.
1507 (defvar markdown-cycle-global-status
1)
1508 (defvar markdown-cycle-subtree-status nil
)
1510 ;; Based on org-end-of-subtree from org.el
1511 (defun markdown-end-of-subtree (&optional invisible-OK
)
1512 "Move to the end of the current subtree.
1513 Only visible heading lines are considered, unless INVISIBLE-OK is
1515 (outline-back-to-heading invisible-OK
)
1517 (level (funcall outline-level
)))
1518 (while (and (not (eobp))
1519 (or first
(> (funcall outline-level
) level
)))
1521 (outline-next-heading))
1522 (if (memq (preceding-char) '(?
\n ?\^M
))
1524 ;; Go to end of line before heading
1526 (if (memq (preceding-char) '(?
\n ?\^M
))
1527 ;; leave blank line before heading
1528 (forward-char -
1)))))
1531 ;; Based on org-cycle from org.el.
1532 (defun markdown-cycle (&optional arg
)
1533 "Visibility cycling for Markdown mode.
1534 If ARG is t, perform global visibility cycling. If the point is
1535 at an atx-style header, cycle visibility of the corresponding
1536 subtree. Otherwise, insert a tab using `indent-relative'."
1539 ((eq arg t
) ;; Global cycling
1541 ((and (eq last-command this-command
)
1542 (eq markdown-cycle-global-status
2))
1543 ;; Move from overview to contents
1545 (message "CONTENTS")
1546 (setq markdown-cycle-global-status
3))
1548 ((and (eq last-command this-command
)
1549 (eq markdown-cycle-global-status
3))
1550 ;; Move from contents to all
1552 (message "SHOW ALL")
1553 (setq markdown-cycle-global-status
1))
1556 ;; Defaults to overview
1558 (message "OVERVIEW")
1559 (setq markdown-cycle-global-status
2))))
1561 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
1562 ;; At a heading: rotate between three different views
1563 (outline-back-to-heading)
1564 (let ((goal-column 0) eoh eol eos
)
1565 ;; Determine boundaries
1567 (outline-back-to-heading)
1569 (beginning-of-line 2)
1570 (while (and (not (eobp)) ;; this is like `next-line'
1571 (get-char-property (1- (point)) 'invisible
))
1572 (beginning-of-line 2)) (setq eol
(point)))
1573 (outline-end-of-heading) (setq eoh
(point))
1574 (markdown-end-of-subtree t
)
1575 (skip-chars-forward " \t\n")
1576 (beginning-of-line 1) ; in case this is an item
1577 (setq eos
(1- (point))))
1578 ;; Find out what to do next and set `this-command'
1581 ;; Nothing is hidden behind this heading
1582 (message "EMPTY ENTRY")
1583 (setq markdown-cycle-subtree-status nil
))
1585 ;; Entire subtree is hidden in one line: open it
1588 (message "CHILDREN")
1589 (setq markdown-cycle-subtree-status
'children
))
1590 ((and (eq last-command this-command
)
1591 (eq markdown-cycle-subtree-status
'children
))
1592 ;; We just showed the children, now show everything.
1595 (setq markdown-cycle-subtree-status
'subtree
))
1597 ;; Default action: hide the subtree.
1600 (setq markdown-cycle-subtree-status
'folded
)))))
1603 (funcall indent-line-function
))))
1605 ;; Based on org-shifttab from org.el.
1606 (defun markdown-shifttab ()
1607 "Global visibility cycling.
1608 Calls `markdown-cycle' with argument t."
1612 ;;; Commands ==================================================================
1614 (defun markdown (&optional output-buffer-name
)
1615 "Run `markdown' on current buffer and insert output in buffer BUFFER-OUTPUT."
1617 (let ((title (buffer-name))
1620 (if (and (boundp 'transient-mark-mode
) transient-mark-mode mark-active
)
1621 (setq begin-region
(region-beginning)
1622 end-region
(region-end))
1623 (setq begin-region
(point-min)
1624 end-region
(point-max)))
1626 (unless output-buffer-name
1627 (setq output-buffer-name markdown-output-buffer-name
))
1629 (shell-command-on-region begin-region end-region markdown-command
1631 (save-current-buffer
1632 (set-buffer output-buffer-name
)
1633 (goto-char (point-min))
1634 (unless (markdown-output-standalone-p)
1635 (markdown-add-xhtml-header-and-footer title
))
1638 ;; Ensure buffer gets raised, even with short command output
1639 (switch-to-buffer-other-window output-buffer-name
)))
1641 (defun markdown-output-standalone-p ()
1642 "Determine whether `markdown-command' output is standalone XHTML.
1643 Standalone XHTML output is identified by an occurrence of
1644 `markdown-xhtml-standalone-regexp' in the first five lines of output."
1646 markdown-xhtml-standalone-regexp
1647 (save-excursion (goto-line 5) (point)) t
))
1649 (defun markdown-add-xhtml-header-and-footer (title)
1650 "Wrap XHTML header and footer with given TITLE around current buffer."
1651 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
1652 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
1653 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
1654 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
1657 (insert "</title>\n")
1658 (if (> (length markdown-css-path
) 0)
1659 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
1662 (when (> (length markdown-xhtml-header-content
) 0)
1663 (insert markdown-xhtml-header-content
))
1664 (insert "\n</head>\n\n"
1666 (goto-char (point-max))
1671 (defun markdown-preview ()
1672 "Run `markdown' on the current buffer and preview the output in a browser."
1674 (markdown markdown-output-buffer-name
)
1675 (browse-url-of-buffer markdown-output-buffer-name
))
1677 (defun markdown-export-file-name ()
1678 "Attempt to generate a filename for Markdown output.
1679 If the current buffer is visiting a file, we construct a new
1680 output filename based on that filename. Otherwise, return nil."
1681 (when (buffer-file-name)
1682 (concat (file-name-sans-extension (buffer-file-name)) ".html")))
1684 (defun markdown-export ()
1685 "Run Markdown on the current buffer, save to a file, and return the filename.
1686 The resulting filename will be constructed using the current filename, but
1687 with the extension removed and replaced with .html."
1689 (let ((output-file (markdown-export-file-name))
1690 (output-buffer-name))
1692 (setq output-buffer-name
(buffer-name (find-file-noselect output-file
)))
1693 (markdown output-buffer-name
)
1694 (with-current-buffer output-buffer-name
1696 (kill-buffer-and-window))
1699 (defun markdown-export-and-view ()
1700 "Export to XHTML using `markdown-export' and browse the resulting file."
1702 (browse-url (markdown-export)))
1704 ;;; WikiLink Following/Markup ========================================================
1706 (require 'thingatpt
)
1708 (defun markdown-wiki-link-p ()
1709 "Return non-nil when `point' is at a true wiki link.
1710 A true wiki link name matches `markdown-regex-wiki-link' but does not
1711 match the current file name after conversion This modifies the data
1712 returned by `match-data'.
1714 If optional argument SHORTCUT is non-nil, we assume that
1715 `markdown-regex-wiki-link' has just been searched for. Note that the
1716 potential wiki link name must be available via `match-string'."
1717 (let ((case-fold-search nil
))
1718 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
1719 (or (not buffer-file-name
)
1720 (not (string-equal (buffer-file-name)
1721 (markdown-convert-wiki-link-to-filename
1722 (match-string 1)))))
1723 (not (save-match-data
1724 (save-excursion))))))
1726 (defun markdown-convert-wiki-link-to-filename (name)
1727 "Generate a filename from the wiki link NAME.
1728 Spaces are converted to underscores, following the convention
1729 used by the Python Markdown WikiLinks extension."
1730 (let ((new-ext (file-name-extension (buffer-file-name)))
1731 (new-basename (replace-regexp-in-string "[[:space:]\n]" "_" name
)))
1732 (concat new-basename
"." new-ext
)))
1734 (defun markdown-follow-wiki-link (name)
1735 "Follow the wiki link NAME.
1736 Convert the name to a file name and call `find-file'. Ensure that
1737 the new buffer remains in `markdown-mode'."
1738 (let ((filename (markdown-convert-wiki-link-to-filename name
)))
1739 (find-file filename
))
1742 (defun markdown-follow-wiki-link-at-point ()
1743 "Find Wiki Link at point.
1744 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
1746 (if (markdown-wiki-link-p)
1747 (markdown-follow-wiki-link (match-string 1))
1748 (error "Point is not at a Wiki Link")))
1750 (defun markdown-next-wiki-link ()
1751 "Jump to next wiki link.
1752 See `markdown-wiki-link-p'."
1754 (if (markdown-wiki-link-p)
1755 ; At a wiki link already, move past it.
1756 (goto-char (+ 1 (match-end 0))))
1758 ; Search for the next wiki link and move to the beginning.
1759 (re-search-forward markdown-regex-wiki-link nil t
)
1760 (goto-char (match-beginning 0))))
1762 (defun markdown-previous-wiki-link ()
1763 "Jump to previous wiki link.
1764 See `markdown-wiki-link-p'."
1766 (re-search-backward markdown-regex-wiki-link nil t
))
1768 (defun markdown-highlight-wiki-link (from to face
)
1769 "Highlight the wiki link in the region between FROM and TO using FACE."
1770 (let ((ov (make-overlay from to
)))
1771 (overlay-put ov
'face face
)))
1773 (defun markdown-unfontify-region-wiki-links (from to
)
1774 "Remove wiki link faces from the region specified by FROM and TO."
1775 (interactive "nfrom: \nnto: ")
1776 (remove-overlays from to
'face markdown-link-face
)
1777 (remove-overlays from to
'face markdown-missing-link-face
))
1779 (defun markdown-fontify-region-wiki-links (from to
)
1780 "Search region given by FROM and TO for wiki links and fontify them.
1781 If a wiki link is found check to see if the backing file exists
1782 and highlight accordingly."
1784 (while (re-search-forward markdown-regex-wiki-link to t
)
1785 (let ((highlight-beginning (match-beginning 0))
1786 (highlight-end (match-end 0))
1788 (markdown-convert-wiki-link-to-filename (match-string 1))))
1789 (if (file-exists-p file-name
)
1790 (markdown-highlight-wiki-link
1791 highlight-beginning highlight-end markdown-link-face
)
1792 (markdown-highlight-wiki-link
1793 highlight-beginning highlight-end markdown-missing-link-face
)))))
1795 (defun markdown-extend-changed-region (from to
)
1796 "Extend region given by FROM and TO so that we can fontify all links.
1797 The region is extended to the first newline before and the first
1799 ;; start looking for the first new line before 'from
1801 (re-search-backward "\n" nil t
)
1802 (let ((new-from (point-min))
1803 (new-to (point-max)))
1804 (if (not (= (point) from
))
1805 (setq new-from
(point)))
1806 ;; do the same thing for the first new line after 'to
1808 (re-search-forward "\n" nil t
)
1809 (if (not (= (point) to
))
1810 (setq new-to
(point)))
1811 (list new-from new-to
)))
1813 (defun markdown-check-change-for-wiki-link (from to change
)
1814 "Check region between FROM and TO for wiki links and re-fontfy as needed.
1815 Designed to be used with the `after-change-functions' hook.
1816 CHANGE is the number of bytes of pre-change text replaced by the
1818 (interactive "nfrom: \nnto: \nnchange: ")
1819 (let* ((inhibit-point-motion-hooks t
)
1821 (modified (buffer-modified-p))
1822 (buffer-undo-list t
)
1823 (inhibit-read-only t
)
1824 (inhibit-point-motion-hooks t
)
1825 (inhibit-modification-hooks t
)
1826 (current-point (point))
1830 ;; Extend the region to fontify so that it starts
1831 ;; and ends at safe places.
1832 (multiple-value-bind (new-from new-to
)
1833 (markdown-extend-changed-region from to
)
1834 ;; Unfontify existing fontification (start from scratch)
1835 (markdown-unfontify-region-wiki-links new-from new-to
)
1836 ;; Now do the fontification.
1837 (markdown-fontify-region-wiki-links new-from new-to
)))
1839 (restore-buffer-modified-p nil
)))
1840 (goto-char current-point
)))
1842 (defun markdown-fontify-buffer-wiki-links ()
1843 "Refontify all wiki links in the buffer."
1845 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
1847 ;;; Miscellaneous =============================================================
1849 (defun markdown-line-number-at-pos (&optional pos
)
1850 "Return (narrowed) buffer line number at position POS.
1851 If POS is nil, use current buffer location.
1852 This is an exact copy of `line-number-at-pos' for use in emacs21."
1853 (let ((opoint (or pos
(point))) start
)
1855 (goto-char (point-min))
1856 (setq start
(point))
1859 (1+ (count-lines start
(point))))))
1861 (defun markdown-nobreak-p ()
1862 "Return nil if it is acceptable to break the current line at the point."
1863 ;; inside in square brackets (e.g., link anchor text)
1864 (looking-back "\\[[^]]*"))
1868 ;;; Mode definition ==========================================================
1870 (defun markdown-show-version ()
1871 "Show the version number in the minibuffer."
1873 (message "markdown-mode, version %s" markdown-mode-version
))
1876 (define-derived-mode markdown-mode text-mode
"Markdown"
1877 "Major mode for editing Markdown files."
1878 ;; Natural Markdown tab width
1881 (make-local-variable 'comment-start
)
1882 (setq comment-start
"<!-- ")
1883 (make-local-variable 'comment-end
)
1884 (setq comment-end
" -->")
1885 (make-local-variable 'comment-start-skip
)
1886 (setq comment-start-skip
"<!--[ \t]*")
1887 (make-local-variable 'comment-column
)
1888 (setq comment-column
0)
1890 (set (make-local-variable 'font-lock-defaults
)
1891 '(markdown-mode-font-lock-keywords))
1892 (set (make-local-variable 'font-lock-multiline
) t
)
1893 ;; For menu support in XEmacs
1894 (easy-menu-add markdown-mode-menu markdown-mode-map
)
1895 ;; Make filling work with lists (unordered, ordered, and definition)
1896 (set (make-local-variable 'paragraph-start
)
1897 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t*][0-9]+\\.\\|^[ \t]*: ")
1899 (make-local-variable 'outline-regexp
)
1900 (setq outline-regexp
"#+")
1901 ;; Cause use of ellipses for invisible text.
1902 (add-to-invisibility-spec '(outline . t
))
1903 ;; Indentation and filling
1904 (make-local-variable 'fill-nobreak-predicate
)
1905 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
1906 (setq indent-line-function markdown-indent-function
)
1908 ;; Prepare hooks for XEmacs compatibility
1909 (when (featurep 'xemacs
)
1910 (make-local-hook 'after-change-functions
)
1911 (make-local-hook 'font-lock-extend-region-functions
)
1912 (make-local-hook 'window-configuration-change-hook
))
1914 ;; Multiline font lock
1915 (add-hook 'font-lock-extend-region-functions
1916 'markdown-font-lock-extend-region
)
1918 ;; Anytime text changes make sure it gets fontified correctly
1919 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
1921 ;; If we left the buffer there is a really good chance we were
1922 ;; creating one of the wiki link documents. Make sure we get
1923 ;; refontified when we come back.
1924 (add-hook 'window-configuration-change-hook
1925 'markdown-fontify-buffer-wiki-links t t
)
1927 ;; do the initial link fontification
1928 (markdown-fontify-buffer-wiki-links))
1930 ;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
1932 ;;; GitHub Flavored Markdown Mode ============================================
1934 (define-derived-mode gfm-mode markdown-mode
"GFM"
1935 "Major mode for editing GitHub Flavored Markdown files."
1939 (provide 'markdown-mode
)
1941 ;;; markdown-mode.el ends here