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