Small documentation fix
[markdown-mode.git] / markdown-mode.el
blob0f63d1e5672cc538eb5fd73cfb1d03dc927c9a0b
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 ;; * Jumping:
328 ;; Use `C-c C-j` to jump from the object at point to its counterpart
329 ;; elsewhere in the text, when possible. Jumps between reference
330 ;; links and definitions; between footnote markers and footnote
331 ;; text. If more than one link uses the same reference text, a
332 ;; new buffer will be created containing clickable links to each
333 ;; link using the given reference in the main buffer.
335 ;; * Wiki-Link Navigation:
337 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
338 ;; wiki links, respectively.
340 ;; * Outline Navigation:
342 ;; Navigation between headings is possible using `outline-mode'.
343 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
344 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
345 ;; next and previous visible headings at the same level as the one
346 ;; at the point. Finally, `C-M-u` will move up to a lower-level
347 ;; (more inclusive) visible heading.
349 ;; * Movement by Block:
351 ;; markdown-mode supports the usual Emacs paragraph movement with
352 ;; `M-{` and `M-}`. These commands treat list items as
353 ;; paragraphs, so they will stop at each line within a block of
354 ;; list items. Additionally, markdown-mode includes movement
355 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
356 ;; of an entire block of text (with blocks being separated by at
357 ;; least one blank line).
359 ;; * Movement by Defun:
361 ;; The usual Emacs commands can be used to move by defuns
362 ;; (top-level major definitions). In markdown-mode, a defun
363 ;; is a section. As usual, `C-M-a` will move the point to
364 ;; the beginning of the current or preceding defun, `C-M-e`
365 ;; will move to the end of the current or following defun,
366 ;; and `C-M-h` will put the region around the entire defun.
368 ;; Many of the commands described above behave differently depending on
369 ;; whether Transient Mark mode is enabled or not. When it makes sense,
370 ;; if Transient Mark mode is on and a region is active, the command
371 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
372 ;; bold). For users who prefer to work outside of Transient Mark mode,
373 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
375 ;; When applicable, commands that specifically act on the region even
376 ;; outside of Transient Mark mode have the same keybinding as the with
377 ;; the exception of an additional `C-` prefix. For example,
378 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
379 ;; the region in Transient Mark mode while `markdown-blockquote-region'
380 ;; is bound to `C-c C-s C-b` and always applies to the region (when
381 ;; nonempty).
383 ;; markdown-mode attempts to be flexible in how it handles
384 ;; indentation. When you press `TAB` repeatedly, the point will cycle
385 ;; through several possible indentation levels corresponding to things
386 ;; you might have in mind when you press `RET` at the end of a line or
387 ;; `TAB`. For example, you may want to start a new list item,
388 ;; continue a list item with hanging indentation, indent for a nested
389 ;; pre block, and so on.
391 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
392 ;; visibility cycling for atx- or hash-style headers. There are two
393 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
394 ;; the table of contents view (headers only), outline view (top-level
395 ;; headers only), and the full document view. Pressing `TAB` while the
396 ;; point is at a header will cycle through levels of visibility for the
397 ;; subtree: completely folded, visible children, and fully visible.
398 ;; Note that mixing hash and underline style headers will give undesired
399 ;; results.
401 ;;; Extensions:
403 ;; Besides supporting the basic Markdown syntax, markdown-mode also
404 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
405 ;; links may be followed automatically by pressing the enter key when
406 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
407 ;; auto-following on enter key may be controlled with the
408 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
409 ;; `M-n` to quickly jump to the previous and next wiki links,
410 ;; respectively. Aliased or piped wiki links of the form
411 ;; `[[link text|PageName]]` are also supported. Since some wikis
412 ;; reverse these components, set `markdown-wiki-link-alias-first'
413 ;; to nil to treat them as `[[PageName|link text]]`.
415 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
416 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
417 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
418 ;; You can do this either by using `M-x customize-group markdown`
419 ;; or by placing the following in your `.emacs` file:
421 ;; (defun markdown-custom ()
422 ;; "markdown-mode-hook"
423 ;; (setq markdown-command "markdown | smartypants"))
424 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
426 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
428 ;; Experimental syntax highlighting for mathematical expressions written
429 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
430 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
431 ;; either via customize or by placing `(setq markdown-enable-itex t)`
432 ;; in `.emacs`, and restarting Emacs.
434 ;;; GitHub Flavored Markdown:
436 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
437 ;; available. The GitHub implementation of differs slightly from
438 ;; standard Markdown. The most important differences are that
439 ;; newlines are significant, triggering hard line breaks, and that
440 ;; underscores inside of words (e.g., variable names) need not be
441 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
442 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
443 ;; not available). Underscores inside of words (such as
444 ;; test_variable) will not trigger emphasis.
446 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
447 ;; replacing spaces in filenames and where the first letter of the
448 ;; filename capitalized. For example, `[[wiki link]]' will map to a
449 ;; file named `Wiki-link` with the same extension as the current file.
451 ;; GFM code blocks, with optional programming language keywords, will
452 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
453 ;; is an active region, the text in the region will be placed inside
454 ;; the code block. You will be prompted for the name of the language,
455 ;; but may press enter to continue without naming a language.
457 ;; For a more complete GitHub-flavored markdown experience, consider
458 ;; adding README.md to your `auto-mode-alist':
460 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
462 ;; For GFM preview can be powered by setting `markdown-command' to
463 ;; use [Docter][]. This may also be configured to work with [Marked][]
464 ;; for `markdown-open-command'.
466 ;; [GFM]: http://github.github.com/github-flavored-markdown/
467 ;; [Docter]: https://github.com/alampros/Docter
469 ;;; Acknowledgments:
471 ;; markdown-mode has benefited greatly from the efforts of the
472 ;; following people:
474 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
475 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
476 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
477 ;; GitHub Flavored Markdown mode (`gfm-mode').
478 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
479 ;; `markdown' with an active region.
480 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
481 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
482 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
483 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
484 ;; visibility cycling functionality was derived, and for a bug fix
485 ;; related to orgtbl-mode.
486 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
487 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
488 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
489 ;; compatibility and custom CSS.
490 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
491 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
492 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
493 ;; comment matching functions were derived.
494 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
495 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
496 ;; functions, bug reports regarding indentation, and
497 ;; fixes for byte-compilation warnings.
498 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
499 ;; enhancements.
500 ;; * George Ogata <george.ogata@gmail.com> for fixing several
501 ;; byte-compilation warnings.
502 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
503 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
504 ;; customizations and XHTML export.
505 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
506 ;; Markdown processors which do not accept input from stdin.
507 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
508 ;; regarding the cl dependency and auto-fill-mode and indentation.
509 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
510 ;; substitution character for mapping wiki links to filenames.
511 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
512 ;; escape shell commands.
513 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
514 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
515 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
516 ;; Emacs Lisp coding conventions.
517 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
518 ;; regexp, refactoring the compilation and preview functions,
519 ;; heading font-lock generalizations, list renumbering,
520 ;; and kill ring save.
521 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
522 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
523 ;; for an autoload token for `gfm-mode'.
524 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
525 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
526 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
527 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
528 ;; declaration in XHTML output.
529 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
530 ;; un-indentation function.
531 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
532 ;; and GFM code block insertion.
533 ;; * Peter Jones <pjones@pmade.com> for link following functions.
534 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
535 ;; externally modified files.
536 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
537 ;; related to orgtbl-mode.
538 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
539 ;; export hooks and unit test improvements.
540 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
542 ;;; Bugs:
544 ;; Although markdown-mode is developed and tested primarily using
545 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
546 ;; priority.
548 ;; If you find any bugs in markdown-mode, please construct a test case
549 ;; or a patch and email me at <jrblevin@sdf.org>.
551 ;;; History:
553 ;; markdown-mode was written and is maintained by Jason Blevins. The
554 ;; first version was released on May 24, 2007.
556 ;; * 2007-05-24: Version 1.1
557 ;; * 2007-05-25: Version 1.2
558 ;; * 2007-06-05: [Version 1.3][]
559 ;; * 2007-06-29: Version 1.4
560 ;; * 2008-05-24: [Version 1.5][]
561 ;; * 2008-06-04: [Version 1.6][]
562 ;; * 2009-10-01: [Version 1.7][]
563 ;; * 2011-08-12: [Version 1.8][]
564 ;; * 2011-08-15: [Version 1.8.1][]
565 ;; * 2013-01-25: [Version 1.9][]
567 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
568 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
569 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
570 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
571 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
572 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
573 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
576 ;;; Code:
578 (require 'easymenu)
579 (require 'outline)
580 (eval-when-compile (require 'cl))
583 ;;; Constants =================================================================
585 (defconst markdown-mode-version "1.9"
586 "Markdown mode version number.")
588 (defconst markdown-output-buffer-name "*markdown-output*"
589 "Name of temporary buffer for markdown command output.")
592 ;;; Customizable Variables ====================================================
594 (defvar markdown-mode-hook nil
595 "Hook run when entering Markdown mode.")
597 (defvar markdown-before-export-hooks nil
598 "Hook run before output XHTML.
599 This hook is abnormal and registered functions are given an argument that is output filename.")
601 (defvar markdown-after-export-hooks nil
602 "Hook run after output XHTML.
603 This hook is abnormal and registered functions are given an argument that is output filename.")
605 (defgroup markdown nil
606 "Major mode for editing text files in Markdown format."
607 :prefix "markdown-"
608 :group 'wp
609 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
611 (defcustom markdown-command "markdown"
612 "Command to run markdown."
613 :group 'markdown
614 :type 'string)
616 (defcustom markdown-command-needs-filename nil
617 "Set to non-nil if `markdown-command' does not accept input from stdin.
618 Instead, it will be passed a filename as the final command line
619 option. As a result, you will only be able to run Markdown from
620 buffers which are visiting a file."
621 :group 'markdown
622 :type 'boolean)
624 (defcustom markdown-open-command nil
625 "Command used for opening Markdown files directly.
626 For example, a standalone Markdown previewer. This command will
627 be called with a single argument: the filename of the current
628 buffer."
629 :group 'markdown
630 :type 'string)
632 (defcustom markdown-hr-strings
633 '("* * * * *"
634 "---------"
635 "* * * * * * * * * * * * * * * * * * * *"
636 "---------------------------------------"
637 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
638 "-------------------------------------------------------------------------------")
639 "Strings to use when inserting horizontal rules.
640 The first string in the list will be the default when inserting a
641 horizontal rule. Strings should be listed in increasing order of
642 prominence for use with promotion and demotion functions."
643 :group 'markdown
644 :type 'list)
646 (defcustom markdown-bold-underscore nil
647 "Use two underscores for bold instead of two asterisks."
648 :group 'markdown
649 :type 'boolean)
651 (defcustom markdown-italic-underscore nil
652 "Use underscores for italic instead of asterisks."
653 :group 'markdown
654 :type 'boolean)
656 (defcustom markdown-indent-function 'markdown-indent-line
657 "Function to use to indent."
658 :group 'markdown
659 :type 'function)
661 (defcustom markdown-indent-on-enter t
662 "Automatically indent new lines when enter key is pressed."
663 :group 'markdown
664 :type 'boolean)
666 (defcustom markdown-follow-wiki-link-on-enter t
667 "Follow wiki link at point (if any) when the enter key is pressed."
668 :group 'markdown
669 :type 'boolean)
671 (defcustom markdown-wiki-link-alias-first t
672 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
673 Otherwise, they will be treated as [[PageName|alias text]]."
674 :group 'markdown
675 :type 'boolean)
677 (defcustom markdown-uri-types
678 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
679 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
680 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
681 "Link types for syntax highlighting of URIs."
682 :group 'markdown
683 :type 'list)
685 (defcustom markdown-enable-math nil
686 "Syntax highlighting for inline LaTeX expressions.
687 This will not take effect until Emacs is restarted."
688 :group 'markdown
689 :type 'boolean)
691 (defcustom markdown-css-path ""
692 "URL of CSS file to link to in the output XHTML."
693 :group 'markdown
694 :type 'string)
696 (defcustom markdown-content-type ""
697 "Content type string for the http-equiv header in XHTML output.
698 When set to a non-empty string, insert the http-equiv attribute.
699 Otherwise, this attribute is omitted."
700 :group 'markdown
701 :type 'string)
703 (defcustom markdown-coding-system nil
704 "Character set string for the http-equiv header in XHTML output.
705 Defaults to `buffer-file-coding-system' (and falling back to
706 `iso-8859-1' when not available). Common settings are `utf-8'
707 and `iso-latin-1'. Use `list-coding-systems' for more choices."
708 :group 'markdown
709 :type 'coding-system)
711 (defcustom markdown-xhtml-header-content ""
712 "Additional content to include in the XHTML <head> block."
713 :group 'markdown
714 :type 'string)
716 (defcustom markdown-xhtml-standalone-regexp
717 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
718 "Regexp indicating whether `markdown-command' output is standalone XHTML."
719 :group 'markdown
720 :type 'regexp)
722 (defcustom markdown-link-space-sub-char
724 "Character to use instead of spaces when mapping wiki links to filenames."
725 :group 'markdown
726 :type 'string)
728 (defcustom markdown-footnote-location 'end
729 "Position where new footnotes are inserted in the document."
730 :group 'markdown
731 :type '(choice (const :tag "At the end of the document" end)
732 (const :tag "Immediately after the paragraph" immediately)
733 (const :tag "Before next header" header)))
736 ;;; Font Lock =================================================================
738 (require 'font-lock)
740 (defvar markdown-italic-face 'markdown-italic-face
741 "Face name to use for italic text.")
743 (defvar markdown-bold-face 'markdown-bold-face
744 "Face name to use for bold text.")
746 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
747 "Face name to use as a base for header delimiters.")
749 (defvar markdown-header-rule-face 'markdown-header-rule-face
750 "Face name to use as a base for header rules.")
752 (defvar markdown-header-face 'markdown-header-face
753 "Face name to use as a base for headers.")
755 (defvar markdown-header-face-1 'markdown-header-face-1
756 "Face name to use for level-1 headers.")
758 (defvar markdown-header-face-2 'markdown-header-face-2
759 "Face name to use for level-2 headers.")
761 (defvar markdown-header-face-3 'markdown-header-face-3
762 "Face name to use for level-3 headers.")
764 (defvar markdown-header-face-4 'markdown-header-face-4
765 "Face name to use for level-4 headers.")
767 (defvar markdown-header-face-5 'markdown-header-face-5
768 "Face name to use for level-5 headers.")
770 (defvar markdown-header-face-6 'markdown-header-face-6
771 "Face name to use for level-6 headers.")
773 (defvar markdown-inline-code-face 'markdown-inline-code-face
774 "Face name to use for inline code.")
776 (defvar markdown-list-face 'markdown-list-face
777 "Face name to use for list markers.")
779 (defvar markdown-blockquote-face 'markdown-blockquote-face
780 "Face name to use for blockquote.")
782 (defvar markdown-pre-face 'markdown-pre-face
783 "Face name to use for preformatted text.")
785 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
786 "Face name to use for programming language identifiers.")
788 (defvar markdown-link-face 'markdown-link-face
789 "Face name to use for links.")
791 (defvar markdown-missing-link-face 'markdown-missing-link-face
792 "Face name to use for links where the linked file does not exist.")
794 (defvar markdown-reference-face 'markdown-reference-face
795 "Face name to use for reference.")
797 (defvar markdown-footnote-face 'markdown-footnote-face
798 "Face name to use for footnote identifiers.")
800 (defvar markdown-url-face 'markdown-url-face
801 "Face name to use for URLs.")
803 (defvar markdown-link-title-face 'markdown-link-title-face
804 "Face name to use for reference link titles.")
806 (defvar markdown-comment-face 'markdown-comment-face
807 "Face name to use for HTML comments.")
809 (defvar markdown-math-face 'markdown-math-face
810 "Face name to use for LaTeX expressions.")
812 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
813 "Face name to use for metadata keys.")
815 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
816 "Face name to use for metadata values.")
818 (defgroup markdown-faces nil
819 "Faces used in Markdown Mode"
820 :group 'markdown
821 :group 'faces)
823 (defface markdown-italic-face
824 '((t (:inherit font-lock-variable-name-face :slant italic)))
825 "Face for italic text."
826 :group 'markdown-faces)
828 (defface markdown-bold-face
829 '((t (:inherit font-lock-variable-name-face :weight bold)))
830 "Face for bold text."
831 :group 'markdown-faces)
833 (defface markdown-header-rule-face
834 '((t (:inherit font-lock-function-name-face :weight bold)))
835 "Base face for headers rules."
836 :group 'markdown-faces)
838 (defface markdown-header-delimiter-face
839 '((t (:inherit font-lock-function-name-face :weight bold)))
840 "Base face for headers hash delimiter."
841 :group 'markdown-faces)
843 (defface markdown-header-face
844 '((t (:inherit font-lock-function-name-face :weight bold)))
845 "Base face for headers."
846 :group 'markdown-faces)
848 (defface markdown-header-face-1
849 '((t (:inherit markdown-header-face)))
850 "Face for level-1 headers."
851 :group 'markdown-faces)
853 (defface markdown-header-face-2
854 '((t (:inherit markdown-header-face)))
855 "Face for level-2 headers."
856 :group 'markdown-faces)
858 (defface markdown-header-face-3
859 '((t (:inherit markdown-header-face)))
860 "Face for level-3 headers."
861 :group 'markdown-faces)
863 (defface markdown-header-face-4
864 '((t (:inherit markdown-header-face)))
865 "Face for level-4 headers."
866 :group 'markdown-faces)
868 (defface markdown-header-face-5
869 '((t (:inherit markdown-header-face)))
870 "Face for level-5 headers."
871 :group 'markdown-faces)
873 (defface markdown-header-face-6
874 '((t (:inherit markdown-header-face)))
875 "Face for level-6 headers."
876 :group 'markdown-faces)
878 (defface markdown-inline-code-face
879 '((t (:inherit font-lock-constant-face)))
880 "Face for inline code."
881 :group 'markdown-faces)
883 (defface markdown-list-face
884 '((t (:inherit font-lock-builtin-face)))
885 "Face for list item markers."
886 :group 'markdown-faces)
888 (defface markdown-blockquote-face
889 '((t (:inherit font-lock-doc-face)))
890 "Face for blockquote sections."
891 :group 'markdown-faces)
893 (defface markdown-pre-face
894 '((t (:inherit font-lock-constant-face)))
895 "Face for preformatted text."
896 :group 'markdown-faces)
898 (defface markdown-language-keyword-face
899 '((t (:inherit font-lock-type-face)))
900 "Face for programming language identifiers."
901 :group 'markdown-faces)
903 (defface markdown-link-face
904 '((t (:inherit font-lock-keyword-face)))
905 "Face for links."
906 :group 'markdown-faces)
908 (defface markdown-missing-link-face
909 '((t (:inherit font-lock-warning-face)))
910 "Face for missing links."
911 :group 'markdown-faces)
913 (defface markdown-reference-face
914 '((t (:inherit font-lock-type-face)))
915 "Face for link references."
916 :group 'markdown-faces)
918 (defface markdown-footnote-face
919 '((t (:inherit font-lock-keyword-face)))
920 "Face for footnote markers."
921 :group 'markdown-faces)
923 (defface markdown-url-face
924 '((t (:inherit font-lock-string-face)))
925 "Face for URLs."
926 :group 'markdown-faces)
928 (defface markdown-link-title-face
929 '((t (:inherit font-lock-comment-face)))
930 "Face for reference link titles."
931 :group 'markdown-faces)
933 (defface markdown-comment-face
934 '((t (:inherit font-lock-comment-face)))
935 "Face for HTML comments."
936 :group 'markdown-faces)
938 (defface markdown-math-face
939 '((t (:inherit font-lock-string-face)))
940 "Face for LaTeX expressions."
941 :group 'markdown-faces)
943 (defface markdown-metadata-key-face
944 '((t (:inherit font-lock-variable-name-face)))
945 "Face for metadata keys."
946 :group 'markdown-faces)
948 (defface markdown-metadata-value-face
949 '((t (:inherit font-lock-string-face)))
950 "Face for metadata values."
951 :group 'markdown-faces)
953 (defconst markdown-regex-link-inline
954 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
955 "Regular expression for a [text](file) or an image link ![text](file).")
957 (defconst markdown-regex-link-reference
958 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
959 "Regular expression for a reference link [text][id].")
961 (defconst markdown-regex-reference-definition
962 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
963 "Regular expression for a link definition [id]: ...")
965 (defconst markdown-regex-footnote
966 "\\(\\[\\^.+?\\]\\)"
967 "Regular expression for a footnote marker [^fn].")
969 (defconst markdown-regex-header
970 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
971 "Regexp identifying Markdown headers.")
973 (defconst markdown-regex-header-1-atx
974 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
975 "Regular expression for level 1 atx-style (hash mark) headers.")
977 (defconst markdown-regex-header-2-atx
978 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
979 "Regular expression for level 2 atx-style (hash mark) headers.")
981 (defconst markdown-regex-header-3-atx
982 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
983 "Regular expression for level 3 atx-style (hash mark) headers.")
985 (defconst markdown-regex-header-4-atx
986 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
987 "Regular expression for level 4 atx-style (hash mark) headers.")
989 (defconst markdown-regex-header-5-atx
990 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
991 "Regular expression for level 5 atx-style (hash mark) headers.")
993 (defconst markdown-regex-header-6-atx
994 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
995 "Regular expression for level 6 atx-style (hash mark) headers.")
997 (defconst markdown-regex-header-1-setext
998 "^\\(.*\\)\n\\(=+\\)$"
999 "Regular expression for level 1 setext-style (underline) headers.")
1001 (defconst markdown-regex-header-2-setext
1002 "^\\(.*\\)\n\\(-+\\)$"
1003 "Regular expression for level 2 setext-style (underline) headers.")
1005 (defconst markdown-regex-header-setext
1006 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1007 "Regular expression for generic setext-style (underline) headers.")
1009 (defconst markdown-regex-header-atx
1010 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1011 "Regular expression for generic atx-style (hash mark) headers.")
1013 (defconst markdown-regex-hr
1014 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1015 "Regular expression for matching Markdown horizontal rules.")
1017 (defconst markdown-regex-code
1018 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1019 "Regular expression for matching inline code fragments.
1021 The first group ensures that the leading backquote character
1022 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1023 character, including newlines, but not two newlines in a row.
1024 The final group requires that the character following the code
1025 fragment is not a backquote.")
1027 (defconst markdown-regex-pre
1028 "^\\( \\|\t\\).*$"
1029 "Regular expression for matching preformatted text sections.")
1031 (defconst markdown-regex-list
1032 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1033 "Regular expression for matching list items.")
1035 (defconst markdown-regex-bold
1036 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1037 "Regular expression for matching bold 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-italic
1045 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1046 "Regular expression for matching italic text.
1047 Group 1 matches the character before the opening asterisk or
1048 underscore, if any, ensuring that it is not a backslash escape.
1049 Group 2 matches the entire expression, including delimiters.
1050 Groups 3 and 5 matches the opening and closing delimiters.
1051 Group 4 matches the text inside the delimiters.")
1053 (defconst markdown-regex-gfm-italic
1054 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1055 "Regular expression for matching italic text in GitHub-flavored Markdown.
1056 Underscores in words are not treated as special.")
1058 (defconst markdown-regex-blockquote
1059 "^[ \t]*\\(>\\).*$"
1060 "Regular expression for matching blockquote lines.")
1062 (defconst markdown-regex-line-break
1063 " $"
1064 "Regular expression for matching line breaks.")
1066 (defconst markdown-regex-wiki-link
1067 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1068 "Regular expression for matching wiki links.
1069 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1070 wiki links of the form [[PageName|link text]]. In this regular
1071 expression, #1 matches the page name and #3 matches the link
1072 text.")
1074 (defconst markdown-regex-uri
1075 (concat
1076 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
1077 "\\):[^]\t\n\r<>,;() ]+")
1078 "Regular expression for matching inline URIs.")
1080 (defconst markdown-regex-angle-uri
1081 (concat
1082 "\\(<\\)\\(\\(?:"
1083 (mapconcat 'identity markdown-uri-types "\\|")
1084 "\\):[^]\t\n\r<>,;()]+\\)\\(>\\)")
1085 "Regular expression for matching inline URIs in angle brackets.")
1087 (defconst markdown-regex-email
1088 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
1089 "Regular expression for matching inline email addresses.")
1091 (defconst markdown-regex-block-separator
1092 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1093 "Regular expression for matching block boundaries.")
1095 (defconst markdown-regex-latex-expression
1096 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1097 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1099 (defconst markdown-regex-latex-display
1100 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1101 "Regular expression for itex \[..\] display mode expressions.")
1103 (defconst markdown-regex-multimarkdown-metadata
1104 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1105 "Regular expression for matching MultiMarkdown metadata.")
1107 (defconst markdown-regex-pandoc-metadata
1108 "^\\(%\\)[ \t]*\\(.*\\)$"
1109 "Regular expression for matching Pandoc metadata.")
1111 (defvar markdown-mode-font-lock-keywords-basic
1112 (list
1113 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1114 (2 markdown-metadata-value-face)))
1115 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1116 (2 markdown-metadata-value-face)))
1117 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1118 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1119 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1120 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1121 (2 markdown-header-rule-face)))
1122 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1123 (2 markdown-header-rule-face)))
1124 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1125 (2 markdown-header-face-1)
1126 (3 markdown-header-delimiter-face)))
1127 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1128 (2 markdown-header-face-2)
1129 (3 markdown-header-delimiter-face)))
1130 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1131 (2 markdown-header-face-3)
1132 (3 markdown-header-delimiter-face)))
1133 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1134 (2 markdown-header-face-4)
1135 (3 markdown-header-delimiter-face)))
1136 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1137 (2 markdown-header-face-5)
1138 (3 markdown-header-delimiter-face)))
1139 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1140 (2 markdown-header-face-6)
1141 (3 markdown-header-delimiter-face)))
1142 (cons markdown-regex-hr 'markdown-header-face)
1143 (cons 'markdown-match-comments '((0 markdown-comment-face t t)))
1144 (cons markdown-regex-code '(2 markdown-inline-code-face))
1145 (cons markdown-regex-angle-uri 'markdown-link-face)
1146 (cons markdown-regex-uri 'markdown-link-face)
1147 (cons markdown-regex-email 'markdown-link-face)
1148 (cons markdown-regex-list '(2 markdown-list-face))
1149 (cons markdown-regex-link-inline '((1 markdown-link-face t)
1150 (2 markdown-url-face t)))
1151 (cons markdown-regex-link-reference '((1 markdown-link-face t)
1152 (2 markdown-reference-face t)))
1153 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1154 (2 markdown-url-face t)
1155 (3 markdown-link-title-face t)))
1156 (cons markdown-regex-footnote 'markdown-footnote-face)
1157 (cons markdown-regex-bold '(2 markdown-bold-face))
1159 "Syntax highlighting for Markdown files.")
1161 (defvar markdown-mode-font-lock-keywords-core
1162 (list
1163 (cons markdown-regex-italic '(2 markdown-italic-face))
1165 "Additional syntax highlighting for Markdown files.
1166 Includes features which are overridden by some variants.")
1168 (defconst markdown-mode-font-lock-keywords-latex
1169 (list
1170 ;; Math mode $..$ or $$..$$
1171 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1172 ;; Display mode equations with brackets: \[ \]
1173 (cons markdown-regex-latex-display 'markdown-math-face)
1174 ;; Equation reference (eq:foo)
1175 (cons "(eq:\\w+)" 'markdown-reference-face)
1176 ;; Equation reference \eqref{foo}
1177 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1178 "Syntax highlighting for LaTeX fragments.")
1180 (defvar markdown-mode-font-lock-keywords
1181 (append
1182 (if markdown-enable-math
1183 markdown-mode-font-lock-keywords-latex)
1184 markdown-mode-font-lock-keywords-basic
1185 markdown-mode-font-lock-keywords-core)
1186 "Default highlighting expressions for Markdown mode.")
1188 ;; Footnotes
1189 (defvar markdown-footnote-counter 0
1190 "Counter for footnote numbers.")
1191 (make-variable-buffer-local 'markdown-footnote-counter)
1193 (defconst markdown-footnote-chars
1194 "[[:alnum:]-]"
1195 "Regular expression maching any character that is allowed in a footnote identifier.")
1198 ;;; Compatibility =============================================================
1200 (defun markdown-replace-regexp-in-string (regexp rep string)
1201 "Replace all matches for REGEXP with REP in STRING.
1202 This is a compatibility wrapper to provide `replace-regexp-in-string'
1203 in XEmacs 21."
1204 (if (featurep 'xemacs)
1205 (replace-in-string string regexp rep)
1206 (replace-regexp-in-string regexp rep string)))
1208 ;; `markdown-use-region-p' is a compatibility function which checks
1209 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1210 (eval-and-compile
1211 (cond
1212 ;; Emacs 23 and newer
1213 ((fboundp 'use-region-p)
1214 (defalias 'markdown-use-region-p 'use-region-p))
1215 ;; Older Emacsen
1216 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1217 (defun markdown-use-region-p ()
1218 "Compatibility wrapper to provide `use-region-p'."
1219 (and transient-mark-mode mark-active)))
1220 ;; XEmacs
1221 ((fboundp 'region-active-p)
1222 (defalias 'markdown-use-region-p 'region-active-p))))
1225 ;;; Markdown Parsing Functions ================================================
1227 (defun markdown-cur-line-blank-p ()
1228 "Return t if the current line is blank and nil otherwise."
1229 (save-excursion
1230 (beginning-of-line)
1231 (re-search-forward "^\\s *$" (point-at-eol) t)))
1233 (defun markdown-prev-line-blank-p ()
1234 "Return t if the previous line is blank and nil otherwise.
1235 If we are at the first line, then consider the previous line to be blank."
1236 (or (= (point-at-bol) (point-min))
1237 (save-excursion
1238 (forward-line -1)
1239 (markdown-cur-line-blank-p))))
1241 (defun markdown-next-line-blank-p ()
1242 "Return t if the next line is blank and nil otherwise.
1243 If we are at the last line, then consider the next line to be blank."
1244 (or (= (point-at-eol) (point-max))
1245 (save-excursion
1246 (forward-line 1)
1247 (markdown-cur-line-blank-p))))
1249 (defun markdown-prev-line-indent-p ()
1250 "Return t if the previous line is indented and nil otherwise."
1251 (save-excursion
1252 (forward-line -1)
1253 (goto-char (point-at-bol))
1254 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
1256 (defun markdown-cur-line-indent ()
1257 "Return the number of leading whitespace characters in the current line."
1258 (save-match-data
1259 (save-excursion
1260 (goto-char (point-at-bol))
1261 (re-search-forward "^[ \t]+" (point-at-eol) t)
1262 (current-column))))
1264 (defun markdown-prev-line-indent ()
1265 "Return the number of leading whitespace characters in the previous line."
1266 (save-excursion
1267 (forward-line -1)
1268 (markdown-cur-line-indent)))
1270 (defun markdown-next-line-indent ()
1271 "Return the number of leading whitespace characters in the next line."
1272 (save-excursion
1273 (forward-line 1)
1274 (markdown-cur-line-indent)))
1276 (defun markdown-cur-non-list-indent ()
1277 "Return beginning position of list item text (not including the list marker).
1278 Return nil if the current line is not the beginning of a list item."
1279 (save-match-data
1280 (save-excursion
1281 (beginning-of-line)
1282 (when (re-search-forward markdown-regex-list (point-at-eol) t)
1283 (current-column)))))
1285 (defun markdown-prev-non-list-indent ()
1286 "Return position of the first non-list-marker on the previous line."
1287 (save-excursion
1288 (forward-line -1)
1289 (markdown-cur-non-list-indent)))
1291 (defun markdown-new-baseline-p ()
1292 "Determine if the current line begins a new baseline level."
1293 (save-excursion
1294 (beginning-of-line)
1295 (save-match-data
1296 (or (looking-at markdown-regex-header)
1297 (looking-at markdown-regex-hr)
1298 (and (null (markdown-cur-non-list-indent))
1299 (= (markdown-cur-line-indent) 0)
1300 (markdown-prev-line-blank-p))))))
1302 (defun markdown-search-backward-baseline ()
1303 "Search backward baseline point with no indentation and not a list item."
1304 (end-of-line)
1305 (let (stop)
1306 (while (not (or stop (bobp)))
1307 (re-search-backward markdown-regex-block-separator nil t)
1308 (when (match-end 2)
1309 (goto-char (match-end 2))
1310 (cond
1311 ((markdown-new-baseline-p)
1312 (setq stop t))
1313 ((looking-at markdown-regex-list)
1314 (setq stop nil))
1315 (t (setq stop t)))))))
1317 (defun markdown-update-list-levels (marker indent levels)
1318 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1319 Here, MARKER is a string representing the type of list, INDENT is an integer
1320 giving the indentation, in spaces, of the current block, and LEVELS is a
1321 list of the indentation levels of parent list items. When LEVELS is nil,
1322 it means we are at baseline (not inside of a nested list)."
1323 (cond
1324 ;; New list item at baseline.
1325 ((and marker (null levels))
1326 (setq levels (list indent)))
1327 ;; List item with greater indentation (four or more spaces).
1328 ;; Increase list level.
1329 ((and marker (>= indent (+ (car levels) 4)))
1330 (setq levels (cons indent levels)))
1331 ;; List item with greater or equal indentation (less than four spaces).
1332 ;; Do not increase list level.
1333 ((and marker (>= indent (car levels)))
1334 levels)
1335 ;; Lesser indentation level.
1336 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1337 ;; indentation could move back more than one list level). Note
1338 ;; that this block need not be the beginning of list item.
1339 ((< indent (car levels))
1340 (while (and (> (length levels) 1)
1341 (< indent (+ (cadr levels) 4)))
1342 (setq levels (cdr levels)))
1343 levels)
1344 ;; Otherwise, do nothing.
1345 (t levels)))
1347 (defun markdown-calculate-list-levels ()
1348 "Calculate list levels at point.
1349 Return a list of the form (n1 n2 n3 ...) where n1 is the
1350 indentation of the deepest nested list item in the branch of
1351 the list at the point, n2 is the indentation of the parent
1352 list item, and so on. The depth of the list item is therefore
1353 the length of the returned list. If the point is not at or
1354 immediately after a list item, return nil."
1355 (save-excursion
1356 (let ((first (point)) levels indent pre-regexp)
1357 ;; Find a baseline point with zero list indentation
1358 (markdown-search-backward-baseline)
1359 ;; Search for all list items between baseline and LOC
1360 (while (re-search-forward markdown-regex-list first t)
1361 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1362 (beginning-of-line)
1363 (cond
1364 ;; Make sure this is not a header or hr
1365 ((markdown-new-baseline-p) (setq levels nil))
1366 ;; Make sure this is not a line from a pre block
1367 ((looking-at pre-regexp))
1368 ;; If not, then update levels
1370 (setq indent (markdown-cur-line-indent))
1371 (setq levels (markdown-update-list-levels (match-string 2)
1372 indent levels))))
1373 (end-of-line))
1374 levels)))
1376 (defun markdown-prev-list-item (level)
1377 "Search backward from point for a list item with indentation LEVEL.
1378 Set point to the beginning of the item, and return point, or nil
1379 upon failure."
1380 (let (bounds indent prev)
1381 (setq prev (point))
1382 (forward-line -1)
1383 (setq indent (markdown-cur-line-indent))
1384 (while
1385 (cond
1386 ;; Stop at beginning of buffer
1387 ((bobp) (setq prev nil))
1388 ;; Continue if current line is blank
1389 ((markdown-cur-line-blank-p) t)
1390 ;; List item
1391 ((and (looking-at markdown-regex-list)
1392 (setq bounds (markdown-cur-list-item-bounds)))
1393 (cond
1394 ;; Continue at item with greater indentation
1395 ((> (nth 3 bounds) level) t)
1396 ;; Stop and return point at item of equal indentation
1397 ((= (nth 3 bounds) level)
1398 (setq prev (point))
1399 nil)
1400 ;; Stop and return nil at item with lesser indentation
1401 ((< (nth 3 bounds) level)
1402 (setq prev nil)
1403 nil)))
1404 ;; Continue while indentation is the same or greater
1405 ((>= indent level) t)
1406 ;; Stop if current indentation is less than list item
1407 ;; and the next is blank
1408 ((and (< indent level)
1409 (markdown-next-line-blank-p))
1410 (setq prev nil))
1411 ;; Stop at a header
1412 ((looking-at markdown-regex-header) (setq prev nil))
1413 ;; Stop at a horizontal rule
1414 ((looking-at markdown-regex-hr) (setq prev nil))
1415 ;; Otherwise, continue.
1416 (t t))
1417 (forward-line -1)
1418 (setq indent (markdown-cur-line-indent)))
1419 prev))
1421 (defun markdown-next-list-item (level)
1422 "Search forward from point for the next list item with indentation LEVEL.
1423 Set point to the beginning of the item, and return point, or nil
1424 upon failure."
1425 (let (bounds indent prev next)
1426 (setq next (point))
1427 (forward-line)
1428 (setq indent (markdown-cur-line-indent))
1429 (while
1430 (cond
1431 ;; Stop at end of the buffer.
1432 ((eobp) (setq prev nil))
1433 ;; Continue if the current line is blank
1434 ((markdown-cur-line-blank-p) t)
1435 ;; List item
1436 ((and (looking-at markdown-regex-list)
1437 (setq bounds (markdown-cur-list-item-bounds)))
1438 (cond
1439 ;; Continue at item with greater indentation
1440 ((> (nth 3 bounds) level) t)
1441 ;; Stop and return point at item of equal indentation
1442 ((= (nth 3 bounds) level)
1443 (setq next (point))
1444 nil)
1445 ;; Stop and return nil at item with lesser indentation
1446 ((< (nth 3 bounds) level)
1447 (setq next nil)
1448 nil)))
1449 ;; Continue while indentation is the same or greater
1450 ((>= indent level) t)
1451 ;; Stop if current indentation is less than list item
1452 ;; and the previous line was blank.
1453 ((and (< indent level)
1454 (markdown-prev-line-blank-p))
1455 (setq next nil))
1456 ;; Stop at a header
1457 ((looking-at markdown-regex-header) (setq next nil))
1458 ;; Stop at a horizontal rule
1459 ((looking-at markdown-regex-hr) (setq next nil))
1460 ;; Otherwise, continue.
1461 (t t))
1462 (forward-line)
1463 (setq indent (markdown-cur-line-indent)))
1464 next))
1466 (defun markdown-cur-list-item-end (level)
1467 "Move to the end of the current list item with nonlist indentation LEVEL.
1468 If the point is not in a list item, do nothing."
1469 (let (indent)
1470 (forward-line)
1471 (setq indent (markdown-cur-line-indent))
1472 (while
1473 (cond
1474 ;; Stop at end of the buffer.
1475 ((eobp) nil)
1476 ;; Continue if the current line is blank
1477 ((markdown-cur-line-blank-p) t)
1478 ;; Continue while indentation is the same or greater
1479 ((>= indent level) t)
1480 ;; Stop if current indentation is less than list item
1481 ;; and the previous line was blank.
1482 ((and (< indent level)
1483 (markdown-prev-line-blank-p))
1484 nil)
1485 ;; Stop at a new list item of the same or lesser indentation
1486 ((looking-at markdown-regex-list) nil)
1487 ;; Stop at a header
1488 ((looking-at markdown-regex-header) nil)
1489 ;; Stop at a horizontal rule
1490 ((looking-at markdown-regex-hr) nil)
1491 ;; Otherwise, continue.
1492 (t t))
1493 (forward-line)
1494 (setq indent (markdown-cur-line-indent)))
1495 ;; Don't skip over whitespace for empty list items (marker and
1496 ;; whitespace only), just move to end of whitespace.
1497 (if (looking-back (concat markdown-regex-list "\\s-*"))
1498 (goto-char (match-end 3))
1499 (skip-syntax-backward "-"))))
1501 (defun markdown-cur-list-item-bounds ()
1502 "Return bounds and indentation of the current list item.
1503 Return a list of the form (begin end indent nonlist-indent).
1504 If the point is not inside a list item, return nil.
1505 Leave match data intact for `markdown-regex-list'."
1506 (let (cur prev-begin prev-end indent nonlist-indent)
1507 ;; Store current location
1508 (setq cur (point))
1509 ;; Verify that cur is between beginning and end of item
1510 (save-excursion
1511 (end-of-line)
1512 (when (re-search-backward markdown-regex-list nil t)
1513 (setq prev-begin (match-beginning 0))
1514 (setq indent (length (match-string 1)))
1515 (setq nonlist-indent (length (match-string 0)))
1516 (save-match-data
1517 (markdown-cur-list-item-end nonlist-indent)
1518 (setq prev-end (point)))
1519 (when (and (>= cur prev-begin)
1520 (<= cur prev-end)
1521 nonlist-indent)
1522 (list prev-begin prev-end indent nonlist-indent))))))
1524 (defun markdown-bounds-of-thing-at-point (thing)
1525 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1526 Does not include trailing newlines when THING is 'line. Handles the
1527 end of buffer case by setting both endpoints equal to the value of
1528 `point-max', since an empty region will trigger empty markup insertion.
1529 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1530 (let* ((bounds (bounds-of-thing-at-point thing))
1531 (a (car bounds))
1532 (b (cdr bounds)))
1533 (when bounds
1534 (when (eq thing 'line)
1535 (cond ((and (eobp) (markdown-cur-line-blank-p))
1536 (setq a b))
1537 ((char-equal (char-before b) ?\^J)
1538 (setq b (1- b)))))
1539 (cons a b))))
1541 (defun markdown-reference-definition (reference)
1542 "Find out whether Markdown REFERENCE is defined.
1543 REFERENCE should include the square brackets, like [this].
1544 When REFERENCE is defined, return a list of the form (text start end)
1545 containing the definition text itself followed by the start and end
1546 locations of the text. Otherwise, return nil.
1547 Leave match data for `markdown-regex-reference-definition'
1548 intact additional processing."
1549 (let ((reference (downcase reference)))
1550 (save-excursion
1551 (goto-char (point-min))
1552 (catch 'found
1553 (while (re-search-forward markdown-regex-reference-definition nil t)
1554 (when (string= reference (downcase (match-string-no-properties 1)))
1555 (throw 'found
1556 (list (match-string-no-properties 2)
1557 (match-beginning 2) (match-end 2)))))))))
1560 ;;; Markdown Font Lock Matching Functions =====================================
1562 (defun markdown-match-comments (last)
1563 "Match HTML comments from the point to LAST."
1564 (cond ((search-forward "<!--" last t)
1565 (backward-char 4)
1566 (let ((beg (point)))
1567 (cond ((search-forward-regexp "--[ \t]*>" last t)
1568 (set-match-data (list beg (point)))
1570 (t nil))))
1571 (t nil)))
1573 (defun markdown-match-pre-blocks (last)
1574 "Match Markdown pre blocks from point to LAST."
1575 (let ((levels (markdown-calculate-list-levels))
1576 indent pre-regexp end-regexp begin end stop)
1577 (while (and (< (point) last) (not end))
1578 ;; Search for a region with sufficient indentation
1579 (if (null levels)
1580 (setq indent 1)
1581 (setq indent (1+ (length levels))))
1582 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1583 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1585 (cond
1586 ;; If not at the beginning of a line, move forward
1587 ((not (bolp)) (forward-line))
1588 ;; Move past blank lines
1589 ((markdown-cur-line-blank-p) (forward-line))
1590 ;; At headers and horizontal rules, reset levels
1591 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1592 ;; If the current line has sufficient indentation, mark out pre block
1593 ((looking-at pre-regexp)
1594 (setq begin (match-beginning 0))
1595 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1596 (not (eobp)))
1597 (forward-line))
1598 (setq end (point)))
1599 ;; If current line has a list marker, update levels, move to end of block
1600 ((looking-at markdown-regex-list)
1601 (setq levels (markdown-update-list-levels
1602 (match-string 2) (markdown-cur-line-indent) levels))
1603 (markdown-end-of-block-element))
1604 ;; If this is the end of the indentation level, adjust levels accordingly.
1605 ;; Only match end of indentation level if levels is not the empty list.
1606 ((and (car levels) (looking-at end-regexp))
1607 (setq levels (markdown-update-list-levels
1608 nil (markdown-cur-line-indent) levels))
1609 (markdown-end-of-block-element))
1610 (t (markdown-end-of-block-element))))
1612 (if (not (and begin end))
1613 ;; Return nil if no pre block was found
1615 ;; Set match data and return t upon success
1616 (set-match-data (list begin end))
1617 t)))
1619 (defun markdown-match-fenced-code-blocks (last)
1620 "Match fenced code blocks from the point to LAST."
1621 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1622 (beginning-of-line)
1623 (let ((beg (point)))
1624 (forward-line)
1625 (cond ((search-forward-regexp
1626 (concat "^" (match-string 1) "~*") last t)
1627 (set-match-data (list beg (point)))
1629 (t nil))))
1630 (t nil)))
1632 (defun markdown-match-gfm-code-blocks (last)
1633 "Match GFM quoted code blocks from point to LAST."
1634 (let (open lang body close all)
1635 (cond ((and (eq major-mode 'gfm-mode)
1636 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1637 (beginning-of-line)
1638 (setq open (list (match-beginning 1) (match-end 1))
1639 lang (list (match-beginning 2) (match-end 2)))
1640 (forward-line)
1641 (setq body (list (point)))
1642 (cond ((search-forward-regexp "^```$" last t)
1643 (setq body (reverse (cons (1- (match-beginning 0)) body))
1644 close (list (match-beginning 0) (match-end 0))
1645 all (list (car open) (match-end 0)))
1646 (set-match-data (append all open lang body close))
1648 (t nil)))
1649 (t nil))))
1651 (defun markdown-match-generic-metadata (regexp last)
1652 "Match generic metadata specified by REGEXP from the point to LAST."
1653 (let ((header-end (save-excursion
1654 (goto-char (point-min))
1655 (if (re-search-forward "\n\n" (point-max) t)
1656 (match-beginning 0)
1657 (point-max)))))
1658 (cond ((>= (point) header-end)
1659 ;; Don't match anything outside of the header.
1660 nil)
1661 ((re-search-forward regexp (min last header-end) t)
1662 ;; If a metadata item is found, it may span several lines.
1663 (let ((key-beginning (match-beginning 1))
1664 (key-end (match-end 1))
1665 (value-beginning (match-beginning 2)))
1666 (while (and (not (looking-at regexp))
1667 (not (> (point) (min last header-end)))
1668 (not (eobp)))
1669 (forward-line))
1670 (unless (eobp)
1671 (forward-line -1)
1672 (end-of-line))
1673 (set-match-data (list key-beginning (point) ; complete metadata
1674 key-beginning key-end ; key
1675 value-beginning (point))) ; value
1677 (t nil))))
1679 (defun markdown-match-multimarkdown-metadata (last)
1680 "Match MultiMarkdown metadata from the point to LAST."
1681 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1683 (defun markdown-match-pandoc-metadata (last)
1684 "Match Pandoc metadata from the point to LAST."
1685 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1687 (defun markdown-font-lock-extend-region ()
1688 "Extend the search region to include an entire block of text.
1689 This helps improve font locking for block constructs such as pre blocks."
1690 ;; Avoid compiler warnings about these global variables from font-lock.el.
1691 ;; See the documentation for variable `font-lock-extend-region-functions'.
1692 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1693 (save-excursion
1694 (goto-char font-lock-beg)
1695 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1696 (goto-char font-lock-end)
1697 (when (re-search-forward "\n\n" nil t)
1698 (beginning-of-line)
1699 (setq font-lock-end (point)))
1700 (setq font-lock-beg found))))
1703 ;;; Syntax Table ==============================================================
1705 (defvar markdown-mode-syntax-table
1706 (let ((tab (make-syntax-table text-mode-syntax-table)))
1707 (modify-syntax-entry ?\" "." tab)
1708 tab)
1709 "Syntax table for `markdown-mode'.")
1712 ;;; Element Insertion =========================================================
1714 (defun markdown-ensure-blank-line-before ()
1715 "If previous line is not already blank, insert a blank line before point."
1716 (unless (bolp) (insert "\n"))
1717 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1719 (defun markdown-ensure-blank-line-after ()
1720 "If following line is not already blank, insert a blank line after point.
1721 Return the point where it was originally."
1722 (save-excursion
1723 (unless (eolp) (insert "\n"))
1724 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1726 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1727 "Insert the strings S1 and S2, wrapping around region or THING.
1728 If a region is specified by the optional BEG and END arguments,
1729 wrap the strings S1 and S2 around that region.
1730 If there is an active region, wrap the strings S1 and S2 around
1731 the region. If there is not an active region but the point is at
1732 THING, wrap that thing (which defaults to word). Otherwise, just
1733 insert S1 and S2 and place the cursor in between. Return the
1734 bounds of the entire wrapped string, or nil if nothing was wrapped
1735 and S1 and S2 were only inserted."
1736 (let (a b bounds new-point)
1737 (cond
1738 ;; Given region
1739 ((and beg end)
1740 (setq a beg
1741 b end
1742 new-point (+ (point) (length s1))))
1743 ;; Active region
1744 ((markdown-use-region-p)
1745 (setq a (region-beginning)
1746 b (region-end)
1747 new-point (+ (point) (length s1))))
1748 ;; Thing (word) at point
1749 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1750 (setq a (car bounds)
1751 b (cdr bounds)
1752 new-point (+ (point) (length s1))))
1753 ;; No active region and no word
1755 (setq a (point)
1756 b (point))))
1757 (goto-char b)
1758 (insert s2)
1759 (goto-char a)
1760 (insert s1)
1761 (when new-point (goto-char new-point))
1762 (if (= a b)
1764 (setq b (+ b (length s1) (length s2)))
1765 (cons a b))))
1767 (defun markdown-point-after-unwrap (cur prefix suffix)
1768 "Return desired position of point after an unwrapping operation.
1769 Two cons cells must be provided. PREFIX gives the bounds of the
1770 prefix string and SUFFIX gives the bounds of the suffix string."
1771 (cond ((< cur (cdr prefix)) (car prefix))
1772 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1773 ((<= cur (cdr suffix))
1774 (- cur (+ (- (cdr prefix) (car prefix))
1775 (- cur (car suffix)))))
1776 (t cur)))
1778 (defun markdown-unwrap-thing-at-point (regexp all text)
1779 "Remove prefix and suffix of thing at point and reposition the point.
1780 When the thing at point matches REGEXP, replace the subexpression
1781 ALL with the string in subexpression TEXT. Reposition the point
1782 in an appropriate location accounting for the removal of prefix
1783 and suffix strings. Return new bounds of string from group TEXT.
1784 When REGEXP is nil, assumes match data is already set."
1785 (when (or (null regexp)
1786 (thing-at-point-looking-at regexp))
1787 (let ((cur (point))
1788 (prefix (cons (match-beginning all) (match-beginning text)))
1789 (suffix (cons (match-end text) (match-end all)))
1790 (bounds (cons (match-beginning text) (match-end text))))
1791 ;; Replace the thing at point
1792 (replace-match (match-string text) t t nil all)
1793 ;; Reposition the point
1794 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1795 ;; Adjust bounds
1796 (setq bounds (cons (car prefix)
1797 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1799 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1800 "Remove prefix and suffix of all things in region.
1801 When a thing in the region matches REGEXP, replace the
1802 subexpression ALL with the string in subexpression TEXT.
1803 Return a cons cell containing updated bounds for the region."
1804 (save-excursion
1805 (goto-char beg)
1806 (let ((removed 0) len-all len-text)
1807 (while (re-search-forward regexp (- end removed) t)
1808 (setq len-all (length (match-string-no-properties all)))
1809 (setq len-text (length (match-string-no-properties text)))
1810 (setq removed (+ removed (- len-all len-text)))
1811 (replace-match (match-string text) t t nil all))
1812 (cons beg (- end removed)))))
1814 (defun markdown-insert-hr (arg)
1815 "Insert or replace a horizonal rule.
1816 By default, use the first element of `markdown-hr-strings'. When
1817 prefixed with C-u, use the last element of `markdown-hr-strings'
1818 instead. When prefixed with an integer from 1 to the length of
1819 `markdown-hr-strings', use the element in that position instead."
1820 (interactive "*P")
1821 (when (thing-at-point-looking-at markdown-regex-hr)
1822 (delete-region (match-beginning 0) (match-end 0)))
1823 (markdown-ensure-blank-line-before)
1824 (cond ((equal arg '(4))
1825 (insert (car (reverse markdown-hr-strings))))
1826 ((and (integerp arg) (> arg 0)
1827 (<= arg (length markdown-hr-strings)))
1828 (insert (nth (1- arg) markdown-hr-strings)))
1830 (insert (car markdown-hr-strings))))
1831 (markdown-ensure-blank-line-after))
1833 (defun markdown-insert-bold ()
1834 "Insert markup to make a region or word bold.
1835 If there is an active region, make the region bold. If the point
1836 is at a non-bold word, make the word bold. If the point is at a
1837 bold word or phrase, remove the bold markup. Otherwise, simply
1838 insert bold delimiters and place the cursor in between them."
1839 (interactive)
1840 (let ((delim (if markdown-bold-underscore "__" "**")))
1841 (if (markdown-use-region-p)
1842 ;; Active region
1843 (let ((bounds (markdown-unwrap-things-in-region
1844 (region-beginning) (region-end)
1845 markdown-regex-bold 2 4)))
1846 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1847 ;; Bold markup removal, bold word at point, or empty markup insertion
1848 (if (thing-at-point-looking-at markdown-regex-bold)
1849 (markdown-unwrap-thing-at-point nil 2 4)
1850 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1852 (defun markdown-insert-italic ()
1853 "Insert markup to make a region or word italic.
1854 If there is an active region, make the region italic. If the point
1855 is at a non-italic word, make the word italic. If the point is at an
1856 italic word or phrase, remove the italic markup. Otherwise, simply
1857 insert italic delimiters and place the cursor in between them."
1858 (interactive)
1859 (let ((delim (if markdown-italic-underscore "_" "*")))
1860 (if (markdown-use-region-p)
1861 ;; Active region
1862 (let ((bounds (markdown-unwrap-things-in-region
1863 (region-beginning) (region-end)
1864 markdown-regex-italic 2 4)))
1865 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1866 ;; Italic markup removal, italic word at point, or empty markup insertion
1867 (if (thing-at-point-looking-at markdown-regex-italic)
1868 (markdown-unwrap-thing-at-point nil 2 4)
1869 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1871 (defun markdown-insert-code ()
1872 "Insert markup to make a region or word an inline code fragment.
1873 If there is an active region, make the region an inline code
1874 fragment. If the point is at a word, make the word an inline
1875 code fragment. Otherwise, simply insert code delimiters and
1876 place the cursor in between them."
1877 (interactive)
1878 (if (markdown-use-region-p)
1879 ;; Active region
1880 (let ((bounds (markdown-unwrap-things-in-region
1881 (region-beginning) (region-end)
1882 markdown-regex-code 2 4)))
1883 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1884 ;; Code markup removal, code markup for word, or empty markup insertion
1885 (if (thing-at-point-looking-at markdown-regex-code)
1886 (markdown-unwrap-thing-at-point nil 2 4)
1887 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1889 (defun markdown-insert-link ()
1890 "Insert an inline link, using region or word as link text if possible.
1891 If there is an active region, use the region as the link text. If the
1892 point is at a word, use the word as the link text. In these cases, the
1893 point will be left at the position for inserting a URL. If there is no
1894 active region and the point is not at word, simply insert link markup and
1895 place the point in the position to enter link text."
1896 (interactive)
1897 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1898 (when bounds
1899 (goto-char (- (cdr bounds) 1)))))
1901 (defun markdown-insert-reference-link-dwim ()
1902 "Insert a reference link of the form [text][label] at point.
1903 If Transient Mark mode is on and a region is active, the region
1904 is used as the link text. Otherwise, the link text will be read
1905 from the minibuffer. The link URL, label, and title will be read
1906 from the minibuffer. The link label definition is placed at the
1907 end of the current paragraph."
1908 (interactive)
1909 (if (markdown-use-region-p)
1910 (call-interactively 'markdown-insert-reference-link-region)
1911 (call-interactively 'markdown-insert-reference-link)))
1913 (defun markdown-insert-reference-link-region (url label title)
1914 "Insert a reference link at point using the region as the link text.
1915 The link will point to URL, will be referenced as LABEL, and will have the
1916 optional title text given by TITLE."
1917 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1918 (let ((text (delete-and-extract-region (region-beginning) (region-end))))
1919 (markdown-insert-reference-link text url label title)))
1921 (defun markdown-insert-reference-link (text url label title)
1922 "Insert a reference link at point.
1923 The link TEXT will point to the given URL and may be referenced using
1924 LABEL. The link TITLE is optional and will be used to populate the
1925 title attribute when converted to XHTML."
1926 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1927 (let (end)
1928 (insert (concat "[" text "][" label "]"))
1929 (setq end (point))
1930 (forward-paragraph)
1931 (insert "\n[")
1932 (if (> (length label) 0)
1933 (insert label)
1934 (insert text))
1935 (insert (concat "]: " url))
1936 (unless (> (length url) 0)
1937 (setq end (point)))
1938 (when (> (length title) 0)
1939 (insert (concat " \"" title "\"")))
1940 (insert "\n")
1941 (unless (looking-at "\n")
1942 (insert "\n"))
1943 (goto-char end)))
1945 (defun markdown-insert-wiki-link ()
1946 "Insert a wiki link of the form [[WikiLink]].
1947 If Transient Mark mode is on and a region is active, it is used
1948 as the link text."
1949 (interactive)
1950 (markdown-wrap-or-insert "[[" "]]")
1951 (backward-char 2))
1953 (defun markdown-insert-image ()
1954 "Insert inline image markup using region or word as alt text if possible.
1955 If there is an active region, use the region as the alt text. If the
1956 point is at a word, use the word as the alt text. In these cases, the
1957 point will be left at the position for inserting a URL. If there is no
1958 active region and the point is not at word, simply insert image markup and
1959 place the point in the position to enter alt text."
1960 (interactive)
1961 (let ((bounds (markdown-wrap-or-insert "![" "]()")))
1962 (when bounds
1963 (goto-char (- (cdr bounds) 1)))))
1965 (defun markdown-remove-header ()
1966 "Remove header markup if point is at a header.
1967 Return bounds of remaining header text if a header was removed
1968 and nil otherwise."
1969 (interactive "*")
1970 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
1971 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
1973 (defun markdown-insert-header (&optional level text setext)
1974 "Insert or replace header markup.
1975 The level of the header is specified by LEVEL and header text is
1976 given by TEXT. LEVEL must be an integer from 1 and 6, and the
1977 default value is 1.
1978 When TEXT is nil, the header text is obtained as follows.
1979 If there is an active region, it is used as the header text.
1980 Otherwise, the current line will be used as the header text.
1981 If there is not an active region and the point is at a header,
1982 remove the header markup and replace with level N header.
1983 Otherwise, insert empty header markup and place the cursor in
1984 between.
1985 The style of the header will be atx (hash marks) unless
1986 SETEXT is non-nil, in which case a setext-style (underlined)
1987 header will be inserted."
1988 (interactive "p\nsHeader text: ")
1989 (setq level (min (max (or level 1) 1) (if setext 2 6)))
1990 ;; Determine header text if not given
1991 (when (null text)
1992 (if (markdown-use-region-p)
1993 ;; Active region
1994 (setq text (delete-and-extract-region (region-beginning) (region-end)))
1995 ;; No active region
1996 (markdown-remove-header)
1997 (setq text (delete-and-extract-region
1998 (line-beginning-position) (line-end-position)))
1999 (when (and setext (string-match "^[ \t]*$" text))
2000 (setq text (read-string "Header text: "))))
2001 (setq text (markdown-compress-whitespace-string text)))
2002 ;; Insertion with given text
2003 (markdown-ensure-blank-line-before)
2004 (if setext
2005 ;; setext
2006 (progn
2007 (insert text "\n")
2008 (dotimes (n (length text))
2009 (insert (if (= level 2) "-" "="))))
2010 ;; atx
2011 (dotimes (count level) (insert "#"))
2012 (insert " " text " ")
2013 (dotimes (count level) (insert "#")))
2014 (markdown-ensure-blank-line-after)
2015 ;; Leave point at end of text
2016 (if setext
2017 (backward-char (1+ (length text)))
2018 (backward-char (1+ level))))
2020 (defun markdown-insert-header-dwim (&optional arg)
2021 "Insert or replace header markup.
2022 The level of the header is determined by the numerical argument,
2023 if present, or the level of the previous header.
2024 The type of the header is determined by the type of the previous header.
2025 See `markdown-insert-header' for details about how the header text
2026 is determined."
2027 (interactive "*P")
2028 (let (level setext)
2029 (save-excursion
2030 (when (re-search-backward markdown-regex-header nil t)
2031 (setq level (markdown-outline-level))
2032 (setq setext (or (match-end 1) (match-end 3)))))
2033 ;; use prefix if given, or level of previous header
2034 (setq level (if arg (prefix-numeric-value arg) level))
2035 ;; match groups 1 and 2 indicate setext headers
2036 (setq setext (and level (<= level 2) setext))
2037 (markdown-insert-header level nil setext)))
2039 (defun markdown-insert-header-atx-1 ()
2040 "Insert a first level atx-style (hash mark) header.
2041 See `markdown-insert-header'."
2042 (interactive "*")
2043 (markdown-insert-header 1 nil nil))
2045 (defun markdown-insert-header-atx-2 ()
2046 "Insert a level two atx-style (hash mark) header.
2047 See `markdown-insert-header'."
2048 (interactive "*")
2049 (markdown-insert-header 2 nil nil))
2051 (defun markdown-insert-header-atx-3 ()
2052 "Insert a level three atx-style (hash mark) header.
2053 See `markdown-insert-header'."
2054 (interactive "*")
2055 (markdown-insert-header 3 nil nil))
2057 (defun markdown-insert-header-atx-4 ()
2058 "Insert a level four atx-style (hash mark) header.
2059 See `markdown-insert-header'."
2060 (interactive "*")
2061 (markdown-insert-header 4 nil nil))
2063 (defun markdown-insert-header-atx-5 ()
2064 "Insert a level five atx-style (hash mark) header.
2065 See `markdown-insert-header'."
2066 (interactive "*")
2067 (markdown-insert-header 5 nil nil))
2069 (defun markdown-insert-header-atx-6 ()
2070 "Insert a sixth level atx-style (hash mark) header.
2071 See `markdown-insert-header'."
2072 (interactive "*")
2073 (markdown-insert-header 6 nil nil))
2075 (defun markdown-insert-header-setext-1 ()
2076 "Insert a setext-style (underlined) first-level header.
2077 See `markdown-insert-header'."
2078 (interactive "*")
2079 (markdown-insert-header 1 nil t))
2081 (defun markdown-insert-header-setext-2 ()
2082 "Insert a setext-style (underlined) second-level header.
2083 See `markdown-insert-header'."
2084 (interactive "*")
2085 (markdown-insert-header 2 nil t))
2087 (defun markdown-blockquote-indentation (loc)
2088 "Return string containing necessary indentation for a blockquote at LOC.
2089 Also see `markdown-pre-indentation'."
2090 (save-excursion
2091 (goto-char loc)
2092 (let* ((list-level (length (markdown-calculate-list-levels)))
2093 (indent ""))
2094 (dotimes (count list-level indent)
2095 (setq indent (concat indent " "))))))
2097 (defun markdown-insert-blockquote ()
2098 "Start a blockquote section (or blockquote the region).
2099 If Transient Mark mode is on and a region is active, it is used as
2100 the blockquote text."
2101 (interactive)
2102 (if (markdown-use-region-p)
2103 (markdown-blockquote-region (region-beginning) (region-end))
2104 (markdown-ensure-blank-line-before)
2105 (insert (markdown-blockquote-indentation (point)) "> ")
2106 (markdown-ensure-blank-line-after)))
2108 (defun markdown-block-region (beg end prefix)
2109 "Format the region using a block prefix.
2110 Arguments BEG and END specify the beginning and end of the
2111 region. The characters PREFIX will appear at the beginning
2112 of each line."
2113 (save-excursion
2114 ;; Ensure that there is a leading blank line
2115 (goto-char beg)
2116 (when (and (>= (point) (+ (point-min) 2))
2117 (not (looking-back "\n\n" 2)))
2118 (insert "\n")
2119 (setq beg (1+ beg))
2120 (setq end (1+ end)))
2121 ;; Move back before any blank lines at the end
2122 (goto-char end)
2123 (while (and (looking-back "\n" 1)
2124 (not (equal (point) (point-min))))
2125 (backward-char)
2126 (setq end (1- end)))
2127 ;; Ensure that there is a trailing blank line
2128 (goto-char end)
2129 (if (not (or (looking-at "\n\n")
2130 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
2131 (insert "\n"))
2132 ;; Insert PREFIX
2133 (goto-char beg)
2134 (beginning-of-line)
2135 (while (< (point-at-bol) end)
2136 (insert prefix)
2137 (setq end (+ (length prefix) end))
2138 (forward-line))))
2140 (defun markdown-blockquote-region (beg end)
2141 "Blockquote the region.
2142 Arguments BEG and END specify the beginning and end of the region."
2143 (interactive "*r")
2144 (markdown-block-region
2145 beg end (concat (markdown-blockquote-indentation
2146 (max (point-min) (1- beg))) "> ")))
2148 (defun markdown-pre-indentation (loc)
2149 "Return string containing necessary whitespace for a pre block at LOC.
2150 Also see `markdown-blockquote-indentation'."
2151 (save-excursion
2152 (goto-char loc)
2153 (let* ((list-level (length (markdown-calculate-list-levels)))
2154 indent)
2155 (dotimes (count (1+ list-level) indent)
2156 (setq indent (concat indent " "))))))
2158 (defun markdown-insert-pre ()
2159 "Start a preformatted section (or apply to the region).
2160 If Transient Mark mode is on and a region is active, it is marked
2161 as preformatted text."
2162 (interactive)
2163 (if (markdown-use-region-p)
2164 (markdown-pre-region (region-beginning) (region-end))
2165 (markdown-ensure-blank-line-before)
2166 (insert (markdown-pre-indentation (point)))
2167 (markdown-ensure-blank-line-after)))
2169 (defun markdown-pre-region (beg end)
2170 "Format the region as preformatted text.
2171 Arguments BEG and END specify the beginning and end of the region."
2172 (interactive "*r")
2173 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2174 (markdown-block-region beg end indent)))
2176 (defun markdown-insert-gfm-code-block (&optional lang)
2177 "Insert GFM code block for language LANG.
2178 If LANG is nil, the language will be queried from user. If a
2179 region is active, wrap this region with the markup instead. If
2180 the region boundaries are not on empty lines, these are added
2181 automatically in order to have the correct markup."
2182 (interactive "sProgramming language: ")
2183 (if (markdown-use-region-p)
2184 (let ((b (region-beginning)) (e (region-end)))
2185 (goto-char b)
2186 ;; if we're on a blank line, insert the quotes here, otherwise
2187 ;; add a new line first
2188 (unless (looking-at "\n")
2189 (newline)
2190 (forward-line -1)
2191 (setq e (1+ e)))
2192 (insert "```" lang)
2193 (goto-char (+ e 3 (length lang)))
2194 ;; if we're on a blank line, don't newline, otherwise the ```
2195 ;; should go on its own line
2196 (unless (looking-back "\n")
2197 (newline))
2198 (insert "```"))
2199 (insert "```" lang)
2200 (newline 2)
2201 (insert "```")
2202 (forward-line -1)))
2205 ;;; Footnotes ======================================================================
2207 (defun markdown-footnote-counter-inc ()
2208 "Increment `markdown-footnote-counter' and return the new value."
2209 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2210 (save-excursion
2211 (goto-char (point-min))
2212 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2213 (point-max) t)
2214 (let ((fn (string-to-number (match-string 1))))
2215 (when (> fn markdown-footnote-counter)
2216 (setq markdown-footnote-counter fn))))))
2217 (incf markdown-footnote-counter))
2219 (defun markdown-footnote-new ()
2220 "Insert footnote with a new number and move point to footnote definition."
2221 (interactive)
2222 (let ((fn (markdown-footnote-counter-inc)))
2223 (insert (format "[^%d]" fn))
2224 (markdown-footnote-text-find-new-location)
2225 (markdown-ensure-blank-line-before)
2226 (unless (markdown-cur-line-blank-p)
2227 (insert "\n"))
2228 (insert (format "[^%d]: " fn))
2229 (markdown-ensure-blank-line-after)))
2231 (defun markdown-footnote-text-find-new-location ()
2232 "Position the cursor at the proper location for a new footnote text."
2233 (cond
2234 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2235 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
2236 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2238 (defun markdown-footnote-kill ()
2239 "Kill the footnote at point.
2240 The footnote text is killed (and added to the kill ring), the
2241 footnote marker is deleted. Point has to be either at the
2242 footnote marker or in the footnote text."
2243 (interactive)
2244 (let (return-pos)
2245 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2246 (markdown-footnote-return) ; we first move to the marker
2247 (setq return-pos 'text)) ; and remember our return position
2248 (let ((marker (markdown-footnote-delete-marker)))
2249 (unless marker
2250 (error "Not at a footnote"))
2251 (let ((text-pos (markdown-footnote-find-text (car marker))))
2252 (unless text-pos
2253 (error "No text for footnote `%s'" (car marker)))
2254 (goto-char text-pos)
2255 (let ((pos (markdown-footnote-kill-text)))
2256 (setq return-pos
2257 (if (and pos (eq return-pos 'text))
2259 (cadr marker))))))
2260 (goto-char return-pos)))
2262 (defun markdown-footnote-delete-marker ()
2263 "Delete a footnote marker at point.
2264 Returns a list (ID START) containing the footnote ID and the
2265 start position of the marker before deletion. If no footnote
2266 marker was deleted, this function returns NIL."
2267 (let ((marker (markdown-footnote-marker-positions)))
2268 (when marker
2269 (delete-region (second marker) (third marker))
2270 (butlast marker))))
2272 (defun markdown-footnote-kill-text ()
2273 "Kill footnote text at point.
2274 Returns the start position of the footnote text before deletion,
2275 or NIL if point was not inside a footnote text.
2277 The killed text is placed in the kill ring (without the footnote
2278 number)."
2279 (let ((fn (markdown-footnote-text-positions)))
2280 (when fn
2281 (let ((text (delete-and-extract-region (second fn) (third fn))))
2282 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2283 (kill-new (match-string 1 text))
2284 (when (and (markdown-cur-line-blank-p)
2285 (markdown-prev-line-blank-p))
2286 (delete-region (1- (point)) (point)))
2287 (second fn)))))
2289 (defun markdown-footnote-goto-text ()
2290 "Jump to the text of the footnote at point."
2291 (interactive)
2292 (let ((fn (car (markdown-footnote-marker-positions))))
2293 (unless fn
2294 (error "Not at a footnote marker"))
2295 (let ((new-pos (markdown-footnote-find-text fn)))
2296 (unless new-pos
2297 (error "No definition found for footnote `%s'" fn))
2298 (goto-char new-pos))))
2300 (defun markdown-footnote-return ()
2301 "Return from a footnote to its footnote number in the main text."
2302 (interactive)
2303 (let ((fn (save-excursion
2304 (car (markdown-footnote-text-positions)))))
2305 (unless fn
2306 (error "Not in a footnote"))
2307 (let ((new-pos (markdown-footnote-find-marker fn)))
2308 (unless new-pos
2309 (error "Footnote marker `%s' not found" fn))
2310 (goto-char new-pos))))
2312 (defun markdown-footnote-find-marker (id)
2313 "Find the location of the footnote marker with ID.
2314 The actual buffer position returned is the position directly
2315 following the marker's closing bracket. If no marker is found,
2316 NIL is returned."
2317 (save-excursion
2318 (goto-char (point-min))
2319 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2320 (skip-chars-backward "^]")
2321 (point))))
2323 (defun markdown-footnote-find-text (id)
2324 "Find the location of the text of footnote ID.
2325 The actual buffer position returned is the position of the first
2326 character of the text, after the footnote's identifier. If no
2327 footnote text is found, NIL is returned."
2328 (save-excursion
2329 (goto-char (point-min))
2330 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2331 (skip-chars-forward "[ \t]")
2332 (point))))
2334 (defun markdown-footnote-marker-positions ()
2335 "Return the position and ID of the footnote marker point is on.
2336 The return value is a list (ID START END). If point is not on a
2337 footnote, NIL is returned."
2338 ;; first make sure we're at a footnote marker
2339 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
2340 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2341 (save-excursion
2342 ;; move point between [ and ^:
2343 (if (looking-at "\\[")
2344 (forward-char 1)
2345 (skip-chars-backward "^["))
2346 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2347 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2349 (defun markdown-footnote-text-positions ()
2350 "Return the start and end positions of the footnote text point is in.
2351 The exact return value is a list of three elements: (ID START END).
2352 The start position is the position of the opening bracket
2353 of the footnote id. The end position is directly after the
2354 newline that ends the footnote. If point is not in a footnote,
2355 NIL is returned instead."
2356 (save-excursion
2357 (let ((fn (progn
2358 (backward-paragraph)
2359 ;; if we're in a multiparagraph footnote, we need to back up further
2360 (while (>= (markdown-next-line-indent) 4)
2361 (backward-paragraph))
2362 (forward-line)
2363 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2364 (list (match-string 1) (point))))))
2365 (when fn
2366 (while (progn
2367 (forward-paragraph)
2368 (>= (markdown-next-line-indent) 4)))
2369 (append fn (list (point)))))))
2372 ;;; Indentation ====================================================================
2374 (defun markdown-indent-find-next-position (cur-pos positions)
2375 "Return the position after the index of CUR-POS in POSITIONS.
2376 Positions are calculated by `markdown-calc-indents'."
2377 (while (and positions
2378 (not (equal cur-pos (car positions))))
2379 (setq positions (cdr positions)))
2380 (or (cadr positions) 0))
2382 (defun markdown-indent-line ()
2383 "Indent the current line using some heuristics.
2384 If the _previous_ command was either `markdown-enter-key' or
2385 `markdown-cycle', then we should cycle to the next
2386 reasonable indentation position. Otherwise, we could have been
2387 called directly by `markdown-enter-key', by an initial call of
2388 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2389 these cases, indent to the default position.
2390 Positions are calculated by `markdown-calc-indents'."
2391 (interactive)
2392 (let ((positions (markdown-calc-indents))
2393 (cur-pos (current-column)))
2394 (if (not (equal this-command 'markdown-cycle))
2395 (indent-line-to (car positions))
2396 (setq positions (sort (delete-dups positions) '<))
2397 (indent-line-to
2398 (markdown-indent-find-next-position cur-pos positions)))))
2400 (defun markdown-calc-indents ()
2401 "Return a list of indentation columns to cycle through.
2402 The first element in the returned list should be considered the
2403 default indentation level. This function does not worry about
2404 duplicate positions, which are handled up by calling functions."
2405 (let (pos prev-line-pos positions)
2407 ;; Indentation of previous line
2408 (setq prev-line-pos (markdown-prev-line-indent))
2409 (setq positions (cons prev-line-pos positions))
2411 ;; Indentation of previous non-list-marker text
2412 (when (setq pos (markdown-prev-non-list-indent))
2413 (setq positions (cons pos positions)))
2415 ;; Indentation required for a pre block in current context
2416 (setq pos (length (markdown-pre-indentation (point))))
2417 (setq positions (cons pos positions))
2419 ;; Indentation of the previous line + tab-width
2420 (if prev-line-pos
2421 (setq positions (cons (+ prev-line-pos tab-width) positions))
2422 (setq positions (cons tab-width positions)))
2424 ;; Indentation of the previous line - tab-width
2425 (if (and prev-line-pos (> prev-line-pos tab-width))
2426 (setq positions (cons (- prev-line-pos tab-width) positions)))
2428 ;; Indentation of all preceeding list markers (when in a list)
2429 (when (setq pos (markdown-calculate-list-levels))
2430 (setq positions (append pos positions)))
2432 ;; First column
2433 (setq positions (cons 0 positions))
2435 ;; Return reversed list
2436 (reverse positions)))
2438 (defun markdown-do-normal-return ()
2439 "Insert a newline and optionally indent the next line."
2440 (newline)
2441 (if markdown-indent-on-enter
2442 (funcall indent-line-function)))
2444 (defun markdown-enter-key ()
2445 "Handle RET according to context.
2446 If there is a wiki link at the point, follow it unless
2447 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2448 it in the usual way."
2449 (interactive)
2450 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2451 (markdown-follow-wiki-link-at-point)
2452 (markdown-do-normal-return)))
2454 (defun markdown-dedent-or-delete (arg)
2455 "Handle BACKSPACE by cycling through indentation points.
2456 When BACKSPACE is pressed, if there is only whitespace
2457 before the current point, then dedent the line one level.
2458 Otherwise, do normal delete by repeating
2459 `backward-delete-char-untabify' ARG times."
2460 (interactive "*p")
2461 (let ((cur-pos (current-column))
2462 (start-of-indention (save-excursion
2463 (back-to-indentation)
2464 (current-column))))
2465 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2466 (let ((result 0))
2467 (dolist (i (markdown-calc-indents))
2468 (when (< i cur-pos)
2469 (setq result (max result i))))
2470 (indent-line-to result))
2471 (backward-delete-char-untabify arg))))
2474 ;;; Markup Completion =========================================================
2476 (defconst markdown-complete-alist
2477 '((markdown-regex-header-atx . markdown-complete-atx)
2478 (markdown-regex-header-setext . markdown-complete-setext)
2479 (markdown-regex-hr . markdown-complete-hr))
2480 "Association list of form (regexp . function) for markup completion.")
2482 (defun markdown-incomplete-atx-p ()
2483 "Return t if ATX header markup is incomplete and nil otherwise.
2484 Assumes match data is available for `markdown-regex-header-atx'.
2485 Checks that the number of trailing hash marks equals the number of leading
2486 hash marks, that there is only a single space before and after the text,
2487 and that there is no extraneous whitespace in the text."
2488 (save-match-data
2489 (or (not (= (length (match-string 1)) (length (match-string 3))))
2490 (not (= (match-beginning 2) (1+ (match-end 1))))
2491 (not (= (match-beginning 3) (1+ (match-end 2))))
2492 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2494 (defun markdown-complete-atx ()
2495 "Complete and normalize ATX headers.
2496 Add or remove hash marks to the end of the header to match the
2497 beginning. Ensure that there is only a single space between hash
2498 marks and header text. Removes extraneous whitespace from header text.
2499 Assumes match data is available for `markdown-regex-header-atx'."
2500 (when (markdown-incomplete-atx-p)
2501 (let* ((new-marker (make-marker))
2502 (new-marker (set-marker new-marker (match-end 2))))
2503 ;; Hash marks and spacing at end
2504 (goto-char (match-end 2))
2505 (delete-region (match-end 2) (match-end 3))
2506 (insert " " (match-string 1))
2507 ;; Remove extraneous whitespace from title
2508 (replace-match (markdown-compress-whitespace-string (match-string 2))
2509 t t nil 2)
2510 ;; Spacing at beginning
2511 (goto-char (match-end 1))
2512 (delete-region (match-end 1) (match-beginning 2))
2513 (insert " ")
2514 ;; Leave point at end of text
2515 (goto-char new-marker))))
2517 (defun markdown-incomplete-setext-p ()
2518 "Return t if setext header markup is incomplete and nil otherwise.
2519 Assumes match data is available for `markdown-regex-header-setext'.
2520 Checks that length of underline matches text and that there is no
2521 extraneous whitespace in the text."
2522 (save-match-data
2523 (or (not (= (length (match-string 1)) (length (match-string 2))))
2524 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2526 (defun markdown-complete-setext ()
2527 "Complete and normalize setext headers.
2528 Add or remove underline characters to match length of header
2529 text. Removes extraneous whitespace from header text. Assumes
2530 match data is available for `markdown-regex-header-setext'."
2531 (when (markdown-incomplete-setext-p)
2532 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2533 (char (char-after (match-beginning 2)))
2534 (level (if (char-equal char ?-) 2 1)))
2535 (goto-char (match-beginning 0))
2536 (delete-region (match-beginning 0) (match-end 0))
2537 (markdown-insert-header level text t))))
2539 (defun markdown-incomplete-hr-p ()
2540 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2541 Assumes match data is available for `markdown-regex-hr'."
2542 (not (member (match-string 0) markdown-hr-strings)))
2544 (defun markdown-complete-hr ()
2545 "Complete horizontal rules.
2546 If horizontal rule string is a member of `markdown-hr-strings',
2547 do nothing. Otherwise, replace with the car of
2548 `markdown-hr-strings'.
2549 Assumes match data is available for `markdown-regex-hr'."
2550 (replace-match (car markdown-hr-strings)))
2552 (defun markdown-complete ()
2553 "Complete markup of object near point or in region when active.
2554 Handle all objects in `markdown-complete-alist', in order.
2555 See `markdown-complete-at-point' and `markdown-complete-region'."
2556 (interactive "*")
2557 (if (markdown-use-region-p)
2558 (markdown-complete-region (region-beginning) (region-end))
2559 (markdown-complete-at-point)))
2561 (defun markdown-complete-at-point ()
2562 "Complete markup of object near point.
2563 Handle all objects in `markdown-complete-alist', in
2564 order."
2565 (interactive "*")
2566 (loop for (regexp . function) in markdown-complete-alist
2567 until (thing-at-point-looking-at (eval regexp))
2568 finally (funcall function)))
2570 (defun markdown-complete-region (beg end)
2571 "Complete markup of object near point.
2572 Handle all objects in `markdown-complete-alist', in
2573 order."
2574 (interactive "*r")
2575 (let* ((end-marker (make-marker))
2576 (end-marker (set-marker end-marker end)))
2577 (loop for (regexp . function) in markdown-complete-alist
2578 do (save-excursion
2579 (goto-char beg)
2580 (while (re-search-forward (eval regexp) end-marker t)
2581 (funcall function))))))
2583 (defun markdown-complete-buffer ()
2584 "Complete markup for all objects in the current buffer."
2585 (interactive "*")
2586 (markdown-complete-region (point-min) (point-max)))
2589 ;;; Markup Cycling ============================================================
2591 (defun markdown-cycle-atx (arg &optional remove)
2592 "Cycle ATX header markup.
2593 Promote header (decrease level) when ARG is 1 and demote
2594 header (increase level) if arg is -1. When REMOVE is non-nil,
2595 remove the header when the level reaches zero and stop cycling
2596 when it reaches six. Otherwise, perform a proper cycling through
2597 levels one through six. Assumes match data is available for
2598 `markdown-regex-header-atx'."
2599 (let* ((old-level (length (match-string 1)))
2600 (new-level (+ old-level arg))
2601 (text (match-string 2)))
2602 (when (not remove)
2603 (setq new-level (% new-level 6))
2604 (setq new-level (cond ((= new-level 0) 6)
2605 ((< new-level 0) (+ new-level 6))
2606 (t new-level))))
2607 (cond
2608 ((= new-level 0)
2609 (markdown-unwrap-thing-at-point nil 0 2))
2610 ((<= new-level 6)
2611 (goto-char (match-beginning 0))
2612 (delete-region (match-beginning 0) (match-end 0))
2613 (markdown-insert-header new-level text nil)))))
2615 (defun markdown-cycle-setext (arg &optional remove)
2616 "Cycle setext header markup.
2617 Promote header (increase level) when ARG is 1 and demote
2618 header (decrease level or remove) if arg is -1. When demoting a
2619 level-two setext header, replace with a level-three atx header.
2620 When REMOVE is non-nil, remove the header when the level reaches
2621 zero. Otherwise, cycle back to a level six atx header. Assumes
2622 match data is available for `markdown-regex-header-setext'."
2623 (let* ((char (char-after (match-beginning 2)))
2624 (old-level (if (char-equal char ?=) 1 2))
2625 (new-level (+ old-level arg))
2626 (text (match-string 1)))
2627 (when (and (not remove) (= new-level 0))
2628 (setq new-level 6))
2629 (cond
2630 ((= new-level 0)
2631 (markdown-unwrap-thing-at-point nil 0 1))
2632 ((<= new-level 2)
2633 (markdown-insert-header new-level nil t))
2634 ((<= new-level 6)
2635 (markdown-insert-header new-level nil nil)))))
2637 (defun markdown-cycle-hr (arg &optional remove)
2638 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2639 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2640 backwards (demote). When REMOVE is non-nil, remove the hr instead
2641 of cycling when the end of the list is reached.
2642 Assumes match data is available for `markdown-regex-hr'."
2643 (let* ((strings (if (= arg 1)
2644 (reverse markdown-hr-strings)
2645 markdown-hr-strings))
2646 (tail (member (match-string 0) strings))
2647 (new (or (cadr tail)
2648 (if remove
2649 (if (= arg 1)
2651 (car tail))
2652 (car strings)))))
2653 (replace-match new)))
2655 (defun markdown-cycle-bold ()
2656 "Cycle bold markup between underscores and asterisks.
2657 Assumes match data is available for `markdown-regex-bold'."
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))))
2664 (defun markdown-cycle-italic ()
2665 "Cycle italic markup between underscores and asterisks.
2666 Assumes match data is available for `markdown-regex-italic'."
2667 (save-excursion
2668 (let* ((old-delim (match-string 3))
2669 (new-delim (if (string-equal old-delim "*") "_" "*")))
2670 (replace-match new-delim t t nil 3)
2671 (replace-match new-delim t t nil 5))))
2674 ;;; Keymap ====================================================================
2676 (defvar markdown-mode-map
2677 (let ((map (make-keymap)))
2678 ;; Element insertion
2679 (define-key map "\C-c\C-al" 'markdown-insert-link)
2680 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
2681 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
2682 (define-key map "\C-c\C-ii" 'markdown-insert-image)
2683 (define-key map "\C-c\C-t0" 'markdown-remove-header)
2684 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
2685 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
2686 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
2687 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
2688 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
2689 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
2690 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
2691 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
2692 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
2693 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
2694 (define-key map "\C-c\C-se" 'markdown-insert-italic)
2695 (define-key map "\C-c\C-pf" 'markdown-insert-code)
2696 (define-key map "\C-c\C-sc" 'markdown-insert-code)
2697 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
2698 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
2699 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
2700 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
2701 (define-key map "\C-c-" 'markdown-insert-hr)
2702 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
2703 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
2704 ;; Footnotes
2705 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
2706 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
2707 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
2708 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
2709 ;; Promotion, Demotion, Completion, and Cycling
2710 (define-key map (kbd "M-<left>") 'markdown-promote)
2711 (define-key map (kbd "M-<right>") 'markdown-demote)
2712 (define-key map (kbd "C-c C-l") 'markdown-promote)
2713 (define-key map (kbd "C-c C-r") 'markdown-demote)
2714 (define-key map (kbd "C-c C-=") 'markdown-complete-or-cycle)
2715 (define-key map (kbd "C-c C-c =") 'markdown-complete-buffer)
2716 ;; Following and Jumping
2717 (define-key map "\C-c\C-o" 'markdown-follow-thing-at-point)
2718 (define-key map "\C-c\C-j" 'markdown-jump)
2719 ;; Indentation
2720 (define-key map "\C-m" 'markdown-enter-key)
2721 (define-key map (kbd "<backspace>") 'markdown-dedent-or-delete)
2722 ;; Visibility cycling
2723 (define-key map (kbd "<tab>") 'markdown-cycle)
2724 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
2725 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
2726 (define-key map (kbd "<backtab>") 'markdown-shifttab)
2727 ;; Header navigation
2728 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
2729 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
2730 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
2731 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
2732 (define-key map (kbd "C-M-u") 'outline-up-heading)
2733 ;; Markdown functions
2734 (define-key map "\C-c\C-cm" 'markdown-other-window)
2735 (define-key map "\C-c\C-cp" 'markdown-preview)
2736 (define-key map "\C-c\C-ce" 'markdown-export)
2737 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
2738 (define-key map "\C-c\C-co" 'markdown-open)
2739 (define-key map "\C-c\C-cw" 'markdown-kill-ring-save)
2740 ;; References
2741 (define-key map "\C-c\C-cc" 'markdown-check-refs)
2742 ;; Lists
2743 (define-key map "\C-c\C-cn" 'markdown-cleanup-list-numbers)
2744 (define-key map (kbd "M-<up>") 'markdown-move-up)
2745 (define-key map (kbd "M-<down>") 'markdown-move-down)
2746 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
2747 ;; Movement
2748 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
2749 (define-key map (kbd "M-]") 'markdown-end-of-block)
2750 (define-key map (kbd "M-n") 'markdown-next-wiki-link)
2751 (define-key map (kbd "M-p") 'markdown-previous-wiki-link)
2752 map)
2753 "Keymap for Markdown major mode.")
2755 (defvar gfm-mode-map
2756 (let ((map (make-sparse-keymap)))
2757 (set-keymap-parent map markdown-mode-map)
2758 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
2759 map)
2760 "Keymap for `gfm-mode'.
2761 See also `markdown-mode-map'.")
2764 ;;; Menu ==================================================================
2766 (easy-menu-define markdown-mode-menu markdown-mode-map
2767 "Menu for Markdown mode"
2768 '("Markdown"
2769 ("Show/Hide"
2770 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
2771 ["Cycle global visibility" markdown-shifttab])
2772 "---"
2773 ["Compile" markdown-other-window]
2774 ["Preview" markdown-preview]
2775 ["Export" markdown-export]
2776 ["Export & View" markdown-export-and-preview]
2777 ["Open" markdown-open]
2778 ["Kill ring save" markdown-kill-ring-save]
2779 "---"
2780 ("Headers (setext)"
2781 ["First level" markdown-insert-setext-header-1]
2782 ["Second level" markdown-insert-setext-header-2])
2783 ("Headers (atx)"
2784 ["First level" markdown-insert-header-atx-1]
2785 ["Second level" markdown-insert-header-atx-2]
2786 ["Third level" markdown-insert-header-atx-3]
2787 ["Fourth level" markdown-insert-header-atx-4]
2788 ["Fifth level" markdown-insert-header-atx-5]
2789 ["Sixth level" markdown-insert-header-atx-6])
2790 "---"
2791 ["Bold" markdown-insert-bold]
2792 ["Italic" markdown-insert-italic]
2793 ["Blockquote" markdown-insert-blockquote]
2794 ["Preformatted" markdown-insert-pre]
2795 ["Code" markdown-insert-code]
2796 "---"
2797 ["Insert inline link" markdown-insert-link]
2798 ["Insert reference link" markdown-insert-reference-link-dwim]
2799 ["Insert image" markdown-insert-image]
2800 ["Insert horizontal rule" markdown-insert-hr]
2801 "---"
2802 ("Footnotes"
2803 ["Insert footnote" markdown-footnote-new]
2804 ["Jump to footnote text" markdown-footnote-goto-text]
2805 ["Return from footnote" markdown-footnote-return])
2806 "---"
2807 ["Check references" markdown-check-refs]
2808 ["Clean up list numbering" markdown-cleanup-list-numbers]
2809 "---"
2810 ["Version" markdown-show-version]
2814 ;;; imenu =====================================================================
2816 (defun markdown-imenu-create-index ()
2817 "Create and return an imenu index alist for the current buffer.
2818 See `imenu-create-index-function' and `imenu--index-alist' for details."
2819 (let* ((root '(nil . nil))
2820 cur-alist
2821 (cur-level 0)
2822 (empty-heading "-")
2823 (self-heading ".")
2824 hashes pos level heading)
2825 (save-excursion
2826 (goto-char (point-min))
2827 (while (re-search-forward markdown-regex-header (point-max) t)
2828 (cond
2829 ((setq heading (match-string-no-properties 1))
2830 (setq pos (match-beginning 1)
2831 level 1))
2832 ((setq heading (match-string-no-properties 3))
2833 (setq pos (match-beginning 3)
2834 level 2))
2835 ((setq hashes (match-string-no-properties 5))
2836 (setq heading (match-string-no-properties 6)
2837 pos (match-beginning 5)
2838 level (length hashes))))
2839 (let ((alist (list (cons heading pos))))
2840 (cond
2841 ((= cur-level level) ; new sibling
2842 (setcdr cur-alist alist)
2843 (setq cur-alist alist))
2844 ((< cur-level level) ; first child
2845 (dotimes (i (- level cur-level 1))
2846 (setq alist (list (cons empty-heading alist))))
2847 (if cur-alist
2848 (let* ((parent (car cur-alist))
2849 (self-pos (cdr parent)))
2850 (setcdr parent (cons (cons self-heading self-pos) alist)))
2851 (setcdr root alist)) ; primogenitor
2852 (setq cur-alist alist)
2853 (setq cur-level level))
2854 (t ; new sibling of an ancestor
2855 (let ((sibling-alist (last (cdr root))))
2856 (dotimes (i (1- level))
2857 (setq sibling-alist (last (cdar sibling-alist))))
2858 (setcdr sibling-alist alist)
2859 (setq cur-alist alist))
2860 (setq cur-level level)))))
2861 (cdr root))))
2864 ;;; References ================================================================
2866 (defconst markdown-refcheck-buffer
2867 "*Undefined references for %buffer%*"
2868 "Pattern for name of buffer for listing undefined references.
2869 The string %buffer% will be replaced by the corresponding
2870 `markdown-mode' buffer name.")
2872 (defconst markdown-links-buffer
2873 "*Reference links for %buffer%*"
2874 "Pattern for name of buffer for listing references.
2875 The string %buffer% will be replaced by the corresponding buffer name.")
2877 (defun markdown-reference-goto-definition ()
2878 "Jump to the definition of the reference at point."
2879 (interactive)
2880 (when (thing-at-point-looking-at markdown-regex-link-reference)
2881 (let* ((label (match-string-no-properties 1))
2882 (reference (match-string-no-properties 2))
2883 (target (downcase (if (string= reference "[]") label reference)))
2884 (loc (cadr (markdown-reference-definition target))))
2885 (if loc
2886 (goto-char loc)
2887 (error "Reference %s not defined." target)))))
2889 (defun markdown-reference-find-links (reference)
2890 "Return a list of all links for REFERENCE.
2891 REFERENCE should include the surrounding square brackets like [this].
2892 Elements of the list have the form (text start line), where
2893 text is the link text, start is the location at the beginning of
2894 the link, and line is the line number on which the link appears."
2895 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
2896 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
2897 ref-quote ref-quote))
2898 links)
2899 (save-excursion
2900 (goto-char (point-min))
2901 (while (re-search-forward regexp nil t)
2902 (let* ((text (or (match-string-no-properties 1)
2903 (match-string-no-properties 2)))
2904 (start (match-beginning 0))
2905 (line (markdown-line-number-at-pos)))
2906 (add-to-list 'links (list text start line)))))
2907 links))
2909 (defun markdown-reference-goto-link (&optional reference)
2910 "Jump to the location of the first use of reference."
2911 (interactive)
2912 (unless reference
2913 (if (thing-at-point-looking-at markdown-regex-reference-definition)
2914 (setq reference (match-string-no-properties 1))
2915 (error "No reference definition at point.")))
2916 (let ((links (markdown-reference-find-links reference)))
2917 (cond ((= (length links) 1)
2918 (goto-char (cadr (car links))))
2919 ((> (length links) 1)
2920 (let ((oldbuf (current-buffer))
2921 (linkbuf (get-buffer-create
2922 (markdown-replace-regexp-in-string
2923 "%buffer%" (buffer-name) markdown-links-buffer))))
2924 (with-current-buffer linkbuf
2925 (when view-mode
2926 (View-exit-and-edit))
2927 (use-local-map button-buffer-map)
2928 (erase-buffer)
2929 (insert "Links using reference " reference ":")
2930 (newline 2)
2931 (dolist (link links)
2932 (let ((button-label (format "%s" (car link)))
2933 (char (cadr link)))
2934 (if (>= emacs-major-version 22)
2935 ;; Create a reference button in Emacs 22
2936 (insert-text-button button-label
2937 :type 'markdown-link-button
2938 'target-buffer oldbuf
2939 'target-char char)
2940 ;; Insert reference as text in Emacs < 22
2941 (insert button-label)))
2942 (insert " (")
2943 (let ((line (third link)))
2944 (if (>= emacs-major-version 22)
2945 ;; Create a line number button in Emacs 22
2946 (insert-button (number-to-string line)
2947 :type 'goto-line-button
2948 'target-buffer oldbuf
2949 'target-line line)
2950 ;; Insert line number as text in Emacs < 22
2951 (insert (number-to-string line))))
2952 (insert ")")
2953 (newline)))
2954 (view-buffer-other-window linkbuf)
2955 (goto-char (point-min))
2956 (forward-line 2))))))
2958 (defun markdown-get-undefined-refs ()
2959 "Return a list of undefined Markdown references.
2960 Result is an alist of pairs (reference . occurrences), where
2961 occurrences is itself another alist of pairs (label . line-number).
2962 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2963 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2964 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2965 (let ((missing))
2966 (save-excursion
2967 (goto-char (point-min))
2968 (while
2969 (re-search-forward markdown-regex-link-reference nil t)
2970 (let* ((label (match-string-no-properties 1))
2971 (reference (match-string-no-properties 2))
2972 (target (downcase (if (string= reference "[]") label reference))))
2973 (unless (markdown-reference-definition target)
2974 (let ((entry (assoc target missing)))
2975 (if (not entry)
2976 (add-to-list 'missing (cons target
2977 (list (cons label (markdown-line-number-at-pos)))) t)
2978 (setcdr entry
2979 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
2980 missing)))
2982 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
2983 "Add blank REF definition to the end of BUFFER.
2984 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2985 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2986 references so that REF disappears from the list of those links."
2987 (with-current-buffer buffer
2988 (when (not (eq major-mode 'markdown-mode))
2989 (error "Not available in current mode"))
2990 (goto-char (point-max))
2991 (indent-new-comment-line)
2992 (insert (concat ref ": ")))
2993 (switch-to-buffer-other-window buffer)
2994 (goto-char (point-max))
2995 (when recheck
2996 (markdown-check-refs t)))
2998 ;; Button which adds an empty Markdown reference definition to the end
2999 ;; of buffer specified as its 'target-buffer property. Reference name
3000 ;; is button's label
3001 (when (>= emacs-major-version 22)
3002 (define-button-type 'markdown-ref-button
3003 'help-echo "Push to create an empty reference definition"
3004 'face 'bold
3005 'action (lambda (b)
3006 (markdown-add-missing-ref-definition
3007 (button-label b) (button-get b 'target-buffer) t))))
3009 ;; Button jumping to line in buffer specified as its 'target-buffer
3010 ;; property. Line number is button's 'line property.
3011 (when (>= emacs-major-version 22)
3012 (define-button-type 'goto-line-button
3013 'help-echo "Push to go to this line"
3014 'face 'italic
3015 'action (lambda (b)
3016 (message (button-get b 'buffer))
3017 (switch-to-buffer-other-window (button-get b 'target-buffer))
3018 ;; use call-interactively to silence compiler
3019 (let ((current-prefix-arg (button-get b 'target-line)))
3020 (call-interactively 'goto-line)))))
3022 ;; Button which jumps to a particular link. Link text is button's label.
3023 (when (>= emacs-major-version 22)
3024 (define-button-type 'markdown-link-button
3025 'help-echo "Push to jump to the link"
3026 'face 'bold
3027 'action (lambda (b)
3028 (switch-to-buffer-other-window (button-get b 'target-buffer))
3029 (goto-char (button-get b 'target-char)))))
3031 (defun markdown-check-refs (&optional silent)
3032 "Show all undefined Markdown references in current `markdown-mode' buffer.
3033 If SILENT is non-nil, do not message anything when no undefined
3034 references found.
3035 Links which have empty reference definitions are considered to be
3036 defined."
3037 (interactive "P")
3038 (when (not (eq major-mode 'markdown-mode))
3039 (error "Not available in current mode"))
3040 (let ((oldbuf (current-buffer))
3041 (refs (markdown-get-undefined-refs))
3042 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
3043 "%buffer%" (buffer-name)
3044 markdown-refcheck-buffer))))
3045 (if (null refs)
3046 (progn
3047 (when (not silent)
3048 (message "No undefined references found"))
3049 (kill-buffer refbuf))
3050 (with-current-buffer refbuf
3051 (when view-mode
3052 (View-exit-and-edit))
3053 (use-local-map button-buffer-map)
3054 (erase-buffer)
3055 (insert "Following references lack definitions:")
3056 (newline 2)
3057 (dolist (ref refs)
3058 (let ((button-label (format "%s" (car ref))))
3059 (if (>= emacs-major-version 22)
3060 ;; Create a reference button in Emacs 22
3061 (insert-text-button button-label
3062 :type 'markdown-ref-button
3063 'target-buffer oldbuf)
3064 ;; Insert reference as text in Emacs < 22
3065 (insert button-label)))
3066 (insert " (")
3067 (dolist (occurrence (cdr ref))
3068 (let ((line (cdr occurrence)))
3069 (if (>= emacs-major-version 22)
3070 ;; Create a line number button in Emacs 22
3071 (insert-button (number-to-string line)
3072 :type 'goto-line-button
3073 'target-buffer oldbuf
3074 'target-line line)
3075 ;; Insert line number as text in Emacs < 22
3076 (insert (number-to-string line)))
3077 (insert " "))) (delete-char -1)
3078 (insert ")")
3079 (newline))
3080 (view-buffer-other-window refbuf)
3081 (goto-char (point-min))
3082 (forward-line 2)))))
3085 ;;; Lists =====================================================================
3087 (defun markdown-insert-list-item (&optional arg)
3088 "Insert a new list item.
3089 If the point is inside unordered list, insert a bullet mark. If
3090 the point is inside ordered list, insert the next number followed
3091 by a period. Use the previous list item to determine the amount
3092 of whitespace to place before and after list markers.
3094 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3095 decrease the indentation by one level.
3097 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3098 increase the indentation by one level."
3099 (interactive "p")
3100 (let (bounds item-indent marker indent new-indent end)
3101 (save-match-data
3102 (setq bounds (markdown-cur-list-item-bounds))
3103 (if (not bounds)
3104 ;; When not in a list, start a new unordered one
3105 (progn
3106 (unless (markdown-cur-line-blank-p)
3107 (insert "\n"))
3108 (insert "* "))
3109 ;; Compute indentation for a new list item
3110 (setq item-indent (nth 2 bounds))
3111 (setq marker (concat (match-string 2) (match-string 3)))
3112 (setq indent (cond
3113 ((= arg 4) (max (- item-indent 4) 0))
3114 ((= arg 16) (+ item-indent 4))
3115 (t item-indent)))
3116 (setq new-indent (make-string indent 32))
3117 (goto-char (nth 1 bounds))
3118 (newline)
3119 (cond
3120 ;; Ordered list
3121 ((string-match "[0-9]" marker)
3122 (if (= arg 16) ;; starting a new column indented one more level
3123 (insert (concat new-indent "1. "))
3124 ;; travel up to the last item and pick the correct number. If
3125 ;; the argument was nil, "new-indent = item-indent" is the same,
3126 ;; so we don't need special treatment. Neat.
3127 (save-excursion
3128 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3129 (forward-line -1)))
3130 (insert (concat new-indent
3131 (int-to-string (1+ (string-to-number (match-string 1))))
3132 ". "))))
3133 ;; Unordered list
3134 ((string-match "[\\*\\+-]" marker)
3135 (insert (concat new-indent marker))))))))
3137 (defun markdown-move-list-item-up ()
3138 "Move the current list item up in the list when possible."
3139 (interactive)
3140 (let (cur prev old)
3141 (when (setq cur (markdown-cur-list-item-bounds))
3142 (setq old (point))
3143 (goto-char (nth 0 cur))
3144 (if (markdown-prev-list-item (nth 3 cur))
3145 (progn
3146 (setq prev (markdown-cur-list-item-bounds))
3147 (condition-case nil
3148 (progn
3149 (transpose-regions (nth 0 prev) (nth 1 prev)
3150 (nth 0 cur) (nth 1 cur) t)
3151 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3152 ;; Catch error in case regions overlap.
3153 (error (goto-char old))))
3154 (goto-char old)))))
3156 (defun markdown-move-list-item-down ()
3157 "Move the current list item down in the list when possible."
3158 (interactive)
3159 (let (cur next old)
3160 (when (setq cur (markdown-cur-list-item-bounds))
3161 (setq old (point))
3162 (if (markdown-next-list-item (nth 3 cur))
3163 (progn
3164 (setq next (markdown-cur-list-item-bounds))
3165 (condition-case nil
3166 (progn
3167 (transpose-regions (nth 0 cur) (nth 1 cur)
3168 (nth 0 next) (nth 1 next) nil)
3169 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3170 ;; Catch error in case regions overlap.
3171 (error (goto-char old))))
3172 (goto-char old)))))
3174 (defun markdown-demote-list-item (&optional bounds)
3175 "Indent (or demote) the current list item.
3176 Optionally, BOUNDS of the current list item may be provided if available."
3177 (interactive)
3178 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3179 (save-excursion
3180 (save-match-data
3181 (let* ((end-marker (make-marker))
3182 (end-marker (set-marker end-marker (nth 1 bounds))))
3183 (goto-char (nth 0 bounds))
3184 (while (< (point) end-marker)
3185 (unless (markdown-cur-line-blank-p)
3186 (insert " "))
3187 (forward-line)))))))
3189 (defun markdown-promote-list-item (&optional bounds)
3190 "Unindent (or promote) the current list item.
3191 Optionally, BOUNDS of the current list item may be provided if available."
3192 (interactive)
3193 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3194 (save-excursion
3195 (save-match-data
3196 (let* ((end-marker (make-marker))
3197 (end-marker (set-marker end-marker (nth 1 bounds)))
3198 num regexp)
3199 (goto-char (nth 0 bounds))
3200 (when (looking-at "^[ ]\\{1,4\\}")
3201 (setq num (- (match-end 0) (match-beginning 0)))
3202 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3203 (while (and (< (point) end-marker)
3204 (re-search-forward regexp end-marker t))
3205 (replace-match "" nil nil)
3206 (forward-line))))))))
3208 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3209 "Update the numbering for level PFX (as a string of spaces).
3211 Assume that the previously found match was for a numbered item in
3212 a list."
3213 (let ((cpfx pfx)
3214 (idx 0)
3215 (continue t)
3216 (step t)
3217 (sep nil))
3218 (while (and continue (not (eobp)))
3219 (setq step t)
3220 (cond
3221 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3222 (setq cpfx (match-string-no-properties 1))
3223 (cond
3224 ((string= cpfx pfx)
3225 (replace-match
3226 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3227 (setq sep nil))
3228 ;; indented a level
3229 ((string< pfx cpfx)
3230 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3231 (setq step nil))
3232 ;; exit the loop
3234 (setq step nil)
3235 (setq continue nil))))
3237 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3238 (setq cpfx (match-string-no-properties 1))
3239 (cond
3240 ;; reset if separated before
3241 ((string= cpfx pfx) (when sep (setq idx 0)))
3242 ((string< cpfx pfx)
3243 (setq step nil)
3244 (setq continue nil))))
3245 (t (setq sep t)))
3247 (when step
3248 (beginning-of-line)
3249 (setq continue (= (forward-line) 0))))
3250 sep))
3252 (defun markdown-cleanup-list-numbers ()
3253 "Update the numbering of ordered lists."
3254 (interactive)
3255 (save-excursion
3256 (goto-char (point-min))
3257 (markdown--cleanup-list-numbers-level "")))
3260 ;;; Outline ===================================================================
3262 (defvar markdown-cycle-global-status 1)
3263 (defvar markdown-cycle-subtree-status nil)
3265 (defun markdown-end-of-subtree (&optional invisible-OK)
3266 "Move to the end of the current subtree.
3267 Only visible heading lines are considered, unless INVISIBLE-OK is
3268 non-nil.
3269 Derived from `org-end-of-subtree'."
3270 (outline-back-to-heading invisible-OK)
3271 (let ((first t)
3272 (level (funcall outline-level)))
3273 (while (and (not (eobp))
3274 (or first (> (funcall outline-level) level)))
3275 (setq first nil)
3276 (outline-next-heading))
3277 (if (memq (preceding-char) '(?\n ?\^M))
3278 (progn
3279 ;; Go to end of line before heading
3280 (forward-char -1)
3281 (if (memq (preceding-char) '(?\n ?\^M))
3282 ;; leave blank line before heading
3283 (forward-char -1)))))
3284 (point))
3286 (defun markdown-cycle (&optional arg)
3287 "Visibility cycling for Markdown mode.
3288 If ARG is t, perform global visibility cycling. If the point is
3289 at an atx-style header, cycle visibility of the corresponding
3290 subtree. Otherwise, insert a tab using `indent-relative'.
3291 Derived from `org-cycle'."
3292 (interactive "P")
3293 (cond
3294 ((eq arg t) ;; Global cycling
3295 (cond
3296 ((and (eq last-command this-command)
3297 (eq markdown-cycle-global-status 2))
3298 ;; Move from overview to contents
3299 (hide-sublevels 1)
3300 (message "CONTENTS")
3301 (setq markdown-cycle-global-status 3))
3303 ((and (eq last-command this-command)
3304 (eq markdown-cycle-global-status 3))
3305 ;; Move from contents to all
3306 (show-all)
3307 (message "SHOW ALL")
3308 (setq markdown-cycle-global-status 1))
3311 ;; Defaults to overview
3312 (hide-body)
3313 (message "OVERVIEW")
3314 (setq markdown-cycle-global-status 2))))
3316 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3317 ;; At a heading: rotate between three different views
3318 (outline-back-to-heading)
3319 (let ((goal-column 0) eoh eol eos)
3320 ;; Determine boundaries
3321 (save-excursion
3322 (outline-back-to-heading)
3323 (save-excursion
3324 (beginning-of-line 2)
3325 (while (and (not (eobp)) ;; this is like `next-line'
3326 (get-char-property (1- (point)) 'invisible))
3327 (beginning-of-line 2)) (setq eol (point)))
3328 (outline-end-of-heading) (setq eoh (point))
3329 (markdown-end-of-subtree t)
3330 (skip-chars-forward " \t\n")
3331 (beginning-of-line 1) ; in case this is an item
3332 (setq eos (1- (point))))
3333 ;; Find out what to do next and set `this-command'
3334 (cond
3335 ((= eos eoh)
3336 ;; Nothing is hidden behind this heading
3337 (message "EMPTY ENTRY")
3338 (setq markdown-cycle-subtree-status nil))
3339 ((>= eol eos)
3340 ;; Entire subtree is hidden in one line: open it
3341 (show-entry)
3342 (show-children)
3343 (message "CHILDREN")
3344 (setq markdown-cycle-subtree-status 'children))
3345 ((and (eq last-command this-command)
3346 (eq markdown-cycle-subtree-status 'children))
3347 ;; We just showed the children, now show everything.
3348 (show-subtree)
3349 (message "SUBTREE")
3350 (setq markdown-cycle-subtree-status 'subtree))
3352 ;; Default action: hide the subtree.
3353 (hide-subtree)
3354 (message "FOLDED")
3355 (setq markdown-cycle-subtree-status 'folded)))))
3358 (indent-for-tab-command))))
3360 (defun markdown-shifttab ()
3361 "Global visibility cycling.
3362 Calls `markdown-cycle' with argument t."
3363 (interactive)
3364 (markdown-cycle t))
3366 (defun markdown-outline-level ()
3367 "Return the depth to which a statement is nested in the outline."
3368 (cond
3369 ((match-end 1) 1)
3370 ((match-end 3) 2)
3371 ((- (match-end 5) (match-beginning 5)))))
3374 ;;; Movement ==================================================================
3376 (defun markdown-beginning-of-defun (&optional arg)
3377 "`beginning-of-defun-function' for Markdown.
3378 Move backward to the beginning of the current or previous section."
3379 (interactive "P")
3380 (or arg (setq arg 1))
3381 (or (re-search-backward markdown-regex-header nil t arg)
3382 (goto-char (point-min))))
3384 (defun markdown-end-of-defun (&optional arg)
3385 "`end-of-defun-function' for Markdown.
3386 Move forward to the end of the current or following section."
3387 (interactive "P")
3388 (or arg (setq arg 1))
3389 (when (looking-at markdown-regex-header)
3390 (goto-char (match-beginning 0))
3391 (forward-char 1))
3392 (if (re-search-forward markdown-regex-header nil t arg)
3393 (goto-char (match-beginning 0))
3394 (goto-char (point-max)))
3395 (skip-syntax-backward "-"))
3397 (defun markdown-beginning-of-block ()
3398 "Move the point to the start of the previous text block."
3399 (interactive)
3400 (if (re-search-backward markdown-regex-block-separator nil t)
3401 (goto-char (or (match-end 2) (match-end 0)))
3402 (goto-char (point-min))))
3404 (defun markdown-end-of-block ()
3405 "Move the point to the start of the next text block."
3406 (interactive)
3407 (beginning-of-line)
3408 (skip-syntax-forward "-")
3409 (when (= (point) (point-min))
3410 (forward-char))
3411 (if (re-search-forward markdown-regex-block-separator nil t)
3412 (goto-char (or (match-end 2) (match-end 0)))
3413 (goto-char (point-max)))
3414 (skip-syntax-backward "-")
3415 (forward-line))
3417 (defun markdown-end-of-block-element ()
3418 "Move the point to the start of the next block unit.
3419 Stops at blank lines, list items, headers, and horizontal rules."
3420 (interactive)
3421 (forward-line)
3422 (while (and (or (not (markdown-prev-line-blank-p))
3423 (markdown-cur-line-blank-p))
3424 (not (or (looking-at markdown-regex-list)
3425 (looking-at markdown-regex-header)
3426 (looking-at markdown-regex-hr)))
3427 (not (eobp)))
3428 (forward-line)))
3431 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3433 (defun markdown-move-up ()
3434 "Move list item up.
3435 Calls `markdown-move-list-item-up'."
3436 (interactive)
3437 (markdown-move-list-item-up))
3439 (defun markdown-move-down ()
3440 "Move list item down.
3441 Calls `markdown-move-list-item-down'."
3442 (interactive)
3443 (markdown-move-list-item-down))
3445 (defun markdown-promote ()
3446 "Either promote header or list item at point or cycle markup.
3447 See `markdown-cycle-atx', `markdown-cycle-setext', and
3448 `markdown-demote-list-item'."
3449 (interactive)
3450 (let (bounds)
3451 (cond
3452 ;; Promote atx header
3453 ((thing-at-point-looking-at markdown-regex-header-atx)
3454 (markdown-cycle-atx -1 t))
3455 ;; Promote setext header
3456 ((thing-at-point-looking-at markdown-regex-header-setext)
3457 (markdown-cycle-setext -1 t))
3458 ;; Promote horizonal rule
3459 ((thing-at-point-looking-at markdown-regex-hr)
3460 (markdown-cycle-hr -1 t))
3461 ;; Promote list item
3462 ((setq bounds (markdown-cur-list-item-bounds))
3463 (markdown-promote-list-item)))))
3465 (defun markdown-demote ()
3466 "Either demote header or list item at point or cycle or remove markup.
3467 See `markdown-cycle-atx', `markdown-cycle-setext', and
3468 `markdown-demote-list-item'."
3469 (interactive)
3470 (let (bounds)
3471 (cond
3472 ;; Demote atx header
3473 ((thing-at-point-looking-at markdown-regex-header-atx)
3474 (markdown-cycle-atx 1 t))
3475 ;; Demote setext header
3476 ((thing-at-point-looking-at markdown-regex-header-setext)
3477 (markdown-cycle-setext 1 t))
3478 ;; Demote horizonal rule
3479 ((thing-at-point-looking-at markdown-regex-hr)
3480 (markdown-cycle-hr 1 t))
3481 ;; Promote list item
3482 ((setq bounds (markdown-cur-list-item-bounds))
3483 (markdown-demote-list-item))
3484 ;; Create a new level one ATX header
3486 (markdown-insert-header-atx-1)))))
3488 (defun markdown-complete-or-cycle (arg)
3489 "Complete or cycle markup of object at point or complete objects in region.
3490 If there is an active region, complete markup in region.
3491 Otherwise, complete or cycle markup of object near point.
3492 When ARG is non-nil, cycle backwards when cycling."
3493 (interactive "*P")
3494 (if (markdown-use-region-p)
3495 ;; Complete markup in region
3496 (markdown-complete-region (region-beginning) (region-end))
3497 ;; Complete or cycle markup at point
3498 (let ((dir (if arg -1 1))
3499 bounds)
3500 (cond
3501 ;; atx header
3502 ((thing-at-point-looking-at markdown-regex-header-atx)
3503 (if (markdown-incomplete-atx-p)
3504 (markdown-complete-atx)
3505 (markdown-cycle-atx dir)))
3506 ;; setext header
3507 ((thing-at-point-looking-at markdown-regex-header-setext)
3508 (if (markdown-incomplete-setext-p)
3509 (markdown-complete-setext)
3510 (markdown-cycle-setext dir)))
3511 ;; horizonal rule
3512 ((thing-at-point-looking-at markdown-regex-hr)
3513 (if (markdown-incomplete-hr-p)
3514 (markdown-complete-hr)
3515 (markdown-cycle-hr dir)))
3516 ;; bold
3517 ((thing-at-point-looking-at markdown-regex-bold)
3518 (markdown-cycle-bold))
3519 ;; italic
3520 ((thing-at-point-looking-at markdown-regex-italic)
3521 (markdown-cycle-italic))))))
3524 ;;; Commands ==================================================================
3526 (defun markdown (&optional output-buffer-name)
3527 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3528 The output buffer name defaults to `markdown-output-buffer-name'.
3529 Return the name of the output buffer used."
3530 (interactive)
3531 (save-window-excursion
3532 (let ((begin-region)
3533 (end-region))
3534 (if (markdown-use-region-p)
3535 (setq begin-region (region-beginning)
3536 end-region (region-end))
3537 (setq begin-region (point-min)
3538 end-region (point-max)))
3540 (unless output-buffer-name
3541 (setq output-buffer-name markdown-output-buffer-name))
3543 (cond
3544 ;; Handle case when `markdown-command' does not read from stdin
3545 (markdown-command-needs-filename
3546 (if (not buffer-file-name)
3547 (error "Must be visiting a file")
3548 (shell-command (concat markdown-command " "
3549 (shell-quote-argument buffer-file-name))
3550 output-buffer-name)))
3551 ;; Pass region to `markdown-command' via stdin
3553 (shell-command-on-region begin-region end-region markdown-command
3554 output-buffer-name))))
3555 output-buffer-name))
3557 (defun markdown-standalone (&optional output-buffer-name)
3558 "Special function to provide standalone HTML output.
3559 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3560 (interactive)
3561 (setq output-buffer-name (markdown output-buffer-name))
3562 (with-current-buffer output-buffer-name
3563 (set-buffer output-buffer-name)
3564 (goto-char (point-min))
3565 (unless (markdown-output-standalone-p)
3566 (markdown-add-xhtml-header-and-footer output-buffer-name))
3567 (html-mode))
3568 output-buffer-name)
3570 (defun markdown-other-window (&optional output-buffer-name)
3571 "Run `markdown-command' on current buffer and display in other window.
3572 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3573 that name."
3574 (interactive)
3575 (display-buffer (markdown-standalone output-buffer-name)))
3577 (defun markdown-output-standalone-p ()
3578 "Determine whether `markdown-command' output is standalone XHTML.
3579 Standalone XHTML output is identified by an occurrence of
3580 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3581 (re-search-forward
3582 markdown-xhtml-standalone-regexp
3583 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3586 (defun markdown-add-xhtml-header-and-footer (title)
3587 "Wrap XHTML header and footer with given TITLE around current buffer."
3588 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3589 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3590 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3591 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3592 "<head>\n<title>")
3593 (insert title)
3594 (insert "</title>\n")
3595 (when (> (length markdown-content-type) 0)
3596 (insert
3597 (format
3598 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3599 markdown-content-type
3600 (or (and markdown-coding-system
3601 (fboundp 'coding-system-get)
3602 (coding-system-get markdown-coding-system
3603 'mime-charset))
3604 (and (fboundp 'coding-system-get)
3605 (coding-system-get buffer-file-coding-system
3606 'mime-charset))
3607 "iso-8859-1"))))
3608 (if (> (length markdown-css-path) 0)
3609 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3610 markdown-css-path
3611 "\" />\n"))
3612 (when (> (length markdown-xhtml-header-content) 0)
3613 (insert markdown-xhtml-header-content))
3614 (insert "\n</head>\n\n"
3615 "<body>\n\n")
3616 (goto-char (point-max))
3617 (insert "\n"
3618 "</body>\n"
3619 "</html>\n"))
3621 (defun markdown-preview (&optional output-buffer-name)
3622 "Run `markdown-command' on the current buffer and view output in browser.
3623 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3624 that name."
3625 (interactive)
3626 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3628 (defun markdown-export-file-name (&optional extension)
3629 "Attempt to generate a filename for Markdown output.
3630 The file extension will be EXTENSION if given, or .html by default.
3631 If the current buffer is visiting a file, we construct a new
3632 output filename based on that filename. Otherwise, return nil."
3633 (when (buffer-file-name)
3634 (unless extension
3635 (setq extension ".html"))
3636 (concat
3637 (cond
3638 ((buffer-file-name)
3639 (file-name-sans-extension (buffer-file-name)))
3640 (t (buffer-name)))
3641 extension)))
3643 (defun markdown-export (&optional output-file)
3644 "Run Markdown on the current buffer, save to file, and return the filename.
3645 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3646 generated by `markdown-export-file-name', which will be constructed using the
3647 current filename, but with the extension removed and replaced with .html."
3648 (interactive)
3649 (unless output-file
3650 (setq output-file (markdown-export-file-name ".html")))
3651 (when output-file
3652 (let ((output-buffer-name))
3653 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
3654 (run-hook-with-args 'markdown-before-export-hooks output-file)
3655 (markdown-standalone output-buffer-name)
3656 (with-current-buffer output-buffer-name
3657 (save-buffer))
3658 (run-hook-with-args 'markdown-after-export-hooks output-file)
3659 output-file)))
3661 (defun markdown-export-and-preview ()
3662 "Export to XHTML using `markdown-export' and browse the resulting file."
3663 (interactive)
3664 (browse-url (markdown-export)))
3666 (defun markdown-open ()
3667 "Open file for the current buffer with `markdown-open-command'."
3668 (interactive)
3669 (if (not markdown-open-command)
3670 (error "Variable `markdown-open-command' must be set")
3671 (if (not buffer-file-name)
3672 (error "Must be visiting a file")
3673 (call-process markdown-open-command
3674 nil nil nil buffer-file-name))))
3676 (defun markdown-kill-ring-save ()
3677 "Run Markdown on file and store output in the kill ring."
3678 (interactive)
3679 (save-window-excursion
3680 (markdown)
3681 (with-current-buffer markdown-output-buffer-name
3682 (kill-ring-save (point-min) (point-max)))))
3685 ;;; Links =====================================================================
3687 (require 'thingatpt)
3689 (defun markdown-link-p ()
3690 "Return non-nil when `point' is at a non-wiki link.
3691 See `markdown-wiki-link-p' for more information."
3692 (let ((case-fold-search nil))
3693 (and (not (markdown-wiki-link-p))
3694 (or (thing-at-point-looking-at markdown-regex-link-inline)
3695 (thing-at-point-looking-at markdown-regex-link-reference)
3696 (thing-at-point-looking-at markdown-regex-uri)
3697 (thing-at-point-looking-at markdown-regex-angle-uri)))))
3699 (defun markdown-link-link ()
3700 "Return the link part of the regular (non-wiki) link at point.
3701 Works with both inline and reference style links. If point is
3702 not at a link or the link reference is not defined returns nil."
3703 (cond
3704 ((thing-at-point-looking-at markdown-regex-link-inline)
3705 (substring-no-properties (match-string 2) 1 -1))
3706 ((thing-at-point-looking-at markdown-regex-link-reference)
3707 (let* ((label (match-string-no-properties 1))
3708 (reference (match-string-no-properties 2))
3709 (target (downcase (if (string= reference "[]") label reference))))
3710 (car (markdown-reference-definition target))))
3711 ((thing-at-point-looking-at markdown-regex-uri)
3712 (match-string-no-properties 0))
3713 ((thing-at-point-looking-at markdown-regex-angle-uri)
3714 (match-string-no-properties 2))
3715 (t nil)))
3717 (defun markdown-follow-link-at-point ()
3718 "Open the current non-wiki link in a browser."
3719 (interactive)
3720 (if (markdown-link-p) (browse-url (markdown-link-link))
3721 (error "Point is not at a Markdown link or URI")))
3724 ;;; WikiLink Following/Markup =================================================
3726 (defun markdown-wiki-link-p ()
3727 "Return non-nil when `point' is at a true wiki link.
3728 A true wiki link name matches `markdown-regex-wiki-link' but does not
3729 match the current file name after conversion. This modifies the data
3730 returned by `match-data'. Note that the potential wiki link name must
3731 be available via `match-string'."
3732 (let ((case-fold-search nil))
3733 (and (thing-at-point-looking-at markdown-regex-wiki-link)
3734 (or (not buffer-file-name)
3735 (not (string-equal (buffer-file-name)
3736 (markdown-convert-wiki-link-to-filename
3737 (markdown-wiki-link-link)))))
3738 (not (save-match-data
3739 (save-excursion))))))
3741 (defun markdown-wiki-link-link ()
3742 "Return the link part of the wiki link using current match data.
3743 The location of the link component depends on the value of
3744 `markdown-wiki-link-alias-first'."
3745 (if markdown-wiki-link-alias-first
3746 (or (match-string-no-properties 4) (match-string-no-properties 2))
3747 (match-string-no-properties 2)))
3749 (defun markdown-convert-wiki-link-to-filename (name)
3750 "Generate a filename from the wiki link NAME.
3751 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3752 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3753 and [[test test]] both map to Test-test.ext."
3754 (let ((basename (markdown-replace-regexp-in-string
3755 "[[:space:]\n]" markdown-link-space-sub-char name)))
3756 (when (eq major-mode 'gfm-mode)
3757 (setq basename (concat (upcase (substring basename 0 1))
3758 (downcase (substring basename 1 nil)))))
3759 (concat basename
3760 (if (buffer-file-name)
3761 (concat "."
3762 (file-name-extension (buffer-file-name)))))))
3764 (defun markdown-follow-wiki-link (name &optional other)
3765 "Follow the wiki link NAME.
3766 Convert the name to a file name and call `find-file'. Ensure that
3767 the new buffer remains in `markdown-mode'. Open the link in another
3768 window when OTHER is non-nil."
3769 (let ((filename (markdown-convert-wiki-link-to-filename name))
3770 (wp (file-name-directory buffer-file-name)))
3771 (when other (other-window 1))
3772 (find-file (concat wp filename)))
3773 (when (not (eq major-mode 'markdown-mode))
3774 (markdown-mode)))
3776 (defun markdown-follow-wiki-link-at-point (&optional arg)
3777 "Find Wiki Link at point.
3778 With prefix argument ARG, open the file in other window.
3779 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3780 (interactive "P")
3781 (if (markdown-wiki-link-p)
3782 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
3783 (error "Point is not at a Wiki Link")))
3785 (defun markdown-next-wiki-link ()
3786 "Jump to next wiki link.
3787 If successful, return point. Otherwise, return nil.
3788 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3789 (interactive)
3790 (let ((opoint (point)))
3791 (when (markdown-wiki-link-p)
3792 ;; At a wiki link already, move past it.
3793 (goto-char (+ (match-end 0) 1)))
3794 ;; Search for the next wiki link and move to the beginning.
3795 (if (re-search-forward markdown-regex-wiki-link nil t)
3796 (goto-char (match-beginning 1))
3797 (goto-char opoint)
3798 nil)))
3800 (defun markdown-previous-wiki-link ()
3801 "Jump to previous wiki link.
3802 If successful, return point. Otherwise, return nil.
3803 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3804 (interactive)
3805 (if (re-search-backward markdown-regex-wiki-link nil t)
3806 (goto-char (match-beginning 1))
3807 nil))
3809 (defun markdown-highlight-wiki-link (from to face)
3810 "Highlight the wiki link in the region between FROM and TO using FACE."
3811 (put-text-property from to 'font-lock-face face))
3813 (defun markdown-unfontify-region-wiki-links (from to)
3814 "Remove wiki link faces from the region specified by FROM and TO."
3815 (interactive "nfrom: \nnto: ")
3816 (remove-text-properties from to '(font-lock-face markdown-link-face))
3817 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
3819 (defun markdown-fontify-region-wiki-links (from to)
3820 "Search region given by FROM and TO for wiki links and fontify them.
3821 If a wiki link is found check to see if the backing file exists
3822 and highlight accordingly."
3823 (goto-char from)
3824 (save-match-data
3825 (while (re-search-forward markdown-regex-wiki-link to t)
3826 (let ((highlight-beginning (match-beginning 1))
3827 (highlight-end (match-end 1))
3828 (file-name
3829 (markdown-convert-wiki-link-to-filename
3830 (markdown-wiki-link-link))))
3831 (if (file-exists-p file-name)
3832 (markdown-highlight-wiki-link
3833 highlight-beginning highlight-end markdown-link-face)
3834 (markdown-highlight-wiki-link
3835 highlight-beginning highlight-end markdown-link-face)
3836 (markdown-highlight-wiki-link
3837 highlight-beginning highlight-end markdown-missing-link-face))))))
3839 (defun markdown-extend-changed-region (from to)
3840 "Extend region given by FROM and TO so that we can fontify all links.
3841 The region is extended to the first newline before and the first
3842 newline after."
3843 ;; start looking for the first new line before 'from
3844 (goto-char from)
3845 (re-search-backward "\n" nil t)
3846 (let ((new-from (point-min))
3847 (new-to (point-max)))
3848 (if (not (= (point) from))
3849 (setq new-from (point)))
3850 ;; do the same thing for the first new line after 'to
3851 (goto-char to)
3852 (re-search-forward "\n" nil t)
3853 (if (not (= (point) to))
3854 (setq new-to (point)))
3855 (values new-from new-to)))
3857 (defun markdown-check-change-for-wiki-link (from to change)
3858 "Check region between FROM and TO for wiki links and re-fontfy as needed.
3859 Designed to be used with the `after-change-functions' hook.
3860 CHANGE is the number of bytes of pre-change text replaced by the
3861 given range."
3862 (interactive "nfrom: \nnto: \nnchange: ")
3863 (let* ((modified (buffer-modified-p))
3864 (buffer-undo-list t)
3865 (inhibit-read-only t)
3866 (inhibit-point-motion-hooks t)
3867 deactivate-mark
3868 buffer-file-truename)
3869 (unwind-protect
3870 (save-excursion
3871 (save-match-data
3872 (save-restriction
3873 ;; Extend the region to fontify so that it starts
3874 ;; and ends at safe places.
3875 (multiple-value-bind (new-from new-to)
3876 (markdown-extend-changed-region from to)
3877 ;; Unfontify existing fontification (start from scratch)
3878 (markdown-unfontify-region-wiki-links new-from new-to)
3879 ;; Now do the fontification.
3880 (markdown-fontify-region-wiki-links new-from new-to)))))
3881 (and (not modified)
3882 (buffer-modified-p)
3883 (set-buffer-modified-p nil)))))
3885 (defun markdown-fontify-buffer-wiki-links ()
3886 "Refontify all wiki links in the buffer."
3887 (interactive)
3888 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
3891 ;;; Following and Jumping =====================================================
3893 (defun markdown-follow-thing-at-point (arg)
3894 "Follow thing at point if possible, such as a reference link or wiki link.
3895 Opens inline and reference links in a browser. Opens wiki links
3896 to other files in the current window, or the another window if
3897 ARG is non-nil.
3898 See `markdown-follow-link-at-point' and
3899 `markdown-follow-wiki-link-at-point'."
3900 (interactive "P")
3901 (cond ((markdown-link-p)
3902 (markdown-follow-link-at-point))
3903 ((markdown-wiki-link-p)
3904 (markdown-follow-wiki-link-at-point arg))
3906 (error "Nothing to follow at point."))))
3908 (defun markdown-jump ()
3909 "Jump to another location based on context at point.
3910 Jumps between reference links and definitions; between footnote
3911 markers and footnote text."
3912 (interactive)
3913 (cond ((markdown-footnote-text-positions)
3914 (message "DEBUG: in footnote text")
3915 (markdown-footnote-return))
3916 ((markdown-footnote-marker-positions)
3917 (markdown-footnote-goto-text))
3918 ((thing-at-point-looking-at markdown-regex-link-reference)
3919 (markdown-reference-goto-definition))
3920 ((thing-at-point-looking-at markdown-regex-reference-definition)
3921 (markdown-reference-goto-link (match-string-no-properties 1)))
3923 (error "Nothing to jump to from context at point."))))
3926 ;;; Miscellaneous =============================================================
3928 (defun markdown-compress-whitespace-string (str)
3929 "Compress whitespace in STR and return result.
3930 Leading and trailing whitespace is removed. Sequences of multiple
3931 spaces, tabs, and newlines are replaced with single spaces."
3932 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
3933 (replace-regexp-in-string "[ \t\n]+" " " str)))
3935 (defun markdown-line-number-at-pos (&optional pos)
3936 "Return (narrowed) buffer line number at position POS.
3937 If POS is nil, use current buffer location.
3938 This is an exact copy of `line-number-at-pos' for use in emacs21."
3939 (let ((opoint (or pos (point))) start)
3940 (save-excursion
3941 (goto-char (point-min))
3942 (setq start (point))
3943 (goto-char opoint)
3944 (forward-line 0)
3945 (1+ (count-lines start (point))))))
3947 (defun markdown-nobreak-p ()
3948 "Return nil if it is acceptable to break the current line at the point."
3949 ;; inside in square brackets (e.g., link anchor text)
3950 (looking-back "\\[[^]]*"))
3953 ;;; Mode Definition ==========================================================
3955 (defun markdown-show-version ()
3956 "Show the version number in the minibuffer."
3957 (interactive)
3958 (message "markdown-mode, version %s" markdown-mode-version))
3960 ;;;###autoload
3961 (define-derived-mode markdown-mode text-mode "Markdown"
3962 "Major mode for editing Markdown files."
3963 ;; Natural Markdown tab width
3964 (setq tab-width 4)
3965 ;; Comments
3966 (make-local-variable 'comment-start)
3967 (setq comment-start "<!-- ")
3968 (make-local-variable 'comment-end)
3969 (setq comment-end " -->")
3970 (make-local-variable 'comment-start-skip)
3971 (setq comment-start-skip "<!--[ \t]*")
3972 (make-local-variable 'comment-column)
3973 (setq comment-column 0)
3974 ;; Font lock.
3975 (set (make-local-variable 'font-lock-defaults)
3976 '(markdown-mode-font-lock-keywords))
3977 (set (make-local-variable 'font-lock-multiline) t)
3978 ;; For imenu support
3979 (setq imenu-create-index-function 'markdown-imenu-create-index)
3980 ;; For menu support in XEmacs
3981 (easy-menu-add markdown-mode-menu markdown-mode-map)
3982 ;; Defun movement
3983 (set (make-local-variable 'beginning-of-defun-function)
3984 'markdown-beginning-of-defun)
3985 (set (make-local-variable 'end-of-defun-function)
3986 'markdown-end-of-defun)
3987 ;; Make filling work with lists (unordered, ordered, and definition)
3988 (set (make-local-variable 'paragraph-start)
3989 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
3990 ;; Outline mode
3991 (make-local-variable 'outline-regexp)
3992 (setq outline-regexp markdown-regex-header)
3993 (make-local-variable 'outline-level)
3994 (setq outline-level 'markdown-outline-level)
3995 ;; Cause use of ellipses for invisible text.
3996 (add-to-invisibility-spec '(outline . t))
3997 ;; Indentation and filling
3998 (make-local-variable 'fill-nobreak-predicate)
3999 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4000 (setq indent-line-function markdown-indent-function)
4002 ;; Prepare hooks for XEmacs compatibility
4003 (when (featurep 'xemacs)
4004 (make-local-hook 'after-change-functions)
4005 (make-local-hook 'font-lock-extend-region-functions)
4006 (make-local-hook 'window-configuration-change-hook))
4008 ;; Multiline font lock
4009 (add-hook 'font-lock-extend-region-functions
4010 'markdown-font-lock-extend-region)
4012 ;; Anytime text changes make sure it gets fontified correctly
4013 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4015 ;; If we left the buffer there is a really good chance we were
4016 ;; creating one of the wiki link documents. Make sure we get
4017 ;; refontified when we come back.
4018 (add-hook 'window-configuration-change-hook
4019 'markdown-fontify-buffer-wiki-links t t)
4021 ;; do the initial link fontification
4022 (markdown-fontify-buffer-wiki-links))
4024 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4027 ;;; GitHub Flavored Markdown Mode ============================================
4029 (defvar gfm-font-lock-keywords
4030 (append
4031 ;; GFM features to match first
4032 (list
4033 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4034 (2 markdown-language-keyword-face)
4035 (3 markdown-pre-face)
4036 (4 markdown-pre-face))))
4037 ;; Basic Markdown features (excluding possibly overridden ones)
4038 markdown-mode-font-lock-keywords-basic
4039 ;; GFM features to match last
4040 (list
4041 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4042 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4044 ;;;###autoload
4045 (define-derived-mode gfm-mode markdown-mode "GFM"
4046 "Major mode for editing GitHub Flavored Markdown files."
4047 (setq markdown-link-space-sub-char "-")
4048 (set (make-local-variable 'font-lock-defaults)
4049 '(gfm-font-lock-keywords))
4050 (auto-fill-mode 0)
4051 ;; Use visual-line-mode if available, fall back to longlines-mode:
4052 (if (fboundp 'visual-line-mode)
4053 (visual-line-mode 1)
4054 (longlines-mode 1))
4055 ;; do the initial link fontification
4056 (markdown-fontify-buffer-wiki-links))
4059 (provide 'markdown-mode)
4061 ;;; markdown-mode.el ends here