Fix docstring
[markdown-mode.git] / markdown-mode.el
blobe4afa9967e086b27ce34d2a0097f687211516136
1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2013 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>
20 ;; Copyright (C) 2011-2012 Donald Ephraim Curtis <dcurtis@milkbox.net>
21 ;; Copyright (C) 2012 Akinori Musha <knu@idaemons.org>
22 ;; Copyright (C) 2012 Zhenlei Jia <zhenlei.jia@gmail.com>
23 ;; Copyright (C) 2012 Peter Jones <pjones@pmade.com>
24 ;; Copyright (C) 2013 Matus Goljer <dota.keys@gmail.com>
26 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
27 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
28 ;; Created: May 24, 2007
29 ;; Version: 1.9
30 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
31 ;; URL: http://jblevins.org/projects/markdown-mode/
33 ;; This file is not part of GNU Emacs.
35 ;; This program is free software; you can redistribute it and/or modify
36 ;; it under the terms of the GNU General Public License as published by
37 ;; the Free Software Foundation; either version 2, or (at your option)
38 ;; any later version.
40 ;; This program is distributed in the hope that it will be useful,
41 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
42 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 ;; GNU General Public License for more details.
45 ;; You should have received a copy of the GNU General Public License
46 ;; along with this program; if not, write to the Free Software
47 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
48 ;; Boston, MA 02110-1301, USA.
50 ;;; Commentary:
52 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
53 ;; text files in GNU Emacs. markdown-mode is free software, licensed
54 ;; under the GNU GPL.
56 ;; [Markdown]: http://daringfireball.net/projects/markdown/
58 ;; The latest stable version is markdown-mode 1.9, released on January 25, 2013:
60 ;; * [markdown-mode.el][]
61 ;; * [Screenshot][][^theme]
62 ;; * [Release notes][]
64 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
65 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
66 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-9
68 ;; [^theme]: The theme used in the screenshot is
69 ;; [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
71 ;; markdown-mode is also available in several package managers, including:
73 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
74 ;; * RedHat and Fedora Linux: [emacs-goodies][]
75 ;; * OpenBSD: [textproc/markdown-mode][]
76 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
77 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
78 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
80 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
81 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
82 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
83 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
84 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
85 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
86 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
88 ;; The latest development version can be downloaded directly
89 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
90 ;; (browsable and clonable) Git repository at
91 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
92 ;; including the full project history, can be cloned via the Git protocol
93 ;; by running
95 ;; git clone git://jblevins.org/git/markdown-mode.git
97 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
99 ;;; Dependencies:
101 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
102 ;; 19 and XEmacs 19, which provides a uniform interface for creating
103 ;; menus in GNU Emacs and XEmacs.
105 ;;; Installation:
107 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
108 ;; the following lines to your `.emacs` file to associate markdown-mode
109 ;; with `.text` files:
111 ;; (autoload 'markdown-mode "markdown-mode"
112 ;; "Major mode for editing Markdown files" t)
113 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
115 ;; There is no consensus on an official file extension so change `.text` to
116 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
118 ;;; Customization:
120 ;; Although no configuration is *necessary* there are a few things
121 ;; that can be customized. The `M-x customize-mode` command
122 ;; provides an interface to all of the possible customizations:
124 ;; * `markdown-command' - the command used to run Markdown (default:
125 ;; `markdown'). This variable may be customized to pass
126 ;; command-line options to your Markdown processor of choice, but
127 ;; this command must accept input from `stdin`. If it does not, a
128 ;; simple wrapper script can be used to write `stdin` to a file
129 ;; and then pass that file to your Markdown interpreter. Ideally,
130 ;; this command will produce an XHTML fragment around which
131 ;; markdown-mode will wrap a header and footer (which can be
132 ;; further customized). However, it attempts to detect whether
133 ;; the command produces standalone XHTML output (via
134 ;; `markdown-xhtml-standalone-regexp'), in which case no header
135 ;; and footer content will be added.
137 ;; * `markdown-command-needs-filename' - set to non-nil if
138 ;; `markdown-command' does not accept input from stdin (default: nil).
139 ;; Instead, it will be passed a filename as the final command-line
140 ;; option. As a result, you will only be able to run Markdown
141 ;; from buffers which are visiting a file.
143 ;; * `markdown-open-command' - the command used for calling a standalone
144 ;; Markdown previewer which is capable of opening Markdown source files
145 ;; directly (default: `nil'). This command will be called
146 ;; with a single argument, the filename of the current buffer.
147 ;; A representative program is the Mac app [Marked][], a
148 ;; live-updating MultiMarkdown previewer which has a command line
149 ;; utility at `/usr/local/bin/mark`.
151 ;; * `markdown-hr-strings' - list of strings to use when inserting
152 ;; horizontal rules, in decreasing order of priority.
154 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
155 ;; underscores for bold instead of two asterisks (default: `nil').
157 ;; * `markdown-italic-underscore' - set to a non-nil value to use
158 ;; underscores for italic instead of asterisks (default: `nil').
160 ;; * `markdown-indent-function' - the function to use for automatic
161 ;; indentation (default: `markdown-indent-line').
163 ;; * `markdown-indent-on-enter' - set to a non-nil value to
164 ;; automatically indent new lines when the enter key is pressed
165 ;; (default: `t')
167 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
168 ;; to automatically open a linked document in a new buffer if the
169 ;; cursor is an wiki link
170 ;; (default: `t')
172 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
173 ;; treat aliased wiki links like `[[link text|PageName]]`.
174 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
176 ;; * `markdown-uri-types' - a list of protocols for URIs that
177 ;; `markdown-mode' should highlight.
179 ;; * `markdown-enable-math' - syntax highlighting for
180 ;; LaTeX fragments (default: `nil').
182 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
184 ;; * `markdown-content-type' - when set to a nonempty string, an
185 ;; `http-equiv` attribute will be included in the XHTML `<head>`
186 ;; block. If needed, the suggested values are
187 ;; `application/xhtml+xml` or `text/html`.
189 ;; * `markdown-coding-system' - used for specifying the character
190 ;; set identifier in the `http-equiv` attribute (see
191 ;; `markdown-content-type'). When set to `nil',
192 ;; `buffer-file-coding-system' will be used (and falling back to
193 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
194 ;; and `iso-latin-1'.
196 ;; * `markdown-xhtml-header-content' - additional content to include
197 ;; in the XHTML `<head>` block.
199 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
200 ;; indicates whether the output of `markdown-command' is standalone
201 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
202 ;; this is not matched, we assume this output is a fragment and add
203 ;; our own header and footer.
205 ;; * `markdown-link-space-sub-char' - a character to replace spaces
206 ;; when mapping wiki links to filenames (default: `_`).
207 ;; For example, use an underscore for compatibility with the
208 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
209 ;; with GitHub wiki links.
211 ;; Additionally, the faces used for syntax highlighting can be modified to
212 ;; your liking by issuing `M-x customize-group RET markdown-faces`
213 ;; or by using the "Markdown Faces" link at the bottom of the mode
214 ;; customization screen.
216 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
218 ;;; Usage:
220 ;; Keybindings are grouped by prefixes based on their function. For
221 ;; example, commands dealing with headers begin with `C-c C-t`. The
222 ;; primary commands in each group will are described below. You can
223 ;; obtain a list of all keybindings by pressing `C-c C-h`.
225 ;; * Anchors: `C-c C-a`
227 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
228 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
229 ;; The label definition will be placed at the end of the current
230 ;; block. `C-c C-a w` acts similarly for wiki links of the form
231 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
232 ;; text in the region is used as the link text.
234 ;; * Commands: `C-c C-c`
236 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
237 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
238 ;; runs Markdown on the current buffer and previews, stores the
239 ;; output in a temporary file, and displays the file in a browser.
240 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
241 ;; and save the result in the file `basename.html`, where
242 ;; `basename` is the name of the Markdown file with the extension
243 ;; removed. *Export and View:* press `C-c C-c v` to export the
244 ;; file and view it in a browser. **For both export commands, the
245 ;; output file will be overwritten without notice.**
246 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
247 ;; using `markdown-open-command'.
249 ;; To summarize:
251 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
252 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
253 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
254 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
255 ;; - `C-c C-c w`: `markdown-command' > kill ring.
256 ;; - `C-c C-c o`: `markdown-open-command'.
258 ;; `C-c C-c c` will check for undefined references. If there are
259 ;; any, a small buffer will open with a list of undefined
260 ;; references and the line numbers on which they appear. In Emacs
261 ;; 22 and greater, selecting a reference from this list and
262 ;; pressing `RET` will insert an empty reference definition at the
263 ;; end of the buffer. Similarly, selecting the line number will
264 ;; jump to the corresponding line.
266 ;; `C-c C-c n` will clean up the numbering of ordered lists.
268 ;; * Images: `C-c C-i`
270 ;; `C-c C-i i` inserts an image, using the active region (if any)
271 ;; as the alt text.
273 ;; * Physical styles: `C-c C-p`
275 ;; These commands all act on text in the active region, if any,
276 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
277 ;; the selected text bold, `C-c C-p f` formats the region as
278 ;; fixed-width text, and `C-c C-p i` is used for italic text.
280 ;; * Logical styles: `C-c C-s`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. Logical styles
284 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
285 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
286 ;; (`C-c C-s s`).
288 ;; * Headers: `C-c C-t`
290 ;; All header commands use text in the active region, if any, as
291 ;; the header text. Otherwise, if the current line is not blank,
292 ;; use the text on the current line. Finally, prompt for header
293 ;; text if there is no active region and the current line is
294 ;; blank. To insert an atx or hash style level-n
295 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
296 ;; top-level setext or underline style header press `C-c C-t t`
297 ;; (mnemonic: title) and for a second-level underline-style header
298 ;; press `C-c C-t s` (mnemonic: section).
300 ;; If the point is at a header, these commands will replace the
301 ;; existing markup in order to update the level and/or type of the
302 ;; header. To remove the markup of the header at the point, press
303 ;; `C-c C-t 0`.
305 ;; * Footnotes: `C-c C-f`
307 ;; To create a new footnote at the point, press `C-c C-f n`.
308 ;; Press `C-c C-f g` with the point at a footnote to jump to the
309 ;; location where the footnote text is defined. Then, press
310 ;; `C-c C-f b` to return to the footnote marker in the main text.
311 ;; When the point is at a footnote marker or in the body of a
312 ;; footnote, press `C-c C-f k` to kill the footnote and add the
313 ;; text to the kill ring.
315 ;; * Other elements:
317 ;; `C-c -` inserts a horizontal rule.
319 ;; * Following Links:
321 ;; Press `C-c C-o` when the point is on an inline or reference
322 ;; link to open the URL in a browser. When the point is at a
323 ;; wiki link, open it in another buffer (in the current window,
324 ;; or in the other window with the `C-u` prefix).
326 ;; * Wiki-Link Navigation:
328 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
329 ;; wiki links, respectively.
331 ;; * Outline Navigation:
333 ;; Navigation between headings is possible using `outline-mode'.
334 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
335 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
336 ;; next and previous visible headings at the same level as the one
337 ;; at the point. Finally, `C-M-u` will move up to a lower-level
338 ;; (more inclusive) visible heading.
340 ;; * Movement by Block:
342 ;; markdown-mode supports the usual Emacs paragraph movement with
343 ;; `M-{` and `M-}`. These commands treat list items as
344 ;; paragraphs, so they will stop at each line within a block of
345 ;; list items. Additionally, markdown-mode includes movement
346 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
347 ;; of an entire block of text (with blocks being separated by at
348 ;; least one blank line).
350 ;; * Movement by Defun:
352 ;; The usual Emacs commands can be used to move by defuns
353 ;; (top-level major definitions). In markdown-mode, a defun
354 ;; is a section. As usual, `C-M-a` will move the point to
355 ;; the beginning of the current or preceding defun, `C-M-e`
356 ;; will move to the end of the current or following defun,
357 ;; and `C-M-h` will put the region around the entire defun.
359 ;; Many of the commands described above behave differently depending on
360 ;; whether Transient Mark mode is enabled or not. When it makes sense,
361 ;; if Transient Mark mode is on and a region is active, the command
362 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
363 ;; bold). For users who prefer to work outside of Transient Mark mode,
364 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
366 ;; When applicable, commands that specifically act on the region even
367 ;; outside of Transient Mark mode have the same keybinding as the with
368 ;; the exception of an additional `C-` prefix. For example,
369 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
370 ;; the region in Transient Mark mode while `markdown-blockquote-region'
371 ;; is bound to `C-c C-s C-b` and always applies to the region (when
372 ;; nonempty).
374 ;; markdown-mode attempts to be flexible in how it handles
375 ;; indentation. When you press `TAB` repeatedly, the point will cycle
376 ;; through several possible indentation levels corresponding to things
377 ;; you might have in mind when you press `RET` at the end of a line or
378 ;; `TAB`. For example, you may want to start a new list item,
379 ;; continue a list item with hanging indentation, indent for a nested
380 ;; pre block, and so on.
382 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
383 ;; visibility cycling for atx- or hash-style headers. There are two
384 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
385 ;; the table of contents view (headers only), outline view (top-level
386 ;; headers only), and the full document view. Pressing `TAB` while the
387 ;; point is at a header will cycle through levels of visibility for the
388 ;; subtree: completely folded, visible children, and fully visible.
389 ;; Note that mixing hash and underline style headers will give undesired
390 ;; results.
392 ;;; Extensions:
394 ;; Besides supporting the basic Markdown syntax, markdown-mode also
395 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
396 ;; links may be followed automatically by pressing the enter key when
397 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
398 ;; auto-following on enter key may be controlled with the
399 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
400 ;; `M-n` to quickly jump to the previous and next wiki links,
401 ;; respectively. Aliased or piped wiki links of the form
402 ;; `[[link text|PageName]]` are also supported. Since some wikis
403 ;; reverse these components, set `markdown-wiki-link-alias-first'
404 ;; to nil to treat them as `[[PageName|link text]]`.
406 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
407 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
408 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
409 ;; You can do this either by using `M-x customize-group markdown`
410 ;; or by placing the following in your `.emacs` file:
412 ;; (defun markdown-custom ()
413 ;; "markdown-mode-hook"
414 ;; (setq markdown-command "markdown | smartypants"))
415 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
417 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
419 ;; Experimental syntax highlighting for mathematical expressions written
420 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
421 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
422 ;; either via customize or by placing `(setq markdown-enable-itex t)`
423 ;; in `.emacs`, and restarting Emacs.
425 ;;; GitHub Flavored Markdown:
427 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
428 ;; available. The GitHub implementation of differs slightly from
429 ;; standard Markdown. The most important differences are that
430 ;; newlines are significant, triggering hard line breaks, and that
431 ;; underscores inside of words (e.g., variable names) need not be
432 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
433 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
434 ;; not available). Underscores inside of words (such as
435 ;; test_variable) will not trigger emphasis.
437 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
438 ;; replacing spaces in filenames and where the first letter of the
439 ;; filename capitalized. For example, `[[wiki link]]' will map to a
440 ;; file named `Wiki-link` with the same extension as the current file.
442 ;; GFM code blocks, with optional programming language keywords, will
443 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
444 ;; is an active region, the text in the region will be placed inside
445 ;; the code block. You will be prompted for the name of the language,
446 ;; but may press enter to continue without naming a language.
448 ;; For a more complete GitHub-flavored markdown experience, consider
449 ;; adding README.md to your `auto-mode-alist':
451 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
453 ;; For GFM preview can be powered by setting `markdown-command' to
454 ;; use [Docter][]. This may also be configured to work with [Marked][]
455 ;; for `markdown-open-command'.
457 ;; [GFM]: http://github.github.com/github-flavored-markdown/
458 ;; [Docter]: https://github.com/alampros/Docter
460 ;;; Acknowledgments:
462 ;; markdown-mode has benefited greatly from the efforts of the
463 ;; following people:
465 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
466 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
467 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
468 ;; GitHub Flavored Markdown mode (`gfm-mode').
469 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
470 ;; `markdown' with an active region.
471 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
472 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
473 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
474 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
475 ;; visibility cycling functionality was derived, and for a bug fix
476 ;; related to orgtbl-mode.
477 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
478 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
479 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
480 ;; compatibility and custom CSS.
481 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
482 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
483 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
484 ;; comment matching functions were derived.
485 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
486 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
487 ;; functions, bug reports regarding indentation, and
488 ;; fixes for byte-compilation warnings.
489 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
490 ;; enhancements.
491 ;; * George Ogata <george.ogata@gmail.com> for fixing several
492 ;; byte-compilation warnings.
493 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
494 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
495 ;; customizations and XHTML export.
496 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
497 ;; Markdown processors which do not accept input from stdin.
498 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
499 ;; regarding the cl dependency and auto-fill-mode and indentation.
500 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
501 ;; substitution character for mapping wiki links to filenames.
502 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
503 ;; escape shell commands.
504 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
505 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
506 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
507 ;; Emacs Lisp coding conventions.
508 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
509 ;; regexp, refactoring the compilation and preview functions,
510 ;; heading font-lock generalizations, list renumbering,
511 ;; and kill ring save.
512 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
513 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
514 ;; for an autoload token for `gfm-mode'.
515 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
516 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
517 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
518 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
519 ;; declaration in XHTML output.
520 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
521 ;; un-indentation function.
522 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
523 ;; and GFM code block insertion.
524 ;; * Peter Jones <pjones@pmade.com> for link following functions.
525 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
526 ;; externally modified files.
527 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
528 ;; related to orgtbl-mode.
529 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
530 ;; export hooks and unit test improvements.
531 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
533 ;;; Bugs:
535 ;; Although markdown-mode is developed and tested primarily using
536 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
537 ;; priority.
539 ;; If you find any bugs in markdown-mode, please construct a test case
540 ;; or a patch and email me at <jrblevin@sdf.org>.
542 ;;; History:
544 ;; markdown-mode was written and is maintained by Jason Blevins. The
545 ;; first version was released on May 24, 2007.
547 ;; * 2007-05-24: Version 1.1
548 ;; * 2007-05-25: Version 1.2
549 ;; * 2007-06-05: [Version 1.3][]
550 ;; * 2007-06-29: Version 1.4
551 ;; * 2008-05-24: [Version 1.5][]
552 ;; * 2008-06-04: [Version 1.6][]
553 ;; * 2009-10-01: [Version 1.7][]
554 ;; * 2011-08-12: [Version 1.8][]
555 ;; * 2011-08-15: [Version 1.8.1][]
556 ;; * 2013-01-25: [Version 1.9][]
558 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
559 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
560 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
561 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
562 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
563 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
564 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
567 ;;; Code:
569 (require 'easymenu)
570 (require 'outline)
571 (eval-when-compile (require 'cl))
574 ;;; Constants =================================================================
576 (defconst markdown-mode-version "1.9"
577 "Markdown mode version number.")
579 (defconst markdown-output-buffer-name "*markdown-output*"
580 "Name of temporary buffer for markdown command output.")
583 ;;; Customizable Variables ====================================================
585 (defvar markdown-mode-hook nil
586 "Hook run when entering Markdown mode.")
588 (defvar markdown-before-export-hooks nil
589 "Hook run before output XHTML.
590 This hook is abnormal and registered functions are given an argument that is output filename.")
592 (defvar markdown-after-export-hooks nil
593 "Hook run after output XHTML.
594 This hook is abnormal and registered functions are given an argument that is output filename.")
596 (defgroup markdown nil
597 "Major mode for editing text files in Markdown format."
598 :prefix "markdown-"
599 :group 'wp
600 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
602 (defcustom markdown-command "markdown"
603 "Command to run markdown."
604 :group 'markdown
605 :type 'string)
607 (defcustom markdown-command-needs-filename nil
608 "Set to non-nil if `markdown-command' does not accept input from stdin.
609 Instead, it will be passed a filename as the final command line
610 option. As a result, you will only be able to run Markdown from
611 buffers which are visiting a file."
612 :group 'markdown
613 :type 'boolean)
615 (defcustom markdown-open-command nil
616 "Command used for opening Markdown files directly.
617 For example, a standalone Markdown previewer. This command will
618 be called with a single argument: the filename of the current
619 buffer."
620 :group 'markdown
621 :type 'string)
623 (defcustom markdown-hr-strings
624 '("* * * * *"
625 "---------"
626 "* * * * * * * * * * * * * * * * * * * *"
627 "---------------------------------------"
628 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
629 "-------------------------------------------------------------------------------")
630 "Strings to use when inserting horizontal rules.
631 The first string in the list will be the default when inserting a
632 horizontal rule. Strings should be listed in increasing order of
633 prominence for use with promotion and demotion functions."
634 :group 'markdown
635 :type 'list)
637 (defcustom markdown-bold-underscore nil
638 "Use two underscores for bold instead of two asterisks."
639 :group 'markdown
640 :type 'boolean)
642 (defcustom markdown-italic-underscore nil
643 "Use underscores for italic instead of asterisks."
644 :group 'markdown
645 :type 'boolean)
647 (defcustom markdown-indent-function 'markdown-indent-line
648 "Function to use to indent."
649 :group 'markdown
650 :type 'function)
652 (defcustom markdown-indent-on-enter t
653 "Automatically indent new lines when enter key is pressed."
654 :group 'markdown
655 :type 'boolean)
657 (defcustom markdown-follow-wiki-link-on-enter t
658 "Follow wiki link at point (if any) when the enter key is pressed."
659 :group 'markdown
660 :type 'boolean)
662 (defcustom markdown-wiki-link-alias-first t
663 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
664 Otherwise, they will be treated as [[PageName|alias text]]."
665 :group 'markdown
666 :type 'boolean)
668 (defcustom markdown-uri-types
669 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
670 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
671 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
672 "Link types for syntax highlighting of URIs."
673 :group 'markdown
674 :type 'list)
676 (defcustom markdown-enable-math nil
677 "Syntax highlighting for inline LaTeX expressions.
678 This will not take effect until Emacs is restarted."
679 :group 'markdown
680 :type 'boolean)
682 (defcustom markdown-css-path ""
683 "URL of CSS file to link to in the output XHTML."
684 :group 'markdown
685 :type 'string)
687 (defcustom markdown-content-type ""
688 "Content type string for the http-equiv header in XHTML output.
689 When set to a non-empty string, insert the http-equiv attribute.
690 Otherwise, this attribute is omitted."
691 :group 'markdown
692 :type 'string)
694 (defcustom markdown-coding-system nil
695 "Character set string for the http-equiv header in XHTML output.
696 Defaults to `buffer-file-coding-system' (and falling back to
697 `iso-8859-1' when not available). Common settings are `utf-8'
698 and `iso-latin-1'. Use `list-coding-systems' for more choices."
699 :group 'markdown
700 :type 'coding-system)
702 (defcustom markdown-xhtml-header-content ""
703 "Additional content to include in the XHTML <head> block."
704 :group 'markdown
705 :type 'string)
707 (defcustom markdown-xhtml-standalone-regexp
708 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
709 "Regexp indicating whether `markdown-command' output is standalone XHTML."
710 :group 'markdown
711 :type 'regexp)
713 (defcustom markdown-link-space-sub-char
715 "Character to use instead of spaces when mapping wiki links to filenames."
716 :group 'markdown
717 :type 'string)
719 (defcustom markdown-footnote-location 'end
720 "Position where new footnotes are inserted in the document."
721 :group 'markdown
722 :type '(choice (const :tag "At the end of the document" end)
723 (const :tag "Immediately after the paragraph" immediately)
724 (const :tag "Before next header" header)))
727 ;;; Font Lock =================================================================
729 (require 'font-lock)
731 (defvar markdown-italic-face 'markdown-italic-face
732 "Face name to use for italic text.")
734 (defvar markdown-bold-face 'markdown-bold-face
735 "Face name to use for bold text.")
737 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
738 "Face name to use as a base for header delimiters.")
740 (defvar markdown-header-rule-face 'markdown-header-rule-face
741 "Face name to use as a base for header rules.")
743 (defvar markdown-header-face 'markdown-header-face
744 "Face name to use as a base for headers.")
746 (defvar markdown-header-face-1 'markdown-header-face-1
747 "Face name to use for level-1 headers.")
749 (defvar markdown-header-face-2 'markdown-header-face-2
750 "Face name to use for level-2 headers.")
752 (defvar markdown-header-face-3 'markdown-header-face-3
753 "Face name to use for level-3 headers.")
755 (defvar markdown-header-face-4 'markdown-header-face-4
756 "Face name to use for level-4 headers.")
758 (defvar markdown-header-face-5 'markdown-header-face-5
759 "Face name to use for level-5 headers.")
761 (defvar markdown-header-face-6 'markdown-header-face-6
762 "Face name to use for level-6 headers.")
764 (defvar markdown-inline-code-face 'markdown-inline-code-face
765 "Face name to use for inline code.")
767 (defvar markdown-list-face 'markdown-list-face
768 "Face name to use for list markers.")
770 (defvar markdown-blockquote-face 'markdown-blockquote-face
771 "Face name to use for blockquote.")
773 (defvar markdown-pre-face 'markdown-pre-face
774 "Face name to use for preformatted text.")
776 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
777 "Face name to use for programming language identifiers.")
779 (defvar markdown-link-face 'markdown-link-face
780 "Face name to use for links.")
782 (defvar markdown-missing-link-face 'markdown-missing-link-face
783 "Face name to use for links where the linked file does not exist.")
785 (defvar markdown-reference-face 'markdown-reference-face
786 "Face name to use for reference.")
788 (defvar markdown-footnote-face 'markdown-footnote-face
789 "Face name to use for footnote identifiers.")
791 (defvar markdown-url-face 'markdown-url-face
792 "Face name to use for URLs.")
794 (defvar markdown-link-title-face 'markdown-link-title-face
795 "Face name to use for reference link titles.")
797 (defvar markdown-comment-face 'markdown-comment-face
798 "Face name to use for HTML comments.")
800 (defvar markdown-math-face 'markdown-math-face
801 "Face name to use for LaTeX expressions.")
803 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
804 "Face name to use for metadata keys.")
806 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
807 "Face name to use for metadata values.")
809 (defgroup markdown-faces nil
810 "Faces used in Markdown Mode"
811 :group 'markdown
812 :group 'faces)
814 (defface markdown-italic-face
815 '((t (:inherit font-lock-variable-name-face :slant italic)))
816 "Face for italic text."
817 :group 'markdown-faces)
819 (defface markdown-bold-face
820 '((t (:inherit font-lock-variable-name-face :weight bold)))
821 "Face for bold text."
822 :group 'markdown-faces)
824 (defface markdown-header-rule-face
825 '((t (:inherit font-lock-function-name-face :weight bold)))
826 "Base face for headers rules."
827 :group 'markdown-faces)
829 (defface markdown-header-delimiter-face
830 '((t (:inherit font-lock-function-name-face :weight bold)))
831 "Base face for headers hash delimiter."
832 :group 'markdown-faces)
834 (defface markdown-header-face
835 '((t (:inherit font-lock-function-name-face :weight bold)))
836 "Base face for headers."
837 :group 'markdown-faces)
839 (defface markdown-header-face-1
840 '((t (:inherit markdown-header-face)))
841 "Face for level-1 headers."
842 :group 'markdown-faces)
844 (defface markdown-header-face-2
845 '((t (:inherit markdown-header-face)))
846 "Face for level-2 headers."
847 :group 'markdown-faces)
849 (defface markdown-header-face-3
850 '((t (:inherit markdown-header-face)))
851 "Face for level-3 headers."
852 :group 'markdown-faces)
854 (defface markdown-header-face-4
855 '((t (:inherit markdown-header-face)))
856 "Face for level-4 headers."
857 :group 'markdown-faces)
859 (defface markdown-header-face-5
860 '((t (:inherit markdown-header-face)))
861 "Face for level-5 headers."
862 :group 'markdown-faces)
864 (defface markdown-header-face-6
865 '((t (:inherit markdown-header-face)))
866 "Face for level-6 headers."
867 :group 'markdown-faces)
869 (defface markdown-inline-code-face
870 '((t (:inherit font-lock-constant-face)))
871 "Face for inline code."
872 :group 'markdown-faces)
874 (defface markdown-list-face
875 '((t (:inherit font-lock-builtin-face)))
876 "Face for list item markers."
877 :group 'markdown-faces)
879 (defface markdown-blockquote-face
880 '((t (:inherit font-lock-doc-face)))
881 "Face for blockquote sections."
882 :group 'markdown-faces)
884 (defface markdown-pre-face
885 '((t (:inherit font-lock-constant-face)))
886 "Face for preformatted text."
887 :group 'markdown-faces)
889 (defface markdown-language-keyword-face
890 '((t (:inherit font-lock-type-face)))
891 "Face for programming language identifiers."
892 :group 'markdown-faces)
894 (defface markdown-link-face
895 '((t (:inherit font-lock-keyword-face)))
896 "Face for links."
897 :group 'markdown-faces)
899 (defface markdown-missing-link-face
900 '((t (:inherit font-lock-warning-face)))
901 "Face for missing links."
902 :group 'markdown-faces)
904 (defface markdown-reference-face
905 '((t (:inherit font-lock-type-face)))
906 "Face for link references."
907 :group 'markdown-faces)
909 (defface markdown-footnote-face
910 '((t (:inherit font-lock-keyword-face)))
911 "Face for footnote markers."
912 :group 'markdown-faces)
914 (defface markdown-url-face
915 '((t (:inherit font-lock-string-face)))
916 "Face for URLs."
917 :group 'markdown-faces)
919 (defface markdown-link-title-face
920 '((t (:inherit font-lock-comment-face)))
921 "Face for reference link titles."
922 :group 'markdown-faces)
924 (defface markdown-comment-face
925 '((t (:inherit font-lock-comment-face)))
926 "Face for HTML comments."
927 :group 'markdown-faces)
929 (defface markdown-math-face
930 '((t (:inherit font-lock-string-face)))
931 "Face for LaTeX expressions."
932 :group 'markdown-faces)
934 (defface markdown-metadata-key-face
935 '((t (:inherit font-lock-variable-name-face)))
936 "Face for metadata keys."
937 :group 'markdown-faces)
939 (defface markdown-metadata-value-face
940 '((t (:inherit font-lock-string-face)))
941 "Face for metadata values."
942 :group 'markdown-faces)
944 (defconst markdown-regex-link-inline
945 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
946 "Regular expression for a [text](file) or an image link ![text](file).")
948 (defconst markdown-regex-link-reference
949 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
950 "Regular expression for a reference link [text][id].")
952 (defconst markdown-regex-reference-definition
953 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
954 "Regular expression for a link definition [id]: ...")
956 (defconst markdown-regex-footnote
957 "\\(\\[\\^.+?\\]\\)"
958 "Regular expression for a footnote marker [^fn].")
960 (defconst markdown-regex-header
961 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
962 "Regexp identifying Markdown headers.")
964 (defconst markdown-regex-header-1-atx
965 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
966 "Regular expression for level 1 atx-style (hash mark) headers.")
968 (defconst markdown-regex-header-2-atx
969 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
970 "Regular expression for level 2 atx-style (hash mark) headers.")
972 (defconst markdown-regex-header-3-atx
973 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
974 "Regular expression for level 3 atx-style (hash mark) headers.")
976 (defconst markdown-regex-header-4-atx
977 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
978 "Regular expression for level 4 atx-style (hash mark) headers.")
980 (defconst markdown-regex-header-5-atx
981 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
982 "Regular expression for level 5 atx-style (hash mark) headers.")
984 (defconst markdown-regex-header-6-atx
985 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
986 "Regular expression for level 6 atx-style (hash mark) headers.")
988 (defconst markdown-regex-header-1-setext
989 "^\\(.*\\)\n\\(=+\\)$"
990 "Regular expression for level 1 setext-style (underline) headers.")
992 (defconst markdown-regex-header-2-setext
993 "^\\(.*\\)\n\\(-+\\)$"
994 "Regular expression for level 2 setext-style (underline) headers.")
996 (defconst markdown-regex-header-setext
997 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
998 "Regular expression for generic setext-style (underline) headers.")
1000 (defconst markdown-regex-header-atx
1001 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1002 "Regular expression for generic atx-style (hash mark) headers.")
1004 (defconst markdown-regex-hr
1005 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1006 "Regular expression for matching Markdown horizontal rules.")
1008 (defconst markdown-regex-code
1009 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1010 "Regular expression for matching inline code fragments.
1012 The first group ensures that the leading backquote character
1013 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1014 character, including newlines, but not two newlines in a row.
1015 The final group requires that the character following the code
1016 fragment is not a backquote.")
1018 (defconst markdown-regex-pre
1019 "^\\( \\|\t\\).*$"
1020 "Regular expression for matching preformatted text sections.")
1022 (defconst markdown-regex-list
1023 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1024 "Regular expression for matching list items.")
1026 (defconst markdown-regex-bold
1027 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1028 "Regular expression for matching bold text.
1029 Group 1 matches the character before the opening asterisk or
1030 underscore, if any, ensuring that it is not a backslash escape.
1031 Group 2 matches the entire expression, including delimiters.
1032 Groups 3 and 5 matches the opening and closing delimiters.
1033 Group 4 matches the text inside the delimiters.")
1035 (defconst markdown-regex-italic
1036 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1037 "Regular expression for matching italic text.
1038 Group 1 matches the character before the opening asterisk or
1039 underscore, if any, ensuring that it is not a backslash escape.
1040 Group 2 matches the entire expression, including delimiters.
1041 Groups 3 and 5 matches the opening and closing delimiters.
1042 Group 4 matches the text inside the delimiters.")
1044 (defconst markdown-regex-gfm-italic
1045 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1046 "Regular expression for matching italic text in GitHub-flavored Markdown.
1047 Underscores in words are not treated as special.")
1049 (defconst markdown-regex-blockquote
1050 "^[ \t]*\\(>\\).*$"
1051 "Regular expression for matching blockquote lines.")
1053 (defconst markdown-regex-line-break
1054 " $"
1055 "Regular expression for matching line breaks.")
1057 (defconst markdown-regex-wiki-link
1058 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1059 "Regular expression for matching wiki links.
1060 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1061 wiki links of the form [[PageName|link text]]. In this regular
1062 expression, #1 matches the page name and #3 matches the link
1063 text.")
1065 (defconst markdown-regex-uri
1066 (concat
1067 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
1068 "\\):[^]\t\n\r<>,;() ]+")
1069 "Regular expression for matching inline URIs.")
1071 (defconst markdown-regex-angle-uri
1072 (concat
1073 "\\(<\\)\\(\\(?:"
1074 (mapconcat 'identity markdown-uri-types "\\|")
1075 "\\):[^]\t\n\r<>,;()]+\\)\\(>\\)")
1076 "Regular expression for matching inline URIs in angle brackets.")
1078 (defconst markdown-regex-email
1079 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
1080 "Regular expression for matching inline email addresses.")
1082 (defconst markdown-regex-block-separator
1083 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1084 "Regular expression for matching block boundaries.")
1086 (defconst markdown-regex-latex-expression
1087 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1088 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1090 (defconst markdown-regex-latex-display
1091 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1092 "Regular expression for itex \[..\] display mode expressions.")
1094 (defconst markdown-regex-multimarkdown-metadata
1095 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1096 "Regular expression for matching MultiMarkdown metadata.")
1098 (defconst markdown-regex-pandoc-metadata
1099 "^\\(%\\)[ \t]*\\(.*\\)$"
1100 "Regular expression for matching Pandoc metadata.")
1102 (defvar markdown-mode-font-lock-keywords-basic
1103 (list
1104 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1105 (2 markdown-metadata-value-face)))
1106 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1107 (2 markdown-metadata-value-face)))
1108 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1109 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1110 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1111 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1112 (2 markdown-header-rule-face)))
1113 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1114 (2 markdown-header-rule-face)))
1115 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1116 (2 markdown-header-face-1)
1117 (3 markdown-header-delimiter-face)))
1118 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1119 (2 markdown-header-face-2)
1120 (3 markdown-header-delimiter-face)))
1121 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1122 (2 markdown-header-face-3)
1123 (3 markdown-header-delimiter-face)))
1124 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1125 (2 markdown-header-face-4)
1126 (3 markdown-header-delimiter-face)))
1127 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1128 (2 markdown-header-face-5)
1129 (3 markdown-header-delimiter-face)))
1130 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1131 (2 markdown-header-face-6)
1132 (3 markdown-header-delimiter-face)))
1133 (cons markdown-regex-hr 'markdown-header-face)
1134 (cons 'markdown-match-comments '((0 markdown-comment-face t t)))
1135 (cons markdown-regex-code '(2 markdown-inline-code-face))
1136 (cons markdown-regex-angle-uri 'markdown-link-face)
1137 (cons markdown-regex-uri 'markdown-link-face)
1138 (cons markdown-regex-email 'markdown-link-face)
1139 (cons markdown-regex-list '(2 markdown-list-face))
1140 (cons markdown-regex-link-inline '((1 markdown-link-face t)
1141 (2 markdown-url-face t)))
1142 (cons markdown-regex-link-reference '((1 markdown-link-face t)
1143 (2 markdown-reference-face t)))
1144 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1145 (2 markdown-url-face t)
1146 (3 markdown-link-title-face t)))
1147 (cons markdown-regex-footnote 'markdown-footnote-face)
1148 (cons markdown-regex-bold '(2 markdown-bold-face))
1150 "Syntax highlighting for Markdown files.")
1152 (defvar markdown-mode-font-lock-keywords-core
1153 (list
1154 (cons markdown-regex-italic '(2 markdown-italic-face))
1156 "Additional syntax highlighting for Markdown files.
1157 Includes features which are overridden by some variants.")
1159 (defconst markdown-mode-font-lock-keywords-latex
1160 (list
1161 ;; Math mode $..$ or $$..$$
1162 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1163 ;; Display mode equations with brackets: \[ \]
1164 (cons markdown-regex-latex-display 'markdown-math-face)
1165 ;; Equation reference (eq:foo)
1166 (cons "(eq:\\w+)" 'markdown-reference-face)
1167 ;; Equation reference \eqref{foo}
1168 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1169 "Syntax highlighting for LaTeX fragments.")
1171 (defvar markdown-mode-font-lock-keywords
1172 (append
1173 (if markdown-enable-math
1174 markdown-mode-font-lock-keywords-latex)
1175 markdown-mode-font-lock-keywords-basic
1176 markdown-mode-font-lock-keywords-core)
1177 "Default highlighting expressions for Markdown mode.")
1179 ;; Footnotes
1180 (defvar markdown-footnote-counter 0
1181 "Counter for footnote numbers.")
1182 (make-variable-buffer-local 'markdown-footnote-counter)
1184 (defconst markdown-footnote-chars
1185 "[[:alnum:]-]"
1186 "Regular expression maching any character that is allowed in a footnote identifier.")
1189 ;;; Compatibility =============================================================
1191 (defun markdown-replace-regexp-in-string (regexp rep string)
1192 "Replace all matches for REGEXP with REP in STRING.
1193 This is a compatibility wrapper to provide `replace-regexp-in-string'
1194 in XEmacs 21."
1195 (if (featurep 'xemacs)
1196 (replace-in-string string regexp rep)
1197 (replace-regexp-in-string regexp rep string)))
1199 ;; `markdown-use-region-p' is a compatibility function which checks
1200 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1201 (eval-and-compile
1202 (cond
1203 ;; Emacs 23 and newer
1204 ((fboundp 'use-region-p)
1205 (defalias 'markdown-use-region-p 'use-region-p))
1206 ;; Older Emacsen
1207 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1208 (defun markdown-use-region-p ()
1209 "Compatibility wrapper to provide `use-region-p'."
1210 (and transient-mark-mode mark-active)))
1211 ;; XEmacs
1212 ((fboundp 'region-active-p)
1213 (defalias 'markdown-use-region-p 'region-active-p))))
1216 ;;; Markdown Parsing Functions ================================================
1218 (defun markdown-cur-line-blank-p ()
1219 "Return t if the current line is blank and nil otherwise."
1220 (save-excursion
1221 (beginning-of-line)
1222 (re-search-forward "^\\s *$" (point-at-eol) t)))
1224 (defun markdown-prev-line-blank-p ()
1225 "Return t if the previous line is blank and nil otherwise.
1226 If we are at the first line, then consider the previous line to be blank."
1227 (or (= (point-at-bol) (point-min))
1228 (save-excursion
1229 (forward-line -1)
1230 (markdown-cur-line-blank-p))))
1232 (defun markdown-next-line-blank-p ()
1233 "Return t if the next line is blank and nil otherwise.
1234 If we are at the last line, then consider the next line to be blank."
1235 (or (= (point-at-eol) (point-max))
1236 (save-excursion
1237 (forward-line 1)
1238 (markdown-cur-line-blank-p))))
1240 (defun markdown-prev-line-indent-p ()
1241 "Return t if the previous line is indented and nil otherwise."
1242 (save-excursion
1243 (forward-line -1)
1244 (goto-char (point-at-bol))
1245 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
1247 (defun markdown-cur-line-indent ()
1248 "Return the number of leading whitespace characters in the current line."
1249 (save-match-data
1250 (save-excursion
1251 (goto-char (point-at-bol))
1252 (re-search-forward "^[ \t]+" (point-at-eol) t)
1253 (current-column))))
1255 (defun markdown-prev-line-indent ()
1256 "Return the number of leading whitespace characters in the previous line."
1257 (save-excursion
1258 (forward-line -1)
1259 (markdown-cur-line-indent)))
1261 (defun markdown-next-line-indent ()
1262 "Return the number of leading whitespace characters in the next line."
1263 (save-excursion
1264 (forward-line 1)
1265 (markdown-cur-line-indent)))
1267 (defun markdown-cur-non-list-indent ()
1268 "Return beginning position of list item text (not including the list marker).
1269 Return nil if the current line is not the beginning of a list item."
1270 (save-match-data
1271 (save-excursion
1272 (beginning-of-line)
1273 (when (re-search-forward markdown-regex-list (point-at-eol) t)
1274 (current-column)))))
1276 (defun markdown-prev-non-list-indent ()
1277 "Return position of the first non-list-marker on the previous line."
1278 (save-excursion
1279 (forward-line -1)
1280 (markdown-cur-non-list-indent)))
1282 (defun markdown-new-baseline-p ()
1283 "Determine if the current line begins a new baseline level."
1284 (save-excursion
1285 (beginning-of-line)
1286 (save-match-data
1287 (or (looking-at markdown-regex-header)
1288 (looking-at markdown-regex-hr)
1289 (and (null (markdown-cur-non-list-indent))
1290 (= (markdown-cur-line-indent) 0)
1291 (markdown-prev-line-blank-p))))))
1293 (defun markdown-search-backward-baseline ()
1294 "Search backward baseline point with no indentation and not a list item."
1295 (end-of-line)
1296 (let (stop)
1297 (while (not (or stop (bobp)))
1298 (re-search-backward markdown-regex-block-separator nil t)
1299 (when (match-end 2)
1300 (goto-char (match-end 2))
1301 (cond
1302 ((markdown-new-baseline-p)
1303 (setq stop t))
1304 ((looking-at markdown-regex-list)
1305 (setq stop nil))
1306 (t (setq stop t)))))))
1308 (defun markdown-update-list-levels (marker indent levels)
1309 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1310 Here, MARKER is a string representing the type of list, INDENT is an integer
1311 giving the indentation, in spaces, of the current block, and LEVELS is a
1312 list of the indentation levels of parent list items. When LEVELS is nil,
1313 it means we are at baseline (not inside of a nested list)."
1314 (cond
1315 ;; New list item at baseline.
1316 ((and marker (null levels))
1317 (setq levels (list indent)))
1318 ;; List item with greater indentation (four or more spaces).
1319 ;; Increase list level.
1320 ((and marker (>= indent (+ (car levels) 4)))
1321 (setq levels (cons indent levels)))
1322 ;; List item with greater or equal indentation (less than four spaces).
1323 ;; Do not increase list level.
1324 ((and marker (>= indent (car levels)))
1325 levels)
1326 ;; Lesser indentation level.
1327 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1328 ;; indentation could move back more than one list level). Note
1329 ;; that this block need not be the beginning of list item.
1330 ((< indent (car levels))
1331 (while (and (> (length levels) 1)
1332 (< indent (+ (cadr levels) 4)))
1333 (setq levels (cdr levels)))
1334 levels)
1335 ;; Otherwise, do nothing.
1336 (t levels)))
1338 (defun markdown-calculate-list-levels ()
1339 "Calculate list levels at point.
1340 Return a list of the form (n1 n2 n3 ...) where n1 is the
1341 indentation of the deepest nested list item in the branch of
1342 the list at the point, n2 is the indentation of the parent
1343 list item, and so on. The depth of the list item is therefore
1344 the length of the returned list. If the point is not at or
1345 immediately after a list item, return nil."
1346 (save-excursion
1347 (let ((first (point)) levels indent pre-regexp)
1348 ;; Find a baseline point with zero list indentation
1349 (markdown-search-backward-baseline)
1350 ;; Search for all list items between baseline and LOC
1351 (while (re-search-forward markdown-regex-list first t)
1352 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1353 (beginning-of-line)
1354 (cond
1355 ;; Make sure this is not a header or hr
1356 ((markdown-new-baseline-p) (setq levels nil))
1357 ;; Make sure this is not a line from a pre block
1358 ((looking-at pre-regexp))
1359 ;; If not, then update levels
1361 (setq indent (markdown-cur-line-indent))
1362 (setq levels (markdown-update-list-levels (match-string 2)
1363 indent levels))))
1364 (end-of-line))
1365 levels)))
1367 (defun markdown-prev-list-item (level)
1368 "Search backward from point for a list item with indentation LEVEL.
1369 Set point to the beginning of the item, and return point, or nil
1370 upon failure."
1371 (let (bounds indent prev)
1372 (setq prev (point))
1373 (forward-line -1)
1374 (setq indent (markdown-cur-line-indent))
1375 (while
1376 (cond
1377 ;; Stop at beginning of buffer
1378 ((bobp) (setq prev nil))
1379 ;; Continue if current line is blank
1380 ((markdown-cur-line-blank-p) t)
1381 ;; List item
1382 ((and (looking-at markdown-regex-list)
1383 (setq bounds (markdown-cur-list-item-bounds)))
1384 (cond
1385 ;; Continue at item with greater indentation
1386 ((> (nth 3 bounds) level) t)
1387 ;; Stop and return point at item of equal indentation
1388 ((= (nth 3 bounds) level)
1389 (setq prev (point))
1390 nil)
1391 ;; Stop and return nil at item with lesser indentation
1392 ((< (nth 3 bounds) level)
1393 (setq prev nil)
1394 nil)))
1395 ;; Continue while indentation is the same or greater
1396 ((>= indent level) t)
1397 ;; Stop if current indentation is less than list item
1398 ;; and the next is blank
1399 ((and (< indent level)
1400 (markdown-next-line-blank-p))
1401 (setq prev nil))
1402 ;; Stop at a header
1403 ((looking-at markdown-regex-header) (setq prev nil))
1404 ;; Stop at a horizontal rule
1405 ((looking-at markdown-regex-hr) (setq prev nil))
1406 ;; Otherwise, continue.
1407 (t t))
1408 (forward-line -1)
1409 (setq indent (markdown-cur-line-indent)))
1410 prev))
1412 (defun markdown-next-list-item (level)
1413 "Search forward from point for the next list item with indentation LEVEL.
1414 Set point to the beginning of the item, and return point, or nil
1415 upon failure."
1416 (let (bounds indent prev next)
1417 (setq next (point))
1418 (forward-line)
1419 (setq indent (markdown-cur-line-indent))
1420 (while
1421 (cond
1422 ;; Stop at end of the buffer.
1423 ((eobp) (setq prev nil))
1424 ;; Continue if the current line is blank
1425 ((markdown-cur-line-blank-p) t)
1426 ;; List item
1427 ((and (looking-at markdown-regex-list)
1428 (setq bounds (markdown-cur-list-item-bounds)))
1429 (cond
1430 ;; Continue at item with greater indentation
1431 ((> (nth 3 bounds) level) t)
1432 ;; Stop and return point at item of equal indentation
1433 ((= (nth 3 bounds) level)
1434 (setq next (point))
1435 nil)
1436 ;; Stop and return nil at item with lesser indentation
1437 ((< (nth 3 bounds) level)
1438 (setq next nil)
1439 nil)))
1440 ;; Continue while indentation is the same or greater
1441 ((>= indent level) t)
1442 ;; Stop if current indentation is less than list item
1443 ;; and the previous line was blank.
1444 ((and (< indent level)
1445 (markdown-prev-line-blank-p))
1446 (setq next nil))
1447 ;; Stop at a header
1448 ((looking-at markdown-regex-header) (setq next nil))
1449 ;; Stop at a horizontal rule
1450 ((looking-at markdown-regex-hr) (setq next nil))
1451 ;; Otherwise, continue.
1452 (t t))
1453 (forward-line)
1454 (setq indent (markdown-cur-line-indent)))
1455 next))
1457 (defun markdown-cur-list-item-end (level)
1458 "Move to the end of the current list item with nonlist indentation LEVEL.
1459 If the point is not in a list item, do nothing."
1460 (let (indent)
1461 (forward-line)
1462 (setq indent (markdown-cur-line-indent))
1463 (while
1464 (cond
1465 ;; Stop at end of the buffer.
1466 ((eobp) nil)
1467 ;; Continue if the current line is blank
1468 ((markdown-cur-line-blank-p) t)
1469 ;; Continue while indentation is the same or greater
1470 ((>= indent level) t)
1471 ;; Stop if current indentation is less than list item
1472 ;; and the previous line was blank.
1473 ((and (< indent level)
1474 (markdown-prev-line-blank-p))
1475 nil)
1476 ;; Stop at a new list item of the same or lesser indentation
1477 ((looking-at markdown-regex-list) nil)
1478 ;; Stop at a header
1479 ((looking-at markdown-regex-header) nil)
1480 ;; Stop at a horizontal rule
1481 ((looking-at markdown-regex-hr) nil)
1482 ;; Otherwise, continue.
1483 (t t))
1484 (forward-line)
1485 (setq indent (markdown-cur-line-indent)))
1486 ;; Don't skip over whitespace for empty list items (marker and
1487 ;; whitespace only), just move to end of whitespace.
1488 (if (looking-back (concat markdown-regex-list "\\s-*"))
1489 (goto-char (match-end 3))
1490 (skip-syntax-backward "-"))))
1492 (defun markdown-cur-list-item-bounds ()
1493 "Return bounds and indentation of the current list item.
1494 Return a list of the form (begin end indent nonlist-indent).
1495 If the point is not inside a list item, return nil.
1496 Leave match data intact for `markdown-regex-list'."
1497 (let (cur prev-begin prev-end indent nonlist-indent)
1498 ;; Store current location
1499 (setq cur (point))
1500 ;; Verify that cur is between beginning and end of item
1501 (save-excursion
1502 (end-of-line)
1503 (when (re-search-backward markdown-regex-list nil t)
1504 (setq prev-begin (match-beginning 0))
1505 (setq indent (length (match-string 1)))
1506 (setq nonlist-indent (length (match-string 0)))
1507 (save-match-data
1508 (markdown-cur-list-item-end nonlist-indent)
1509 (setq prev-end (point)))
1510 (when (and (>= cur prev-begin)
1511 (<= cur prev-end)
1512 nonlist-indent)
1513 (list prev-begin prev-end indent nonlist-indent))))))
1515 (defun markdown-bounds-of-thing-at-point (thing)
1516 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1517 Does not include trailing newlines when THING is 'line. Handles the
1518 end of buffer case by setting both endpoints equal to the value of
1519 `point-max', since an empty region will trigger empty markup insertion.
1520 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1521 (let* ((bounds (bounds-of-thing-at-point thing))
1522 (a (car bounds))
1523 (b (cdr bounds)))
1524 (when bounds
1525 (when (eq thing 'line)
1526 (cond ((and (eobp) (markdown-cur-line-blank-p))
1527 (setq a b))
1528 ((char-equal (char-before b) ?\^J)
1529 (setq b (1- b)))))
1530 (cons a b))))
1532 (defun markdown-reference-definition (reference)
1533 "Find out whether Markdown REFERENCE is defined.
1534 REFERENCE should include the square brackets, like [this].
1535 When REFERENCE is defined, return a list of the form (text start end)
1536 containing the definition text itself followed by the start and end
1537 locations of the text. Otherwise, return nil.
1538 Leave match data for `markdown-regex-reference-definition'
1539 intact additional processing."
1540 (let ((reference (downcase reference)))
1541 (save-excursion
1542 (goto-char (point-min))
1543 (catch 'found
1544 (while (re-search-forward markdown-regex-reference-definition nil t)
1545 (when (string= reference (downcase (match-string-no-properties 1)))
1546 (throw 'found
1547 (list (match-string-no-properties 2)
1548 (match-beginning 2) (match-end 2)))))))))
1551 ;;; Markdown Font Lock Matching Functions =====================================
1553 (defun markdown-match-comments (last)
1554 "Match HTML comments from the point to LAST."
1555 (cond ((search-forward "<!--" last t)
1556 (backward-char 4)
1557 (let ((beg (point)))
1558 (cond ((search-forward-regexp "--[ \t]*>" last t)
1559 (set-match-data (list beg (point)))
1561 (t nil))))
1562 (t nil)))
1564 (defun markdown-match-pre-blocks (last)
1565 "Match Markdown pre blocks from point to LAST."
1566 (let ((levels (markdown-calculate-list-levels))
1567 indent pre-regexp end-regexp begin end stop)
1568 (while (and (< (point) last) (not end))
1569 ;; Search for a region with sufficient indentation
1570 (if (null levels)
1571 (setq indent 1)
1572 (setq indent (1+ (length levels))))
1573 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1574 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1576 (cond
1577 ;; If not at the beginning of a line, move forward
1578 ((not (bolp)) (forward-line))
1579 ;; Move past blank lines
1580 ((markdown-cur-line-blank-p) (forward-line))
1581 ;; At headers and horizontal rules, reset levels
1582 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1583 ;; If the current line has sufficient indentation, mark out pre block
1584 ((looking-at pre-regexp)
1585 (setq begin (match-beginning 0))
1586 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1587 (not (eobp)))
1588 (forward-line))
1589 (setq end (point)))
1590 ;; If current line has a list marker, update levels, move to end of block
1591 ((looking-at markdown-regex-list)
1592 (setq levels (markdown-update-list-levels
1593 (match-string 2) (markdown-cur-line-indent) levels))
1594 (markdown-end-of-block-element))
1595 ;; If this is the end of the indentation level, adjust levels accordingly.
1596 ;; Only match end of indentation level if levels is not the empty list.
1597 ((and (car levels) (looking-at end-regexp))
1598 (setq levels (markdown-update-list-levels
1599 nil (markdown-cur-line-indent) levels))
1600 (markdown-end-of-block-element))
1601 (t (markdown-end-of-block-element))))
1603 (if (not (and begin end))
1604 ;; Return nil if no pre block was found
1606 ;; Set match data and return t upon success
1607 (set-match-data (list begin end))
1608 t)))
1610 (defun markdown-match-fenced-code-blocks (last)
1611 "Match fenced code blocks from the point to LAST."
1612 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1613 (beginning-of-line)
1614 (let ((beg (point)))
1615 (forward-line)
1616 (cond ((search-forward-regexp
1617 (concat "^" (match-string 1) "~*") last t)
1618 (set-match-data (list beg (point)))
1620 (t nil))))
1621 (t nil)))
1623 (defun markdown-match-gfm-code-blocks (last)
1624 "Match GFM quoted code blocks from point to LAST."
1625 (let (open lang body close all)
1626 (cond ((and (eq major-mode 'gfm-mode)
1627 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1628 (beginning-of-line)
1629 (setq open (list (match-beginning 1) (match-end 1))
1630 lang (list (match-beginning 2) (match-end 2)))
1631 (forward-line)
1632 (setq body (list (point)))
1633 (cond ((search-forward-regexp "^```$" last t)
1634 (setq body (reverse (cons (1- (match-beginning 0)) body))
1635 close (list (match-beginning 0) (match-end 0))
1636 all (list (car open) (match-end 0)))
1637 (set-match-data (append all open lang body close))
1639 (t nil)))
1640 (t nil))))
1642 (defun markdown-match-generic-metadata (regexp last)
1643 "Match generic metadata specified by REGEXP from the point to LAST."
1644 (let ((header-end (save-excursion
1645 (goto-char (point-min))
1646 (if (re-search-forward "\n\n" (point-max) t)
1647 (match-beginning 0)
1648 (point-max)))))
1649 (cond ((>= (point) header-end)
1650 ;; Don't match anything outside of the header.
1651 nil)
1652 ((re-search-forward regexp (min last header-end) t)
1653 ;; If a metadata item is found, it may span several lines.
1654 (let ((key-beginning (match-beginning 1))
1655 (key-end (match-end 1))
1656 (value-beginning (match-beginning 2)))
1657 (while (and (not (looking-at regexp))
1658 (not (> (point) (min last header-end)))
1659 (not (eobp)))
1660 (forward-line))
1661 (unless (eobp)
1662 (forward-line -1)
1663 (end-of-line))
1664 (set-match-data (list key-beginning (point) ; complete metadata
1665 key-beginning key-end ; key
1666 value-beginning (point))) ; value
1668 (t nil))))
1670 (defun markdown-match-multimarkdown-metadata (last)
1671 "Match MultiMarkdown metadata from the point to LAST."
1672 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1674 (defun markdown-match-pandoc-metadata (last)
1675 "Match Pandoc metadata from the point to LAST."
1676 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1678 (defun markdown-font-lock-extend-region ()
1679 "Extend the search region to include an entire block of text.
1680 This helps improve font locking for block constructs such as pre blocks."
1681 ;; Avoid compiler warnings about these global variables from font-lock.el.
1682 ;; See the documentation for variable `font-lock-extend-region-functions'.
1683 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1684 (save-excursion
1685 (goto-char font-lock-beg)
1686 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1687 (goto-char font-lock-end)
1688 (when (re-search-forward "\n\n" nil t)
1689 (beginning-of-line)
1690 (setq font-lock-end (point)))
1691 (setq font-lock-beg found))))
1694 ;;; Syntax Table ==============================================================
1696 (defvar markdown-mode-syntax-table
1697 (let ((tab (make-syntax-table text-mode-syntax-table)))
1698 (modify-syntax-entry ?\" "." tab)
1699 tab)
1700 "Syntax table for `markdown-mode'.")
1703 ;;; Element Insertion =========================================================
1705 (defun markdown-ensure-blank-line-before ()
1706 "If previous line is not already blank, insert a blank line before point."
1707 (unless (bolp) (insert "\n"))
1708 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1710 (defun markdown-ensure-blank-line-after ()
1711 "If following line is not already blank, insert a blank line after point.
1712 Return the point where it was originally."
1713 (save-excursion
1714 (unless (eolp) (insert "\n"))
1715 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1717 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1718 "Insert the strings S1 and S2, wrapping around region or THING.
1719 If a region is specified by the optional BEG and END arguments,
1720 wrap the strings S1 and S2 around that region.
1721 If there is an active region, wrap the strings S1 and S2 around
1722 the region. If there is not an active region but the point is at
1723 THING, wrap that thing (which defaults to word). Otherwise, just
1724 insert S1 and S2 and place the cursor in between. Return the
1725 bounds of the entire wrapped string, or nil if nothing was wrapped
1726 and S1 and S2 were only inserted."
1727 (let (a b bounds new-point)
1728 (cond
1729 ;; Given region
1730 ((and beg end)
1731 (setq a beg
1732 b end
1733 new-point (+ (point) (length s1))))
1734 ;; Active region
1735 ((markdown-use-region-p)
1736 (setq a (region-beginning)
1737 b (region-end)
1738 new-point (+ (point) (length s1))))
1739 ;; Thing (word) at point
1740 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1741 (setq a (car bounds)
1742 b (cdr bounds)
1743 new-point (+ (point) (length s1))))
1744 ;; No active region and no word
1746 (setq a (point)
1747 b (point))))
1748 (goto-char b)
1749 (insert s2)
1750 (goto-char a)
1751 (insert s1)
1752 (when new-point (goto-char new-point))
1753 (if (= a b)
1755 (setq b (+ b (length s1) (length s2)))
1756 (cons a b))))
1758 (defun markdown-point-after-unwrap (cur prefix suffix)
1759 "Return desired position of point after an unwrapping operation.
1760 Two cons cells must be provided. PREFIX gives the bounds of the
1761 prefix string and SUFFIX gives the bounds of the suffix string."
1762 (cond ((< cur (cdr prefix)) (car prefix))
1763 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1764 ((<= cur (cdr suffix))
1765 (- cur (+ (- (cdr prefix) (car prefix))
1766 (- cur (car suffix)))))
1767 (t cur)))
1769 (defun markdown-unwrap-thing-at-point (regexp all text)
1770 "Remove prefix and suffix of thing at point and reposition the point.
1771 When the thing at point matches REGEXP, replace the subexpression
1772 ALL with the string in subexpression TEXT. Reposition the point
1773 in an appropriate location accounting for the removal of prefix
1774 and suffix strings. Return new bounds of string from group TEXT.
1775 When REGEXP is nil, assumes match data is already set."
1776 (when (or (null regexp)
1777 (thing-at-point-looking-at regexp))
1778 (let ((cur (point))
1779 (prefix (cons (match-beginning all) (match-beginning text)))
1780 (suffix (cons (match-end text) (match-end all)))
1781 (bounds (cons (match-beginning text) (match-end text))))
1782 ;; Replace the thing at point
1783 (replace-match (match-string text) t t nil all)
1784 ;; Reposition the point
1785 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1786 ;; Adjust bounds
1787 (setq bounds (cons (car prefix)
1788 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1790 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1791 "Remove prefix and suffix of all things in region.
1792 When a thing in the region matches REGEXP, replace the
1793 subexpression ALL with the string in subexpression TEXT.
1794 Return a cons cell containing updated bounds for the region."
1795 (save-excursion
1796 (goto-char beg)
1797 (let ((removed 0) len-all len-text)
1798 (while (re-search-forward regexp (- end removed) t)
1799 (setq len-all (length (match-string-no-properties all)))
1800 (setq len-text (length (match-string-no-properties text)))
1801 (setq removed (+ removed (- len-all len-text)))
1802 (replace-match (match-string text) t t nil all))
1803 (cons beg (- end removed)))))
1805 (defun markdown-insert-hr (arg)
1806 "Insert or replace a horizonal rule.
1807 By default, use the first element of `markdown-hr-strings'. When
1808 prefixed with C-u, use the last element of `markdown-hr-strings'
1809 instead. When prefixed with an integer from 1 to the length of
1810 `markdown-hr-strings', use the element in that position instead."
1811 (interactive "*P")
1812 (when (thing-at-point-looking-at markdown-regex-hr)
1813 (delete-region (match-beginning 0) (match-end 0)))
1814 (markdown-ensure-blank-line-before)
1815 (cond ((equal arg '(4))
1816 (insert (car (reverse markdown-hr-strings))))
1817 ((and (integerp arg) (> arg 0)
1818 (<= arg (length markdown-hr-strings)))
1819 (insert (nth (1- arg) markdown-hr-strings)))
1821 (insert (car markdown-hr-strings))))
1822 (markdown-ensure-blank-line-after))
1824 (defun markdown-insert-bold ()
1825 "Insert markup to make a region or word bold.
1826 If there is an active region, make the region bold. If the point
1827 is at a non-bold word, make the word bold. If the point is at a
1828 bold word or phrase, remove the bold markup. Otherwise, simply
1829 insert bold delimiters and place the cursor in between them."
1830 (interactive)
1831 (let ((delim (if markdown-bold-underscore "__" "**")))
1832 (if (markdown-use-region-p)
1833 ;; Active region
1834 (let ((bounds (markdown-unwrap-things-in-region
1835 (region-beginning) (region-end)
1836 markdown-regex-bold 2 4)))
1837 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1838 ;; Bold markup removal, bold word at point, or empty markup insertion
1839 (if (thing-at-point-looking-at markdown-regex-bold)
1840 (markdown-unwrap-thing-at-point nil 2 4)
1841 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1843 (defun markdown-insert-italic ()
1844 "Insert markup to make a region or word italic.
1845 If there is an active region, make the region italic. If the point
1846 is at a non-italic word, make the word italic. If the point is at an
1847 italic word or phrase, remove the italic markup. Otherwise, simply
1848 insert italic delimiters and place the cursor in between them."
1849 (interactive)
1850 (let ((delim (if markdown-italic-underscore "_" "*")))
1851 (if (markdown-use-region-p)
1852 ;; Active region
1853 (let ((bounds (markdown-unwrap-things-in-region
1854 (region-beginning) (region-end)
1855 markdown-regex-italic 2 4)))
1856 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1857 ;; Italic markup removal, italic word at point, or empty markup insertion
1858 (if (thing-at-point-looking-at markdown-regex-italic)
1859 (markdown-unwrap-thing-at-point nil 2 4)
1860 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1862 (defun markdown-insert-code ()
1863 "Insert markup to make a region or word an inline code fragment.
1864 If there is an active region, make the region an inline code
1865 fragment. If the point is at a word, make the word an inline
1866 code fragment. Otherwise, simply insert code delimiters and
1867 place the cursor in between them."
1868 (interactive)
1869 (if (markdown-use-region-p)
1870 ;; Active region
1871 (let ((bounds (markdown-unwrap-things-in-region
1872 (region-beginning) (region-end)
1873 markdown-regex-code 2 4)))
1874 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1875 ;; Code markup removal, code markup for word, or empty markup insertion
1876 (if (thing-at-point-looking-at markdown-regex-code)
1877 (markdown-unwrap-thing-at-point nil 2 4)
1878 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1880 (defun markdown-insert-link ()
1881 "Insert an inline link, using region or word as link text if possible.
1882 If there is an active region, use the region as the link text. If the
1883 point is at a word, use the word as the link text. In these cases, the
1884 point will be left at the position for inserting a URL. If there is no
1885 active region and the point is not at word, simply insert link markup and
1886 place the point in the position to enter link text."
1887 (interactive)
1888 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1889 (when bounds
1890 (goto-char (- (cdr bounds) 1)))))
1892 (defun markdown-insert-reference-link-dwim ()
1893 "Insert a reference link of the form [text][label] at point.
1894 If Transient Mark mode is on and a region is active, the region
1895 is used as the link text. Otherwise, the link text will be read
1896 from the minibuffer. The link URL, label, and title will be read
1897 from the minibuffer. The link label definition is placed at the
1898 end of the current paragraph."
1899 (interactive)
1900 (if (markdown-use-region-p)
1901 (call-interactively 'markdown-insert-reference-link-region)
1902 (call-interactively 'markdown-insert-reference-link)))
1904 (defun markdown-insert-reference-link-region (url label title)
1905 "Insert a reference link at point using the region as the link text.
1906 The link will point to URL, will be referenced as LABEL, and will have the
1907 optional title text given by TITLE."
1908 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1909 (let ((text (delete-and-extract-region (region-beginning) (region-end))))
1910 (markdown-insert-reference-link text url label title)))
1912 (defun markdown-insert-reference-link (text url label title)
1913 "Insert a reference link at point.
1914 The link TEXT will point to the given URL and may be referenced using
1915 LABEL. The link TITLE is optional and will be used to populate the
1916 title attribute when converted to XHTML."
1917 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1918 (let (end)
1919 (insert (concat "[" text "][" label "]"))
1920 (setq end (point))
1921 (forward-paragraph)
1922 (insert "\n[")
1923 (if (> (length label) 0)
1924 (insert label)
1925 (insert text))
1926 (insert (concat "]: " url))
1927 (unless (> (length url) 0)
1928 (setq end (point)))
1929 (when (> (length title) 0)
1930 (insert (concat " \"" title "\"")))
1931 (insert "\n")
1932 (unless (looking-at "\n")
1933 (insert "\n"))
1934 (goto-char end)))
1936 (defun markdown-insert-wiki-link ()
1937 "Insert a wiki link of the form [[WikiLink]].
1938 If Transient Mark mode is on and a region is active, it is used
1939 as the link text."
1940 (interactive)
1941 (markdown-wrap-or-insert "[[" "]]")
1942 (backward-char 2))
1944 (defun markdown-insert-image ()
1945 "Insert inline image markup using region or word as alt text if possible.
1946 If there is an active region, use the region as the alt text. If the
1947 point is at a word, use the word as the alt text. In these cases, the
1948 point will be left at the position for inserting a URL. If there is no
1949 active region and the point is not at word, simply insert image markup and
1950 place the point in the position to enter alt text."
1951 (interactive)
1952 (let ((bounds (markdown-wrap-or-insert "![" "]()")))
1953 (when bounds
1954 (goto-char (- (cdr bounds) 1)))))
1956 (defun markdown-remove-header ()
1957 "Remove header markup if point is at a header.
1958 Return bounds of remaining header text if a header was removed
1959 and nil otherwise."
1960 (interactive "*")
1961 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
1962 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
1964 (defun markdown-insert-header (&optional level text setext)
1965 "Insert or replace header markup.
1966 The level of the header is specified by LEVEL and header text is
1967 given by TEXT. LEVEL must be an integer from 1 and 6, and the
1968 default value is 1.
1969 When TEXT is nil, the header text is obtained as follows.
1970 If there is an active region, it is used as the header text.
1971 Otherwise, the current line will be used as the header text.
1972 If there is not an active region and the point is at a header,
1973 remove the header markup and replace with level N header.
1974 Otherwise, insert empty header markup and place the cursor in
1975 between.
1976 The style of the header will be atx (hash marks) unless
1977 SETEXT is non-nil, in which case a setext-style (underlined)
1978 header will be inserted."
1979 (interactive "p\nsHeader text: ")
1980 (setq level (min (max (or level 1) 1) (if setext 2 6)))
1981 ;; Determine header text if not given
1982 (when (null text)
1983 (if (markdown-use-region-p)
1984 ;; Active region
1985 (setq text (delete-and-extract-region (region-beginning) (region-end)))
1986 ;; No active region
1987 (markdown-remove-header)
1988 (setq text (delete-and-extract-region
1989 (line-beginning-position) (line-end-position)))
1990 (when (and setext (string-match "^[ \t]*$" text))
1991 (setq text (read-string "Header text: "))))
1992 (setq text (markdown-compress-whitespace-string text)))
1993 ;; Insertion with given text
1994 (markdown-ensure-blank-line-before)
1995 (if setext
1996 ;; setext
1997 (progn
1998 (insert text "\n")
1999 (dotimes (n (length text))
2000 (insert (if (= level 2) "-" "="))))
2001 ;; atx
2002 (dotimes (count level) (insert "#"))
2003 (insert " " text " ")
2004 (dotimes (count level) (insert "#")))
2005 (markdown-ensure-blank-line-after)
2006 ;; Leave point at end of text
2007 (if setext
2008 (backward-char (1+ (length text)))
2009 (backward-char (1+ level))))
2011 (defun markdown-insert-header-dwim (&optional arg)
2012 "Insert or replace header markup.
2013 The level of the header is determined by the numerical argument,
2014 if present, or the level of the previous header.
2015 The type of the header is determined by the type of the previous header.
2016 See `markdown-insert-header' for details about how the header text
2017 is determined."
2018 (interactive "*P")
2019 (let (level setext)
2020 (save-excursion
2021 (when (re-search-backward markdown-regex-header nil t)
2022 (setq level (markdown-outline-level))
2023 (setq setext (or (match-end 1) (match-end 3)))))
2024 ;; use prefix if given, or level of previous header
2025 (setq level (if arg (prefix-numeric-value arg) level))
2026 ;; match groups 1 and 2 indicate setext headers
2027 (setq setext (and level (<= level 2) setext))
2028 (markdown-insert-header level nil setext)))
2030 (defun markdown-insert-header-atx-1 ()
2031 "Insert a first level atx-style (hash mark) header.
2032 See `markdown-insert-header'."
2033 (interactive "*")
2034 (markdown-insert-header 1 nil nil))
2036 (defun markdown-insert-header-atx-2 ()
2037 "Insert a level two atx-style (hash mark) header.
2038 See `markdown-insert-header'."
2039 (interactive "*")
2040 (markdown-insert-header 2 nil nil))
2042 (defun markdown-insert-header-atx-3 ()
2043 "Insert a level three atx-style (hash mark) header.
2044 See `markdown-insert-header'."
2045 (interactive "*")
2046 (markdown-insert-header 3 nil nil))
2048 (defun markdown-insert-header-atx-4 ()
2049 "Insert a level four atx-style (hash mark) header.
2050 See `markdown-insert-header'."
2051 (interactive "*")
2052 (markdown-insert-header 4 nil nil))
2054 (defun markdown-insert-header-atx-5 ()
2055 "Insert a level five atx-style (hash mark) header.
2056 See `markdown-insert-header'."
2057 (interactive "*")
2058 (markdown-insert-header 5 nil nil))
2060 (defun markdown-insert-header-atx-6 ()
2061 "Insert a sixth level atx-style (hash mark) header.
2062 See `markdown-insert-header'."
2063 (interactive "*")
2064 (markdown-insert-header 6 nil nil))
2066 (defun markdown-insert-header-setext-1 ()
2067 "Insert a setext-style (underlined) first-level header.
2068 See `markdown-insert-header'."
2069 (interactive "*")
2070 (markdown-insert-header 1 nil t))
2072 (defun markdown-insert-header-setext-2 ()
2073 "Insert a setext-style (underlined) second-level header.
2074 See `markdown-insert-header'."
2075 (interactive "*")
2076 (markdown-insert-header 2 nil t))
2078 (defun markdown-blockquote-indentation (loc)
2079 "Return string containing necessary indentation for a blockquote at LOC.
2080 Also see `markdown-pre-indentation'."
2081 (save-excursion
2082 (goto-char loc)
2083 (let* ((list-level (length (markdown-calculate-list-levels)))
2084 (indent ""))
2085 (dotimes (count list-level indent)
2086 (setq indent (concat indent " "))))))
2088 (defun markdown-insert-blockquote ()
2089 "Start a blockquote section (or blockquote the region).
2090 If Transient Mark mode is on and a region is active, it is used as
2091 the blockquote text."
2092 (interactive)
2093 (if (markdown-use-region-p)
2094 (markdown-blockquote-region (region-beginning) (region-end))
2095 (markdown-ensure-blank-line-before)
2096 (insert (markdown-blockquote-indentation (point)) "> ")
2097 (markdown-ensure-blank-line-after)))
2099 (defun markdown-block-region (beg end prefix)
2100 "Format the region using a block prefix.
2101 Arguments BEG and END specify the beginning and end of the
2102 region. The characters PREFIX will appear at the beginning
2103 of each line."
2104 (save-excursion
2105 ;; Ensure that there is a leading blank line
2106 (goto-char beg)
2107 (when (and (>= (point) (+ (point-min) 2))
2108 (not (looking-back "\n\n" 2)))
2109 (insert "\n")
2110 (setq beg (1+ beg))
2111 (setq end (1+ end)))
2112 ;; Move back before any blank lines at the end
2113 (goto-char end)
2114 (while (and (looking-back "\n" 1)
2115 (not (equal (point) (point-min))))
2116 (backward-char)
2117 (setq end (1- end)))
2118 ;; Ensure that there is a trailing blank line
2119 (goto-char end)
2120 (if (not (or (looking-at "\n\n")
2121 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
2122 (insert "\n"))
2123 ;; Insert PREFIX
2124 (goto-char beg)
2125 (beginning-of-line)
2126 (while (< (point-at-bol) end)
2127 (insert prefix)
2128 (setq end (+ (length prefix) end))
2129 (forward-line))))
2131 (defun markdown-blockquote-region (beg end)
2132 "Blockquote the region.
2133 Arguments BEG and END specify the beginning and end of the region."
2134 (interactive "*r")
2135 (markdown-block-region
2136 beg end (concat (markdown-blockquote-indentation
2137 (max (point-min) (1- beg))) "> ")))
2139 (defun markdown-pre-indentation (loc)
2140 "Return string containing necessary whitespace for a pre block at LOC.
2141 Also see `markdown-blockquote-indentation'."
2142 (save-excursion
2143 (goto-char loc)
2144 (let* ((list-level (length (markdown-calculate-list-levels)))
2145 indent)
2146 (dotimes (count (1+ list-level) indent)
2147 (setq indent (concat indent " "))))))
2149 (defun markdown-insert-pre ()
2150 "Start a preformatted section (or apply to the region).
2151 If Transient Mark mode is on and a region is active, it is marked
2152 as preformatted text."
2153 (interactive)
2154 (if (markdown-use-region-p)
2155 (markdown-pre-region (region-beginning) (region-end))
2156 (markdown-ensure-blank-line-before)
2157 (insert (markdown-pre-indentation (point)))
2158 (markdown-ensure-blank-line-after)))
2160 (defun markdown-pre-region (beg end)
2161 "Format the region as preformatted text.
2162 Arguments BEG and END specify the beginning and end of the region."
2163 (interactive "*r")
2164 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2165 (markdown-block-region beg end indent)))
2167 (defun markdown-insert-gfm-code-block (&optional lang)
2168 "Insert GFM code block for language LANG.
2169 If LANG is nil, the language will be queried from user. If a
2170 region is active, wrap this region with the markup instead. If
2171 the region boundaries are not on empty lines, these are added
2172 automatically in order to have the correct markup."
2173 (interactive "sProgramming language: ")
2174 (if (markdown-use-region-p)
2175 (let ((b (region-beginning)) (e (region-end)))
2176 (goto-char b)
2177 ;; if we're on a blank line, insert the quotes here, otherwise
2178 ;; add a new line first
2179 (unless (looking-at "\n")
2180 (newline)
2181 (forward-line -1)
2182 (setq e (1+ e)))
2183 (insert "```" lang)
2184 (goto-char (+ e 3 (length lang)))
2185 ;; if we're on a blank line, don't newline, otherwise the ```
2186 ;; should go on its own line
2187 (unless (looking-back "\n")
2188 (newline))
2189 (insert "```"))
2190 (insert "```" lang)
2191 (newline 2)
2192 (insert "```")
2193 (forward-line -1)))
2196 ;;; Footnotes ======================================================================
2198 (defun markdown-footnote-counter-inc ()
2199 "Increment `markdown-footnote-counter' and return the new value."
2200 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2201 (save-excursion
2202 (goto-char (point-min))
2203 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2204 (point-max) t)
2205 (let ((fn (string-to-number (match-string 1))))
2206 (when (> fn markdown-footnote-counter)
2207 (setq markdown-footnote-counter fn))))))
2208 (incf markdown-footnote-counter))
2210 (defun markdown-footnote-new ()
2211 "Insert footnote with a new number and move point to footnote definition."
2212 (interactive)
2213 (let ((fn (markdown-footnote-counter-inc)))
2214 (insert (format "[^%d]" fn))
2215 (markdown-footnote-text-find-new-location)
2216 (markdown-ensure-blank-line-before)
2217 (unless (markdown-cur-line-blank-p)
2218 (insert "\n"))
2219 (insert (format "[^%d]: " fn))
2220 (markdown-ensure-blank-line-after)))
2222 (defun markdown-footnote-text-find-new-location ()
2223 "Position the cursor at the proper location for a new footnote text."
2224 (cond
2225 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2226 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
2227 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2229 (defun markdown-footnote-kill ()
2230 "Kill the footnote at point.
2231 The footnote text is killed (and added to the kill ring), the
2232 footnote marker is deleted. Point has to be either at the
2233 footnote marker or in the footnote text."
2234 (interactive)
2235 (let (return-pos)
2236 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2237 (markdown-footnote-return) ; we first move to the marker
2238 (setq return-pos 'text)) ; and remember our return position
2239 (let ((marker (markdown-footnote-delete-marker)))
2240 (unless marker
2241 (error "Not at a footnote"))
2242 (let ((text-pos (markdown-footnote-find-text (car marker))))
2243 (unless text-pos
2244 (error "No text for footnote `%s'" (car marker)))
2245 (goto-char text-pos)
2246 (let ((pos (markdown-footnote-kill-text)))
2247 (setq return-pos
2248 (if (and pos (eq return-pos 'text))
2250 (cadr marker))))))
2251 (goto-char return-pos)))
2253 (defun markdown-footnote-delete-marker ()
2254 "Delete a footnote marker at point.
2255 Returns a list (ID START) containing the footnote ID and the
2256 start position of the marker before deletion. If no footnote
2257 marker was deleted, this function returns NIL."
2258 (let ((marker (markdown-footnote-marker-positions)))
2259 (when marker
2260 (delete-region (second marker) (third marker))
2261 (butlast marker))))
2263 (defun markdown-footnote-kill-text ()
2264 "Kill footnote text at point.
2265 Returns the start position of the footnote text before deletion,
2266 or NIL if point was not inside a footnote text.
2268 The killed text is placed in the kill ring (without the footnote
2269 number)."
2270 (let ((fn (markdown-footnote-text-positions)))
2271 (when fn
2272 (let ((text (delete-and-extract-region (second fn) (third fn))))
2273 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2274 (kill-new (match-string 1 text))
2275 (when (and (markdown-cur-line-blank-p)
2276 (markdown-prev-line-blank-p))
2277 (delete-region (1- (point)) (point)))
2278 (second fn)))))
2280 (defun markdown-footnote-goto-text ()
2281 "Jump to the text of the footnote at point."
2282 (interactive)
2283 (let ((fn (car (markdown-footnote-marker-positions))))
2284 (unless fn
2285 (error "Not at a footnote marker"))
2286 (let ((new-pos (markdown-footnote-find-text fn)))
2287 (unless new-pos
2288 (error "No definition found for footnote `%s'" fn))
2289 (goto-char new-pos))))
2291 (defun markdown-footnote-return ()
2292 "Return from a footnote to its footnote number in the main text."
2293 (interactive)
2294 (let ((fn (save-excursion
2295 (car (markdown-footnote-text-positions)))))
2296 (unless fn
2297 (error "Not in a footnote"))
2298 (let ((new-pos (markdown-footnote-find-marker fn)))
2299 (unless new-pos
2300 (error "Footnote marker `%s' not found" fn))
2301 (goto-char new-pos))))
2303 (defun markdown-footnote-find-marker (id)
2304 "Find the location of the footnote marker with ID.
2305 The actual buffer position returned is the position directly
2306 following the marker's closing bracket. If no marker is found,
2307 NIL is returned."
2308 (save-excursion
2309 (goto-char (point-min))
2310 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2311 (skip-chars-backward "^]")
2312 (point))))
2314 (defun markdown-footnote-find-text (id)
2315 "Find the location of the text of footnote ID.
2316 The actual buffer position returned is the position of the first
2317 character of the text, after the footnote's identifier. If no
2318 footnote text is found, NIL is returned."
2319 (save-excursion
2320 (goto-char (point-min))
2321 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2322 (skip-chars-forward "[ \t]")
2323 (point))))
2325 (defun markdown-footnote-marker-positions ()
2326 "Return the position and ID of the footnote marker point is on.
2327 The return value is a list (ID START END). If point is not on a
2328 footnote, NIL is returned."
2329 ;; first make sure we're at a footnote marker
2330 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
2331 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2332 (save-excursion
2333 ;; move point between [ and ^:
2334 (if (looking-at "\\[")
2335 (forward-char 1)
2336 (skip-chars-backward "^["))
2337 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2338 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2340 (defun markdown-footnote-text-positions ()
2341 "Return the start and end positions of the footnote text point is in.
2342 The exact return value is a list of three elements: (ID START END).
2343 The start position is the position of the opening bracket
2344 of the footnote id. The end position is directly after the
2345 newline that ends the footnote. If point is not in a footnote,
2346 NIL is returned instead."
2347 (save-excursion
2348 (let ((fn (progn
2349 (backward-paragraph)
2350 ;; if we're in a multiparagraph footnote, we need to back up further
2351 (while (>= (markdown-next-line-indent) 4)
2352 (backward-paragraph))
2353 (forward-line)
2354 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2355 (list (match-string 1) (point))))))
2356 (when fn
2357 (while (progn
2358 (forward-paragraph)
2359 (>= (markdown-next-line-indent) 4)))
2360 (append fn (list (point)))))))
2363 ;;; Indentation ====================================================================
2365 (defun markdown-indent-find-next-position (cur-pos positions)
2366 "Return the position after the index of CUR-POS in POSITIONS.
2367 Positions are calculated by `markdown-calc-indents'."
2368 (while (and positions
2369 (not (equal cur-pos (car positions))))
2370 (setq positions (cdr positions)))
2371 (or (cadr positions) 0))
2373 (defun markdown-indent-line ()
2374 "Indent the current line using some heuristics.
2375 If the _previous_ command was either `markdown-enter-key' or
2376 `markdown-cycle', then we should cycle to the next
2377 reasonable indentation position. Otherwise, we could have been
2378 called directly by `markdown-enter-key', by an initial call of
2379 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2380 these cases, indent to the default position.
2381 Positions are calculated by `markdown-calc-indents'."
2382 (interactive)
2383 (let ((positions (markdown-calc-indents))
2384 (cur-pos (current-column)))
2385 (if (not (equal this-command 'markdown-cycle))
2386 (indent-line-to (car positions))
2387 (setq positions (sort (delete-dups positions) '<))
2388 (indent-line-to
2389 (markdown-indent-find-next-position cur-pos positions)))))
2391 (defun markdown-calc-indents ()
2392 "Return a list of indentation columns to cycle through.
2393 The first element in the returned list should be considered the
2394 default indentation level. This function does not worry about
2395 duplicate positions, which are handled up by calling functions."
2396 (let (pos prev-line-pos positions)
2398 ;; Indentation of previous line
2399 (setq prev-line-pos (markdown-prev-line-indent))
2400 (setq positions (cons prev-line-pos positions))
2402 ;; Indentation of previous non-list-marker text
2403 (when (setq pos (markdown-prev-non-list-indent))
2404 (setq positions (cons pos positions)))
2406 ;; Indentation required for a pre block in current context
2407 (setq pos (length (markdown-pre-indentation (point))))
2408 (setq positions (cons pos positions))
2410 ;; Indentation of the previous line + tab-width
2411 (if prev-line-pos
2412 (setq positions (cons (+ prev-line-pos tab-width) positions))
2413 (setq positions (cons tab-width positions)))
2415 ;; Indentation of the previous line - tab-width
2416 (if (and prev-line-pos (> prev-line-pos tab-width))
2417 (setq positions (cons (- prev-line-pos tab-width) positions)))
2419 ;; Indentation of all preceeding list markers (when in a list)
2420 (when (setq pos (markdown-calculate-list-levels))
2421 (setq positions (append pos positions)))
2423 ;; First column
2424 (setq positions (cons 0 positions))
2426 ;; Return reversed list
2427 (reverse positions)))
2429 (defun markdown-do-normal-return ()
2430 "Insert a newline and optionally indent the next line."
2431 (newline)
2432 (if markdown-indent-on-enter
2433 (funcall indent-line-function)))
2435 (defun markdown-enter-key ()
2436 "Handle RET according to context.
2437 If there is a wiki link at the point, follow it unless
2438 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2439 it in the usual way."
2440 (interactive)
2441 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2442 (markdown-follow-wiki-link-at-point)
2443 (markdown-do-normal-return)))
2445 (defun markdown-dedent-or-delete (arg)
2446 "Handle BACKSPACE by cycling through indentation points.
2447 When BACKSPACE is pressed, if there is only whitespace
2448 before the current point, then dedent the line one level.
2449 Otherwise, do normal delete by repeating
2450 `backward-delete-char-untabify' ARG times."
2451 (interactive "*p")
2452 (let ((cur-pos (current-column))
2453 (start-of-indention (save-excursion
2454 (back-to-indentation)
2455 (current-column))))
2456 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2457 (let ((result 0))
2458 (dolist (i (markdown-calc-indents))
2459 (when (< i cur-pos)
2460 (setq result (max result i))))
2461 (indent-line-to result))
2462 (backward-delete-char-untabify arg))))
2465 ;;; Markup Completion =========================================================
2467 (defconst markdown-complete-alist
2468 '((markdown-regex-header-atx . markdown-complete-atx)
2469 (markdown-regex-header-setext . markdown-complete-setext)
2470 (markdown-regex-hr . markdown-complete-hr))
2471 "Association list of form (regexp . function) for markup completion.")
2473 (defun markdown-incomplete-atx-p ()
2474 "Return t if ATX header markup is incomplete and nil otherwise.
2475 Assumes match data is available for `markdown-regex-header-atx'.
2476 Checks that the number of trailing hash marks equals the number of leading
2477 hash marks, that there is only a single space before and after the text,
2478 and that there is no extraneous whitespace in the text."
2479 (save-match-data
2480 (or (not (= (length (match-string 1)) (length (match-string 3))))
2481 (not (= (match-beginning 2) (1+ (match-end 1))))
2482 (not (= (match-beginning 3) (1+ (match-end 2))))
2483 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2485 (defun markdown-complete-atx ()
2486 "Complete and normalize ATX headers.
2487 Add or remove hash marks to the end of the header to match the
2488 beginning. Ensure that there is only a single space between hash
2489 marks and header text. Removes extraneous whitespace from header text.
2490 Assumes match data is available for `markdown-regex-header-atx'."
2491 (when (markdown-incomplete-atx-p)
2492 (let* ((new-marker (make-marker))
2493 (new-marker (set-marker new-marker (match-end 2))))
2494 ;; Hash marks and spacing at end
2495 (goto-char (match-end 2))
2496 (delete-region (match-end 2) (match-end 3))
2497 (insert " " (match-string 1))
2498 ;; Remove extraneous whitespace from title
2499 (replace-match (markdown-compress-whitespace-string (match-string 2))
2500 t t nil 2)
2501 ;; Spacing at beginning
2502 (goto-char (match-end 1))
2503 (delete-region (match-end 1) (match-beginning 2))
2504 (insert " ")
2505 ;; Leave point at end of text
2506 (goto-char new-marker))))
2508 (defun markdown-incomplete-setext-p ()
2509 "Return t if setext header markup is incomplete and nil otherwise.
2510 Assumes match data is available for `markdown-regex-header-setext'.
2511 Checks that length of underline matches text and that there is no
2512 extraneous whitespace in the text."
2513 (save-match-data
2514 (or (not (= (length (match-string 1)) (length (match-string 2))))
2515 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2517 (defun markdown-complete-setext ()
2518 "Complete and normalize setext headers.
2519 Add or remove underline characters to match length of header
2520 text. Removes extraneous whitespace from header text. Assumes
2521 match data is available for `markdown-regex-header-setext'."
2522 (when (markdown-incomplete-setext-p)
2523 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2524 (char (char-after (match-beginning 2)))
2525 (level (if (char-equal char ?-) 2 1)))
2526 (goto-char (match-beginning 0))
2527 (delete-region (match-beginning 0) (match-end 0))
2528 (markdown-insert-header level text t))))
2530 (defun markdown-incomplete-hr-p ()
2531 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2532 Assumes match data is available for `markdown-regex-hr'."
2533 (not (member (match-string 0) markdown-hr-strings)))
2535 (defun markdown-complete-hr ()
2536 "Complete horizontal rules.
2537 If horizontal rule string is a member of `markdown-hr-strings',
2538 do nothing. Otherwise, replace with the car of
2539 `markdown-hr-strings'.
2540 Assumes match data is available for `markdown-regex-hr'."
2541 (replace-match (car markdown-hr-strings)))
2543 (defun markdown-complete ()
2544 "Complete markup of object near point or in region when active.
2545 Handle all objects in `markdown-complete-alist', in order.
2546 See `markdown-complete-at-point' and `markdown-complete-region'."
2547 (interactive "*")
2548 (if (markdown-use-region-p)
2549 (markdown-complete-region (region-beginning) (region-end))
2550 (markdown-complete-at-point)))
2552 (defun markdown-complete-at-point ()
2553 "Complete markup of object near point.
2554 Handle all objects in `markdown-complete-alist', in
2555 order."
2556 (interactive "*")
2557 (loop for (regexp . function) in markdown-complete-alist
2558 until (thing-at-point-looking-at (eval regexp))
2559 finally (funcall function)))
2561 (defun markdown-complete-region (beg end)
2562 "Complete markup of object near point.
2563 Handle all objects in `markdown-complete-alist', in
2564 order."
2565 (interactive "*r")
2566 (let* ((end-marker (make-marker))
2567 (end-marker (set-marker end-marker end)))
2568 (loop for (regexp . function) in markdown-complete-alist
2569 do (save-excursion
2570 (goto-char beg)
2571 (while (re-search-forward (eval regexp) end-marker t)
2572 (funcall function))))))
2574 (defun markdown-complete-buffer ()
2575 "Complete markup for all objects in the current buffer."
2576 (interactive "*")
2577 (markdown-complete-region (point-min) (point-max)))
2580 ;;; Markup Cycling ============================================================
2582 (defun markdown-cycle-atx (arg &optional remove)
2583 "Cycle ATX header markup.
2584 Promote header (decrease level) when ARG is 1 and demote
2585 header (increase level) if arg is -1. When REMOVE is non-nil,
2586 remove the header when the level reaches zero and stop cycling
2587 when it reaches six. Otherwise, perform a proper cycling through
2588 levels one through six. Assumes match data is available for
2589 `markdown-regex-header-atx'."
2590 (let* ((old-level (length (match-string 1)))
2591 (new-level (+ old-level arg))
2592 (text (match-string 2)))
2593 (when (not remove)
2594 (setq new-level (% new-level 6))
2595 (setq new-level (cond ((= new-level 0) 6)
2596 ((< new-level 0) (+ new-level 6))
2597 (t new-level))))
2598 (cond
2599 ((= new-level 0)
2600 (markdown-unwrap-thing-at-point nil 0 2))
2601 ((<= new-level 6)
2602 (goto-char (match-beginning 0))
2603 (delete-region (match-beginning 0) (match-end 0))
2604 (markdown-insert-header new-level text nil)))))
2606 (defun markdown-cycle-setext (arg &optional remove)
2607 "Cycle setext header markup.
2608 Promote header (increase level) when ARG is 1 and demote
2609 header (decrease level or remove) if arg is -1. When demoting a
2610 level-two setext header, replace with a level-three atx header.
2611 When REMOVE is non-nil, remove the header when the level reaches
2612 zero. Otherwise, cycle back to a level six atx header. Assumes
2613 match data is available for `markdown-regex-header-setext'."
2614 (let* ((char (char-after (match-beginning 2)))
2615 (old-level (if (char-equal char ?=) 1 2))
2616 (new-level (+ old-level arg))
2617 (text (match-string 1)))
2618 (when (and (not remove) (= new-level 0))
2619 (setq new-level 6))
2620 (cond
2621 ((= new-level 0)
2622 (markdown-unwrap-thing-at-point nil 0 1))
2623 ((<= new-level 2)
2624 (markdown-insert-header new-level nil t))
2625 ((<= new-level 6)
2626 (markdown-insert-header new-level nil nil)))))
2628 (defun markdown-cycle-hr (arg &optional remove)
2629 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2630 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2631 backwards (demote). When REMOVE is non-nil, remove the hr instead
2632 of cycling when the end of the list is reached.
2633 Assumes match data is available for `markdown-regex-hr'."
2634 (let* ((strings (if (= arg 1)
2635 (reverse markdown-hr-strings)
2636 markdown-hr-strings))
2637 (tail (member (match-string 0) strings))
2638 (new (or (cadr tail)
2639 (if remove
2640 (if (= arg 1)
2642 (car tail))
2643 (car strings)))))
2644 (replace-match new)))
2646 (defun markdown-cycle-bold ()
2647 "Cycle bold markup between underscores and asterisks.
2648 Assumes match data is available for `markdown-regex-bold'."
2649 (save-excursion
2650 (let* ((old-delim (match-string 3))
2651 (new-delim (if (string-equal old-delim "**") "__" "**")))
2652 (replace-match new-delim t t nil 3)
2653 (replace-match new-delim t t nil 5))))
2655 (defun markdown-cycle-italic ()
2656 "Cycle italic markup between underscores and asterisks.
2657 Assumes match data is available for `markdown-regex-italic'."
2658 (save-excursion
2659 (let* ((old-delim (match-string 3))
2660 (new-delim (if (string-equal old-delim "*") "_" "*")))
2661 (replace-match new-delim t t nil 3)
2662 (replace-match new-delim t t nil 5))))
2665 ;;; Keymap ====================================================================
2667 (defvar markdown-mode-map
2668 (let ((map (make-keymap)))
2669 ;; Element insertion
2670 (define-key map "\C-c\C-al" 'markdown-insert-link)
2671 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
2672 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
2673 (define-key map "\C-c\C-ii" 'markdown-insert-image)
2674 (define-key map "\C-c\C-t0" 'markdown-remove-header)
2675 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
2676 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
2677 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
2678 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
2679 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
2680 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
2681 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
2682 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
2683 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
2684 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
2685 (define-key map "\C-c\C-se" 'markdown-insert-italic)
2686 (define-key map "\C-c\C-pf" 'markdown-insert-code)
2687 (define-key map "\C-c\C-sc" 'markdown-insert-code)
2688 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
2689 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
2690 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
2691 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
2692 (define-key map "\C-c-" 'markdown-insert-hr)
2693 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
2694 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
2695 ;; Footnotes
2696 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
2697 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
2698 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
2699 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
2700 ;; Promotion, Demotion, Completion, and Cycling
2701 (define-key map (kbd "M-<left>") 'markdown-promote)
2702 (define-key map (kbd "M-<right>") 'markdown-demote)
2703 (define-key map (kbd "C-c C-l") 'markdown-promote)
2704 (define-key map (kbd "C-c C-r") 'markdown-demote)
2705 (define-key map (kbd "C-c C-=") 'markdown-complete-or-cycle)
2706 (define-key map (kbd "C-c C-c =") 'markdown-complete-buffer)
2707 ;; Link Following
2708 (define-key map "\C-c\C-o" 'markdown-follow-thing-at-point)
2709 ;; Indentation
2710 (define-key map "\C-m" 'markdown-enter-key)
2711 (define-key map (kbd "<backspace>") 'markdown-dedent-or-delete)
2712 ;; Visibility cycling
2713 (define-key map (kbd "<tab>") 'markdown-cycle)
2714 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
2715 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
2716 (define-key map (kbd "<backtab>") 'markdown-shifttab)
2717 ;; Header navigation
2718 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
2719 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
2720 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
2721 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
2722 (define-key map (kbd "C-M-u") 'outline-up-heading)
2723 ;; Markdown functions
2724 (define-key map "\C-c\C-cm" 'markdown-other-window)
2725 (define-key map "\C-c\C-cp" 'markdown-preview)
2726 (define-key map "\C-c\C-ce" 'markdown-export)
2727 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
2728 (define-key map "\C-c\C-co" 'markdown-open)
2729 (define-key map "\C-c\C-cw" 'markdown-kill-ring-save)
2730 ;; References
2731 (define-key map "\C-c\C-cc" 'markdown-check-refs)
2732 ;; Lists
2733 (define-key map "\C-c\C-cn" 'markdown-cleanup-list-numbers)
2734 (define-key map (kbd "M-<up>") 'markdown-move-up)
2735 (define-key map (kbd "M-<down>") 'markdown-move-down)
2736 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
2737 ;; Movement
2738 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
2739 (define-key map (kbd "M-]") 'markdown-end-of-block)
2740 (define-key map (kbd "M-n") 'markdown-next-wiki-link)
2741 (define-key map (kbd "M-p") 'markdown-previous-wiki-link)
2742 map)
2743 "Keymap for Markdown major mode.")
2745 (defvar gfm-mode-map
2746 (let ((map (make-sparse-keymap)))
2747 (set-keymap-parent map markdown-mode-map)
2748 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
2749 map)
2750 "Keymap for `gfm-mode'.
2751 See also `markdown-mode-map'.")
2754 ;;; Menu ==================================================================
2756 (easy-menu-define markdown-mode-menu markdown-mode-map
2757 "Menu for Markdown mode"
2758 '("Markdown"
2759 ("Show/Hide"
2760 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
2761 ["Cycle global visibility" markdown-shifttab])
2762 "---"
2763 ["Compile" markdown-other-window]
2764 ["Preview" markdown-preview]
2765 ["Export" markdown-export]
2766 ["Export & View" markdown-export-and-preview]
2767 ["Open" markdown-open]
2768 ["Kill ring save" markdown-kill-ring-save]
2769 "---"
2770 ("Headers (setext)"
2771 ["First level" markdown-insert-setext-header-1]
2772 ["Second level" markdown-insert-setext-header-2])
2773 ("Headers (atx)"
2774 ["First level" markdown-insert-header-atx-1]
2775 ["Second level" markdown-insert-header-atx-2]
2776 ["Third level" markdown-insert-header-atx-3]
2777 ["Fourth level" markdown-insert-header-atx-4]
2778 ["Fifth level" markdown-insert-header-atx-5]
2779 ["Sixth level" markdown-insert-header-atx-6])
2780 "---"
2781 ["Bold" markdown-insert-bold]
2782 ["Italic" markdown-insert-italic]
2783 ["Blockquote" markdown-insert-blockquote]
2784 ["Preformatted" markdown-insert-pre]
2785 ["Code" markdown-insert-code]
2786 "---"
2787 ["Insert inline link" markdown-insert-link]
2788 ["Insert reference link" markdown-insert-reference-link-dwim]
2789 ["Insert image" markdown-insert-image]
2790 ["Insert horizontal rule" markdown-insert-hr]
2791 "---"
2792 ("Footnotes"
2793 ["Insert footnote" markdown-footnote-new]
2794 ["Jump to footnote text" markdown-footnote-goto-text]
2795 ["Return from footnote" markdown-footnote-return])
2796 "---"
2797 ["Check references" markdown-check-refs]
2798 ["Clean up list numbering" markdown-cleanup-list-numbers]
2799 "---"
2800 ["Version" markdown-show-version]
2804 ;;; imenu =====================================================================
2806 (defun markdown-imenu-create-index ()
2807 "Create and return an imenu index alist for the current buffer.
2808 See `imenu-create-index-function' and `imenu--index-alist' for details."
2809 (let* ((root '(nil . nil))
2810 cur-alist
2811 (cur-level 0)
2812 (empty-heading "-")
2813 (self-heading ".")
2814 hashes pos level heading)
2815 (save-excursion
2816 (goto-char (point-min))
2817 (while (re-search-forward markdown-regex-header (point-max) t)
2818 (cond
2819 ((setq heading (match-string-no-properties 1))
2820 (setq pos (match-beginning 1)
2821 level 1))
2822 ((setq heading (match-string-no-properties 3))
2823 (setq pos (match-beginning 3)
2824 level 2))
2825 ((setq hashes (match-string-no-properties 5))
2826 (setq heading (match-string-no-properties 6)
2827 pos (match-beginning 5)
2828 level (length hashes))))
2829 (let ((alist (list (cons heading pos))))
2830 (cond
2831 ((= cur-level level) ; new sibling
2832 (setcdr cur-alist alist)
2833 (setq cur-alist alist))
2834 ((< cur-level level) ; first child
2835 (dotimes (i (- level cur-level 1))
2836 (setq alist (list (cons empty-heading alist))))
2837 (if cur-alist
2838 (let* ((parent (car cur-alist))
2839 (self-pos (cdr parent)))
2840 (setcdr parent (cons (cons self-heading self-pos) alist)))
2841 (setcdr root alist)) ; primogenitor
2842 (setq cur-alist alist)
2843 (setq cur-level level))
2844 (t ; new sibling of an ancestor
2845 (let ((sibling-alist (last (cdr root))))
2846 (dotimes (i (1- level))
2847 (setq sibling-alist (last (cdar sibling-alist))))
2848 (setcdr sibling-alist alist)
2849 (setq cur-alist alist))
2850 (setq cur-level level)))))
2851 (cdr root))))
2854 ;;; Reference Checking ========================================================
2856 (defconst markdown-refcheck-buffer
2857 "*Undefined references for %buffer%*"
2858 "Pattern for name of buffer for listing undefined references.
2859 The string %buffer% will be replaced by the corresponding
2860 `markdown-mode' buffer name.")
2862 (defun markdown-get-undefined-refs ()
2863 "Return a list of undefined Markdown references.
2864 Result is an alist of pairs (reference . occurrences), where
2865 occurrences is itself another alist of pairs (label . line-number).
2866 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2867 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2868 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2869 (let ((missing))
2870 (save-excursion
2871 (goto-char (point-min))
2872 (while
2873 (re-search-forward markdown-regex-link-reference nil t)
2874 (let* ((label (match-string-no-properties 1))
2875 (reference (match-string-no-properties 2))
2876 (target (downcase (if (string= reference "[]") label reference))))
2877 (unless (markdown-reference-definition target)
2878 (let ((entry (assoc target missing)))
2879 (if (not entry)
2880 (add-to-list 'missing (cons target
2881 (list (cons label (markdown-line-number-at-pos)))) t)
2882 (setcdr entry
2883 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
2884 missing)))
2886 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
2887 "Add blank REF definition to the end of BUFFER.
2888 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2889 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2890 references so that REF disappears from the list of those links."
2891 (with-current-buffer buffer
2892 (when (not (eq major-mode 'markdown-mode))
2893 (error "Not available in current mode"))
2894 (goto-char (point-max))
2895 (indent-new-comment-line)
2896 (insert (concat ref ": ")))
2897 (switch-to-buffer-other-window buffer)
2898 (goto-char (point-max))
2899 (when recheck
2900 (markdown-check-refs t)))
2902 ;; Button which adds an empty Markdown reference definition to the end
2903 ;; of buffer specified as its 'target-buffer property. Reference name
2904 ;; is button's label
2905 (when (>= emacs-major-version 22)
2906 (define-button-type 'markdown-ref-button
2907 'help-echo "Push to create an empty reference definition"
2908 'face 'bold
2909 'action (lambda (b)
2910 (markdown-add-missing-ref-definition
2911 (button-label b) (button-get b 'target-buffer) t))))
2913 ;; Button jumping to line in buffer specified as its 'target-buffer
2914 ;; property. Line number is button's 'line property.
2915 (when (>= emacs-major-version 22)
2916 (define-button-type 'goto-line-button
2917 'help-echo "Push to go to this line"
2918 'face 'italic
2919 'action (lambda (b)
2920 (message (button-get b 'buffer))
2921 (switch-to-buffer-other-window (button-get b 'target-buffer))
2922 ;; use call-interactively to silence compiler
2923 (let ((current-prefix-arg (button-get b 'target-line)))
2924 (call-interactively 'goto-line)))))
2926 (defun markdown-check-refs (&optional silent)
2927 "Show all undefined Markdown references in current `markdown-mode' buffer.
2928 If SILENT is non-nil, do not message anything when no undefined
2929 references found.
2930 Links which have empty reference definitions are considered to be
2931 defined."
2932 (interactive "P")
2933 (when (not (eq major-mode 'markdown-mode))
2934 (error "Not available in current mode"))
2935 (let ((oldbuf (current-buffer))
2936 (refs (markdown-get-undefined-refs))
2937 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
2938 "%buffer%" (buffer-name)
2939 markdown-refcheck-buffer))))
2940 (if (null refs)
2941 (progn
2942 (when (not silent)
2943 (message "No undefined references found"))
2944 (kill-buffer refbuf))
2945 (with-current-buffer refbuf
2946 (when view-mode
2947 (View-exit-and-edit))
2948 (use-local-map button-buffer-map)
2949 (erase-buffer)
2950 (insert "Following references lack definitions:")
2951 (newline 2)
2952 (dolist (ref refs)
2953 (let ((button-label (format "%s" (car ref))))
2954 (if (>= emacs-major-version 22)
2955 ;; Create a reference button in Emacs 22
2956 (insert-text-button button-label
2957 :type 'markdown-ref-button
2958 'target-buffer oldbuf)
2959 ;; Insert reference as text in Emacs < 22
2960 (insert button-label)))
2961 (insert " (")
2962 (dolist (occurrence (cdr ref))
2963 (let ((line (cdr occurrence)))
2964 (if (>= emacs-major-version 22)
2965 ;; Create a line number button in Emacs 22
2966 (insert-button (number-to-string line)
2967 :type 'goto-line-button
2968 'target-buffer oldbuf
2969 'target-line line)
2970 ;; Insert line number as text in Emacs < 22
2971 (insert (number-to-string line)))
2972 (insert " "))) (delete-char -1)
2973 (insert ")")
2974 (newline))
2975 (view-buffer-other-window refbuf)
2976 (goto-char (point-min))
2977 (forward-line 2)))))
2980 ;;; Lists =====================================================================
2982 (defun markdown-insert-list-item (&optional arg)
2983 "Insert a new list item.
2984 If the point is inside unordered list, insert a bullet mark. If
2985 the point is inside ordered list, insert the next number followed
2986 by a period. Use the previous list item to determine the amount
2987 of whitespace to place before and after list markers.
2989 With a \\[universal-argument] prefix (i.e., when ARG is 4),
2990 decrease the indentation by one level.
2992 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
2993 increase the indentation by one level."
2994 (interactive "p")
2995 (let (bounds item-indent marker indent new-indent end)
2996 (save-match-data
2997 (setq bounds (markdown-cur-list-item-bounds))
2998 (if (not bounds)
2999 ;; When not in a list, start a new unordered one
3000 (progn
3001 (unless (markdown-cur-line-blank-p)
3002 (insert "\n"))
3003 (insert "* "))
3004 ;; Compute indentation for a new list item
3005 (setq item-indent (nth 2 bounds))
3006 (setq marker (concat (match-string 2) (match-string 3)))
3007 (setq indent (cond
3008 ((= arg 4) (max (- item-indent 4) 0))
3009 ((= arg 16) (+ item-indent 4))
3010 (t item-indent)))
3011 (setq new-indent (make-string indent 32))
3012 (goto-char (nth 1 bounds))
3013 (newline)
3014 (cond
3015 ;; Ordered list
3016 ((string-match "[0-9]" marker)
3017 (if (= arg 16) ;; starting a new column indented one more level
3018 (insert (concat new-indent "1. "))
3019 ;; travel up to the last item and pick the correct number. If
3020 ;; the argument was nil, "new-indent = item-indent" is the same,
3021 ;; so we don't need special treatment. Neat.
3022 (save-excursion
3023 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3024 (forward-line -1)))
3025 (insert (concat new-indent
3026 (int-to-string (1+ (string-to-number (match-string 1))))
3027 ". "))))
3028 ;; Unordered list
3029 ((string-match "[\\*\\+-]" marker)
3030 (insert (concat new-indent marker))))))))
3032 (defun markdown-move-list-item-up ()
3033 "Move the current list item up in the list when possible."
3034 (interactive)
3035 (let (cur prev old)
3036 (when (setq cur (markdown-cur-list-item-bounds))
3037 (setq old (point))
3038 (goto-char (nth 0 cur))
3039 (if (markdown-prev-list-item (nth 3 cur))
3040 (progn
3041 (setq prev (markdown-cur-list-item-bounds))
3042 (condition-case nil
3043 (progn
3044 (transpose-regions (nth 0 prev) (nth 1 prev)
3045 (nth 0 cur) (nth 1 cur) t)
3046 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3047 ;; Catch error in case regions overlap.
3048 (error (goto-char old))))
3049 (goto-char old)))))
3051 (defun markdown-move-list-item-down ()
3052 "Move the current list item down in the list when possible."
3053 (interactive)
3054 (let (cur next old)
3055 (when (setq cur (markdown-cur-list-item-bounds))
3056 (setq old (point))
3057 (if (markdown-next-list-item (nth 3 cur))
3058 (progn
3059 (setq next (markdown-cur-list-item-bounds))
3060 (condition-case nil
3061 (progn
3062 (transpose-regions (nth 0 cur) (nth 1 cur)
3063 (nth 0 next) (nth 1 next) nil)
3064 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3065 ;; Catch error in case regions overlap.
3066 (error (goto-char old))))
3067 (goto-char old)))))
3069 (defun markdown-demote-list-item (&optional bounds)
3070 "Indent (or demote) the current list item.
3071 Optionally, BOUNDS of the current list item may be provided if available."
3072 (interactive)
3073 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3074 (save-excursion
3075 (save-match-data
3076 (let* ((end-marker (make-marker))
3077 (end-marker (set-marker end-marker (nth 1 bounds))))
3078 (goto-char (nth 0 bounds))
3079 (while (< (point) end-marker)
3080 (unless (markdown-cur-line-blank-p)
3081 (insert " "))
3082 (forward-line)))))))
3084 (defun markdown-promote-list-item (&optional bounds)
3085 "Unindent (or promote) the current list item.
3086 Optionally, BOUNDS of the current list item may be provided if available."
3087 (interactive)
3088 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3089 (save-excursion
3090 (save-match-data
3091 (let* ((end-marker (make-marker))
3092 (end-marker (set-marker end-marker (nth 1 bounds)))
3093 num regexp)
3094 (goto-char (nth 0 bounds))
3095 (when (looking-at "^[ ]\\{1,4\\}")
3096 (setq num (- (match-end 0) (match-beginning 0)))
3097 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3098 (while (and (< (point) end-marker)
3099 (re-search-forward regexp end-marker t))
3100 (replace-match "" nil nil)
3101 (forward-line))))))))
3103 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3104 "Update the numbering for level PFX (as a string of spaces).
3106 Assume that the previously found match was for a numbered item in
3107 a list."
3108 (let ((cpfx pfx)
3109 (idx 0)
3110 (continue t)
3111 (step t)
3112 (sep nil))
3113 (while (and continue (not (eobp)))
3114 (setq step t)
3115 (cond
3116 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3117 (setq cpfx (match-string-no-properties 1))
3118 (cond
3119 ((string= cpfx pfx)
3120 (replace-match
3121 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3122 (setq sep nil))
3123 ;; indented a level
3124 ((string< pfx cpfx)
3125 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3126 (setq step nil))
3127 ;; exit the loop
3129 (setq step nil)
3130 (setq continue nil))))
3132 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3133 (setq cpfx (match-string-no-properties 1))
3134 (cond
3135 ;; reset if separated before
3136 ((string= cpfx pfx) (when sep (setq idx 0)))
3137 ((string< cpfx pfx)
3138 (setq step nil)
3139 (setq continue nil))))
3140 (t (setq sep t)))
3142 (when step
3143 (beginning-of-line)
3144 (setq continue (= (forward-line) 0))))
3145 sep))
3147 (defun markdown-cleanup-list-numbers ()
3148 "Update the numbering of ordered lists."
3149 (interactive)
3150 (save-excursion
3151 (goto-char (point-min))
3152 (markdown--cleanup-list-numbers-level "")))
3155 ;;; Outline ===================================================================
3157 (defvar markdown-cycle-global-status 1)
3158 (defvar markdown-cycle-subtree-status nil)
3160 (defun markdown-end-of-subtree (&optional invisible-OK)
3161 "Move to the end of the current subtree.
3162 Only visible heading lines are considered, unless INVISIBLE-OK is
3163 non-nil.
3164 Derived from `org-end-of-subtree'."
3165 (outline-back-to-heading invisible-OK)
3166 (let ((first t)
3167 (level (funcall outline-level)))
3168 (while (and (not (eobp))
3169 (or first (> (funcall outline-level) level)))
3170 (setq first nil)
3171 (outline-next-heading))
3172 (if (memq (preceding-char) '(?\n ?\^M))
3173 (progn
3174 ;; Go to end of line before heading
3175 (forward-char -1)
3176 (if (memq (preceding-char) '(?\n ?\^M))
3177 ;; leave blank line before heading
3178 (forward-char -1)))))
3179 (point))
3181 (defun markdown-cycle (&optional arg)
3182 "Visibility cycling for Markdown mode.
3183 If ARG is t, perform global visibility cycling. If the point is
3184 at an atx-style header, cycle visibility of the corresponding
3185 subtree. Otherwise, insert a tab using `indent-relative'.
3186 Derived from `org-cycle'."
3187 (interactive "P")
3188 (cond
3189 ((eq arg t) ;; Global cycling
3190 (cond
3191 ((and (eq last-command this-command)
3192 (eq markdown-cycle-global-status 2))
3193 ;; Move from overview to contents
3194 (hide-sublevels 1)
3195 (message "CONTENTS")
3196 (setq markdown-cycle-global-status 3))
3198 ((and (eq last-command this-command)
3199 (eq markdown-cycle-global-status 3))
3200 ;; Move from contents to all
3201 (show-all)
3202 (message "SHOW ALL")
3203 (setq markdown-cycle-global-status 1))
3206 ;; Defaults to overview
3207 (hide-body)
3208 (message "OVERVIEW")
3209 (setq markdown-cycle-global-status 2))))
3211 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3212 ;; At a heading: rotate between three different views
3213 (outline-back-to-heading)
3214 (let ((goal-column 0) eoh eol eos)
3215 ;; Determine boundaries
3216 (save-excursion
3217 (outline-back-to-heading)
3218 (save-excursion
3219 (beginning-of-line 2)
3220 (while (and (not (eobp)) ;; this is like `next-line'
3221 (get-char-property (1- (point)) 'invisible))
3222 (beginning-of-line 2)) (setq eol (point)))
3223 (outline-end-of-heading) (setq eoh (point))
3224 (markdown-end-of-subtree t)
3225 (skip-chars-forward " \t\n")
3226 (beginning-of-line 1) ; in case this is an item
3227 (setq eos (1- (point))))
3228 ;; Find out what to do next and set `this-command'
3229 (cond
3230 ((= eos eoh)
3231 ;; Nothing is hidden behind this heading
3232 (message "EMPTY ENTRY")
3233 (setq markdown-cycle-subtree-status nil))
3234 ((>= eol eos)
3235 ;; Entire subtree is hidden in one line: open it
3236 (show-entry)
3237 (show-children)
3238 (message "CHILDREN")
3239 (setq markdown-cycle-subtree-status 'children))
3240 ((and (eq last-command this-command)
3241 (eq markdown-cycle-subtree-status 'children))
3242 ;; We just showed the children, now show everything.
3243 (show-subtree)
3244 (message "SUBTREE")
3245 (setq markdown-cycle-subtree-status 'subtree))
3247 ;; Default action: hide the subtree.
3248 (hide-subtree)
3249 (message "FOLDED")
3250 (setq markdown-cycle-subtree-status 'folded)))))
3253 (indent-for-tab-command))))
3255 (defun markdown-shifttab ()
3256 "Global visibility cycling.
3257 Calls `markdown-cycle' with argument t."
3258 (interactive)
3259 (markdown-cycle t))
3261 (defun markdown-outline-level ()
3262 "Return the depth to which a statement is nested in the outline."
3263 (cond
3264 ((match-end 1) 1)
3265 ((match-end 3) 2)
3266 ((- (match-end 5) (match-beginning 5)))))
3269 ;;; Movement ==================================================================
3271 (defun markdown-beginning-of-defun (&optional arg)
3272 "`beginning-of-defun-function' for Markdown.
3273 Move backward to the beginning of the current or previous section."
3274 (interactive "P")
3275 (or arg (setq arg 1))
3276 (or (re-search-backward markdown-regex-header nil t arg)
3277 (goto-char (point-min))))
3279 (defun markdown-end-of-defun (&optional arg)
3280 "`end-of-defun-function' for Markdown.
3281 Move forward to the end of the current or following section."
3282 (interactive "P")
3283 (or arg (setq arg 1))
3284 (when (looking-at markdown-regex-header)
3285 (goto-char (match-beginning 0))
3286 (forward-char 1))
3287 (if (re-search-forward markdown-regex-header nil t arg)
3288 (goto-char (match-beginning 0))
3289 (goto-char (point-max)))
3290 (skip-syntax-backward "-"))
3292 (defun markdown-beginning-of-block ()
3293 "Move the point to the start of the previous text block."
3294 (interactive)
3295 (if (re-search-backward markdown-regex-block-separator nil t)
3296 (goto-char (or (match-end 2) (match-end 0)))
3297 (goto-char (point-min))))
3299 (defun markdown-end-of-block ()
3300 "Move the point to the start of the next text block."
3301 (interactive)
3302 (beginning-of-line)
3303 (skip-syntax-forward "-")
3304 (when (= (point) (point-min))
3305 (forward-char))
3306 (if (re-search-forward markdown-regex-block-separator nil t)
3307 (goto-char (or (match-end 2) (match-end 0)))
3308 (goto-char (point-max)))
3309 (skip-syntax-backward "-")
3310 (forward-line))
3312 (defun markdown-end-of-block-element ()
3313 "Move the point to the start of the next block unit.
3314 Stops at blank lines, list items, headers, and horizontal rules."
3315 (interactive)
3316 (forward-line)
3317 (while (and (or (not (markdown-prev-line-blank-p))
3318 (markdown-cur-line-blank-p))
3319 (not (or (looking-at markdown-regex-list)
3320 (looking-at markdown-regex-header)
3321 (looking-at markdown-regex-hr)))
3322 (not (eobp)))
3323 (forward-line)))
3326 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3328 (defun markdown-move-up ()
3329 "Move list item up.
3330 Calls `markdown-move-list-item-up'."
3331 (interactive)
3332 (markdown-move-list-item-up))
3334 (defun markdown-move-down ()
3335 "Move list item down.
3336 Calls `markdown-move-list-item-down'."
3337 (interactive)
3338 (markdown-move-list-item-down))
3340 (defun markdown-promote ()
3341 "Either promote header or list item at point or cycle markup.
3342 See `markdown-cycle-atx', `markdown-cycle-setext', and
3343 `markdown-demote-list-item'."
3344 (interactive)
3345 (let (bounds)
3346 (cond
3347 ;; Promote atx header
3348 ((thing-at-point-looking-at markdown-regex-header-atx)
3349 (markdown-cycle-atx -1 t))
3350 ;; Promote setext header
3351 ((thing-at-point-looking-at markdown-regex-header-setext)
3352 (markdown-cycle-setext -1 t))
3353 ;; Promote horizonal rule
3354 ((thing-at-point-looking-at markdown-regex-hr)
3355 (markdown-cycle-hr -1 t))
3356 ;; Promote list item
3357 ((setq bounds (markdown-cur-list-item-bounds))
3358 (markdown-promote-list-item)))))
3360 (defun markdown-demote ()
3361 "Either demote header or list item at point or cycle or remove markup.
3362 See `markdown-cycle-atx', `markdown-cycle-setext', and
3363 `markdown-demote-list-item'."
3364 (interactive)
3365 (let (bounds)
3366 (cond
3367 ;; Demote atx header
3368 ((thing-at-point-looking-at markdown-regex-header-atx)
3369 (markdown-cycle-atx 1 t))
3370 ;; Demote setext header
3371 ((thing-at-point-looking-at markdown-regex-header-setext)
3372 (markdown-cycle-setext 1 t))
3373 ;; Demote horizonal rule
3374 ((thing-at-point-looking-at markdown-regex-hr)
3375 (markdown-cycle-hr 1 t))
3376 ;; Promote list item
3377 ((setq bounds (markdown-cur-list-item-bounds))
3378 (markdown-demote-list-item))
3379 ;; Create a new level one ATX header
3381 (markdown-insert-header-atx-1)))))
3383 (defun markdown-complete-or-cycle (arg)
3384 "Complete or cycle markup of object at point or complete objects in region.
3385 If there is an active region, complete markup in region.
3386 Otherwise, complete or cycle markup of object near point.
3387 When ARG is non-nil, cycle backwards when cycling."
3388 (interactive "*P")
3389 (if (markdown-use-region-p)
3390 ;; Complete markup in region
3391 (markdown-complete-region (region-beginning) (region-end))
3392 ;; Complete or cycle markup at point
3393 (let ((dir (if arg -1 1))
3394 bounds)
3395 (cond
3396 ;; atx header
3397 ((thing-at-point-looking-at markdown-regex-header-atx)
3398 (if (markdown-incomplete-atx-p)
3399 (markdown-complete-atx)
3400 (markdown-cycle-atx dir)))
3401 ;; setext header
3402 ((thing-at-point-looking-at markdown-regex-header-setext)
3403 (if (markdown-incomplete-setext-p)
3404 (markdown-complete-setext)
3405 (markdown-cycle-setext dir)))
3406 ;; horizonal rule
3407 ((thing-at-point-looking-at markdown-regex-hr)
3408 (if (markdown-incomplete-hr-p)
3409 (markdown-complete-hr)
3410 (markdown-cycle-hr dir)))
3411 ;; bold
3412 ((thing-at-point-looking-at markdown-regex-bold)
3413 (markdown-cycle-bold))
3414 ;; italic
3415 ((thing-at-point-looking-at markdown-regex-italic)
3416 (markdown-cycle-italic))))))
3419 ;;; Commands ==================================================================
3421 (defun markdown (&optional output-buffer-name)
3422 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3423 The output buffer name defaults to `markdown-output-buffer-name'.
3424 Return the name of the output buffer used."
3425 (interactive)
3426 (save-window-excursion
3427 (let ((begin-region)
3428 (end-region))
3429 (if (markdown-use-region-p)
3430 (setq begin-region (region-beginning)
3431 end-region (region-end))
3432 (setq begin-region (point-min)
3433 end-region (point-max)))
3435 (unless output-buffer-name
3436 (setq output-buffer-name markdown-output-buffer-name))
3438 (cond
3439 ;; Handle case when `markdown-command' does not read from stdin
3440 (markdown-command-needs-filename
3441 (if (not buffer-file-name)
3442 (error "Must be visiting a file")
3443 (shell-command (concat markdown-command " "
3444 (shell-quote-argument buffer-file-name))
3445 output-buffer-name)))
3446 ;; Pass region to `markdown-command' via stdin
3448 (shell-command-on-region begin-region end-region markdown-command
3449 output-buffer-name))))
3450 output-buffer-name))
3452 (defun markdown-standalone (&optional output-buffer-name)
3453 "Special function to provide standalone HTML output.
3454 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3455 (interactive)
3456 (setq output-buffer-name (markdown output-buffer-name))
3457 (with-current-buffer output-buffer-name
3458 (set-buffer output-buffer-name)
3459 (goto-char (point-min))
3460 (unless (markdown-output-standalone-p)
3461 (markdown-add-xhtml-header-and-footer output-buffer-name))
3462 (html-mode))
3463 output-buffer-name)
3465 (defun markdown-other-window (&optional output-buffer-name)
3466 "Run `markdown-command' on current buffer and display in other window.
3467 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3468 that name."
3469 (interactive)
3470 (display-buffer (markdown-standalone output-buffer-name)))
3472 (defun markdown-output-standalone-p ()
3473 "Determine whether `markdown-command' output is standalone XHTML.
3474 Standalone XHTML output is identified by an occurrence of
3475 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3476 (re-search-forward
3477 markdown-xhtml-standalone-regexp
3478 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3481 (defun markdown-add-xhtml-header-and-footer (title)
3482 "Wrap XHTML header and footer with given TITLE around current buffer."
3483 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3484 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3485 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3486 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3487 "<head>\n<title>")
3488 (insert title)
3489 (insert "</title>\n")
3490 (when (> (length markdown-content-type) 0)
3491 (insert
3492 (format
3493 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3494 markdown-content-type
3495 (or (and markdown-coding-system
3496 (fboundp 'coding-system-get)
3497 (coding-system-get markdown-coding-system
3498 'mime-charset))
3499 (and (fboundp 'coding-system-get)
3500 (coding-system-get buffer-file-coding-system
3501 'mime-charset))
3502 "iso-8859-1"))))
3503 (if (> (length markdown-css-path) 0)
3504 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3505 markdown-css-path
3506 "\" />\n"))
3507 (when (> (length markdown-xhtml-header-content) 0)
3508 (insert markdown-xhtml-header-content))
3509 (insert "\n</head>\n\n"
3510 "<body>\n\n")
3511 (goto-char (point-max))
3512 (insert "\n"
3513 "</body>\n"
3514 "</html>\n"))
3516 (defun markdown-preview (&optional output-buffer-name)
3517 "Run `markdown-command' on the current buffer and view output in browser.
3518 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3519 that name."
3520 (interactive)
3521 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3523 (defun markdown-export-file-name (&optional extension)
3524 "Attempt to generate a filename for Markdown output.
3525 The file extension will be EXTENSION if given, or .html by default.
3526 If the current buffer is visiting a file, we construct a new
3527 output filename based on that filename. Otherwise, return nil."
3528 (when (buffer-file-name)
3529 (unless extension
3530 (setq extension ".html"))
3531 (concat
3532 (cond
3533 ((buffer-file-name)
3534 (file-name-sans-extension (buffer-file-name)))
3535 (t (buffer-name)))
3536 extension)))
3538 (defun markdown-export (&optional output-file)
3539 "Run Markdown on the current buffer, save to file, and return the filename.
3540 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3541 generated by `markdown-export-file-name', which will be constructed using the
3542 current filename, but with the extension removed and replaced with .html."
3543 (interactive)
3544 (unless output-file
3545 (setq output-file (markdown-export-file-name ".html")))
3546 (when output-file
3547 (let ((output-buffer-name))
3548 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
3549 (run-hook-with-args 'markdown-before-export-hooks output-file)
3550 (markdown-standalone output-buffer-name)
3551 (with-current-buffer output-buffer-name
3552 (save-buffer))
3553 (run-hook-with-args 'markdown-after-export-hooks output-file)
3554 output-file)))
3556 (defun markdown-export-and-preview ()
3557 "Export to XHTML using `markdown-export' and browse the resulting file."
3558 (interactive)
3559 (browse-url (markdown-export)))
3561 (defun markdown-open ()
3562 "Open file for the current buffer with `markdown-open-command'."
3563 (interactive)
3564 (if (not markdown-open-command)
3565 (error "Variable `markdown-open-command' must be set")
3566 (if (not buffer-file-name)
3567 (error "Must be visiting a file")
3568 (call-process markdown-open-command
3569 nil nil nil buffer-file-name))))
3571 (defun markdown-kill-ring-save ()
3572 "Run Markdown on file and store output in the kill ring."
3573 (interactive)
3574 (save-window-excursion
3575 (markdown)
3576 (with-current-buffer markdown-output-buffer-name
3577 (kill-ring-save (point-min) (point-max)))))
3580 ;;; Links =====================================================================
3582 (require 'thingatpt)
3584 (defun markdown-link-p ()
3585 "Return non-nil when `point' is at a non-wiki link.
3586 See `markdown-wiki-link-p' for more information."
3587 (let ((case-fold-search nil))
3588 (and (not (markdown-wiki-link-p))
3589 (or (thing-at-point-looking-at markdown-regex-link-inline)
3590 (thing-at-point-looking-at markdown-regex-link-reference)
3591 (thing-at-point-looking-at markdown-regex-uri)
3592 (thing-at-point-looking-at markdown-regex-angle-uri)))))
3594 (defun markdown-link-link ()
3595 "Return the link part of the regular (non-wiki) link at point.
3596 Works with both inline and reference style links. If point is
3597 not at a link or the link reference is not defined returns nil."
3598 (cond
3599 ((thing-at-point-looking-at markdown-regex-link-inline)
3600 (substring-no-properties (match-string 2) 1 -1))
3601 ((thing-at-point-looking-at markdown-regex-link-reference)
3602 (let* ((label (match-string-no-properties 1))
3603 (reference (match-string-no-properties 2))
3604 (target (downcase (if (string= reference "[]") label reference))))
3605 (car (markdown-reference-definition target))))
3606 ((thing-at-point-looking-at markdown-regex-uri)
3607 (match-string-no-properties 0))
3608 ((thing-at-point-looking-at markdown-regex-angle-uri)
3609 (match-string-no-properties 2))
3610 (t nil)))
3612 (defun markdown-follow-link-at-point ()
3613 "Open the current non-wiki link in a browser."
3614 (interactive)
3615 (if (markdown-link-p) (browse-url (markdown-link-link))
3616 (error "Point is not at a Markdown link or URI")))
3619 ;;; WikiLink Following/Markup =================================================
3621 (defun markdown-wiki-link-p ()
3622 "Return non-nil when `point' is at a true wiki link.
3623 A true wiki link name matches `markdown-regex-wiki-link' but does not
3624 match the current file name after conversion. This modifies the data
3625 returned by `match-data'. Note that the potential wiki link name must
3626 be available via `match-string'."
3627 (let ((case-fold-search nil))
3628 (and (thing-at-point-looking-at markdown-regex-wiki-link)
3629 (or (not buffer-file-name)
3630 (not (string-equal (buffer-file-name)
3631 (markdown-convert-wiki-link-to-filename
3632 (markdown-wiki-link-link)))))
3633 (not (save-match-data
3634 (save-excursion))))))
3636 (defun markdown-wiki-link-link ()
3637 "Return the link part of the wiki link using current match data.
3638 The location of the link component depends on the value of
3639 `markdown-wiki-link-alias-first'."
3640 (if markdown-wiki-link-alias-first
3641 (or (match-string-no-properties 4) (match-string-no-properties 2))
3642 (match-string-no-properties 2)))
3644 (defun markdown-convert-wiki-link-to-filename (name)
3645 "Generate a filename from the wiki link NAME.
3646 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3647 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3648 and [[test test]] both map to Test-test.ext."
3649 (let ((basename (markdown-replace-regexp-in-string
3650 "[[:space:]\n]" markdown-link-space-sub-char name)))
3651 (when (eq major-mode 'gfm-mode)
3652 (setq basename (concat (upcase (substring basename 0 1))
3653 (downcase (substring basename 1 nil)))))
3654 (concat basename
3655 (if (buffer-file-name)
3656 (concat "."
3657 (file-name-extension (buffer-file-name)))))))
3659 (defun markdown-follow-wiki-link (name &optional other)
3660 "Follow the wiki link NAME.
3661 Convert the name to a file name and call `find-file'. Ensure that
3662 the new buffer remains in `markdown-mode'. Open the link in another
3663 window when OTHER is non-nil."
3664 (let ((filename (markdown-convert-wiki-link-to-filename name))
3665 (wp (file-name-directory buffer-file-name)))
3666 (when other (other-window 1))
3667 (find-file (concat wp filename)))
3668 (when (not (eq major-mode 'markdown-mode))
3669 (markdown-mode)))
3671 (defun markdown-follow-wiki-link-at-point (&optional arg)
3672 "Find Wiki Link at point.
3673 With prefix argument ARG, open the file in other window.
3674 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3675 (interactive "P")
3676 (if (markdown-wiki-link-p)
3677 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
3678 (error "Point is not at a Wiki Link")))
3680 (defun markdown-next-wiki-link ()
3681 "Jump to next wiki link.
3682 If successful, return point. Otherwise, return nil.
3683 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3684 (interactive)
3685 (let ((opoint (point)))
3686 (when (markdown-wiki-link-p)
3687 ;; At a wiki link already, move past it.
3688 (goto-char (+ (match-end 0) 1)))
3689 ;; Search for the next wiki link and move to the beginning.
3690 (if (re-search-forward markdown-regex-wiki-link nil t)
3691 (goto-char (match-beginning 1))
3692 (goto-char opoint)
3693 nil)))
3695 (defun markdown-previous-wiki-link ()
3696 "Jump to previous wiki link.
3697 If successful, return point. Otherwise, return nil.
3698 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3699 (interactive)
3700 (if (re-search-backward markdown-regex-wiki-link nil t)
3701 (goto-char (match-beginning 1))
3702 nil))
3704 (defun markdown-highlight-wiki-link (from to face)
3705 "Highlight the wiki link in the region between FROM and TO using FACE."
3706 (put-text-property from to 'font-lock-face face))
3708 (defun markdown-unfontify-region-wiki-links (from to)
3709 "Remove wiki link faces from the region specified by FROM and TO."
3710 (interactive "nfrom: \nnto: ")
3711 (remove-text-properties from to '(font-lock-face markdown-link-face))
3712 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
3714 (defun markdown-fontify-region-wiki-links (from to)
3715 "Search region given by FROM and TO for wiki links and fontify them.
3716 If a wiki link is found check to see if the backing file exists
3717 and highlight accordingly."
3718 (goto-char from)
3719 (save-match-data
3720 (while (re-search-forward markdown-regex-wiki-link to t)
3721 (let ((highlight-beginning (match-beginning 1))
3722 (highlight-end (match-end 1))
3723 (file-name
3724 (markdown-convert-wiki-link-to-filename
3725 (markdown-wiki-link-link))))
3726 (if (file-exists-p file-name)
3727 (markdown-highlight-wiki-link
3728 highlight-beginning highlight-end markdown-link-face)
3729 (markdown-highlight-wiki-link
3730 highlight-beginning highlight-end markdown-link-face)
3731 (markdown-highlight-wiki-link
3732 highlight-beginning highlight-end markdown-missing-link-face))))))
3734 (defun markdown-extend-changed-region (from to)
3735 "Extend region given by FROM and TO so that we can fontify all links.
3736 The region is extended to the first newline before and the first
3737 newline after."
3738 ;; start looking for the first new line before 'from
3739 (goto-char from)
3740 (re-search-backward "\n" nil t)
3741 (let ((new-from (point-min))
3742 (new-to (point-max)))
3743 (if (not (= (point) from))
3744 (setq new-from (point)))
3745 ;; do the same thing for the first new line after 'to
3746 (goto-char to)
3747 (re-search-forward "\n" nil t)
3748 (if (not (= (point) to))
3749 (setq new-to (point)))
3750 (values new-from new-to)))
3752 (defun markdown-check-change-for-wiki-link (from to change)
3753 "Check region between FROM and TO for wiki links and re-fontfy as needed.
3754 Designed to be used with the `after-change-functions' hook.
3755 CHANGE is the number of bytes of pre-change text replaced by the
3756 given range."
3757 (interactive "nfrom: \nnto: \nnchange: ")
3758 (let* ((modified (buffer-modified-p))
3759 (buffer-undo-list t)
3760 (inhibit-read-only t)
3761 (inhibit-point-motion-hooks t)
3762 deactivate-mark
3763 buffer-file-truename)
3764 (unwind-protect
3765 (save-excursion
3766 (save-match-data
3767 (save-restriction
3768 ;; Extend the region to fontify so that it starts
3769 ;; and ends at safe places.
3770 (multiple-value-bind (new-from new-to)
3771 (markdown-extend-changed-region from to)
3772 ;; Unfontify existing fontification (start from scratch)
3773 (markdown-unfontify-region-wiki-links new-from new-to)
3774 ;; Now do the fontification.
3775 (markdown-fontify-region-wiki-links new-from new-to)))))
3776 (and (not modified)
3777 (buffer-modified-p)
3778 (set-buffer-modified-p nil)))))
3780 (defun markdown-fontify-buffer-wiki-links ()
3781 "Refontify all wiki links in the buffer."
3782 (interactive)
3783 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
3786 ;;; Generic Following =========================================================
3788 (defun markdown-follow-thing-at-point (arg)
3789 "Follow thing at point if possible, such as a reference link or wiki link.
3790 Opens inline and reference links in a browser. Opens wiki links
3791 to other files in the current window, or the another window if
3792 ARG is non-nil.
3793 See `markdown-follow-link-at-point' and
3794 `markdown-follow-wiki-link-at-point'."
3795 (interactive "P")
3796 (cond ((markdown-link-p)
3797 (markdown-follow-link-at-point))
3798 ((markdown-wiki-link-p)
3799 (markdown-follow-wiki-link-at-point arg))))
3802 ;;; Miscellaneous =============================================================
3804 (defun markdown-compress-whitespace-string (str)
3805 "Compress whitespace in STR and return result.
3806 Leading and trailing whitespace is removed. Sequences of multiple
3807 spaces, tabs, and newlines are replaced with single spaces."
3808 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
3809 (replace-regexp-in-string "[ \t\n]+" " " str)))
3811 (defun markdown-line-number-at-pos (&optional pos)
3812 "Return (narrowed) buffer line number at position POS.
3813 If POS is nil, use current buffer location.
3814 This is an exact copy of `line-number-at-pos' for use in emacs21."
3815 (let ((opoint (or pos (point))) start)
3816 (save-excursion
3817 (goto-char (point-min))
3818 (setq start (point))
3819 (goto-char opoint)
3820 (forward-line 0)
3821 (1+ (count-lines start (point))))))
3823 (defun markdown-nobreak-p ()
3824 "Return nil if it is acceptable to break the current line at the point."
3825 ;; inside in square brackets (e.g., link anchor text)
3826 (looking-back "\\[[^]]*"))
3829 ;;; Mode Definition ==========================================================
3831 (defun markdown-show-version ()
3832 "Show the version number in the minibuffer."
3833 (interactive)
3834 (message "markdown-mode, version %s" markdown-mode-version))
3836 ;;;###autoload
3837 (define-derived-mode markdown-mode text-mode "Markdown"
3838 "Major mode for editing Markdown files."
3839 ;; Natural Markdown tab width
3840 (setq tab-width 4)
3841 ;; Comments
3842 (make-local-variable 'comment-start)
3843 (setq comment-start "<!-- ")
3844 (make-local-variable 'comment-end)
3845 (setq comment-end " -->")
3846 (make-local-variable 'comment-start-skip)
3847 (setq comment-start-skip "<!--[ \t]*")
3848 (make-local-variable 'comment-column)
3849 (setq comment-column 0)
3850 ;; Font lock.
3851 (set (make-local-variable 'font-lock-defaults)
3852 '(markdown-mode-font-lock-keywords))
3853 (set (make-local-variable 'font-lock-multiline) t)
3854 ;; For imenu support
3855 (setq imenu-create-index-function 'markdown-imenu-create-index)
3856 ;; For menu support in XEmacs
3857 (easy-menu-add markdown-mode-menu markdown-mode-map)
3858 ;; Defun movement
3859 (set (make-local-variable 'beginning-of-defun-function)
3860 'markdown-beginning-of-defun)
3861 (set (make-local-variable 'end-of-defun-function)
3862 'markdown-end-of-defun)
3863 ;; Make filling work with lists (unordered, ordered, and definition)
3864 (set (make-local-variable 'paragraph-start)
3865 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
3866 ;; Outline mode
3867 (make-local-variable 'outline-regexp)
3868 (setq outline-regexp markdown-regex-header)
3869 (make-local-variable 'outline-level)
3870 (setq outline-level 'markdown-outline-level)
3871 ;; Cause use of ellipses for invisible text.
3872 (add-to-invisibility-spec '(outline . t))
3873 ;; Indentation and filling
3874 (make-local-variable 'fill-nobreak-predicate)
3875 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
3876 (setq indent-line-function markdown-indent-function)
3878 ;; Prepare hooks for XEmacs compatibility
3879 (when (featurep 'xemacs)
3880 (make-local-hook 'after-change-functions)
3881 (make-local-hook 'font-lock-extend-region-functions)
3882 (make-local-hook 'window-configuration-change-hook))
3884 ;; Multiline font lock
3885 (add-hook 'font-lock-extend-region-functions
3886 'markdown-font-lock-extend-region)
3888 ;; Anytime text changes make sure it gets fontified correctly
3889 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
3891 ;; If we left the buffer there is a really good chance we were
3892 ;; creating one of the wiki link documents. Make sure we get
3893 ;; refontified when we come back.
3894 (add-hook 'window-configuration-change-hook
3895 'markdown-fontify-buffer-wiki-links t t)
3897 ;; do the initial link fontification
3898 (markdown-fontify-buffer-wiki-links))
3900 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
3903 ;;; GitHub Flavored Markdown Mode ============================================
3905 (defvar gfm-font-lock-keywords
3906 (append
3907 ;; GFM features to match first
3908 (list
3909 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
3910 (2 markdown-language-keyword-face)
3911 (3 markdown-pre-face)
3912 (4 markdown-pre-face))))
3913 ;; Basic Markdown features (excluding possibly overridden ones)
3914 markdown-mode-font-lock-keywords-basic
3915 ;; GFM features to match last
3916 (list
3917 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
3918 "Default highlighting expressions for GitHub-flavored Markdown mode.")
3920 ;;;###autoload
3921 (define-derived-mode gfm-mode markdown-mode "GFM"
3922 "Major mode for editing GitHub Flavored Markdown files."
3923 (setq markdown-link-space-sub-char "-")
3924 (set (make-local-variable 'font-lock-defaults)
3925 '(gfm-font-lock-keywords))
3926 (auto-fill-mode 0)
3927 ;; Use visual-line-mode if available, fall back to longlines-mode:
3928 (if (fboundp 'visual-line-mode)
3929 (visual-line-mode 1)
3930 (longlines-mode 1))
3931 ;; do the initial link fontification
3932 (markdown-fontify-buffer-wiki-links))
3935 (provide 'markdown-mode)
3937 ;;; markdown-mode.el ends here