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