Avoid duplication of header regexes
[markdown-mode.git] / markdown-mode.el
blob53125c0152e6be43e8cd05b1549c542a09bd037e
1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2011 Jason R. Blevins <jrblevin@sdf.org>
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>
16 ;; Copyright (C) 2011 Jeremiah Dodds <jeremiah.dodds@gmail.com>
17 ;; Copyright (C) 2011 Christopher J. Madsen <cjm@cjmweb.net>
18 ;; Copyright (C) 2011 Shigeru Fukaya <shigeru.fukaya@gmail.com>
20 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
21 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
22 ;; Created: May 24, 2007
23 ;; Version: 1.8.1
24 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
25 ;; URL: http://jblevins.org/projects/markdown-mode/
27 ;; This file is not part of GNU Emacs.
29 ;; This program is free software; you can redistribute it and/or modify
30 ;; it under the terms of the GNU General Public License as published by
31 ;; the Free Software Foundation; either version 2, or (at your option)
32 ;; any later version.
34 ;; This program is distributed in the hope that it will be useful,
35 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
36 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 ;; GNU General Public License for more details.
39 ;; You should have received a copy of the GNU General Public License
40 ;; along with this program; if not, write to the Free Software
41 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
42 ;; Boston, MA 02110-1301, USA.
44 ;;; Commentary:
46 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
47 ;; text files in GNU Emacs. markdown-mode is free software, licensed
48 ;; under the GNU GPL.
50 ;; [Markdown]: http://daringfireball.net/projects/markdown/
52 ;; The latest stable version is markdown-mode 1.8.1, released on August 15, 2011:
54 ;; * [markdown-mode.el][]
55 ;; * [Screenshot][]
56 ;; * [Release notes][]
58 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
59 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
60 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
62 ;; markdown-mode is also available in several package managers, including:
64 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
65 ;; * RedHat and Fedora Linux: [emacs-goodies][]
66 ;; * OpenBSD: [textproc/markdown-mode][]
67 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
69 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
70 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
71 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
72 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
74 ;; The latest development version can be downloaded directly
75 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
76 ;; (browsable and clonable) Git repository at
77 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
78 ;; including the full project history, can be cloned via the Git protocol
79 ;; by running
81 ;; git clone git://jblevins.org/git/markdown-mode.git
83 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
85 ;;; Dependencies:
87 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
88 ;; 19 and XEmacs 19, which provides a uniform interface for creating
89 ;; menus in GNU Emacs and XEmacs.
91 ;;; Installation:
93 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
94 ;; the following lines to your `.emacs` file to associate markdown-mode
95 ;; with `.text` files:
97 ;; (autoload 'markdown-mode "markdown-mode"
98 ;; "Major mode for editing Markdown files" t)
99 ;; (setq auto-mode-alist
100 ;; (cons '("\\.text" . markdown-mode) auto-mode-alist))
102 ;; There is no consensus on an official file extension so change `.text` to
103 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
105 ;;; Customization:
107 ;; Although no configuration is *necessary* there are a few things
108 ;; that can be customized. The `M-x customize-mode` command
109 ;; provides an interface to all of the possible customizations:
111 ;; * `markdown-command' - the command used to run Markdown (default:
112 ;; `markdown'). This variable may be customized to pass
113 ;; command-line options to your Markdown processor of choice, but
114 ;; this command must accept input from `stdin`. If it does not, a
115 ;; simple wrapper script can be used to write `stdin` to a file
116 ;; and then pass that file to your Markdown interpreter. Ideally,
117 ;; this command will produce an XHTML fragment around which
118 ;; markdown-mode will wrap a header and footer (which can be
119 ;; further customized). However, it attempts to detect whether
120 ;; the command produces standalone XHTML output (via
121 ;; `markdown-xhtml-standalone-regexp'), in which case no header
122 ;; and footer content will be added.
124 ;; * `markdown-command-needs-filename' - set to non-nil if
125 ;; `markdown-command' does not accept input from stdin (default: nil).
126 ;; Instead, it will be passed a filename as the final command-line
127 ;; option. As a result, you will only be able to run Markdown
128 ;; from buffers which are visiting a file.
130 ;; * `markdown-hr-string' - string to use when inserting horizontal
131 ;; rules (default: `* * * * *').
133 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
134 ;; underscores for bold instead of two asterisks (default: `nil').
136 ;; * `markdown-italic-underscore' - set to a non-nil value to use
137 ;; underscores for italic instead of asterisks (default: `nil').
139 ;; * `markdown-indent-function' - the function to use for automatic
140 ;; indentation (default: `markdown-indent-line').
142 ;; * `markdown-indent-on-enter' - set to a non-nil value to
143 ;; automatically indent new lines when the enter key is pressed
144 ;; (default: `t')
146 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
147 ;; to automatically open a linked document in a new buffer if the
148 ;; cursor is an wiki link
149 ;; (default: `t')
151 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
152 ;; treat aliased wiki links like `[[link text|PageName]]`.
153 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
155 ;; * `markdown-uri-types' - a list of protocols for URIs that
156 ;; `markdown-mode' should highlight.
158 ;; * `markdown-enable-math' - syntax highlighting for
159 ;; LaTeX fragments (default: `nil').
161 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
163 ;; * `markdown-xhtml-header-content' - additional content to include
164 ;; in the XHTML `<head>` block.
166 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
167 ;; indicates whether the output of `markdown-command' is standalone
168 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
169 ;; this is not matched, we assume this output is a fragment and add
170 ;; our own header and footer.
172 ;; * `markdown-link-space-sub-char' - a character to replace spaces
173 ;; when mapping wiki links to filenames (default: `_`).
174 ;; For example, use an underscore for compatibility with the
175 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
176 ;; with Github wiki links.
178 ;; Additionally, the faces used for syntax highlighting can be modified to
179 ;; your liking by issuing `M-x customize-group RET markdown-faces`
180 ;; or by using the "Markdown Faces" link at the bottom of the mode
181 ;; customization screen.
183 ;;; Usage:
185 ;; Keybindings are grouped by prefixes based on their function. For
186 ;; example, commands dealing with headers begin with `C-c C-t`. The
187 ;; primary commands in each group will are described below. You can
188 ;; obtain a list of all keybindings by pressing `C-c C-h`.
190 ;; * Anchors: `C-c C-a`
192 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
193 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
194 ;; The label definition will be placed at the end of the current
195 ;; block. `C-c C-a w` acts similarly for wiki links of the form
196 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
197 ;; text in the region is used as the link text.
199 ;; * Commands: `C-c C-c`
201 ;; `C-c C-c m` will run Markdown on the current buffer and preview
202 ;; the output in another buffer while `C-c C-c p` runs Markdown on
203 ;; the current buffer and previews the output in a browser.
204 ;; `C-c C-c e` will run Markdown on the current buffer and save
205 ;; the result in the file `basename.html`, where `basename` is the
206 ;; name of the Markdown file with the extension removed. **This
207 ;; file will be overwritten without notice.** Press `C-c C-c v`
208 ;; to view the exported file in a browser.
210 ;; `C-c C-c c` will check for undefined references. If there are
211 ;; any, a small buffer will open with a list of undefined
212 ;; references and the line numbers on which they appear. In Emacs
213 ;; 22 and greater, selecting a reference from this list and
214 ;; pressing `RET` will insert an empty reference definition at the
215 ;; end of the buffer. Similarly, selecting the line number will
216 ;; jump to the corresponding line.
218 ;; * Images: `C-c C-i`
220 ;; `C-c C-i i` inserts an image, using the active region (if any)
221 ;; as the alt text.
223 ;; * Physical styles: `C-c C-p`
225 ;; These commands all act on text in the active region, if any,
226 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
227 ;; the selected text bold, `C-c C-p f` formats the region as
228 ;; fixed-width text, and `C-c C-p i` is used for italic text.
230 ;; * Logical styles: `C-c C-s`
232 ;; These commands all act on text in the active region, if any,
233 ;; and insert empty markup fragments otherwise. Logical styles
234 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
235 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
236 ;; (`C-c C-s s`).
238 ;; * Headers: `C-c C-t`
240 ;; All header commands use text in the active region, if any, as
241 ;; the header text. To insert an atx or hash style level-n
242 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
243 ;; top-level setext or underline style header press `C-c C-t t`
244 ;; (mnemonic: title) and for a second-level underline-style header
245 ;; press `C-c C-t s` (mnemonic: section).
247 ;; * Other elements:
249 ;; `C-c -` inserts a horizontal rule.
251 ;; * Wiki-Link Navigation:
253 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
254 ;; wiki links, respectively.
256 ;; * Outline Navigation:
258 ;; Navigation between headings is possible using `outline-mode'.
259 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
260 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
261 ;; next and previous visible headings at the same level as the one
262 ;; at the point. Finally, `C-M-u` will move up to a lower-level
263 ;; (more inclusive) visible heading.
265 ;; Many of the commands described above behave differently depending on
266 ;; whether Transient Mark mode is enabled or not. When it makes sense,
267 ;; if Transient Mark mode is on and a region is active, the command
268 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
269 ;; bold). For users who prefer to work outside of Transient Mark mode,
270 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
272 ;; When applicable, commands that specifically act on the region even
273 ;; outside of Transient Mark mode have the same keybinding as the with
274 ;; the exception of an additional `C-` prefix. For example,
275 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
276 ;; the region in Transient Mark mode while `markdown-blockquote-region'
277 ;; is bound to `C-c C-s C-b` and always applies to the region (when
278 ;; nonempty).
280 ;; markdown-mode attempts to be flexible in how it handles
281 ;; indentation. When you press `TAB` repeatedly, the point will cycle
282 ;; through several possible indentation levels corresponding to things
283 ;; you might have in mind when you press `RET` at the end of a line or
284 ;; `TAB`. For example, you may want to start a new list item,
285 ;; continue a list item with hanging indentation, indent for a nested
286 ;; pre block, and so on.
288 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
289 ;; visibility cycling for atx- or hash-style headers. There are two
290 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
291 ;; the table of contents view (headers only), outline view (top-level
292 ;; headers only), and the full document view. Pressing `TAB` while the
293 ;; point is at a header will cycle through levels of visibility for the
294 ;; subtree: completely folded, visible children, and fully visible.
295 ;; Note that mixing hash and underline style headers will give undesired
296 ;; results.
298 ;;; Extensions:
300 ;; Besides supporting the basic Markdown syntax, markdown-mode also
301 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
302 ;; links may be followed automatically by hitting the enter key when
303 ;; your curser is on a wiki link or by hitting `C-c C-f`. The
304 ;; autofollowing on enter key may be controlled with the
305 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
306 ;; `M-n` to quickly jump to the previous and next wiki links,
307 ;; respectively. Aliased or piped wiki links of the form
308 ;; `[[link text|PageName]]` are also supported. Since some wikis
309 ;; reverse these components, set `markdown-wiki-link-alias-first'
310 ;; to nil to treat them as `[[PageName|link text]]`.
312 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
313 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
314 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
315 ;; You can do this either by using `M-x customize-group markdown`
316 ;; or by placing the following in your `.emacs` file:
318 ;; (defun markdown-custom ()
319 ;; "markdown-mode-hook"
320 ;; (setq markdown-command "markdown | smartypants"))
321 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
323 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
325 ;; Experimental syntax highlighting for mathematical expressions written
326 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
327 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
328 ;; either via customize or by placing `(setq markdown-enable-itex t)`
329 ;; in `.emacs`, and restarting Emacs.
331 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
332 ;; mode, `gfm-mode', is also available. The GitHub implementation of
333 ;; differs slightly from standard Markdown. Most importantly, newlines are
334 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
335 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
336 ;; `visual-line-mode' is not available). Wiki links in this mode will be
337 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
338 ;; where the first letter of the filename capitalized. For example,
339 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
340 ;; extension as the current file.
342 ;;; Acknowledgments:
344 ;; markdown-mode has benefited greatly from the efforts of the
345 ;; following people:
347 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
348 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
349 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
350 ;; GitHub Flavored Markdown mode (`gfm-mode').
351 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
352 ;; `markdown' with an active region.
353 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
354 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
355 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
356 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
357 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
358 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
359 ;; compatibility and custom CSS.
360 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
361 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
362 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
363 ;; * Joost Kremers <j.kremers@em.uni-frankfurt.de> for bug reports
364 ;; regarding indentation.
365 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
366 ;; enhancements.
367 ;; * George Ogata <george.ogata@gmail.com> for fixing several
368 ;; byte-compilation warnings.
369 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
370 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
371 ;; customizations and XHTML export.
372 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
373 ;; Markdown processors which do not accept input from stdin.
374 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
375 ;; regarding the cl dependency and auto-fill-mode and indentation.
376 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
377 ;; substitution character for mapping wiki links to filenames.
378 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
379 ;; escape shell commands.
380 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
381 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
382 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
383 ;; Emacs Lisp coding conventions.
384 ;; * Donald Curtis <dcurtis@coe.edu> for fixing the `paragraph-fill' regexp.
385 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
387 ;;; Bugs:
389 ;; Although markdown-mode is developed and tested primarily using
390 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
391 ;; priority.
393 ;; If you find any bugs in markdown-mode, please construct a test case
394 ;; or a patch and email me at <jrblevin@sdf.org>.
396 ;;; History:
398 ;; markdown-mode was written and is maintained by Jason Blevins. The
399 ;; first version was released on May 24, 2007.
401 ;; * 2007-05-24: Version 1.1
402 ;; * 2007-05-25: Version 1.2
403 ;; * 2007-06-05: [Version 1.3][]
404 ;; * 2007-06-29: Version 1.4
405 ;; * 2008-05-24: [Version 1.5][]
406 ;; * 2008-06-04: [Version 1.6][]
407 ;; * 2009-10-01: [Version 1.7][]
408 ;; * 2011-08-12: [Version 1.8][]
409 ;; * 2011-08-15: [Version 1.8.1][]
411 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
412 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
413 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
414 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
415 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
416 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
419 ;;; Code:
421 (require 'easymenu)
422 (require 'outline)
423 (eval-when-compile (require 'cl))
425 ;;; Constants =================================================================
427 (defconst markdown-mode-version "1.8.1"
428 "Markdown mode version number.")
430 (defconst markdown-output-buffer-name "*markdown-output*"
431 "Name of temporary buffer for markdown command output.")
433 ;;; Customizable variables ====================================================
435 (defvar markdown-mode-hook nil
436 "Hook run when entering Markdown mode.")
438 (defgroup markdown nil
439 "Major mode for editing text files in Markdown format."
440 :prefix "markdown-"
441 :group 'wp
442 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
444 (defcustom markdown-command "markdown"
445 "Command to run markdown."
446 :group 'markdown
447 :type 'string)
449 (defcustom markdown-command-needs-filename nil
450 "Set to non-nil if `markdown-command' does not accept input from stdin.
451 Instead, it will be passed a filename as the final command-line
452 option. As a result, you will only be able to run Markdown from
453 buffers which are visiting a file."
454 :group 'markdown
455 :type 'boolean)
457 (defcustom markdown-hr-string "* * * * *"
458 "String to use for horizonal rules."
459 :group 'markdown
460 :type 'string)
462 (defcustom markdown-bold-underscore nil
463 "Use two underscores for bold instead of two asterisks."
464 :group 'markdown
465 :type 'boolean)
467 (defcustom markdown-italic-underscore nil
468 "Use underscores for italic instead of asterisks."
469 :group 'markdown
470 :type 'boolean)
472 (defcustom markdown-indent-function 'markdown-indent-line
473 "Function to use to indent."
474 :group 'markdown
475 :type 'function)
477 (defcustom markdown-indent-on-enter t
478 "Automatically indent new lines when enter key is pressed."
479 :group 'markdown
480 :type 'boolean)
482 (defcustom markdown-follow-wiki-link-on-enter t
483 "Follow wiki link at point (if any) when the enter key is pressed."
484 :group 'markdown
485 :type 'boolean)
487 (defcustom markdown-wiki-link-alias-first t
488 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
489 Otherwise, they will be treated as [[PageName|alias text]]."
490 :group 'markdown
491 :type 'boolean)
493 (defcustom markdown-uri-types
494 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
495 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
496 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
497 "Link types for syntax highlighting of URIs."
498 :group 'markdown
499 :type 'list)
501 (defcustom markdown-enable-math nil
502 "Syntax highlighting for inline LaTeX expressions.
503 This will not take effect until Emacs is restarted."
504 :group 'markdown
505 :type 'boolean)
507 (defcustom markdown-css-path ""
508 "URL of CSS file to link to in the output XHTML."
509 :group 'markdown
510 :type 'string)
512 (defcustom markdown-xhtml-header-content ""
513 "Additional content to include in the XHTML <head> block."
514 :group 'markdown
515 :type 'string)
517 (defcustom markdown-xhtml-standalone-regexp
518 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
519 "Regexp indicating whether `markdown-command' output is standalone XHTML."
520 :group 'markdown
521 :type 'regexp)
523 (defcustom markdown-link-space-sub-char
525 "Character to use instead of spaces when mapping wiki links to filenames."
526 :group 'markdown
527 :type 'string)
529 (defcustom markdown-footnote-location 'end
530 "Position where new footnotes are inserted in the document."
531 :group 'markdown
532 :type '(choice (const :tag "At the end of the document" end)
533 (const :tag "Immediately after the paragraph" immediately)
534 (const :tag "Before next header" header)))
536 ;;; Font lock =================================================================
538 (require 'font-lock)
540 (defvar markdown-italic-face 'markdown-italic-face
541 "Face name to use for italic text.")
543 (defvar markdown-bold-face 'markdown-bold-face
544 "Face name to use for bold text.")
546 (defvar markdown-header-face 'markdown-header-face
547 "Face name to use as a base for headers.")
549 (defvar markdown-header-face-1 'markdown-header-face-1
550 "Face name to use for level-1 headers.")
552 (defvar markdown-header-face-2 'markdown-header-face-2
553 "Face name to use for level-2 headers.")
555 (defvar markdown-header-face-3 'markdown-header-face-3
556 "Face name to use for level-3 headers.")
558 (defvar markdown-header-face-4 'markdown-header-face-4
559 "Face name to use for level-4 headers.")
561 (defvar markdown-header-face-5 'markdown-header-face-5
562 "Face name to use for level-5 headers.")
564 (defvar markdown-header-face-6 'markdown-header-face-6
565 "Face name to use for level-6 headers.")
567 (defvar markdown-inline-code-face 'markdown-inline-code-face
568 "Face name to use for inline code.")
570 (defvar markdown-list-face 'markdown-list-face
571 "Face name to use for list markers.")
573 (defvar markdown-blockquote-face 'markdown-blockquote-face
574 "Face name to use for blockquote.")
576 (defvar markdown-pre-face 'markdown-pre-face
577 "Face name to use for preformatted text.")
579 (defvar markdown-link-face 'markdown-link-face
580 "Face name to use for links.")
582 (defvar markdown-missing-link-face 'markdown-missing-link-face
583 "Face name to use for links where the linked file does not exist.")
585 (defvar markdown-reference-face 'markdown-reference-face
586 "Face name to use for reference.")
588 (defvar markdown-footnote-face 'markdown-footnote-face
589 "Face name to use for footnote identifiers.")
591 (defvar markdown-url-face 'markdown-url-face
592 "Face name to use for URLs.")
594 (defvar markdown-link-title-face 'markdown-link-title-face
595 "Face name to use for reference link titles.")
597 (defvar markdown-comment-face 'markdown-comment-face
598 "Face name to use for HTML comments.")
600 (defvar markdown-math-face 'markdown-math-face
601 "Face name to use for LaTeX expressions.")
603 (defgroup markdown-faces nil
604 "Faces used in Markdown Mode"
605 :group 'markdown
606 :group 'faces)
608 (defface markdown-italic-face
609 '((t (:inherit font-lock-variable-name-face :slant italic)))
610 "Face for italic text."
611 :group 'markdown-faces)
613 (defface markdown-bold-face
614 '((t (:inherit font-lock-variable-name-face :weight bold)))
615 "Face for bold text."
616 :group 'markdown-faces)
618 (defface markdown-header-face
619 '((t (:inherit font-lock-function-name-face :weight bold)))
620 "Base face for headers."
621 :group 'markdown-faces)
623 (defface markdown-header-face-1
624 '((t (:inherit markdown-header-face)))
625 "Face for level-1 headers."
626 :group 'markdown-faces)
628 (defface markdown-header-face-2
629 '((t (:inherit markdown-header-face)))
630 "Face for level-2 headers."
631 :group 'markdown-faces)
633 (defface markdown-header-face-3
634 '((t (:inherit markdown-header-face)))
635 "Face for level-3 headers."
636 :group 'markdown-faces)
638 (defface markdown-header-face-4
639 '((t (:inherit markdown-header-face)))
640 "Face for level-4 headers."
641 :group 'markdown-faces)
643 (defface markdown-header-face-5
644 '((t (:inherit markdown-header-face)))
645 "Face for level-5 headers."
646 :group 'markdown-faces)
648 (defface markdown-header-face-6
649 '((t (:inherit markdown-header-face)))
650 "Face for level-6 headers."
651 :group 'markdown-faces)
653 (defface markdown-inline-code-face
654 '((t (:inherit font-lock-constant-face)))
655 "Face for inline code."
656 :group 'markdown-faces)
658 (defface markdown-list-face
659 '((t (:inherit font-lock-builtin-face)))
660 "Face for list item markers."
661 :group 'markdown-faces)
663 (defface markdown-blockquote-face
664 '((t (:inherit font-lock-doc-face)))
665 "Face for blockquote sections."
666 :group 'markdown-faces)
668 (defface markdown-pre-face
669 '((t (:inherit font-lock-constant-face)))
670 "Face for preformatted text."
671 :group 'markdown-faces)
673 (defface markdown-link-face
674 '((t (:inherit font-lock-keyword-face)))
675 "Face for links."
676 :group 'markdown-faces)
678 (defface markdown-missing-link-face
679 '((t (:inherit font-lock-warning-face)))
680 "Face for missing links."
681 :group 'markdown-faces)
683 (defface markdown-reference-face
684 '((t (:inherit font-lock-type-face)))
685 "Face for link references."
686 :group 'markdown-faces)
688 (defface markdown-footnote-face
689 '((t (:inherit font-lock-keyword-face)))
690 "Face for footnote markers."
691 :group 'markdown-faces)
693 (defface markdown-url-face
694 '((t (:inherit font-lock-string-face)))
695 "Face for URLs."
696 :group 'markdown-faces)
698 (defface markdown-link-title-face
699 '((t (:inherit font-lock-comment-face)))
700 "Face for reference link titles."
701 :group 'markdown-faces)
703 (defface markdown-comment-face
704 '((t (:inherit font-lock-comment-face)))
705 "Face for HTML comments."
706 :group 'markdown-faces)
708 (defface markdown-math-face
709 '((t (:inherit font-lock-string-face)))
710 "Face for LaTeX expressions."
711 :group 'markdown-faces)
713 (defconst markdown-regex-link-inline
714 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
715 "Regular expression for a [text](file) or an image link ![text](file).")
717 (defconst markdown-regex-link-reference
718 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
719 "Regular expression for a reference link [text][id].")
721 (defconst markdown-regex-reference-definition
722 "^ \\{0,3\\}\\(\\[[^^]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
723 "Regular expression for a link definition [id]: ...")
725 (defconst markdown-regex-footnote
726 "\\(\\[\\^.+?\\]\\)"
727 "Regular expression for a footnote marker [^fn]")
729 (defconst markdown-regex-header
730 "#+\\|\\S-.*\n\\(?:\\(===+\\)\\|\\(---+\\)\\)$"
731 "Regexp identifying Markdown headers.")
733 (defconst markdown-regex-header-1-atx
734 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
735 "Regular expression for level 1 atx-style (hash mark) headers.")
737 (defconst markdown-regex-header-2-atx
738 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
739 "Regular expression for level 2 atx-style (hash mark) headers.")
741 (defconst markdown-regex-header-3-atx
742 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
743 "Regular expression for level 3 atx-style (hash mark) headers.")
745 (defconst markdown-regex-header-4-atx
746 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
747 "Regular expression for level 4 atx-style (hash mark) headers.")
749 (defconst markdown-regex-header-5-atx
750 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
751 "Regular expression for level 5 atx-style (hash mark) headers.")
753 (defconst markdown-regex-header-6-atx
754 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
755 "Regular expression for level 6 atx-style (hash mark) headers.")
757 (defconst markdown-regex-header-1-setext
758 "^\\(.*\\)\n\\(===+\\)$"
759 "Regular expression for level 1 setext-style (underline) headers.")
761 (defconst markdown-regex-header-2-setext
762 "^\\(.*\\)\n\\(---+\\)$"
763 "Regular expression for level 2 setext-style (underline) headers.")
765 (defconst markdown-regex-hr
766 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
767 "Regular expression for matching Markdown horizontal rules.")
769 (defconst markdown-regex-code
770 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ]\\(.\\|\n[^\n]\\)*?[^ \\]\\)\\3\\)"
771 "Regular expression for matching inline code fragments.")
773 (defconst markdown-regex-pre
774 "^\\( \\|\t\\).*$"
775 "Regular expression for matching preformatted text sections.")
777 (defconst markdown-regex-list
778 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
779 "Regular expression for matching list markers.")
781 (defconst markdown-regex-bold
782 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)"
783 "Regular expression for matching bold text.")
785 (defconst markdown-regex-italic
786 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
787 "Regular expression for matching italic text.")
789 (defconst markdown-regex-blockquote
790 "^>.*$"
791 "Regular expression for matching blockquote lines.")
793 (defconst markdown-regex-line-break
794 " $"
795 "Regular expression for matching line breaks.")
797 (defconst markdown-regex-wiki-link
798 "\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]"
799 "Regular expression for matching wiki links.
800 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
801 wiki links of the form [[PageName|link text]]. In this regular
802 expression, #1 matches the page name and #3 matches the link
803 text.")
805 (defconst markdown-regex-uri
806 (concat
807 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
808 "\\):[^]\t\n\r<>,;() ]+")
809 "Regular expression for matching inline URIs.")
811 (defconst markdown-regex-angle-uri
812 (concat
813 "\\(<\\)\\("
814 (mapconcat 'identity markdown-uri-types "\\|")
815 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
816 "Regular expression for matching inline URIs in angle brackets.")
818 (defconst markdown-regex-email
819 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
820 "Regular expression for matching inline email addresses.")
822 (defconst markdown-regex-latex-expression
823 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
824 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
826 (defconst markdown-regex-latex-display
827 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
828 "Regular expression for itex \[..\] display mode expressions.")
830 (defconst markdown-regex-list-indent
831 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
832 "Regular expression for matching indentation of list items.")
834 (defvar markdown-mode-font-lock-keywords-basic
835 (list
836 '(markdown-match-pre-blocks 0 markdown-pre-face t t)
837 '(markdown-match-fenced-code-blocks 0 markdown-pre-face t t)
838 (cons markdown-regex-blockquote 'markdown-blockquote-face)
839 (cons markdown-regex-header-1-setext 'markdown-header-face-1)
840 (cons markdown-regex-header-2-setext 'markdown-header-face-2)
841 (cons markdown-regex-header-1-atx 'markdown-header-face-1)
842 (cons markdown-regex-header-2-atx 'markdown-header-face-2)
843 (cons markdown-regex-header-3-atx 'markdown-header-face-3)
844 (cons markdown-regex-header-4-atx 'markdown-header-face-4)
845 (cons markdown-regex-header-5-atx 'markdown-header-face-5)
846 (cons markdown-regex-header-6-atx 'markdown-header-face-6)
847 (cons markdown-regex-hr 'markdown-header-face)
848 '(markdown-match-comments 0 markdown-comment-face t t)
849 (cons markdown-regex-code '(2 markdown-inline-code-face))
850 (cons markdown-regex-angle-uri 'markdown-link-face)
851 (cons markdown-regex-uri 'markdown-link-face)
852 (cons markdown-regex-email 'markdown-link-face)
853 (cons markdown-regex-list 'markdown-list-face)
854 (cons markdown-regex-link-inline
855 '((1 markdown-link-face t)
856 (2 markdown-url-face t)))
857 (cons markdown-regex-link-reference
858 '((1 markdown-link-face t)
859 (2 markdown-reference-face t)))
860 (cons markdown-regex-reference-definition
861 '((1 markdown-reference-face t)
862 (2 markdown-url-face t)
863 (3 markdown-link-title-face t)))
864 (cons markdown-regex-footnote 'markdown-footnote-face)
865 (cons markdown-regex-bold '(2 markdown-bold-face))
866 (cons markdown-regex-italic '(2 markdown-italic-face))
868 "Syntax highlighting for Markdown files.")
870 (defconst markdown-mode-font-lock-keywords-latex
871 (list
872 ;; Math mode $..$ or $$..$$
873 (cons markdown-regex-latex-expression '(2 markdown-math-face))
874 ;; Display mode equations with brackets: \[ \]
875 (cons markdown-regex-latex-display 'markdown-math-face)
876 ;; Equation reference (eq:foo)
877 (cons "(eq:\\w+)" 'markdown-reference-face)
878 ;; Equation reference \eqref{foo}
879 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
880 "Syntax highlighting for LaTeX fragments.")
882 (defvar markdown-mode-font-lock-keywords
883 (append
884 (if markdown-enable-math
885 markdown-mode-font-lock-keywords-latex)
886 markdown-mode-font-lock-keywords-basic)
887 "Default highlighting expressions for Markdown mode.")
889 ;; Footnotes
890 (defvar markdown-footnote-counter 0
891 "Counter for footnote numbers.")
892 (make-variable-buffer-local 'markdown-footnote-counter)
894 (defconst markdown-footnote-chars
895 "[[:alnum:]-]"
896 "Regular expression maching any character that is allowed in a footnote identifier.")
900 ;;; Compatibility =============================================================
902 ;; Handle replace-regexp-in-string in XEmacs 21
903 (defun markdown-replace-regexp-in-string (regexp rep string)
904 "Compatibility wrapper to provide `replace-regexp-in-string'."
905 (if (featurep 'xemacs)
906 (replace-in-string string regexp rep)
907 (replace-regexp-in-string regexp rep string)))
911 ;;; Markdown parsing functions ================================================
913 (defun markdown-cur-line-blank-p ()
914 "Return t if the current line is blank and nil otherwise."
915 (save-excursion
916 (beginning-of-line)
917 (re-search-forward "^\\s *$" (point-at-eol) t)))
919 (defun markdown-prev-line-blank-p ()
920 "Return t if the previous line is blank and nil otherwise.
921 If we are at the first line, then consider the previous line to be blank."
922 (save-excursion
923 (if (= (point-at-bol) (point-min))
925 (forward-line -1)
926 (markdown-cur-line-blank-p))))
928 (defun markdown-next-line-blank-p ()
929 "Return t if the next line is blank and nil otherwise.
930 If we are at the last line, then consider the next line to be blank."
931 (save-excursion
932 (if (= (point-at-bol) (point-max))
934 (forward-line 1)
935 (markdown-cur-line-blank-p))))
937 (defun markdown-prev-line-indent-p ()
938 "Return t if the previous line is indented and nil otherwise."
939 (save-excursion
940 (forward-line -1)
941 (goto-char (point-at-bol))
942 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
944 (defun markdown-cur-line-indent ()
945 "Return the number of leading whitespace characters in the current line."
946 (save-excursion
947 (goto-char (point-at-bol))
948 (re-search-forward "^\\s +" (point-at-eol) t)
949 (current-column)))
951 (defun markdown-prev-line-indent ()
952 "Return the number of leading whitespace characters in the previous line."
953 (save-excursion
954 (forward-line -1)
955 (markdown-cur-line-indent)))
957 (defun markdown-next-line-indent ()
958 "Return the number of leading whitespace characters in the next line."
959 (save-excursion
960 (forward-line 1)
961 (markdown-cur-line-indent)))
963 (defun markdown-cur-non-list-indent ()
964 "Return the number of leading whitespace characters in the current line."
965 (save-excursion
966 (beginning-of-line)
967 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
968 (current-column))))
970 (defun markdown-prev-non-list-indent ()
971 "Return position of the first non-list-marker on the previous line."
972 (save-excursion
973 (forward-line -1)
974 (markdown-cur-non-list-indent)))
976 (defun markdown--next-block ()
977 "Move the point to the start of the next text block."
978 (forward-line)
979 (while (and (or (not (markdown-prev-line-blank-p))
980 (markdown-cur-line-blank-p))
981 (not (eobp)))
982 (forward-line)))
984 (defun markdown--end-of-level (level)
985 "Move the point to the end of region with indentation at least LEVEL."
986 (let (indent)
987 (while (and (not (< (setq indent (markdown-cur-line-indent)) level))
988 (not (>= indent (+ level 4)))
989 (not (eobp)))
990 (markdown--next-block))
991 (unless (eobp)
992 ;; Move back before any trailing blank lines
993 (while (and (markdown-prev-line-blank-p)
994 (not (bobp)))
995 (forward-line -1))
996 (forward-line -1)
997 (end-of-line))))
999 ; From html-helper-mode
1000 (defun markdown-match-comments (last)
1001 "Match HTML comments from the point to LAST."
1002 (cond ((search-forward "<!--" last t)
1003 (backward-char 4)
1004 (let ((beg (point)))
1005 (cond ((search-forward-regexp "--[ \t]*>" last t)
1006 (set-match-data (list beg (point)))
1008 (t nil))))
1009 (t nil)))
1011 (defun markdown-match-pre-blocks (last)
1012 "Match Markdown pre blocks from point to LAST.
1013 A region matches as if it is indented at least four spaces
1014 relative to the nearest previous block of lesser non-list-marker
1015 indentation."
1017 (let (cur-begin cur-end cur-indent prev-indent prev-list stop match found)
1018 ;; Don't start in the middle of a block
1019 (unless (and (bolp)
1020 (markdown-prev-line-blank-p)
1021 (not (markdown-cur-line-blank-p)))
1022 (markdown--next-block))
1024 ;; Move to the first full block in the region with indent 4 or more
1025 (while (and (not (>= (setq cur-indent (markdown-cur-line-indent)) 4))
1026 (not (>= (point) last)))
1027 (markdown--next-block))
1028 (setq cur-begin (point))
1029 (markdown--end-of-level cur-indent)
1030 (setq cur-end (point))
1031 (setq match nil)
1032 (setq stop (> cur-begin cur-end))
1034 (while (and (<= cur-end last) (not stop) (not match))
1035 ;; Move to the nearest preceding block of lesser (non-marker) indentation
1036 (setq prev-indent (+ cur-indent 1))
1037 (goto-char cur-begin)
1038 (setq found nil)
1039 (while (and (>= prev-indent cur-indent)
1040 (not (and prev-list
1041 (eq prev-indent cur-indent)))
1042 (not (bobp)))
1044 ;; Move point to the last line of the previous block.
1045 (forward-line -1)
1046 (while (and (markdown-cur-line-blank-p)
1047 (not (bobp)))
1048 (forward-line -1))
1050 ;; Update the indentation level using either the
1051 ;; non-list-marker indentation, if the previous line is the
1052 ;; start of a list, or the actual indentation.
1053 (setq prev-list (markdown-cur-non-list-indent))
1054 (setq prev-indent (or prev-list
1055 (markdown-cur-line-indent)))
1056 (setq found t))
1058 ;; If the loop didn't execute
1059 (unless found
1060 (setq prev-indent 0))
1062 ;; Compare with prev-indent minus its remainder mod 4
1063 (setq prev-indent (- prev-indent (mod prev-indent 4)))
1065 ;; Set match data and return t if we have a match
1066 (if (>= cur-indent (+ prev-indent 4))
1067 ;; Match
1068 (progn
1069 (setq match t)
1070 (set-match-data (list cur-begin cur-end))
1071 ;; Leave point at end of block
1072 (goto-char cur-end)
1073 (forward-line))
1075 ;; Move to the next block (if possible)
1076 (goto-char cur-end)
1077 (markdown--next-block)
1078 (setq cur-begin (point))
1079 (setq cur-indent (markdown-cur-line-indent))
1080 (markdown--end-of-level cur-indent)
1081 (setq cur-end (point))
1082 (setq stop (equal cur-begin cur-end))))
1083 match))
1085 (defun markdown-match-fenced-code-blocks (last)
1086 "Match fenced code blocks from the point to LAST."
1087 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1088 (beginning-of-line)
1089 (let ((beg (point)))
1090 (forward-line)
1091 (cond ((search-forward-regexp
1092 (concat "^" (match-string 1) "~*") last t)
1093 (set-match-data (list beg (point)))
1095 (t nil))))
1096 (t nil)))
1098 (defun markdown-font-lock-extend-region ()
1099 "Extend the search region to include an entire block of text.
1100 This helps improve font locking for block constructs such as pre blocks."
1101 ;; Avoid compiler warnings about these global variables from font-lock.el.
1102 ;; See the documentation for variable `font-lock-extend-region-functions'.
1103 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1104 (save-excursion
1105 (goto-char font-lock-beg)
1106 (let ((found (re-search-backward "\n\n" nil t)))
1107 (when found
1108 (goto-char font-lock-end)
1109 (when (re-search-forward "\n\n" nil t)
1110 (beginning-of-line)
1111 (setq font-lock-end (point)))
1112 (setq font-lock-beg found)))))
1116 ;;; Syntax Table ==============================================================
1118 (defvar markdown-mode-syntax-table
1119 (let ((markdown-mode-syntax-table (make-syntax-table)))
1120 (modify-syntax-entry ?\" "w" markdown-mode-syntax-table)
1121 markdown-mode-syntax-table)
1122 "Syntax table for `markdown-mode'.")
1126 ;;; Element Insertion =========================================================
1128 (defun markdown-wrap-or-insert (s1 s2)
1129 "Insert the strings S1 and S2.
1130 If Transient Mark mode is on and a region is active, wrap the strings S1
1131 and S2 around the region."
1132 (if (and transient-mark-mode mark-active)
1133 (let ((a (region-beginning)) (b (region-end)))
1134 (goto-char a)
1135 (insert s1)
1136 (goto-char (+ b (length s1)))
1137 (insert s2))
1138 (insert s1 s2)))
1140 (defun markdown-insert-hr ()
1141 "Insert a horizonal rule using `markdown-hr-string'."
1142 (interactive)
1143 ;; Leading blank line
1144 (when (and (>= (point) (+ (point-min) 2))
1145 (not (looking-back "\n\n" 2)))
1146 (insert "\n"))
1147 ;; Insert custom HR string
1148 (insert (concat markdown-hr-string "\n"))
1149 ;; Following blank line
1150 (backward-char)
1151 (unless (looking-at "\n\n")
1152 (insert "\n")))
1154 (defun markdown-insert-bold ()
1155 "Insert markup for a bold word or phrase.
1156 If Transient Mark mode is on and a region is active, it is made bold."
1157 (interactive)
1158 (if markdown-bold-underscore
1159 (markdown-wrap-or-insert "__" "__")
1160 (markdown-wrap-or-insert "**" "**"))
1161 (backward-char 2))
1163 (defun markdown-insert-italic ()
1164 "Insert markup for an italic word or phrase.
1165 If Transient Mark mode is on and a region is active, it is made italic."
1166 (interactive)
1167 (if markdown-italic-underscore
1168 (markdown-wrap-or-insert "_" "_")
1169 (markdown-wrap-or-insert "*" "*"))
1170 (backward-char 1))
1172 (defun markdown-insert-code ()
1173 "Insert markup for an inline code fragment.
1174 If Transient Mark mode is on and a region is active, it is marked
1175 as inline code."
1176 (interactive)
1177 (markdown-wrap-or-insert "`" "`")
1178 (backward-char 1))
1180 (defun markdown-insert-link ()
1181 "Insert an inline link of the form []().
1182 If Transient Mark mode is on and a region is active, it is used
1183 as the link text."
1184 (interactive)
1185 (markdown-wrap-or-insert "[" "]")
1186 (insert "()")
1187 (backward-char 1))
1189 (defun markdown-insert-reference-link-dwim ()
1190 "Insert a reference link of the form [text][label] at point.
1191 If Transient Mark mode is on and a region is active, the region
1192 is used as the link text. Otherwise, the link text will be read
1193 from the minibuffer. The link URL, label, and title will be read
1194 from the minibuffer. The link label definition is placed at the
1195 end of the current paragraph."
1196 (interactive)
1197 (if (and transient-mark-mode mark-active)
1198 (call-interactively 'markdown-insert-reference-link-region)
1199 (call-interactively 'markdown-insert-reference-link)))
1201 (defun markdown-insert-reference-link-region (url label title)
1202 "Insert a reference link at point using the region as the link text."
1203 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1204 (let ((text (buffer-substring (region-beginning) (region-end))))
1205 (delete-region (region-beginning) (region-end))
1206 (markdown-insert-reference-link text url label title)))
1208 (defun markdown-insert-reference-link (text url label title)
1209 "Insert a reference link at point.
1210 The link label definition is placed at the end of the current
1211 paragraph."
1212 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1213 (let (end)
1214 (insert (concat "[" text "][" label "]"))
1215 (setq end (point))
1216 (forward-paragraph)
1217 (insert "\n[")
1218 (if (> (length label) 0)
1219 (insert label)
1220 (insert text))
1221 (insert (concat "]: " url))
1222 (unless (> (length url) 0)
1223 (setq end (point)))
1224 (when (> (length title) 0)
1225 (insert (concat " \"" title "\"")))
1226 (insert "\n")
1227 (unless (looking-at "\n")
1228 (insert "\n"))
1229 (goto-char end)))
1231 (defun markdown-insert-wiki-link ()
1232 "Insert a wiki link of the form [[WikiLink]].
1233 If Transient Mark mode is on and a region is active, it is used
1234 as the link text."
1235 (interactive)
1236 (markdown-wrap-or-insert "[[" "]]")
1237 (backward-char 2))
1239 (defun markdown-insert-image ()
1240 "Insert an inline image tag of the form ![]().
1241 If Transient Mark mode is on and a region is active, it is used
1242 as the alt text of the image."
1243 (interactive)
1244 (markdown-wrap-or-insert "![" "]")
1245 (insert "()")
1246 (backward-char 1))
1248 (defun markdown-insert-header-1 ()
1249 "Insert a first level atx-style (hash mark) header.
1250 If Transient Mark mode is on and a region is active, it is used
1251 as the header text."
1252 (interactive)
1253 (markdown-insert-header 1))
1255 (defun markdown-insert-header-2 ()
1256 "Insert a second level atx-style (hash mark) header.
1257 If Transient Mark mode is on and a region is active, it is used
1258 as the header text."
1259 (interactive)
1260 (markdown-insert-header 2))
1262 (defun markdown-insert-header-3 ()
1263 "Insert a third level atx-style (hash mark) header.
1264 If Transient Mark mode is on and a region is active, it is used
1265 as the header text."
1266 (interactive)
1267 (markdown-insert-header 3))
1269 (defun markdown-insert-header-4 ()
1270 "Insert a fourth level atx-style (hash mark) header.
1271 If Transient Mark mode is on and a region is active, it is used
1272 as the header text."
1273 (interactive)
1274 (markdown-insert-header 4))
1276 (defun markdown-insert-header-5 ()
1277 "Insert a fifth level atx-style (hash mark) header.
1278 If Transient Mark mode is on and a region is active, it is used
1279 as the header text."
1280 (interactive)
1281 (markdown-insert-header 5))
1283 (defun markdown-insert-header-6 ()
1284 "Insert a sixth level atx-style (hash mark) header.
1285 If Transient Mark mode is on and a region is active, it is used
1286 as the header text."
1287 (interactive)
1288 (markdown-insert-header 6))
1290 (defun markdown-insert-header (n)
1291 "Insert an atx-style (hash mark) header.
1292 With no prefix argument, insert a level-1 header. With prefix N,
1293 insert a level-N header. If Transient Mark mode is on and the
1294 region is active, it is used as the header text."
1295 (interactive "p")
1296 (unless n ; Test to see if n is defined
1297 (setq n 1)) ; Default to level 1 header
1298 (let (hdr hdrl hdrr)
1299 (dotimes (count n hdr)
1300 (setq hdr (concat "#" hdr))) ; Build a hash mark header string
1301 (setq hdrl (concat hdr " "))
1302 (setq hdrr (concat " " hdr))
1303 (markdown-wrap-or-insert hdrl hdrr))
1304 (backward-char (+ 1 n)))
1306 (defun markdown-insert-title ()
1307 "Insert a setext-style (underline) first level header.
1308 If Transient Mark mode is on and a region is active, it is used
1309 as the header text."
1310 (interactive)
1311 (if (and transient-mark-mode mark-active)
1312 (let ((a (region-beginning))
1313 (b (region-end))
1314 (len 0)
1315 (hdr))
1316 (setq len (- b a))
1317 (dotimes (count len hdr)
1318 (setq hdr (concat "=" hdr))) ; Build a === title underline
1319 (end-of-line)
1320 (insert "\n" hdr "\n"))
1321 (insert "\n==========\n")
1322 (backward-char 12)))
1324 (defun markdown-insert-section ()
1325 "Insert a setext-style (underline) second level header.
1326 If Transient Mark mode is on and a region is active, it is used
1327 as the header text."
1328 (interactive)
1329 (if (and transient-mark-mode mark-active)
1330 (let ((a (region-beginning))
1331 (b (region-end))
1332 (len 0)
1333 (hdr))
1334 (setq len (- b a))
1335 (dotimes (count len hdr)
1336 (setq hdr (concat "-" hdr))) ; Build a --- section underline
1337 (end-of-line)
1338 (insert "\n" hdr "\n"))
1339 (insert "\n----------\n")
1340 (backward-char 12)))
1342 (defun markdown-insert-blockquote ()
1343 "Start a blockquote section (or blockquote the region).
1344 If Transient Mark mode is on and a region is active, it is used as
1345 the blockquote text."
1346 (interactive)
1347 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1348 (markdown-blockquote-region (region-beginning) (region-end))
1349 (insert "> ")))
1351 (defun markdown-block-region (beg end prefix)
1352 "Format the region using a block prefix.
1353 Arguments BEG and END specify the beginning and end of the
1354 region. The characters PREFIX will appear at the beginning
1355 of each line."
1356 (if mark-active
1357 (save-excursion
1358 ;; Ensure that there is a leading blank line
1359 (goto-char beg)
1360 (when (and (>= (point) (+ (point-min) 2))
1361 (not (looking-back "\n\n" 2)))
1362 (insert "\n")
1363 (setq beg (1+ beg))
1364 (setq end (1+ end)))
1365 ;; Move back before any blank lines at the end
1366 (goto-char end)
1367 (while (and (looking-back "\n" 1)
1368 (not (equal (point) (point-min))))
1369 (backward-char)
1370 (setq end (1- end)))
1371 ;; Ensure that there is a trailing blank line
1372 (goto-char end)
1373 (if (not (or (looking-at "\n\n")
1374 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
1375 (insert "\n"))
1376 ;; Insert PREFIX
1377 (goto-char beg)
1378 (beginning-of-line)
1379 (while (< (point-at-bol) end)
1380 (insert prefix)
1381 (setq end (+ (length prefix) end))
1382 (forward-line)))))
1384 (defun markdown-blockquote-region (beg end)
1385 "Blockquote the region.
1386 Arguments BEG and END specify the beginning and end of the region."
1387 (interactive "*r")
1388 (markdown-block-region beg end "> "))
1390 (defun markdown-insert-pre ()
1391 "Start a preformatted section (or apply to the region).
1392 If Transient Mark mode is on and a region is active, it is marked
1393 as preformatted text."
1394 (interactive)
1395 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1396 (markdown-pre-region (region-beginning) (region-end))
1397 (insert " ")))
1399 (defun markdown-pre-region (beg end)
1400 "Format the region as preformatted text.
1401 Arguments BEG and END specify the beginning and end of the region."
1402 (interactive "*r")
1403 (markdown-block-region beg end " "))
1405 ;;; Footnotes ======================================================================
1407 (defun markdown-footnote-counter-inc ()
1408 "Increment markdown-footnote-counter and return the new value."
1409 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
1410 (save-excursion
1411 (goto-char (point-min))
1412 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
1413 (point-max) t)
1414 (let ((fn (string-to-number (match-string 1))))
1415 (when (> fn markdown-footnote-counter)
1416 (setq markdown-footnote-counter fn))))))
1417 (incf markdown-footnote-counter))
1419 (defun markdown-footnote-new ()
1420 "Insert a footnote with a new number and jump to a position to enter the
1421 footnote text."
1422 (interactive)
1423 (let ((fn (markdown-footnote-counter-inc)))
1424 (insert (format "[^%d]" fn))
1425 (markdown-footnote-text-find-new-location)
1426 (insert (format "[^%d]: " fn))))
1428 (defun markdown-footnote-text-find-new-location ()
1429 "Position the cursor at the proper location for a new footnote text."
1430 (cond
1431 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
1432 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
1433 ((eq markdown-footnote-location 'header)
1434 ;; search for a header. if none is found, go to the end of the document.
1435 (catch 'eof
1436 (while (progn
1437 (forward-paragraph)
1438 (unless (re-search-forward markdown-regex-header nil t)
1439 (throw 'eof nil))
1440 (backward-paragraph)
1441 (not (looking-at (concat "\n" markdown-regex-header))))))))
1442 ;; make sure we're on an empty line:
1443 (unless (markdown-cur-line-blank-p)
1444 (insert "\n"))
1445 ;; and make sure the previous line is empty:
1446 (unless (markdown-prev-line-blank-p)
1447 (insert "\n"))
1448 ;; then make sure there's an empty line following the footnote:
1449 (unless (markdown-next-line-blank-p)
1450 (insert "\n")
1451 (forward-line -1)))
1453 (defun markdown-footnote-goto-text ()
1454 "Jump to the text of the footnote under the cursor."
1455 (interactive)
1456 ;; first make sure we're at a footnote marker
1457 (unless (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
1458 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
1459 (error "Not at a footnote"))
1460 (let* ((fn nil)
1461 (new-pos (save-excursion
1462 ;; move point between [ and ^:
1463 (if (looking-at "\\[")
1464 (forward-char 1)
1465 (skip-chars-backward "^["))
1466 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
1467 (setq fn (match-string 1))
1468 (goto-char (point-min))
1469 (re-search-forward (concat "^\\[" fn "\\]:") nil t))))
1470 (unless new-pos
1471 (error "No definition found for footnote `%s'" fn))
1472 (goto-char new-pos)
1473 (skip-chars-forward "[:space:]")))
1475 (defun markdown-footnote-return ()
1476 "Return from a footnote to its footnote number in the main text."
1477 (interactive)
1478 (let ((fn (save-excursion
1479 (backward-paragraph)
1480 ;; if we're in a multiparagraph footnote, we need to back up further
1481 (while (>= (markdown-next-line-indent) 4)
1482 (backward-paragraph))
1483 (forward-line)
1484 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
1485 (match-string 1)))))
1486 (unless fn
1487 (error "Not in a footnote"))
1488 (let ((new-pos (save-excursion
1489 (goto-char (point-min))
1490 (re-search-forward (concat "\\[" fn "\\]\\([^:]\\|\\'\\)") nil t))))
1491 (unless new-pos
1492 (error "Footnote `%s' not found" fn))
1493 (goto-char new-pos)
1494 (skip-chars-backward "^]"))))
1496 ;;; Indentation ====================================================================
1498 (defun markdown-indent-find-next-position (cur-pos positions)
1499 "Return the position after the index of CUR-POS in POSITIONS."
1500 (while (and positions
1501 (not (equal cur-pos (car positions))))
1502 (setq positions (cdr positions)))
1503 (or (cadr positions) 0))
1505 (defun markdown-indent-line ()
1506 "Indent the current line using some heuristics.
1507 If the _previous_ command was either `markdown-enter-key' or
1508 `markdown-cycle', then we should cycle to the next
1509 reasonable indentation position. Otherwise, we could have been
1510 called directly by `markdown-enter-key', by an initial call of
1511 `markdown-cycle', or indirectly by `auto-fill-mode'. In
1512 these cases, indent to the default position."
1513 (interactive)
1514 (let ((positions (markdown-calc-indents))
1515 (cur-pos (current-column)))
1516 (if (not (equal this-command 'markdown-cycle))
1517 (indent-line-to (car positions))
1518 (setq positions (sort (delete-dups positions) '<))
1519 (indent-line-to
1520 (markdown-indent-find-next-position cur-pos positions)))))
1522 (defun markdown-calc-indents ()
1523 "Return a list of indentation columns to cycle through.
1524 The first element in the returned list should be considered the
1525 default indentation level."
1526 (let (pos prev-line-pos positions)
1528 ;; Previous line indent
1529 (setq prev-line-pos (markdown-prev-line-indent))
1530 (setq positions (cons prev-line-pos positions))
1532 ;; Previous non-list-marker indent
1533 (setq pos (markdown-prev-non-list-indent))
1534 (when pos
1535 (setq positions (cons pos positions))
1536 (setq positions (cons (+ pos tab-width) positions)))
1538 ;; Indentation of the previous line + tab-width
1539 (cond
1540 (prev-line-pos
1541 (setq positions (cons (+ prev-line-pos tab-width) positions)))
1543 (setq positions (cons tab-width positions))))
1545 ;; Indentation of the previous line - tab-width
1546 (if (and prev-line-pos
1547 (> prev-line-pos tab-width))
1548 (setq positions (cons (- prev-line-pos tab-width) positions)))
1550 ;; Indentation of preceeding list item
1551 (setq pos
1552 (save-excursion
1553 (forward-line -1)
1554 (catch 'break
1555 (while (not (equal (point) (point-min)))
1556 (forward-line -1)
1557 (goto-char (point-at-bol))
1558 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1559 (throw 'break (length (match-string 1)))))
1560 nil)))
1561 (if (and pos (not (eq pos prev-line-pos)))
1562 (setq positions (cons pos positions)))
1564 ;; First column
1565 (setq positions (cons 0 positions))
1567 (reverse positions)))
1569 (defun markdown-do-normal-return ()
1570 "Insert a newline and optionally indent the next line."
1571 (newline)
1572 (if markdown-indent-on-enter
1573 (funcall indent-line-function)))
1575 (defun markdown-enter-key ()
1576 "Handle RET according to context.
1577 If there is a wiki link at the point, follow it unless
1578 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1579 it in the usual way."
1580 (interactive)
1581 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
1582 (markdown-follow-wiki-link-at-point)
1583 (markdown-do-normal-return)))
1587 ;;; Keymap ====================================================================
1589 (defvar markdown-mode-map
1590 (let ((map (make-keymap)))
1591 ;; Element insertion
1592 (define-key map "\C-c\C-al" 'markdown-insert-link)
1593 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
1594 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
1595 (define-key map "\C-c\C-ii" 'markdown-insert-image)
1596 (define-key map "\C-c\C-t1" 'markdown-insert-header-1)
1597 (define-key map "\C-c\C-t2" 'markdown-insert-header-2)
1598 (define-key map "\C-c\C-t3" 'markdown-insert-header-3)
1599 (define-key map "\C-c\C-t4" 'markdown-insert-header-4)
1600 (define-key map "\C-c\C-t5" 'markdown-insert-header-5)
1601 (define-key map "\C-c\C-t6" 'markdown-insert-header-6)
1602 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
1603 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
1604 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
1605 (define-key map "\C-c\C-se" 'markdown-insert-italic)
1606 (define-key map "\C-c\C-pf" 'markdown-insert-code)
1607 (define-key map "\C-c\C-sc" 'markdown-insert-code)
1608 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
1609 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
1610 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
1611 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
1612 (define-key map "\C-c-" 'markdown-insert-hr)
1613 (define-key map "\C-c\C-tt" 'markdown-insert-title)
1614 (define-key map "\C-c\C-ts" 'markdown-insert-section)
1615 ;; Footnotes
1616 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
1617 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
1618 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
1619 ;; WikiLink Following
1620 (define-key map "\C-c\C-w" 'markdown-follow-wiki-link-at-point)
1621 (define-key map "\M-n" 'markdown-next-wiki-link)
1622 (define-key map "\M-p" 'markdown-previous-wiki-link)
1623 ;; Indentation
1624 (define-key map "\C-m" 'markdown-enter-key)
1625 ;; Visibility cycling
1626 (define-key map (kbd "<tab>") 'markdown-cycle)
1627 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
1628 ;; Header navigation
1629 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
1630 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
1631 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
1632 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
1633 (define-key map (kbd "C-M-u") 'outline-up-heading)
1634 ;; Markdown functions
1635 (define-key map "\C-c\C-cm" 'markdown)
1636 (define-key map "\C-c\C-cp" 'markdown-preview)
1637 (define-key map "\C-c\C-ce" 'markdown-export)
1638 (define-key map "\C-c\C-cv" 'markdown-export-and-view)
1639 ;; References
1640 (define-key map "\C-c\C-cc" 'markdown-check-refs)
1641 map)
1642 "Keymap for Markdown major mode.")
1644 ;;; Menu ==================================================================
1646 (easy-menu-define markdown-mode-menu markdown-mode-map
1647 "Menu for Markdown mode"
1648 '("Markdown"
1649 ("Show/Hide"
1650 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
1651 ["Cycle global visibility" markdown-shifttab])
1652 "---"
1653 ["Compile" markdown]
1654 ["Preview" markdown-preview]
1655 ["Export" markdown-export]
1656 ["Export & View" markdown-export-and-view]
1657 "---"
1658 ("Headers (setext)"
1659 ["Insert Title" markdown-insert-title]
1660 ["Insert Section" markdown-insert-section])
1661 ("Headers (atx)"
1662 ["First level" markdown-insert-header-1]
1663 ["Second level" markdown-insert-header-2]
1664 ["Third level" markdown-insert-header-3]
1665 ["Fourth level" markdown-insert-header-4]
1666 ["Fifth level" markdown-insert-header-5]
1667 ["Sixth level" markdown-insert-header-6])
1668 "---"
1669 ["Bold" markdown-insert-bold]
1670 ["Italic" markdown-insert-italic]
1671 ["Blockquote" markdown-insert-blockquote]
1672 ["Preformatted" markdown-insert-pre]
1673 ["Code" markdown-insert-code]
1674 "---"
1675 ["Insert inline link" markdown-insert-link]
1676 ["Insert reference link" markdown-insert-reference-link-dwim]
1677 ["Insert image" markdown-insert-image]
1678 ["Insert horizontal rule" markdown-insert-hr]
1679 "---"
1680 ("Footnotes"
1681 ["Insert footnote" markdown-footnote-new]
1682 ["Jump to footnote text" markdown-footnote-goto-text]
1683 ["Return from footnote" markdown-footnote-return])
1684 "---"
1685 ["Check references" markdown-check-refs]
1686 "---"
1687 ["Version" markdown-show-version]
1692 ;;; References ================================================================
1694 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
1696 (defconst markdown-refcheck-buffer
1697 "*Undefined references for %buffer%*"
1698 "Pattern for name of buffer for listing undefined references.
1699 The string %buffer% will be replaced by the corresponding
1700 `markdown-mode' buffer name.")
1702 (defun markdown-has-reference-definition (reference)
1703 "Find out whether Markdown REFERENCE is defined.
1705 REFERENCE should include the square brackets, like [this]."
1706 (let ((reference (downcase reference)))
1707 (save-excursion
1708 (goto-char (point-min))
1709 (catch 'found
1710 (while (re-search-forward markdown-regex-reference-definition nil t)
1711 (when (string= reference (downcase (match-string-no-properties 1)))
1712 (throw 'found t)))))))
1714 (defun markdown-get-undefined-refs ()
1715 "Return a list of undefined Markdown references.
1717 Result is an alist of pairs (reference . occurencies), where
1718 occurencies is itself another alist of pairs (label .
1719 line-number).
1721 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
1722 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
1723 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
1724 (let ((missing))
1725 (save-excursion
1726 (goto-char (point-min))
1727 (while
1728 (re-search-forward markdown-regex-link-reference nil t)
1729 (let* ((label (match-string-no-properties 1))
1730 (reference (match-string-no-properties 2))
1731 (target (downcase (if (string= reference "[]") label reference))))
1732 (unless (markdown-has-reference-definition target)
1733 (let ((entry (assoc target missing)))
1734 (if (not entry)
1735 (add-to-list 'missing (cons target
1736 (list (cons label (markdown-line-number-at-pos)))) t)
1737 (setcdr entry
1738 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
1739 missing)))
1741 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
1742 "Add blank REF definition to the end of BUFFER.
1744 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
1746 When RECHECK is non-nil, BUFFER gets rechecked for undefined
1747 references so that REF disappears from the list of those links."
1748 (with-current-buffer buffer
1749 (when (not (eq major-mode 'markdown-mode))
1750 (error "Not available in current mode"))
1751 (goto-char (point-max))
1752 (indent-new-comment-line)
1753 (insert (concat ref ": ")))
1754 (switch-to-buffer-other-window buffer)
1755 (goto-char (point-max))
1756 (when recheck
1757 (markdown-check-refs t)))
1759 ;; Button which adds an empty Markdown reference definition to the end
1760 ;; of buffer specified as its 'target-buffer property. Reference name
1761 ;; is button's label
1762 (when (>= emacs-major-version 22)
1763 (define-button-type 'markdown-ref-button
1764 'help-echo "Push to create an empty reference definition"
1765 'face 'bold
1766 'action (lambda (b)
1767 (markdown-add-missing-ref-definition
1768 (button-label b) (button-get b 'target-buffer) t))))
1770 ;; Button jumping to line in buffer specified as its 'target-buffer
1771 ;; property. Line number is button's 'line property.
1772 (when (>= emacs-major-version 22)
1773 (define-button-type 'goto-line-button
1774 'help-echo "Push to go to this line"
1775 'face 'italic
1776 'action (lambda (b)
1777 (message (button-get b 'buffer))
1778 (switch-to-buffer-other-window (button-get b 'target-buffer))
1779 ;; use call-interactively to silence compiler
1780 (call-interactively 'goto-line (button-get b 'target-line)))))
1782 (defun markdown-check-refs (&optional silent)
1783 "Show all undefined Markdown references in current `markdown-mode' buffer.
1785 If SILENT is non-nil, do not message anything when no undefined
1786 references found.
1788 Links which have empty reference definitions are considered to be
1789 defined."
1790 (interactive "P")
1791 (when (not (eq major-mode 'markdown-mode))
1792 (error "Not available in current mode"))
1793 (let ((oldbuf (current-buffer))
1794 (refs (markdown-get-undefined-refs))
1795 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
1796 "%buffer%" (buffer-name)
1797 markdown-refcheck-buffer))))
1798 (if (null refs)
1799 (progn
1800 (when (not silent)
1801 (message "No undefined references found"))
1802 (kill-buffer refbuf))
1803 (with-current-buffer refbuf
1804 (when view-mode
1805 (View-exit-and-edit))
1806 (erase-buffer)
1807 (insert "Following references lack definitions:")
1808 (newline 2)
1809 (dolist (ref refs)
1810 (let ((button-label (format "%s" (car ref))))
1811 (if (>= emacs-major-version 22)
1812 ;; Create a reference button in Emacs 22
1813 (insert-text-button button-label
1814 :type 'markdown-ref-button
1815 'target-buffer oldbuf)
1816 ;; Insert reference as text in Emacs < 22
1817 (insert button-label)))
1818 (insert " (")
1819 (dolist (occurency (cdr ref))
1820 (let ((line (cdr occurency)))
1821 (if (>= emacs-major-version 22)
1822 ;; Create a line number button in Emacs 22
1823 (insert-button (number-to-string line)
1824 :type 'goto-line-button
1825 'target-buffer oldbuf
1826 'target-line line)
1827 ;; Insert line number as text in Emacs < 22
1828 (insert (number-to-string line)))
1829 (insert " "))) (delete-char -1)
1830 (insert ")")
1831 (newline))
1832 (view-buffer-other-window refbuf)
1833 (goto-char (point-min))
1834 (forward-line 2)))))
1836 ;;; Outline ===================================================================
1838 ;; The following visibility cycling code was taken from org-mode
1839 ;; by Carsten Dominik and adapted for markdown-mode.
1841 (defvar markdown-cycle-global-status 1)
1842 (defvar markdown-cycle-subtree-status nil)
1844 ;; Based on org-end-of-subtree from org.el
1845 (defun markdown-end-of-subtree (&optional invisible-OK)
1846 "Move to the end of the current subtree.
1847 Only visible heading lines are considered, unless INVISIBLE-OK is
1848 non-nil."
1849 (outline-back-to-heading invisible-OK)
1850 (let ((first t)
1851 (level (funcall outline-level)))
1852 (while (and (not (eobp))
1853 (or first (> (funcall outline-level) level)))
1854 (setq first nil)
1855 (outline-next-heading))
1856 (if (memq (preceding-char) '(?\n ?\^M))
1857 (progn
1858 ;; Go to end of line before heading
1859 (forward-char -1)
1860 (if (memq (preceding-char) '(?\n ?\^M))
1861 ;; leave blank line before heading
1862 (forward-char -1)))))
1863 (point))
1865 ;; Based on org-cycle from org.el.
1866 (defun markdown-cycle (&optional arg)
1867 "Visibility cycling for Markdown mode.
1868 If ARG is t, perform global visibility cycling. If the point is
1869 at an atx-style header, cycle visibility of the corresponding
1870 subtree. Otherwise, insert a tab using `indent-relative'."
1871 (interactive "P")
1872 (cond
1873 ((eq arg t) ;; Global cycling
1874 (cond
1875 ((and (eq last-command this-command)
1876 (eq markdown-cycle-global-status 2))
1877 ;; Move from overview to contents
1878 (hide-sublevels 1)
1879 (message "CONTENTS")
1880 (setq markdown-cycle-global-status 3))
1882 ((and (eq last-command this-command)
1883 (eq markdown-cycle-global-status 3))
1884 ;; Move from contents to all
1885 (show-all)
1886 (message "SHOW ALL")
1887 (setq markdown-cycle-global-status 1))
1890 ;; Defaults to overview
1891 (hide-body)
1892 (message "OVERVIEW")
1893 (setq markdown-cycle-global-status 2))))
1895 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
1896 ;; At a heading: rotate between three different views
1897 (outline-back-to-heading)
1898 (let ((goal-column 0) eoh eol eos)
1899 ;; Determine boundaries
1900 (save-excursion
1901 (outline-back-to-heading)
1902 (save-excursion
1903 (beginning-of-line 2)
1904 (while (and (not (eobp)) ;; this is like `next-line'
1905 (get-char-property (1- (point)) 'invisible))
1906 (beginning-of-line 2)) (setq eol (point)))
1907 (outline-end-of-heading) (setq eoh (point))
1908 (markdown-end-of-subtree t)
1909 (skip-chars-forward " \t\n")
1910 (beginning-of-line 1) ; in case this is an item
1911 (setq eos (1- (point))))
1912 ;; Find out what to do next and set `this-command'
1913 (cond
1914 ((= eos eoh)
1915 ;; Nothing is hidden behind this heading
1916 (message "EMPTY ENTRY")
1917 (setq markdown-cycle-subtree-status nil))
1918 ((>= eol eos)
1919 ;; Entire subtree is hidden in one line: open it
1920 (show-entry)
1921 (show-children)
1922 (message "CHILDREN")
1923 (setq markdown-cycle-subtree-status 'children))
1924 ((and (eq last-command this-command)
1925 (eq markdown-cycle-subtree-status 'children))
1926 ;; We just showed the children, now show everything.
1927 (show-subtree)
1928 (message "SUBTREE")
1929 (setq markdown-cycle-subtree-status 'subtree))
1931 ;; Default action: hide the subtree.
1932 (hide-subtree)
1933 (message "FOLDED")
1934 (setq markdown-cycle-subtree-status 'folded)))))
1937 (indent-for-tab-command))))
1939 ;; Based on org-shifttab from org.el.
1940 (defun markdown-shifttab ()
1941 "Global visibility cycling.
1942 Calls `markdown-cycle' with argument t."
1943 (interactive)
1944 (markdown-cycle t))
1946 (defun markdown-outline-level ()
1947 "Return the depth to which a statement is nested in the outline."
1948 (cond
1949 ((match-end 1) 1)
1950 ((match-end 2) 2)
1951 ((- (match-end 0) (match-beginning 0)))))
1953 ;;; Commands ==================================================================
1955 (defun markdown (&optional output-buffer-name)
1956 "Run `markdown' on current buffer and insert output in buffer BUFFER-OUTPUT."
1957 (interactive)
1958 (let ((title (buffer-name))
1959 (begin-region)
1960 (end-region))
1961 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1962 (setq begin-region (region-beginning)
1963 end-region (region-end))
1964 (setq begin-region (point-min)
1965 end-region (point-max)))
1967 (unless output-buffer-name
1968 (setq output-buffer-name markdown-output-buffer-name))
1970 (if markdown-command-needs-filename
1971 ;; Handle case when `markdown-command' does not read from stdin
1972 (if (not buffer-file-name)
1973 (error "Must be visiting a file")
1974 (shell-command (concat markdown-command " "
1975 (shell-quote-argument buffer-file-name))
1976 output-buffer-name))
1977 ;; Pass region to `markdown-command' via stdin
1978 (shell-command-on-region begin-region end-region markdown-command
1979 output-buffer-name))
1981 ;; Add header and footer and switch to html-mode.
1982 (save-current-buffer
1983 (set-buffer output-buffer-name)
1984 (goto-char (point-min))
1985 (unless (markdown-output-standalone-p)
1986 (markdown-add-xhtml-header-and-footer title))
1987 (html-mode))
1989 ;; Ensure buffer gets raised, even with short command output
1990 (switch-to-buffer-other-window output-buffer-name)))
1992 (defun markdown-output-standalone-p ()
1993 "Determine whether `markdown-command' output is standalone XHTML.
1994 Standalone XHTML output is identified by an occurrence of
1995 `markdown-xhtml-standalone-regexp' in the first five lines of output."
1996 (re-search-forward
1997 markdown-xhtml-standalone-regexp
1998 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
2001 (defun markdown-add-xhtml-header-and-footer (title)
2002 "Wrap XHTML header and footer with given TITLE around current buffer."
2003 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
2004 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
2005 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
2006 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
2007 "<head>\n<title>")
2008 (insert title)
2009 (insert "</title>\n")
2010 (if (> (length markdown-css-path) 0)
2011 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
2012 markdown-css-path
2013 "\" />\n"))
2014 (when (> (length markdown-xhtml-header-content) 0)
2015 (insert markdown-xhtml-header-content))
2016 (insert "\n</head>\n\n"
2017 "<body>\n\n")
2018 (goto-char (point-max))
2019 (insert "\n"
2020 "</body>\n"
2021 "</html>\n"))
2023 (defun markdown-preview ()
2024 "Run `markdown' on the current buffer and preview the output in a browser."
2025 (interactive)
2026 (markdown markdown-output-buffer-name)
2027 (browse-url-of-buffer markdown-output-buffer-name))
2029 (defun markdown-export-file-name ()
2030 "Attempt to generate a filename for Markdown output.
2031 If the current buffer is visiting a file, we construct a new
2032 output filename based on that filename. Otherwise, return nil."
2033 (when (buffer-file-name)
2034 (concat (file-name-sans-extension (buffer-file-name)) ".html")))
2036 (defun markdown-export ()
2037 "Run Markdown on the current buffer, save to a file, and return the filename.
2038 The resulting filename will be constructed using the current filename, but
2039 with the extension removed and replaced with .html."
2040 (interactive)
2041 (let ((output-file (markdown-export-file-name))
2042 (output-buffer-name))
2043 (when output-file
2044 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
2045 (markdown output-buffer-name)
2046 (with-current-buffer output-buffer-name
2047 (save-buffer)
2048 (kill-buffer-and-window))
2049 output-file)))
2051 (defun markdown-export-and-view ()
2052 "Export to XHTML using `markdown-export' and browse the resulting file."
2053 (interactive)
2054 (browse-url (markdown-export)))
2056 ;;; WikiLink Following/Markup =================================================
2058 (require 'thingatpt)
2060 (defun markdown-wiki-link-p ()
2061 "Return non-nil when `point' is at a true wiki link.
2062 A true wiki link name matches `markdown-regex-wiki-link' but does not
2063 match the current file name after conversion. This modifies the data
2064 returned by `match-data'. Note that the potential wiki link name must
2065 be available via `match-string'."
2066 (let ((case-fold-search nil))
2067 (and (thing-at-point-looking-at markdown-regex-wiki-link)
2068 (or (not buffer-file-name)
2069 (not (string-equal (buffer-file-name)
2070 (markdown-convert-wiki-link-to-filename
2071 (markdown-wiki-link-link)))))
2072 (not (save-match-data
2073 (save-excursion))))))
2075 (defun markdown-wiki-link-link ()
2076 "Return the link part of the wiki link using current match data.
2077 The location of the link component depends on the value of
2078 `markdown-wiki-link-alias-first'."
2079 (if markdown-wiki-link-alias-first
2080 (or (match-string 3) (match-string 1))
2081 (match-string 1)))
2083 (defun markdown-convert-wiki-link-to-filename (name)
2084 "Generate a filename from the wiki link NAME.
2085 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
2086 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
2087 and [[test test]] both map to Test-test.ext."
2088 (let ((basename (markdown-replace-regexp-in-string
2089 "[[:space:]\n]" markdown-link-space-sub-char name)))
2090 (when (eq major-mode 'gfm-mode)
2091 (setq basename (concat (upcase (substring basename 0 1))
2092 (substring basename 1 nil))))
2093 (concat basename
2094 (if (buffer-file-name)
2095 (concat "."
2096 (file-name-extension (buffer-file-name)))))))
2098 (defun markdown-follow-wiki-link (name)
2099 "Follow the wiki link NAME.
2100 Convert the name to a file name and call `find-file'. Ensure that
2101 the new buffer remains in `markdown-mode'."
2102 (let ((filename (markdown-convert-wiki-link-to-filename name)))
2103 (find-file filename))
2104 (markdown-mode))
2106 (defun markdown-follow-wiki-link-at-point ()
2107 "Find Wiki Link at point.
2108 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
2109 (interactive)
2110 (if (markdown-wiki-link-p)
2111 (markdown-follow-wiki-link (markdown-wiki-link-link))
2112 (error "Point is not at a Wiki Link")))
2114 (defun markdown-next-wiki-link ()
2115 "Jump to next wiki link.
2116 See `markdown-wiki-link-p'."
2117 (interactive)
2118 (if (markdown-wiki-link-p)
2119 ; At a wiki link already, move past it.
2120 (goto-char (+ 1 (match-end 0))))
2121 (save-match-data
2122 ; Search for the next wiki link and move to the beginning.
2123 (re-search-forward markdown-regex-wiki-link nil t)
2124 (goto-char (match-beginning 0))))
2126 (defun markdown-previous-wiki-link ()
2127 "Jump to previous wiki link.
2128 See `markdown-wiki-link-p'."
2129 (interactive)
2130 (re-search-backward markdown-regex-wiki-link nil t))
2132 (defun markdown-highlight-wiki-link (from to face)
2133 "Highlight the wiki link in the region between FROM and TO using FACE."
2134 (put-text-property from to 'font-lock-face face))
2136 (defun markdown-unfontify-region-wiki-links (from to)
2137 "Remove wiki link faces from the region specified by FROM and TO."
2138 (interactive "nfrom: \nnto: ")
2139 (remove-text-properties from to '(font-lock-face markdown-link-face))
2140 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
2142 (defun markdown-fontify-region-wiki-links (from to)
2143 "Search region given by FROM and TO for wiki links and fontify them.
2144 If a wiki link is found check to see if the backing file exists
2145 and highlight accordingly."
2146 (goto-char from)
2147 (while (re-search-forward markdown-regex-wiki-link to t)
2148 (let ((highlight-beginning (match-beginning 0))
2149 (highlight-end (match-end 0))
2150 (file-name
2151 (markdown-convert-wiki-link-to-filename
2152 (markdown-wiki-link-link))))
2153 (if (file-exists-p file-name)
2154 (markdown-highlight-wiki-link
2155 highlight-beginning highlight-end markdown-link-face)
2156 (markdown-highlight-wiki-link
2157 highlight-beginning highlight-end markdown-missing-link-face)))))
2159 (defun markdown-extend-changed-region (from to)
2160 "Extend region given by FROM and TO so that we can fontify all links.
2161 The region is extended to the first newline before and the first
2162 newline after."
2163 ;; start looking for the first new line before 'from
2164 (goto-char from)
2165 (re-search-backward "\n" nil t)
2166 (let ((new-from (point-min))
2167 (new-to (point-max)))
2168 (if (not (= (point) from))
2169 (setq new-from (point)))
2170 ;; do the same thing for the first new line after 'to
2171 (goto-char to)
2172 (re-search-forward "\n" nil t)
2173 (if (not (= (point) to))
2174 (setq new-to (point)))
2175 (list new-from new-to)))
2177 (defun markdown-check-change-for-wiki-link (from to change)
2178 "Check region between FROM and TO for wiki links and re-fontfy as needed.
2179 Designed to be used with the `after-change-functions' hook.
2180 CHANGE is the number of bytes of pre-change text replaced by the
2181 given range."
2182 (interactive "nfrom: \nnto: \nnchange: ")
2183 (let* ((inhibit-quit t)
2184 (modified (buffer-modified-p))
2185 (buffer-undo-list t)
2186 (inhibit-read-only t)
2187 (inhibit-point-motion-hooks t)
2188 (inhibit-modification-hooks t)
2189 (current-point (point))
2190 deactivate-mark)
2191 (unwind-protect
2192 (save-match-data
2193 (save-restriction
2194 ;; Extend the region to fontify so that it starts
2195 ;; and ends at safe places.
2196 (multiple-value-bind (new-from new-to)
2197 (markdown-extend-changed-region from to)
2198 ;; Unfontify existing fontification (start from scratch)
2199 (markdown-unfontify-region-wiki-links new-from new-to)
2200 ;; Now do the fontification.
2201 (markdown-fontify-region-wiki-links new-from new-to)))
2202 (unless modified
2203 (if (fboundp 'restore-buffer-modified-p)
2204 (restore-buffer-modified-p nil)
2205 (set-buffer-modified-p nil))))
2206 (goto-char current-point))))
2208 (defun markdown-fontify-buffer-wiki-links ()
2209 "Refontify all wiki links in the buffer."
2210 (interactive)
2211 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
2213 ;;; Miscellaneous =============================================================
2215 (defun markdown-line-number-at-pos (&optional pos)
2216 "Return (narrowed) buffer line number at position POS.
2217 If POS is nil, use current buffer location.
2218 This is an exact copy of `line-number-at-pos' for use in emacs21."
2219 (let ((opoint (or pos (point))) start)
2220 (save-excursion
2221 (goto-char (point-min))
2222 (setq start (point))
2223 (goto-char opoint)
2224 (forward-line 0)
2225 (1+ (count-lines start (point))))))
2227 (defun markdown-nobreak-p ()
2228 "Return nil if it is acceptable to break the current line at the point."
2229 ;; inside in square brackets (e.g., link anchor text)
2230 (looking-back "\\[[^]]*"))
2234 ;;; Mode definition ==========================================================
2236 (defun markdown-show-version ()
2237 "Show the version number in the minibuffer."
2238 (interactive)
2239 (message "markdown-mode, version %s" markdown-mode-version))
2241 ;;;###autoload
2242 (define-derived-mode markdown-mode text-mode "Markdown"
2243 "Major mode for editing Markdown files."
2244 ;; Natural Markdown tab width
2245 (setq tab-width 4)
2246 ;; Comments
2247 (make-local-variable 'comment-start)
2248 (setq comment-start "<!-- ")
2249 (make-local-variable 'comment-end)
2250 (setq comment-end " -->")
2251 (make-local-variable 'comment-start-skip)
2252 (setq comment-start-skip "<!--[ \t]*")
2253 (make-local-variable 'comment-column)
2254 (setq comment-column 0)
2255 ;; Font lock.
2256 (set (make-local-variable 'font-lock-defaults)
2257 '(markdown-mode-font-lock-keywords))
2258 (set (make-local-variable 'font-lock-multiline) t)
2259 ;; For menu support in XEmacs
2260 (easy-menu-add markdown-mode-menu markdown-mode-map)
2261 ;; Make filling work with lists (unordered, ordered, and definition)
2262 (set (make-local-variable 'paragraph-start)
2263 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
2264 ;; Outline mode
2265 (make-local-variable 'outline-regexp)
2266 (setq outline-regexp markdown-regex-header)
2267 (make-local-variable 'outline-level)
2268 (setq outline-level 'markdown-outline-level)
2269 ;; Cause use of ellipses for invisible text.
2270 (add-to-invisibility-spec '(outline . t))
2271 ;; Indentation and filling
2272 (make-local-variable 'fill-nobreak-predicate)
2273 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
2274 (setq indent-line-function markdown-indent-function)
2276 ;; Prepare hooks for XEmacs compatibility
2277 (when (featurep 'xemacs)
2278 (make-local-hook 'after-change-functions)
2279 (make-local-hook 'font-lock-extend-region-functions)
2280 (make-local-hook 'window-configuration-change-hook))
2282 ;; Multiline font lock
2283 (add-hook 'font-lock-extend-region-functions
2284 'markdown-font-lock-extend-region)
2286 ;; Anytime text changes make sure it gets fontified correctly
2287 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
2289 ;; If we left the buffer there is a really good chance we were
2290 ;; creating one of the wiki link documents. Make sure we get
2291 ;; refontified when we come back.
2292 (add-hook 'window-configuration-change-hook
2293 'markdown-fontify-buffer-wiki-links t t)
2295 ;; do the initial link fontification
2296 (markdown-fontify-buffer-wiki-links))
2298 ;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
2300 ;;; GitHub Flavored Markdown Mode ============================================
2302 (define-derived-mode gfm-mode markdown-mode "GFM"
2303 "Major mode for editing GitHub Flavored Markdown files."
2304 (setq markdown-link-space-sub-char "-")
2305 (auto-fill-mode 0)
2306 ;; Use visual-line-mode if available, fall back to longlines-mode:
2307 (if (fboundp 'visual-line-mode)
2308 (visual-line-mode 1)
2309 (longlines-mode 1)))
2311 (provide 'markdown-mode)
2313 ;;; markdown-mode.el ends here