Place definitions at end of 'block'
[markdown-mode.git] / markdown-mode.el
bloba21782bab5b4411bc445340e5ad63e45b479fe4c
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.
128 ;; * `markdown-command-needs-filename' - by default, `markdown-mode'
129 ;; will pass the Markdown content to `markdown-command' using
130 ;; standard input (`stdin`). If `markdown-command' does not
131 ;; accept standard input, then `markdown-command-needs-filename'
132 ;; should be set to non-nil, which instructs `markdown-mode' to
133 ;; pass the name of the file as the final command-line argument.
134 ;; Note that with this option, you will only be able to run
135 ;; `markdown-command' from buffers which are visiting a file.
137 ;; * `markdown-open-command' - the command used for calling a standalone
138 ;; Markdown previewer which is capable of opening Markdown source files
139 ;; directly (default: `nil'). This command will be called
140 ;; with a single argument, the filename of the current buffer.
141 ;; A representative program is the Mac app [Marked][], a
142 ;; live-updating MultiMarkdown previewer which has a command line
143 ;; utility at `/usr/local/bin/mark`.
145 ;; * `markdown-hr-strings' - list of strings to use when inserting
146 ;; horizontal rules. Different strings will not be distinguished
147 ;; when converted to HTML--they will all be converted to
148 ;; `<hr/>`--but they may add visual distinction and style to plain
149 ;; text documents. To maintain some notion of promotion and
150 ;; demotion, keep these sorted from largest to smallest.
152 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
153 ;; underscores for bold instead of two asterisks (default: `nil').
155 ;; * `markdown-italic-underscore' - set to a non-nil value to use
156 ;; underscores for italic instead of asterisks (default: `nil').
158 ;; * `markdown-indent-function' - the function to use for automatic
159 ;; indentation (default: `markdown-indent-line').
161 ;; * `markdown-indent-on-enter' - set to a non-nil value to
162 ;; automatically indent new lines when the enter key is pressed
163 ;; (default: `t')
165 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
166 ;; to automatically open a linked document in a new buffer if the
167 ;; cursor is an wiki link
168 ;; (default: `t')
170 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
171 ;; treat aliased wiki links like `[[link text|PageName]]`.
172 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
174 ;; * `markdown-uri-types' - a list of protocols for URIs that
175 ;; `markdown-mode' should highlight.
177 ;; * `markdown-enable-math' - syntax highlighting for
178 ;; LaTeX fragments (default: `nil').
180 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
182 ;; * `markdown-content-type' - when set to a nonempty string, an
183 ;; `http-equiv` attribute will be included in the XHTML `<head>`
184 ;; block. If needed, the suggested values are
185 ;; `application/xhtml+xml` or `text/html`.
187 ;; * `markdown-coding-system' - used for specifying the character
188 ;; set identifier in the `http-equiv` attribute (see
189 ;; `markdown-content-type'). When set to `nil',
190 ;; `buffer-file-coding-system' will be used (and falling back to
191 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
192 ;; and `iso-latin-1'.
194 ;; * `markdown-xhtml-header-content' - additional content to include
195 ;; in the XHTML `<head>` block.
197 ;; * `markdown-command-needs-filename' - set to non-nil if
198 ;; `markdown-command' does not accept input from stdin (default: nil).
199 ;; Instead, it will be passed a filename as the final command-line
200 ;; argument. As a result, you will only be able to run Markdown
201 ;; from buffers which are visiting a file.
203 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
204 ;; `markdown-mode' uses to determine whether the output of
205 ;; `markdown-command' is a standalone XHTML document or an XHTML
206 ;; fragment (default: `"^\\(\<\\?xml\\|\<!DOCTYPE\\|\<html\\)"`). If
207 ;; this regular expression not matched in the first five lines of
208 ;; output, `markdown-mode' assumes the output is a fragment and
209 ;; adds a header and footer.
211 ;; * `markdown-link-space-sub-char' - a character to replace spaces
212 ;; when mapping wiki links to filenames (default: `_`).
213 ;; For example, use an underscore for compatibility with the
214 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
215 ;; with GitHub wiki links.
217 ;; Additionally, the faces used for syntax highlighting can be modified to
218 ;; your liking by issuing `M-x customize-group RET markdown-faces`
219 ;; or by using the "Markdown Faces" link at the bottom of the mode
220 ;; customization screen.
222 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
224 ;;; Usage:
226 ;; Keybindings are grouped by prefixes based on their function. For
227 ;; example, commands dealing with headers begin with `C-c C-t`. The
228 ;; primary commands in each group will are described below. You can
229 ;; obtain a list of all keybindings by pressing `C-c C-h`.
231 ;; * Anchors: `C-c C-a`
233 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
234 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
235 ;; The label definition will be placed at the end of the current
236 ;; block. `C-c C-a w` acts similarly for wiki links of the form
237 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
238 ;; text in the region is used as the link text.
240 ;; * Commands: `C-c C-c`
242 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
243 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
244 ;; runs Markdown on the current buffer and previews, stores the
245 ;; output in a temporary file, and displays the file in a browser.
246 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
247 ;; and save the result in the file `basename.html`, where
248 ;; `basename` is the name of the Markdown file with the extension
249 ;; removed. *Export and View:* press `C-c C-c v` to export the
250 ;; file and view it in a browser. **For both export commands, the
251 ;; output file will be overwritten without notice.**
252 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
253 ;; using `markdown-open-command'.
255 ;; To summarize:
257 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
258 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
259 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
260 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
261 ;; - `C-c C-c w`: `markdown-command' > kill ring.
262 ;; - `C-c C-c o`: `markdown-open-command'.
264 ;; `C-c C-c c` will check for undefined references. If there are
265 ;; any, a small buffer will open with a list of undefined
266 ;; references and the line numbers on which they appear. In Emacs
267 ;; 22 and greater, selecting a reference from this list and
268 ;; pressing `RET` will insert an empty reference definition at the
269 ;; end of the buffer. Similarly, selecting the line number will
270 ;; jump to the corresponding line.
272 ;; `C-c C-c n` will clean up the numbering of ordered lists.
274 ;; * Images: `C-c C-i`
276 ;; `C-c C-i i` inserts markup for an inline image, using the
277 ;; active region (if any) or the word at point as the alt text.
278 ;; To insert reference-style image markup, provide a `C-u` prefix.
280 ;; * Physical styles: `C-c C-p`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
284 ;; the selected text bold, `C-c C-p f` formats the region as
285 ;; fixed-width text, and `C-c C-p i` is used for italic text.
287 ;; * Logical styles: `C-c C-s`
289 ;; These commands all act on text in the active region, if any,
290 ;; and insert empty markup fragments otherwise. Logical styles
291 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
292 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
293 ;; (`C-c C-s s`).
295 ;; * Headers: `C-c C-t`
297 ;; All header commands use text in the active region, if any, as
298 ;; the header text. Otherwise, if the current line is not blank,
299 ;; use the text on the current line. Finally, prompt for header
300 ;; text if there is no active region and the current line is
301 ;; blank. To insert an atx or hash style level-n
302 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
303 ;; top-level setext or underline style header press `C-c C-t t`
304 ;; (mnemonic: title) and for a second-level underline-style header
305 ;; press `C-c C-t s` (mnemonic: section).
307 ;; If the point is at a header, these commands will replace the
308 ;; existing markup in order to update the level and/or type of the
309 ;; header. To remove the markup of the header at the point, press
310 ;; `C-c C-t 0`.
312 ;; * Footnotes: `C-c C-f`
314 ;; To create a new footnote at the point, press `C-c C-f n`.
315 ;; Press `C-c C-f g` with the point at a footnote to jump to the
316 ;; location where the footnote text is defined. Then, press
317 ;; `C-c C-f b` to return to the footnote marker in the main text.
318 ;; When the point is at a footnote marker or in the body of a
319 ;; footnote, press `C-c C-f k` to kill the footnote and add the
320 ;; text to the kill ring.
322 ;; * Other elements:
324 ;; `C-c -` inserts a horizontal rule. By default, insert the
325 ;; first string in the list `markdown-hr-strings' (the most
326 ;; prominent rule). With a `C-u` prefix, insert the last string.
327 ;; With a numeric prefix `N`, insert the string in position `N`
328 ;; (counting from 1).
330 ;; * Following Links:
332 ;; Press `C-c C-o` when the point is on an inline or reference
333 ;; link to open the URL in a browser. When the point is at a
334 ;; wiki link, open it in another buffer (in the current window,
335 ;; or in the other window with the `C-u` prefix).
336 ;; To move between links, use `M-p` and `M-n` to quickly jump
337 ;; to the previous or next link of any type.
339 ;; * Jumping:
341 ;; Use `C-c C-j` to jump from the object at point to its counterpart
342 ;; elsewhere in the text, when possible. Jumps between reference
343 ;; links and definitions; between footnote markers and footnote
344 ;; text. If more than one link uses the same reference name, a
345 ;; new buffer will be created containing clickable buttons for jumping
346 ;; to each link. You may press `TAB` or `S-TAB` to jump between
347 ;; buttons in this window.
349 ;; * Killing Elements:
351 ;; Press `C-c C-k` to kill the thing at point and add important
352 ;; text, without markup, to the kill ring. Possible things to
353 ;; kill include (roughly in order of precedece): inline code,
354 ;; headers, horizonal rules, links (add link text to kill ring),
355 ;; images (add alt text to kill ring), angle URIs, email
356 ;; addresses, bold, italics, reference definitions (add URI to
357 ;; kill ring), footnote markers and text (kill both marker and
358 ;; text, add text to kill ring), and list items.
360 ;; * Outline Navigation:
362 ;; Navigation between headings is possible using `outline-mode'.
363 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
364 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
365 ;; next and previous visible headings at the same level as the one
366 ;; at the point. Finally, `C-M-u` will move up to a lower-level
367 ;; (more inclusive) visible heading.
369 ;; * Movement by Block:
371 ;; markdown-mode supports the usual Emacs paragraph movement with
372 ;; `M-{` and `M-}`. These commands treat list items as
373 ;; paragraphs, so they will stop at each line within a block of
374 ;; list items. Additionally, markdown-mode includes movement
375 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
376 ;; of an entire block of text (with blocks being separated by at
377 ;; least one blank line).
379 ;; * Movement by Defun:
381 ;; The usual Emacs commands can be used to move by defuns
382 ;; (top-level major definitions). In markdown-mode, a defun
383 ;; is a section. As usual, `C-M-a` will move the point to
384 ;; the beginning of the current or preceding defun, `C-M-e`
385 ;; will move to the end of the current or following defun,
386 ;; and `C-M-h` will put the region around the entire defun.
388 ;; Many of the commands described above behave differently depending on
389 ;; whether Transient Mark mode is enabled or not. When it makes sense,
390 ;; if Transient Mark mode is on and a region is active, the command
391 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
392 ;; bold). For users who prefer to work outside of Transient Mark mode,
393 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
395 ;; When applicable, commands that specifically act on the region even
396 ;; outside of Transient Mark mode have the same keybinding as the with
397 ;; the exception of an additional `C-` prefix. For example,
398 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
399 ;; the region in Transient Mark mode while `markdown-blockquote-region'
400 ;; is bound to `C-c C-s C-b` and always applies to the region (when
401 ;; nonempty).
403 ;; Note that these region-specific functions are useful in many
404 ;; cases where it may not be obvious. For example, yanking text from
405 ;; the kill ring sets the mark at the beginning of the yanked text
406 ;; and moves the point to the end. Therefore, the (inactive) region
407 ;; contains the yanked text. So, `C-y` then `C-c C-s C-b` will yank
408 ;; text and make it a blockquote.
410 ;; markdown-mode attempts to be flexible in how it handles
411 ;; indentation. When you press `TAB` repeatedly, the point will cycle
412 ;; through several possible indentation levels corresponding to things
413 ;; you might have in mind when you press `RET` at the end of a line or
414 ;; `TAB`. For example, you may want to start a new list item,
415 ;; continue a list item with hanging indentation, indent for a nested
416 ;; pre block, and so on.
418 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
419 ;; visibility cycling for atx- or hash-style headers. There are two
420 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
421 ;; the table of contents view (headers only), outline view (top-level
422 ;; headers only), and the full document view. Pressing `TAB` while the
423 ;; point is at a header will cycle through levels of visibility for the
424 ;; subtree: completely folded, visible children, and fully visible.
425 ;; Note that mixing hash and underline style headers will give undesired
426 ;; results.
428 ;;; Extensions:
430 ;; Besides supporting the basic Markdown syntax, markdown-mode also
431 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
432 ;; links may be followed automatically by pressing the enter key when
433 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
434 ;; auto-following on enter key may be controlled with the
435 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
436 ;; `M-n` to quickly jump to the previous and next wiki links,
437 ;; respectively. Aliased or piped wiki links of the form
438 ;; `[[link text|PageName]]` are also supported. Since some wikis
439 ;; reverse these components, set `markdown-wiki-link-alias-first'
440 ;; to nil to treat them as `[[PageName|link text]]`.
442 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
443 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
444 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
445 ;; You can do this either by using `M-x customize-group markdown`
446 ;; or by placing the following in your `.emacs` file:
448 ;; (defun markdown-custom ()
449 ;; "markdown-mode-hook"
450 ;; (setq markdown-command "markdown | smartypants"))
451 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
453 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
455 ;; Experimental syntax highlighting for mathematical expressions written
456 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
457 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
458 ;; either via customize or by placing `(setq markdown-enable-itex t)`
459 ;; in `.emacs`, and restarting Emacs.
461 ;;; GitHub Flavored Markdown:
463 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
464 ;; available. The GitHub implementation of differs slightly from
465 ;; standard Markdown. The most important differences are that
466 ;; newlines are significant, triggering hard line breaks, and that
467 ;; underscores inside of words (e.g., variable names) need not be
468 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
469 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
470 ;; not available). Underscores inside of words (such as
471 ;; test_variable) will not trigger emphasis.
473 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
474 ;; replacing spaces in filenames and where the first letter of the
475 ;; filename capitalized. For example, `[[wiki link]]' will map to a
476 ;; file named `Wiki-link` with the same extension as the current file.
478 ;; GFM code blocks, with optional programming language keywords, will
479 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
480 ;; is an active region, the text in the region will be placed inside
481 ;; the code block. You will be prompted for the name of the language,
482 ;; but may press enter to continue without naming a language.
484 ;; For a more complete GitHub-flavored markdown experience, consider
485 ;; adding README.md to your `auto-mode-alist':
487 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
489 ;; For GFM preview can be powered by setting `markdown-command' to
490 ;; use [Docter][]. This may also be configured to work with [Marked][]
491 ;; for `markdown-open-command'.
493 ;; [GFM]: http://github.github.com/github-flavored-markdown/
494 ;; [Docter]: https://github.com/alampros/Docter
496 ;;; Acknowledgments:
498 ;; markdown-mode has benefited greatly from the efforts of the
499 ;; following people:
501 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
502 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
503 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
504 ;; GitHub Flavored Markdown mode (`gfm-mode').
505 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
506 ;; `markdown' with an active region.
507 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
508 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
509 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
510 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
511 ;; visibility cycling functionality was derived, and for a bug fix
512 ;; related to `orgtbl-mode'.
513 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
514 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
515 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
516 ;; compatibility and custom CSS.
517 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
518 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
519 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
520 ;; comment matching functions were derived.
521 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
522 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
523 ;; functions, bug reports regarding indentation, and
524 ;; fixes for byte-compilation warnings.
525 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
526 ;; enhancements.
527 ;; * George Ogata <george.ogata@gmail.com> for fixing several
528 ;; byte-compilation warnings.
529 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
530 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
531 ;; customizations and XHTML export.
532 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
533 ;; Markdown processors which do not accept input from stdin.
534 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
535 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
536 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
537 ;; substitution character for mapping wiki links to filenames.
538 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
539 ;; escape shell commands.
540 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
541 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
542 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
543 ;; Emacs Lisp coding conventions.
544 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
545 ;; regexp, refactoring the compilation and preview functions,
546 ;; heading font-lock generalizations, list renumbering,
547 ;; and kill ring save.
548 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
549 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
550 ;; for an autoload token for `gfm-mode'.
551 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
552 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
553 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
554 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
555 ;; declaration in XHTML output.
556 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
557 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
558 ;; and GFM code block insertion.
559 ;; * Peter Jones <pjones@pmade.com> for link following functions.
560 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
561 ;; externally modified files.
562 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
563 ;; related to `orgtbl-mode'.
564 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
565 ;; export hooks and unit test improvements.
566 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
567 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
568 ;; completion.
570 ;;; Bugs:
572 ;; Although markdown-mode is developed and tested primarily using
573 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
574 ;; priority.
576 ;; If you find any bugs in markdown-mode, please construct a test case
577 ;; or a patch and email me at <jrblevin@sdf.org>.
579 ;;; History:
581 ;; markdown-mode was written and is maintained by Jason Blevins. The
582 ;; first version was released on May 24, 2007.
584 ;; * 2007-05-24: Version 1.1
585 ;; * 2007-05-25: Version 1.2
586 ;; * 2007-06-05: [Version 1.3][]
587 ;; * 2007-06-29: Version 1.4
588 ;; * 2007-10-11: [Version 1.5][]
589 ;; * 2008-06-04: [Version 1.6][]
590 ;; * 2009-10-01: [Version 1.7][]
591 ;; * 2011-08-12: [Version 1.8][]
592 ;; * 2011-08-15: [Version 1.8.1][]
593 ;; * 2013-01-25: [Version 1.9][]
595 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
596 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
597 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
598 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
599 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
600 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
601 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
604 ;;; Code:
606 (require 'easymenu)
607 (require 'outline)
608 (eval-when-compile (require 'cl))
611 ;;; Constants =================================================================
613 (defconst markdown-mode-version "1.9"
614 "Markdown mode version number.")
616 (defconst markdown-output-buffer-name "*markdown-output*"
617 "Name of temporary buffer for markdown command output.")
620 ;;; Global Variables ==========================================================
622 (defvar markdown-reference-label-history nil
623 "History of used reference labels.")
626 ;;; Customizable Variables ====================================================
628 (defvar markdown-mode-hook nil
629 "Hook run when entering Markdown mode.")
631 (defvar markdown-before-export-hooks nil
632 "Hook run before output XHTML.
633 This hook is abnormal and registered functions are given an argument that is output filename.")
635 (defvar markdown-after-export-hooks nil
636 "Hook run after output XHTML.
637 This hook is abnormal and registered functions are given an argument that is output filename.")
639 (defgroup markdown nil
640 "Major mode for editing text files in Markdown format."
641 :prefix "markdown-"
642 :group 'wp
643 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
645 (defcustom markdown-command "markdown"
646 "Command to run markdown."
647 :group 'markdown
648 :type 'string)
650 (defcustom markdown-command-needs-filename nil
651 "Set to non-nil if `markdown-command' does not accept input from stdin.
652 Instead, it will be passed a filename as the final command line
653 option. As a result, you will only be able to run Markdown from
654 buffers which are visiting a file."
655 :group 'markdown
656 :type 'boolean)
658 (defcustom markdown-open-command nil
659 "Command used for opening Markdown files directly.
660 For example, a standalone Markdown previewer. This command will
661 be called with a single argument: the filename of the current
662 buffer."
663 :group 'markdown
664 :type 'string)
666 (defcustom markdown-hr-strings
667 '("-------------------------------------------------------------------------------"
668 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
669 "---------------------------------------"
670 "* * * * * * * * * * * * * * * * * * * *"
671 "---------"
672 "* * * * *")
673 "Strings to use when inserting horizontal rules.
674 The first string in the list will be the default when inserting a
675 horizontal rule. Strings should be listed in decreasing order of
676 prominence (as in headers from level one to six) for use with
677 promotion and demotion functions."
678 :group 'markdown
679 :type 'list)
681 (defcustom markdown-bold-underscore nil
682 "Use two underscores for bold instead of two asterisks."
683 :group 'markdown
684 :type 'boolean)
686 (defcustom markdown-italic-underscore nil
687 "Use underscores for italic instead of asterisks."
688 :group 'markdown
689 :type 'boolean)
691 (defcustom markdown-indent-function 'markdown-indent-line
692 "Function to use to indent."
693 :group 'markdown
694 :type 'function)
696 (defcustom markdown-indent-on-enter t
697 "Automatically indent new lines when enter key is pressed."
698 :group 'markdown
699 :type 'boolean)
701 (defcustom markdown-follow-wiki-link-on-enter t
702 "Follow wiki link at point (if any) when the enter key is pressed."
703 :group 'markdown
704 :type 'boolean)
706 (defcustom markdown-wiki-link-alias-first t
707 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
708 Otherwise, they will be treated as [[PageName|alias text]]."
709 :group 'markdown
710 :type 'boolean)
712 (defcustom markdown-uri-types
713 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
714 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
715 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
716 "Link types for syntax highlighting of URIs."
717 :group 'markdown
718 :type 'list)
720 (defcustom markdown-enable-math nil
721 "Syntax highlighting for inline LaTeX expressions.
722 This will not take effect until Emacs is restarted."
723 :group 'markdown
724 :type 'boolean)
726 (defcustom markdown-css-path ""
727 "URL of CSS file to link to in the output XHTML."
728 :group 'markdown
729 :type 'string)
731 (defcustom markdown-content-type ""
732 "Content type string for the http-equiv header in XHTML output.
733 When set to a non-empty string, insert the http-equiv attribute.
734 Otherwise, this attribute is omitted."
735 :group 'markdown
736 :type 'string)
738 (defcustom markdown-coding-system nil
739 "Character set string for the http-equiv header in XHTML output.
740 Defaults to `buffer-file-coding-system' (and falling back to
741 `iso-8859-1' when not available). Common settings are `utf-8'
742 and `iso-latin-1'. Use `list-coding-systems' for more choices."
743 :group 'markdown
744 :type 'coding-system)
746 (defcustom markdown-xhtml-header-content ""
747 "Additional content to include in the XHTML <head> block."
748 :group 'markdown
749 :type 'string)
751 (defcustom markdown-xhtml-standalone-regexp
752 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
753 "Regexp indicating whether `markdown-command' output is standalone XHTML."
754 :group 'markdown
755 :type 'regexp)
757 (defcustom markdown-link-space-sub-char
759 "Character to use instead of spaces when mapping wiki links to filenames."
760 :group 'markdown
761 :type 'string)
763 (defcustom markdown-reference-location 'header
764 "Position where new reference definitions are inserted in the document."
765 :group 'markdown
766 :type '(choice (const :tag "At the end of the document" end)
767 (const :tag "Immediately after the current block" immediately)
768 (const :tag "Before next header" header)))
770 (defcustom markdown-footnote-location 'end
771 "Position where new footnotes are inserted in the document."
772 :group 'markdown
773 :type '(choice (const :tag "At the end of the document" end)
774 (const :tag "Immediately after the current block" immediately)
775 (const :tag "Before next header" header)))
778 ;;; Font Lock =================================================================
780 (require 'font-lock)
782 (defvar markdown-italic-face 'markdown-italic-face
783 "Face name to use for italic text.")
785 (defvar markdown-bold-face 'markdown-bold-face
786 "Face name to use for bold text.")
788 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
789 "Face name to use as a base for header delimiters.")
791 (defvar markdown-header-rule-face 'markdown-header-rule-face
792 "Face name to use as a base for header rules.")
794 (defvar markdown-header-face 'markdown-header-face
795 "Face name to use as a base for headers.")
797 (defvar markdown-header-face-1 'markdown-header-face-1
798 "Face name to use for level-1 headers.")
800 (defvar markdown-header-face-2 'markdown-header-face-2
801 "Face name to use for level-2 headers.")
803 (defvar markdown-header-face-3 'markdown-header-face-3
804 "Face name to use for level-3 headers.")
806 (defvar markdown-header-face-4 'markdown-header-face-4
807 "Face name to use for level-4 headers.")
809 (defvar markdown-header-face-5 'markdown-header-face-5
810 "Face name to use for level-5 headers.")
812 (defvar markdown-header-face-6 'markdown-header-face-6
813 "Face name to use for level-6 headers.")
815 (defvar markdown-inline-code-face 'markdown-inline-code-face
816 "Face name to use for inline code.")
818 (defvar markdown-list-face 'markdown-list-face
819 "Face name to use for list markers.")
821 (defvar markdown-blockquote-face 'markdown-blockquote-face
822 "Face name to use for blockquote.")
824 (defvar markdown-pre-face 'markdown-pre-face
825 "Face name to use for preformatted text.")
827 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
828 "Face name to use for programming language identifiers.")
830 (defvar markdown-link-face 'markdown-link-face
831 "Face name to use for links.")
833 (defvar markdown-missing-link-face 'markdown-missing-link-face
834 "Face name to use for links where the linked file does not exist.")
836 (defvar markdown-reference-face 'markdown-reference-face
837 "Face name to use for reference.")
839 (defvar markdown-footnote-face 'markdown-footnote-face
840 "Face name to use for footnote identifiers.")
842 (defvar markdown-url-face 'markdown-url-face
843 "Face name to use for URLs.")
845 (defvar markdown-link-title-face 'markdown-link-title-face
846 "Face name to use for reference link titles.")
848 (defvar markdown-line-break-face 'markdown-line-break-face
849 "Face name to use for hard line breaks.")
851 (defvar markdown-comment-face 'markdown-comment-face
852 "Face name to use for HTML comments.")
854 (defvar markdown-math-face 'markdown-math-face
855 "Face name to use for LaTeX expressions.")
857 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
858 "Face name to use for metadata keys.")
860 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
861 "Face name to use for metadata values.")
863 (defgroup markdown-faces nil
864 "Faces used in Markdown Mode"
865 :group 'markdown
866 :group 'faces)
868 (defface markdown-italic-face
869 '((t (:inherit font-lock-variable-name-face :slant italic)))
870 "Face for italic text."
871 :group 'markdown-faces)
873 (defface markdown-bold-face
874 '((t (:inherit font-lock-variable-name-face :weight bold)))
875 "Face for bold text."
876 :group 'markdown-faces)
878 (defface markdown-header-rule-face
879 '((t (:inherit font-lock-function-name-face :weight bold)))
880 "Base face for headers rules."
881 :group 'markdown-faces)
883 (defface markdown-header-delimiter-face
884 '((t (:inherit font-lock-function-name-face :weight bold)))
885 "Base face for headers hash delimiter."
886 :group 'markdown-faces)
888 (defface markdown-header-face
889 '((t (:inherit font-lock-function-name-face :weight bold)))
890 "Base face for headers."
891 :group 'markdown-faces)
893 (defface markdown-header-face-1
894 '((t (:inherit markdown-header-face)))
895 "Face for level-1 headers."
896 :group 'markdown-faces)
898 (defface markdown-header-face-2
899 '((t (:inherit markdown-header-face)))
900 "Face for level-2 headers."
901 :group 'markdown-faces)
903 (defface markdown-header-face-3
904 '((t (:inherit markdown-header-face)))
905 "Face for level-3 headers."
906 :group 'markdown-faces)
908 (defface markdown-header-face-4
909 '((t (:inherit markdown-header-face)))
910 "Face for level-4 headers."
911 :group 'markdown-faces)
913 (defface markdown-header-face-5
914 '((t (:inherit markdown-header-face)))
915 "Face for level-5 headers."
916 :group 'markdown-faces)
918 (defface markdown-header-face-6
919 '((t (:inherit markdown-header-face)))
920 "Face for level-6 headers."
921 :group 'markdown-faces)
923 (defface markdown-inline-code-face
924 '((t (:inherit font-lock-constant-face)))
925 "Face for inline code."
926 :group 'markdown-faces)
928 (defface markdown-list-face
929 '((t (:inherit font-lock-builtin-face)))
930 "Face for list item markers."
931 :group 'markdown-faces)
933 (defface markdown-blockquote-face
934 '((t (:inherit font-lock-doc-face)))
935 "Face for blockquote sections."
936 :group 'markdown-faces)
938 (defface markdown-pre-face
939 '((t (:inherit font-lock-constant-face)))
940 "Face for preformatted text."
941 :group 'markdown-faces)
943 (defface markdown-language-keyword-face
944 '((t (:inherit font-lock-type-face)))
945 "Face for programming language identifiers."
946 :group 'markdown-faces)
948 (defface markdown-link-face
949 '((t (:inherit font-lock-keyword-face)))
950 "Face for links."
951 :group 'markdown-faces)
953 (defface markdown-missing-link-face
954 '((t (:inherit font-lock-warning-face)))
955 "Face for missing links."
956 :group 'markdown-faces)
958 (defface markdown-reference-face
959 '((t (:inherit font-lock-type-face)))
960 "Face for link references."
961 :group 'markdown-faces)
963 (defface markdown-footnote-face
964 '((t (:inherit font-lock-keyword-face)))
965 "Face for footnote markers."
966 :group 'markdown-faces)
968 (defface markdown-url-face
969 '((t (:inherit font-lock-string-face)))
970 "Face for URLs."
971 :group 'markdown-faces)
973 (defface markdown-link-title-face
974 '((t (:inherit font-lock-comment-face)))
975 "Face for reference link titles."
976 :group 'markdown-faces)
978 (defface markdown-line-break-face
979 '((t (:inherit font-lock-constant-face :underline t)))
980 "Face for hard line breaks."
981 :group 'markdown-faces)
983 (defface markdown-comment-face
984 '((t (:inherit font-lock-comment-face)))
985 "Face for HTML comments."
986 :group 'markdown-faces)
988 (defface markdown-math-face
989 '((t (:inherit font-lock-string-face)))
990 "Face for LaTeX expressions."
991 :group 'markdown-faces)
993 (defface markdown-metadata-key-face
994 '((t (:inherit font-lock-variable-name-face)))
995 "Face for metadata keys."
996 :group 'markdown-faces)
998 (defface markdown-metadata-value-face
999 '((t (:inherit font-lock-string-face)))
1000 "Face for metadata values."
1001 :group 'markdown-faces)
1003 (defconst markdown-regex-link-inline
1004 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
1005 "Regular expression for a [text](file) or an image link ![text](file).
1006 Group 1 matches the leading exclamation point, if any.
1007 Group 2 matchs the entire square bracket term, including the text.
1008 Group 3 matches the text inside the square brackets.
1009 Group 4 matches the entire parenthesis term, including the URL and title.
1010 Group 5 matches the URL.
1011 Group 6 matches (optional) title.")
1013 (defconst markdown-regex-link-reference
1014 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
1015 "Regular expression for a reference link [text][id].
1016 Group 1 matches the leading exclamation point, if any.
1017 Group 2 matchs the entire first square bracket term, including the text.
1018 Group 3 matches the text inside the square brackets.
1019 Group 4 matches the entire second square bracket term.
1020 Group 5 matches the reference label.")
1022 (defconst markdown-regex-reference-definition
1023 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1024 "Regular expression for a link definition [id]: ...")
1026 (defconst markdown-regex-footnote
1027 "\\(\\[\\^.+?\\]\\)"
1028 "Regular expression for a footnote marker [^fn].")
1030 (defconst markdown-regex-header
1031 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1032 "Regexp identifying Markdown headers.")
1034 (defconst markdown-regex-header-1-atx
1035 "^\\(#\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1036 "Regular expression for level 1 atx-style (hash mark) headers.")
1038 (defconst markdown-regex-header-2-atx
1039 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1040 "Regular expression for level 2 atx-style (hash mark) headers.")
1042 (defconst markdown-regex-header-3-atx
1043 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1044 "Regular expression for level 3 atx-style (hash mark) headers.")
1046 (defconst markdown-regex-header-4-atx
1047 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1048 "Regular expression for level 4 atx-style (hash mark) headers.")
1050 (defconst markdown-regex-header-5-atx
1051 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1052 "Regular expression for level 5 atx-style (hash mark) headers.")
1054 (defconst markdown-regex-header-6-atx
1055 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1056 "Regular expression for level 6 atx-style (hash mark) headers.")
1058 (defconst markdown-regex-header-1-setext
1059 "^\\(.*\\)\n\\(=+\\)$"
1060 "Regular expression for level 1 setext-style (underline) headers.")
1062 (defconst markdown-regex-header-2-setext
1063 "^\\(.*\\)\n\\(-+\\)$"
1064 "Regular expression for level 2 setext-style (underline) headers.")
1066 (defconst markdown-regex-header-setext
1067 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1068 "Regular expression for generic setext-style (underline) headers.")
1070 (defconst markdown-regex-header-atx
1071 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1072 "Regular expression for generic atx-style (hash mark) headers.")
1074 (defconst markdown-regex-hr
1075 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1076 "Regular expression for matching Markdown horizontal rules.")
1078 (defconst markdown-regex-code
1079 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1080 "Regular expression for matching inline code fragments.
1082 The first group ensures that the leading backquote character
1083 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1084 character, including newlines, but not two newlines in a row.
1085 The final group requires that the character following the code
1086 fragment is not a backquote.")
1088 (defconst markdown-regex-pre
1089 "^\\( \\|\t\\).*$"
1090 "Regular expression for matching preformatted text sections.")
1092 (defconst markdown-regex-list
1093 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1094 "Regular expression for matching list items.")
1096 (defconst markdown-regex-bold
1097 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1098 "Regular expression for matching bold text.
1099 Group 1 matches the character before the opening asterisk or
1100 underscore, if any, ensuring that it is not a backslash escape.
1101 Group 2 matches the entire expression, including delimiters.
1102 Groups 3 and 5 matches the opening and closing delimiters.
1103 Group 4 matches the text inside the delimiters.")
1105 (defconst markdown-regex-italic
1106 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1107 "Regular expression for matching italic text.
1108 Group 1 matches the character before the opening asterisk or
1109 underscore, if any, ensuring that it is not a backslash escape.
1110 Group 2 matches the entire expression, including delimiters.
1111 Groups 3 and 5 matches the opening and closing delimiters.
1112 Group 4 matches the text inside the delimiters.")
1114 (defconst markdown-regex-gfm-italic
1115 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1116 "Regular expression for matching italic text in GitHub-flavored Markdown.
1117 Underscores in words are not treated as special.")
1119 (defconst markdown-regex-blockquote
1120 "^[ \t]*\\(>\\).*$"
1121 "Regular expression for matching blockquote lines.")
1123 (defconst markdown-regex-line-break
1124 "[^ \n\t][ \t]*\\( \\)$"
1125 "Regular expression for matching line breaks.")
1127 (defconst markdown-regex-wiki-link
1128 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1129 "Regular expression for matching wiki links.
1130 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1131 wiki links of the form [[PageName|link text]]. In this regular
1132 expression, #1 matches the page name and #3 matches the link
1133 text.")
1135 (defconst markdown-regex-uri
1136 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1137 "Regular expression for matching inline URIs.")
1139 (defconst markdown-regex-angle-uri
1140 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1141 "Regular expression for matching inline URIs in angle brackets.")
1143 (defconst markdown-regex-email
1144 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1145 "Regular expression for matching inline email addresses.")
1147 (defconst markdown-regex-link-generic
1148 (concat "\\(?:" markdown-regex-wiki-link
1149 "\\|" markdown-regex-link-inline
1150 "\\|" markdown-regex-link-reference
1151 "\\|" markdown-regex-angle-uri "\\)")
1152 "Regular expression for matching any recognized link.")
1154 (defconst markdown-regex-block-separator
1155 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1156 "Regular expression for matching block boundaries.")
1158 (defconst markdown-regex-latex-expression
1159 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1160 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1162 (defconst markdown-regex-latex-display
1163 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1164 "Regular expression for itex \[..\] display mode expressions.")
1166 (defconst markdown-regex-multimarkdown-metadata
1167 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1168 "Regular expression for matching MultiMarkdown metadata.")
1170 (defconst markdown-regex-pandoc-metadata
1171 "^\\(%\\)[ \t]*\\(.*\\)$"
1172 "Regular expression for matching Pandoc metadata.")
1174 (defvar markdown-mode-font-lock-keywords-basic
1175 (list
1176 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1177 (2 markdown-metadata-value-face)))
1178 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1179 (2 markdown-metadata-value-face)))
1180 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1181 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1182 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1183 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1184 (2 markdown-header-rule-face)))
1185 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1186 (2 markdown-header-rule-face)))
1187 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1188 (2 markdown-header-face-6)
1189 (3 markdown-header-delimiter-face)))
1190 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1191 (2 markdown-header-face-5)
1192 (3 markdown-header-delimiter-face)))
1193 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1194 (2 markdown-header-face-4)
1195 (3 markdown-header-delimiter-face)))
1196 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1197 (2 markdown-header-face-3)
1198 (3 markdown-header-delimiter-face)))
1199 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1200 (2 markdown-header-face-2)
1201 (3 markdown-header-delimiter-face)))
1202 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1203 (2 markdown-header-face-1)
1204 (3 markdown-header-delimiter-face)))
1205 (cons markdown-regex-hr 'markdown-header-face)
1206 (cons 'markdown-match-comments '((0 markdown-comment-face)))
1207 (cons 'markdown-match-code '((0 markdown-inline-code-face)))
1208 (cons markdown-regex-angle-uri 'markdown-link-face)
1209 (cons markdown-regex-uri 'markdown-link-face)
1210 (cons markdown-regex-email 'markdown-link-face)
1211 (cons markdown-regex-list '(2 markdown-list-face))
1212 (cons markdown-regex-footnote 'markdown-footnote-face)
1213 (cons markdown-regex-link-inline '((1 markdown-link-face t t)
1214 (2 markdown-link-face t)
1215 (4 markdown-url-face t)
1216 (6 markdown-link-title-face t t)))
1217 (cons markdown-regex-link-reference '((1 markdown-link-face t t)
1218 (2 markdown-link-face t)
1219 (4 markdown-reference-face t)))
1220 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1221 (2 markdown-url-face t)
1222 (3 markdown-link-title-face t)))
1223 (cons markdown-regex-bold '(2 markdown-bold-face))
1224 (cons markdown-regex-line-break '(1 markdown-line-break-face prepend))
1226 "Syntax highlighting for Markdown files.")
1228 (defvar markdown-mode-font-lock-keywords-core
1229 (list
1230 (cons markdown-regex-italic '(2 markdown-italic-face))
1232 "Additional syntax highlighting for Markdown files.
1233 Includes features which are overridden by some variants.")
1235 (defconst markdown-mode-font-lock-keywords-latex
1236 (list
1237 ;; Math mode $..$ or $$..$$
1238 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1239 ;; Display mode equations with brackets: \[ \]
1240 (cons markdown-regex-latex-display 'markdown-math-face)
1241 ;; Equation reference (eq:foo)
1242 (cons "(eq:\\w+)" 'markdown-reference-face)
1243 ;; Equation reference \eqref{foo}
1244 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1245 "Syntax highlighting for LaTeX fragments.")
1247 (defvar markdown-mode-font-lock-keywords
1248 (append
1249 (if markdown-enable-math
1250 markdown-mode-font-lock-keywords-latex)
1251 markdown-mode-font-lock-keywords-basic
1252 markdown-mode-font-lock-keywords-core)
1253 "Default highlighting expressions for Markdown mode.")
1255 ;; Footnotes
1256 (defvar markdown-footnote-counter 0
1257 "Counter for footnote numbers.")
1258 (make-variable-buffer-local 'markdown-footnote-counter)
1260 (defconst markdown-footnote-chars
1261 "[[:alnum:]-]"
1262 "Regular expression maching any character that is allowed in a footnote identifier.")
1265 ;;; Compatibility =============================================================
1267 (defun markdown-replace-regexp-in-string (regexp rep string)
1268 "Replace ocurrences of REGEXP with REP in STRING.
1269 This is a compatibility wrapper to provide `replace-regexp-in-string'
1270 in XEmacs 21."
1271 (if (featurep 'xemacs)
1272 (replace-in-string string regexp rep)
1273 (replace-regexp-in-string regexp rep string)))
1275 ;; `markdown-use-region-p' is a compatibility function which checks
1276 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1277 (eval-and-compile
1278 (cond
1279 ;; Emacs 23 and newer
1280 ((fboundp 'use-region-p)
1281 (defalias 'markdown-use-region-p 'use-region-p))
1282 ;; Older Emacsen
1283 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1284 (defun markdown-use-region-p ()
1285 "Compatibility wrapper to provide `use-region-p'."
1286 (and transient-mark-mode mark-active)))
1287 ;; XEmacs
1288 ((fboundp 'region-active-p)
1289 (defalias 'markdown-use-region-p 'region-active-p))))
1291 (defun markdown-use-buttons-p ()
1292 "Determine whether this Emacs supports buttons."
1293 (or (featurep 'button) (locate-library "button")))
1296 ;;; Markdown Parsing Functions ================================================
1298 (defun markdown-cur-line-blank-p ()
1299 "Return t if the current line is blank and nil otherwise."
1300 (save-excursion
1301 (beginning-of-line)
1302 (re-search-forward "^\\s *$" (line-end-position) t)))
1304 (defun markdown-prev-line-blank-p ()
1305 "Return t if the previous line is blank and nil otherwise.
1306 If we are at the first line, then consider the previous line to be blank."
1307 (or (= (line-beginning-position) (point-min))
1308 (save-excursion
1309 (forward-line -1)
1310 (markdown-cur-line-blank-p))))
1312 (defun markdown-next-line-blank-p ()
1313 "Return t if the next line is blank and nil otherwise.
1314 If we are at the last line, then consider the next line to be blank."
1315 (or (= (line-end-position) (point-max))
1316 (save-excursion
1317 (forward-line 1)
1318 (markdown-cur-line-blank-p))))
1320 (defun markdown-prev-line-indent-p ()
1321 "Return t if the previous line is indented and nil otherwise."
1322 (save-excursion
1323 (forward-line -1)
1324 (goto-char (line-beginning-position))
1325 (if (re-search-forward "^\\s " (line-end-position) t) t)))
1327 (defun markdown-cur-line-indent ()
1328 "Return the number of leading whitespace characters in the current line."
1329 (save-match-data
1330 (save-excursion
1331 (goto-char (line-beginning-position))
1332 (re-search-forward "^[ \t]+" (line-end-position) t)
1333 (current-column))))
1335 (defun markdown-prev-line-indent ()
1336 "Return the number of leading whitespace characters in the previous line."
1337 (save-excursion
1338 (forward-line -1)
1339 (markdown-cur-line-indent)))
1341 (defun markdown-next-line-indent ()
1342 "Return the number of leading whitespace characters in the next line."
1343 (save-excursion
1344 (forward-line 1)
1345 (markdown-cur-line-indent)))
1347 (defun markdown-cur-non-list-indent ()
1348 "Return beginning position of list item text (not including the list marker).
1349 Return nil if the current line is not the beginning of a list item."
1350 (save-match-data
1351 (save-excursion
1352 (beginning-of-line)
1353 (when (re-search-forward markdown-regex-list (line-end-position) t)
1354 (current-column)))))
1356 (defun markdown-prev-non-list-indent ()
1357 "Return position of the first non-list-marker on the previous line."
1358 (save-excursion
1359 (forward-line -1)
1360 (markdown-cur-non-list-indent)))
1362 (defun markdown-new-baseline-p ()
1363 "Determine if the current line begins a new baseline level."
1364 (save-excursion
1365 (beginning-of-line)
1366 (save-match-data
1367 (or (looking-at markdown-regex-header)
1368 (looking-at markdown-regex-hr)
1369 (and (null (markdown-cur-non-list-indent))
1370 (= (markdown-cur-line-indent) 0)
1371 (markdown-prev-line-blank-p))))))
1373 (defun markdown-search-backward-baseline ()
1374 "Search backward baseline point with no indentation and not a list item."
1375 (end-of-line)
1376 (let (stop)
1377 (while (not (or stop (bobp)))
1378 (re-search-backward markdown-regex-block-separator nil t)
1379 (when (match-end 2)
1380 (goto-char (match-end 2))
1381 (cond
1382 ((markdown-new-baseline-p)
1383 (setq stop t))
1384 ((looking-at markdown-regex-list)
1385 (setq stop nil))
1386 (t (setq stop t)))))))
1388 (defun markdown-update-list-levels (marker indent levels)
1389 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1390 Here, MARKER is a string representing the type of list, INDENT is an integer
1391 giving the indentation, in spaces, of the current block, and LEVELS is a
1392 list of the indentation levels of parent list items. When LEVELS is nil,
1393 it means we are at baseline (not inside of a nested list)."
1394 (cond
1395 ;; New list item at baseline.
1396 ((and marker (null levels))
1397 (setq levels (list indent)))
1398 ;; List item with greater indentation (four or more spaces).
1399 ;; Increase list level.
1400 ((and marker (>= indent (+ (car levels) 4)))
1401 (setq levels (cons indent levels)))
1402 ;; List item with greater or equal indentation (less than four spaces).
1403 ;; Do not increase list level.
1404 ((and marker (>= indent (car levels)))
1405 levels)
1406 ;; Lesser indentation level.
1407 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1408 ;; indentation could move back more than one list level). Note
1409 ;; that this block need not be the beginning of list item.
1410 ((< indent (car levels))
1411 (while (and (> (length levels) 1)
1412 (< indent (+ (cadr levels) 4)))
1413 (setq levels (cdr levels)))
1414 levels)
1415 ;; Otherwise, do nothing.
1416 (t levels)))
1418 (defun markdown-calculate-list-levels ()
1419 "Calculate list levels at point.
1420 Return a list of the form (n1 n2 n3 ...) where n1 is the
1421 indentation of the deepest nested list item in the branch of
1422 the list at the point, n2 is the indentation of the parent
1423 list item, and so on. The depth of the list item is therefore
1424 the length of the returned list. If the point is not at or
1425 immediately after a list item, return nil."
1426 (save-excursion
1427 (let ((first (point)) levels indent pre-regexp)
1428 ;; Find a baseline point with zero list indentation
1429 (markdown-search-backward-baseline)
1430 ;; Search for all list items between baseline and LOC
1431 (while (and (< (point) first)
1432 (re-search-forward markdown-regex-list first t))
1433 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1434 (beginning-of-line)
1435 (cond
1436 ;; Make sure this is not a header or hr
1437 ((markdown-new-baseline-p) (setq levels nil))
1438 ;; Make sure this is not a line from a pre block
1439 ((looking-at pre-regexp))
1440 ;; If not, then update levels
1442 (setq indent (markdown-cur-line-indent))
1443 (setq levels (markdown-update-list-levels (match-string 2)
1444 indent levels))))
1445 (end-of-line))
1446 levels)))
1448 (defun markdown-prev-list-item (level)
1449 "Search backward from point for a list item with indentation LEVEL.
1450 Set point to the beginning of the item, and return point, or nil
1451 upon failure."
1452 (let (bounds indent prev)
1453 (setq prev (point))
1454 (forward-line -1)
1455 (setq indent (markdown-cur-line-indent))
1456 (while
1457 (cond
1458 ;; Stop at beginning of buffer
1459 ((bobp) (setq prev nil))
1460 ;; Continue if current line is blank
1461 ((markdown-cur-line-blank-p) t)
1462 ;; List item
1463 ((and (looking-at markdown-regex-list)
1464 (setq bounds (markdown-cur-list-item-bounds)))
1465 (cond
1466 ;; Continue at item with greater indentation
1467 ((> (nth 3 bounds) level) t)
1468 ;; Stop and return point at item of equal indentation
1469 ((= (nth 3 bounds) level)
1470 (setq prev (point))
1471 nil)
1472 ;; Stop and return nil at item with lesser indentation
1473 ((< (nth 3 bounds) level)
1474 (setq prev nil)
1475 nil)))
1476 ;; Continue while indentation is the same or greater
1477 ((>= indent level) t)
1478 ;; Stop if current indentation is less than list item
1479 ;; and the next is blank
1480 ((and (< indent level)
1481 (markdown-next-line-blank-p))
1482 (setq prev nil))
1483 ;; Stop at a header
1484 ((looking-at markdown-regex-header) (setq prev nil))
1485 ;; Stop at a horizontal rule
1486 ((looking-at markdown-regex-hr) (setq prev nil))
1487 ;; Otherwise, continue.
1488 (t t))
1489 (forward-line -1)
1490 (setq indent (markdown-cur-line-indent)))
1491 prev))
1493 (defun markdown-next-list-item (level)
1494 "Search forward from point for the next list item with indentation LEVEL.
1495 Set point to the beginning of the item, and return point, or nil
1496 upon failure."
1497 (let (bounds indent prev next)
1498 (setq next (point))
1499 (forward-line)
1500 (setq indent (markdown-cur-line-indent))
1501 (while
1502 (cond
1503 ;; Stop at end of the buffer.
1504 ((eobp) (setq prev nil))
1505 ;; Continue if the current line is blank
1506 ((markdown-cur-line-blank-p) t)
1507 ;; List item
1508 ((and (looking-at markdown-regex-list)
1509 (setq bounds (markdown-cur-list-item-bounds)))
1510 (cond
1511 ;; Continue at item with greater indentation
1512 ((> (nth 3 bounds) level) t)
1513 ;; Stop and return point at item of equal indentation
1514 ((= (nth 3 bounds) level)
1515 (setq next (point))
1516 nil)
1517 ;; Stop and return nil at item with lesser indentation
1518 ((< (nth 3 bounds) level)
1519 (setq next nil)
1520 nil)))
1521 ;; Continue while indentation is the same or greater
1522 ((>= indent level) t)
1523 ;; Stop if current indentation is less than list item
1524 ;; and the previous line was blank.
1525 ((and (< indent level)
1526 (markdown-prev-line-blank-p))
1527 (setq next nil))
1528 ;; Stop at a header
1529 ((looking-at markdown-regex-header) (setq next nil))
1530 ;; Stop at a horizontal rule
1531 ((looking-at markdown-regex-hr) (setq next nil))
1532 ;; Otherwise, continue.
1533 (t t))
1534 (forward-line)
1535 (setq indent (markdown-cur-line-indent)))
1536 next))
1538 (defun markdown-cur-list-item-end (level)
1539 "Move to the end of the current list item with nonlist indentation LEVEL.
1540 If the point is not in a list item, do nothing."
1541 (let (indent)
1542 (forward-line)
1543 (setq indent (markdown-cur-line-indent))
1544 (while
1545 (cond
1546 ;; Stop at end of the buffer.
1547 ((eobp) nil)
1548 ;; Continue if the current line is blank
1549 ((markdown-cur-line-blank-p) t)
1550 ;; Continue while indentation is the same or greater
1551 ((>= indent level) t)
1552 ;; Stop if current indentation is less than list item
1553 ;; and the previous line was blank.
1554 ((and (< indent level)
1555 (markdown-prev-line-blank-p))
1556 nil)
1557 ;; Stop at a new list item of the same or lesser indentation
1558 ((looking-at markdown-regex-list) nil)
1559 ;; Stop at a header
1560 ((looking-at markdown-regex-header) nil)
1561 ;; Stop at a horizontal rule
1562 ((looking-at markdown-regex-hr) nil)
1563 ;; Otherwise, continue.
1564 (t t))
1565 (forward-line)
1566 (setq indent (markdown-cur-line-indent)))
1567 ;; Don't skip over whitespace for empty list items (marker and
1568 ;; whitespace only), just move to end of whitespace.
1569 (if (looking-back (concat markdown-regex-list "\\s-*"))
1570 (goto-char (match-end 3))
1571 (skip-syntax-backward "-"))))
1573 (defun markdown-cur-list-item-bounds ()
1574 "Return bounds and indentation of the current list item.
1575 Return a list of the form (begin end indent nonlist-indent marker).
1576 If the point is not inside a list item, return nil.
1577 Leave match data intact for `markdown-regex-list'."
1578 (let (cur prev-begin prev-end indent nonlist-indent marker)
1579 ;; Store current location
1580 (setq cur (point))
1581 ;; Verify that cur is between beginning and end of item
1582 (save-excursion
1583 (end-of-line)
1584 (when (re-search-backward markdown-regex-list nil t)
1585 (setq prev-begin (match-beginning 0))
1586 (setq indent (length (match-string 1)))
1587 (setq nonlist-indent (length (match-string 0)))
1588 (setq marker (concat (match-string 2) (match-string 3)))
1589 (save-match-data
1590 (markdown-cur-list-item-end nonlist-indent)
1591 (setq prev-end (point)))
1592 (when (and (>= cur prev-begin)
1593 (<= cur prev-end)
1594 nonlist-indent)
1595 (list prev-begin prev-end indent nonlist-indent marker))))))
1597 (defun markdown-bounds-of-thing-at-point (thing)
1598 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1599 Does not include trailing newlines when THING is 'line. Handles the
1600 end of buffer case by setting both endpoints equal to the value of
1601 `point-max', since an empty region will trigger empty markup insertion.
1602 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1603 (let* ((bounds (bounds-of-thing-at-point thing))
1604 (a (car bounds))
1605 (b (cdr bounds)))
1606 (when bounds
1607 (when (eq thing 'line)
1608 (cond ((and (eobp) (markdown-cur-line-blank-p))
1609 (setq a b))
1610 ((char-equal (char-before b) ?\^J)
1611 (setq b (1- b)))))
1612 (cons a b))))
1614 (defun markdown-reference-definition (reference)
1615 "Find out whether Markdown REFERENCE is defined.
1616 REFERENCE should include the square brackets, like [this].
1617 When REFERENCE is defined, return a list of the form (text start end)
1618 containing the definition text itself followed by the start and end
1619 locations of the text. Otherwise, return nil.
1620 Leave match data for `markdown-regex-reference-definition'
1621 intact additional processing."
1622 (let ((reference (downcase reference)))
1623 (save-excursion
1624 (goto-char (point-min))
1625 (catch 'found
1626 (while (re-search-forward markdown-regex-reference-definition nil t)
1627 (when (string= reference (downcase (match-string-no-properties 1)))
1628 (throw 'found
1629 (list (match-string-no-properties 2)
1630 (match-beginning 2) (match-end 2)))))))))
1632 (defun markdown-get-defined-references ()
1633 "Return a list of all defined reference labels (including square brackets)."
1634 (save-excursion
1635 (goto-char (point-min))
1636 (let (refs)
1637 (while (re-search-forward markdown-regex-reference-definition nil t)
1638 (let ((target (match-string-no-properties 1)))
1639 (add-to-list 'refs target t)))
1640 refs)))
1643 ;;; Markdown Font Lock Matching Functions =====================================
1645 (defun markdown-match-comments (last)
1646 "Match HTML comments from the point to LAST."
1647 (cond ((search-forward "<!--" last t)
1648 (backward-char 4)
1649 (let ((beg (point)))
1650 (cond ((search-forward-regexp "--[ \t]*>" last t)
1651 (set-match-data (list beg (point)))
1653 (t nil))))
1654 (t nil)))
1656 (defun markdown-match-code (last)
1657 "Match inline code from the point to LAST."
1658 (unless (bobp)
1659 (backward-char 1))
1660 (cond ((re-search-forward markdown-regex-code last t)
1661 (set-match-data (list (match-beginning 2) (match-end 2)))
1662 (goto-char (match-end 0))
1664 (t (forward-char 2) nil)))
1666 (defun markdown-match-pre-blocks (last)
1667 "Match Markdown pre blocks from point to LAST."
1668 (let ((levels (markdown-calculate-list-levels))
1669 indent pre-regexp end-regexp begin end stop)
1670 (while (and (< (point) last) (not end))
1671 ;; Search for a region with sufficient indentation
1672 (if (null levels)
1673 (setq indent 1)
1674 (setq indent (1+ (length levels))))
1675 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1676 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1678 (cond
1679 ;; If not at the beginning of a line, move forward
1680 ((not (bolp)) (forward-line))
1681 ;; Move past blank lines
1682 ((markdown-cur-line-blank-p) (forward-line))
1683 ;; At headers and horizontal rules, reset levels
1684 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1685 ;; If the current line has sufficient indentation, mark out pre block
1686 ((looking-at pre-regexp)
1687 (setq begin (match-beginning 0))
1688 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1689 (not (eobp)))
1690 (forward-line))
1691 (setq end (point)))
1692 ;; If current line has a list marker, update levels, move to end of block
1693 ((looking-at markdown-regex-list)
1694 (setq levels (markdown-update-list-levels
1695 (match-string 2) (markdown-cur-line-indent) levels))
1696 (markdown-end-of-block-element))
1697 ;; If this is the end of the indentation level, adjust levels accordingly.
1698 ;; Only match end of indentation level if levels is not the empty list.
1699 ((and (car levels) (looking-at end-regexp))
1700 (setq levels (markdown-update-list-levels
1701 nil (markdown-cur-line-indent) levels))
1702 (markdown-end-of-block-element))
1703 (t (markdown-end-of-block-element))))
1705 (if (not (and begin end))
1706 ;; Return nil if no pre block was found
1708 ;; Set match data and return t upon success
1709 (set-match-data (list begin end))
1710 t)))
1712 (defun markdown-match-fenced-code-blocks (last)
1713 "Match fenced code blocks from the point to LAST."
1714 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1715 (beginning-of-line)
1716 (let ((beg (point)))
1717 (forward-line)
1718 (cond ((search-forward-regexp
1719 (concat "^" (match-string 1) "~*") last t)
1720 (set-match-data (list beg (point)))
1722 (t nil))))
1723 (t nil)))
1725 (defun markdown-match-gfm-code-blocks (last)
1726 "Match GFM quoted code blocks from point to LAST."
1727 (let (open lang body close all)
1728 (cond ((and (eq major-mode 'gfm-mode)
1729 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1730 (beginning-of-line)
1731 (setq open (list (match-beginning 1) (match-end 1))
1732 lang (list (match-beginning 2) (match-end 2)))
1733 (forward-line)
1734 (setq body (list (point)))
1735 (cond ((search-forward-regexp "^```$" last t)
1736 (setq body (reverse (cons (1- (match-beginning 0)) body))
1737 close (list (match-beginning 0) (match-end 0))
1738 all (list (car open) (match-end 0)))
1739 (set-match-data (append all open lang body close))
1741 (t nil)))
1742 (t nil))))
1744 (defun markdown-match-generic-metadata (regexp last)
1745 "Match generic metadata specified by REGEXP from the point to LAST."
1746 (let ((header-end (save-excursion
1747 (goto-char (point-min))
1748 (if (re-search-forward "\n\n" (point-max) t)
1749 (match-beginning 0)
1750 (point-max)))))
1751 (cond ((>= (point) header-end)
1752 ;; Don't match anything outside of the header.
1753 nil)
1754 ((re-search-forward regexp (min last header-end) t)
1755 ;; If a metadata item is found, it may span several lines.
1756 (let ((key-beginning (match-beginning 1))
1757 (key-end (match-end 1))
1758 (value-beginning (match-beginning 2)))
1759 (while (and (not (looking-at regexp))
1760 (not (> (point) (min last header-end)))
1761 (not (eobp)))
1762 (forward-line))
1763 (unless (eobp)
1764 (forward-line -1)
1765 (end-of-line))
1766 (set-match-data (list key-beginning (point) ; complete metadata
1767 key-beginning key-end ; key
1768 value-beginning (point))) ; value
1770 (t nil))))
1772 (defun markdown-match-multimarkdown-metadata (last)
1773 "Match MultiMarkdown metadata from the point to LAST."
1774 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1776 (defun markdown-match-pandoc-metadata (last)
1777 "Match Pandoc metadata from the point to LAST."
1778 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1780 (defun markdown-font-lock-extend-region ()
1781 "Extend the search region to include an entire block of text.
1782 This helps improve font locking for block constructs such as pre blocks."
1783 ;; Avoid compiler warnings about these global variables from font-lock.el.
1784 ;; See the documentation for variable `font-lock-extend-region-functions'.
1785 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1786 (save-excursion
1787 (goto-char font-lock-beg)
1788 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1789 (goto-char font-lock-end)
1790 (when (re-search-forward "\n\n" nil t)
1791 (beginning-of-line)
1792 (setq font-lock-end (point)))
1793 (setq font-lock-beg found))))
1796 ;;; Syntax Table ==============================================================
1798 (defvar markdown-mode-syntax-table
1799 (let ((tab (make-syntax-table text-mode-syntax-table)))
1800 (modify-syntax-entry ?\" "." tab)
1801 tab)
1802 "Syntax table for `markdown-mode'.")
1805 ;;; Element Insertion =========================================================
1807 (defun markdown-ensure-blank-line-before ()
1808 "If previous line is not already blank, insert a blank line before point."
1809 (unless (bolp) (insert "\n"))
1810 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1812 (defun markdown-ensure-blank-line-after ()
1813 "If following line is not already blank, insert a blank line after point.
1814 Return the point where it was originally."
1815 (save-excursion
1816 (unless (eolp) (insert "\n"))
1817 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1819 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1820 "Insert the strings S1 and S2, wrapping around region or THING.
1821 If a region is specified by the optional BEG and END arguments,
1822 wrap the strings S1 and S2 around that region.
1823 If there is an active region, wrap the strings S1 and S2 around
1824 the region. If there is not an active region but the point is at
1825 THING, wrap that thing (which defaults to word). Otherwise, just
1826 insert S1 and S2 and place the cursor in between. Return the
1827 bounds of the entire wrapped string, or nil if nothing was wrapped
1828 and S1 and S2 were only inserted."
1829 (let (a b bounds new-point)
1830 (cond
1831 ;; Given region
1832 ((and beg end)
1833 (setq a beg
1834 b end
1835 new-point (+ (point) (length s1))))
1836 ;; Active region
1837 ((markdown-use-region-p)
1838 (setq a (region-beginning)
1839 b (region-end)
1840 new-point (+ (point) (length s1))))
1841 ;; Thing (word) at point
1842 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1843 (setq a (car bounds)
1844 b (cdr bounds)
1845 new-point (+ (point) (length s1))))
1846 ;; No active region and no word
1848 (setq a (point)
1849 b (point))))
1850 (goto-char b)
1851 (insert s2)
1852 (goto-char a)
1853 (insert s1)
1854 (when new-point (goto-char new-point))
1855 (if (= a b)
1857 (setq b (+ b (length s1) (length s2)))
1858 (cons a b))))
1860 (defun markdown-point-after-unwrap (cur prefix suffix)
1861 "Return desired position of point after an unwrapping operation.
1862 CUR gives the position of the point before the operation.
1863 Additionally, two cons cells must be provided. PREFIX gives the
1864 bounds of the prefix string and SUFFIX gives the bounds of the
1865 suffix string."
1866 (cond ((< cur (cdr prefix)) (car prefix))
1867 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1868 ((<= cur (cdr suffix))
1869 (- cur (+ (- (cdr prefix) (car prefix))
1870 (- cur (car suffix)))))
1871 (t cur)))
1873 (defun markdown-unwrap-thing-at-point (regexp all text)
1874 "Remove prefix and suffix of thing at point and reposition the point.
1875 When the thing at point matches REGEXP, replace the subexpression
1876 ALL with the string in subexpression TEXT. Reposition the point
1877 in an appropriate location accounting for the removal of prefix
1878 and suffix strings. Return new bounds of string from group TEXT.
1879 When REGEXP is nil, assumes match data is already set."
1880 (when (or (null regexp)
1881 (thing-at-point-looking-at regexp))
1882 (let ((cur (point))
1883 (prefix (cons (match-beginning all) (match-beginning text)))
1884 (suffix (cons (match-end text) (match-end all)))
1885 (bounds (cons (match-beginning text) (match-end text))))
1886 ;; Replace the thing at point
1887 (replace-match (match-string text) t t nil all)
1888 ;; Reposition the point
1889 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1890 ;; Adjust bounds
1891 (setq bounds (cons (car prefix)
1892 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1894 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1895 "Remove prefix and suffix of all things in region from BEG to END.
1896 When a thing in the region matches REGEXP, replace the
1897 subexpression ALL with the string in subexpression TEXT.
1898 Return a cons cell containing updated bounds for the region."
1899 (save-excursion
1900 (goto-char beg)
1901 (let ((removed 0) len-all len-text)
1902 (while (re-search-forward regexp (- end removed) t)
1903 (setq len-all (length (match-string-no-properties all)))
1904 (setq len-text (length (match-string-no-properties text)))
1905 (setq removed (+ removed (- len-all len-text)))
1906 (replace-match (match-string text) t t nil all))
1907 (cons beg (- end removed)))))
1909 (defun markdown-insert-hr (arg)
1910 "Insert or replace a horizonal rule.
1911 By default, use the first element of `markdown-hr-strings'. When
1912 ARG is non-nil, as when given a prefix, select a different
1913 element as follows. When prefixed with \\[universal-argument],
1914 use the last element of `markdown-hr-strings' instead. When
1915 prefixed with an integer from 1 to the length of
1916 `markdown-hr-strings', use the element in that position instead."
1917 (interactive "*P")
1918 (when (thing-at-point-looking-at markdown-regex-hr)
1919 (delete-region (match-beginning 0) (match-end 0)))
1920 (markdown-ensure-blank-line-before)
1921 (cond ((equal arg '(4))
1922 (insert (car (reverse markdown-hr-strings))))
1923 ((and (integerp arg) (> arg 0)
1924 (<= arg (length markdown-hr-strings)))
1925 (insert (nth (1- arg) markdown-hr-strings)))
1927 (insert (car markdown-hr-strings))))
1928 (markdown-ensure-blank-line-after))
1930 (defun markdown-insert-bold ()
1931 "Insert markup to make a region or word bold.
1932 If there is an active region, make the region bold. If the point
1933 is at a non-bold word, make the word bold. If the point is at a
1934 bold word or phrase, remove the bold markup. Otherwise, simply
1935 insert bold delimiters and place the cursor in between them."
1936 (interactive)
1937 (let ((delim (if markdown-bold-underscore "__" "**")))
1938 (if (markdown-use-region-p)
1939 ;; Active region
1940 (let ((bounds (markdown-unwrap-things-in-region
1941 (region-beginning) (region-end)
1942 markdown-regex-bold 2 4)))
1943 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1944 ;; Bold markup removal, bold word at point, or empty markup insertion
1945 (if (thing-at-point-looking-at markdown-regex-bold)
1946 (markdown-unwrap-thing-at-point nil 2 4)
1947 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1949 (defun markdown-insert-italic ()
1950 "Insert markup to make a region or word italic.
1951 If there is an active region, make the region italic. If the point
1952 is at a non-italic word, make the word italic. If the point is at an
1953 italic word or phrase, remove the italic markup. Otherwise, simply
1954 insert italic delimiters and place the cursor in between them."
1955 (interactive)
1956 (let ((delim (if markdown-italic-underscore "_" "*")))
1957 (if (markdown-use-region-p)
1958 ;; Active region
1959 (let ((bounds (markdown-unwrap-things-in-region
1960 (region-beginning) (region-end)
1961 markdown-regex-italic 2 4)))
1962 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1963 ;; Italic markup removal, italic word at point, or empty markup insertion
1964 (if (thing-at-point-looking-at markdown-regex-italic)
1965 (markdown-unwrap-thing-at-point nil 2 4)
1966 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1968 (defun markdown-insert-code ()
1969 "Insert markup to make a region or word an inline code fragment.
1970 If there is an active region, make the region an inline code
1971 fragment. If the point is at a word, make the word an inline
1972 code fragment. Otherwise, simply insert code delimiters and
1973 place the cursor in between them."
1974 (interactive)
1975 (if (markdown-use-region-p)
1976 ;; Active region
1977 (let ((bounds (markdown-unwrap-things-in-region
1978 (region-beginning) (region-end)
1979 markdown-regex-code 2 4)))
1980 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1981 ;; Code markup removal, code markup for word, or empty markup insertion
1982 (if (thing-at-point-looking-at markdown-regex-code)
1983 (markdown-unwrap-thing-at-point nil 2 4)
1984 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1986 (defun markdown-insert-link ()
1987 "Insert an inline link, using region or word as link text if possible.
1988 If there is an active region, use the region as the link text. If the
1989 point is at a word, use the word as the link text. In these cases, the
1990 point will be left at the position for inserting a URL. If there is no
1991 active region and the point is not at word, simply insert link markup and
1992 place the point in the position to enter link text."
1993 (interactive)
1994 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1995 (when bounds
1996 (goto-char (- (cdr bounds) 1)))))
1998 (defun markdown-insert-reference-link (text label &optional url title)
1999 "Insert a reference link and, optionally, a reference definition.
2000 The link TEXT will be inserted followed by the optional LABEL.
2001 If a URL is given, also insert a definition for the reference
2002 LABEL after the end of the paragraph. If a TITLE is given, it
2003 will be added to the end of the reference definition and will be
2004 used to populate the title attribute when converted to XHTML. If
2005 URL is nil, insert only the link portion (for example, when a
2006 reference label is already defined)."
2007 (insert (concat "[" text "][" label "]"))
2008 (when url
2009 (let ((end (point))
2010 (label (if (> (length label) 0) label text)))
2011 (cond
2012 ((eq markdown-reference-location 'end) (goto-char (point-max)))
2013 ((eq markdown-reference-location 'immediately) (markdown-end-of-block))
2014 ((eq markdown-reference-location 'header) (markdown-end-of-defun)))
2015 (unless (markdown-cur-line-blank-p) (insert "\n"))
2016 (insert "\n[" label "]: " url)
2017 (unless (> (length url) 0)
2018 (setq end (point)))
2019 (when (> (length title) 0)
2020 (insert " \"" title "\""))
2021 (insert "\n")
2022 (unless (or (eobp) (looking-at "\n"))
2023 (insert "\n"))
2024 (goto-char end)
2025 (when (> (length url) 0)
2026 (message
2027 (substitute-command-keys
2028 "Defined reference [%s], press \\[markdown-jump] to jump there")
2029 (or label text))))))
2031 (defun markdown-insert-reference-link-dwim ()
2032 "Insert a reference link of the form [text][label] at point.
2033 If there is an active region, the text in the region will be used
2034 as the link text. If the point is at a word, it will be used as
2035 the link text. Otherwise, the link text will be read from the
2036 minibuffer. The link label will be read from the minibuffer in
2037 both cases, with completion from the set of currently defined
2038 references. To create an implicit reference link, press RET to
2039 accept the default, an empty label. If the entered referenced
2040 label is not defined, additionally prompt for the URL
2041 and (optional) title. The reference definition is placed at the
2042 end of the current paragraph."
2043 (interactive)
2044 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2045 (markdown-get-defined-references)))
2046 (bounds (or (and (markdown-use-region-p)
2047 (cons (region-beginning) (region-end)))
2048 (markdown-bounds-of-thing-at-point 'word)))
2049 (text (if bounds
2050 (buffer-substring (car bounds) (cdr bounds))
2051 (read-string "Link Text: ")))
2052 (label (completing-read
2053 "Link Label (default: none): " defined-labels
2054 nil nil nil 'markdown-reference-label-history nil))
2055 (ref (markdown-reference-definition
2056 (concat "[" (if (> (length label) 0) label text) "]")))
2057 (url (unless ref (read-string "Link URL: ")))
2058 (title (when (> (length url) 0)
2059 (read-string "Link Title (optional): "))))
2060 (when bounds (delete-region (car bounds) (cdr bounds)))
2061 (markdown-insert-reference-link text label url title)))
2063 (defun markdown-insert-uri ()
2064 "Insert markup for an inline URI.
2065 If there is an active region, use it as the URI. If the point is
2066 at a URI, wrap it with angle brackets. If the point is at an
2067 inline URI, remove the angle brackets. Otherwise, simply insert
2068 angle brackets place the point between them."
2069 (interactive)
2070 (if (markdown-use-region-p)
2071 ;; Active region
2072 (let ((bounds (markdown-unwrap-things-in-region
2073 (region-beginning) (region-end)
2074 markdown-regex-angle-uri 0 2)))
2075 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
2076 ;; Markup removal, URI at point, or empty markup insertion
2077 (if (thing-at-point-looking-at markdown-regex-angle-uri)
2078 (markdown-unwrap-thing-at-point nil 0 2)
2079 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
2081 (defun markdown-insert-wiki-link ()
2082 "Insert a wiki link of the form [[WikiLink]].
2083 If Transient Mark mode is on and a region is active, it is used
2084 as the link text."
2085 (interactive)
2086 (markdown-wrap-or-insert "[[" "]]")
2087 (backward-char 2))
2089 (defun markdown-insert-image (&optional arg)
2090 "Insert image markup using region or word as alt text if possible.
2091 If there is an active region, use the region as the alt text. If the
2092 point is at a word, use the word as the alt text. In these cases, the
2093 point will be left at the position for inserting a URL. If there is no
2094 active region and the point is not at word, simply insert image markup and
2095 place the point in the position to enter alt text. If ARG is nil, insert
2096 inline image markup. Otherwise, insert reference image markup."
2097 (interactive "*P")
2098 (let ((bounds (if arg
2099 (markdown-wrap-or-insert "![" "][]")
2100 (markdown-wrap-or-insert "![" "]()"))))
2101 (when bounds
2102 (goto-char (- (cdr bounds) 1)))))
2104 (defun markdown-remove-header ()
2105 "Remove header markup if point is at a header.
2106 Return bounds of remaining header text if a header was removed
2107 and nil otherwise."
2108 (interactive "*")
2109 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2110 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2112 (defun markdown-insert-header (&optional level text setext)
2113 "Insert or replace header markup.
2114 The level of the header is specified by LEVEL and header text is
2115 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2116 default value is 1.
2117 When TEXT is nil, the header text is obtained as follows.
2118 If there is an active region, it is used as the header text.
2119 Otherwise, the current line will be used as the header text.
2120 If there is not an active region and the point is at a header,
2121 remove the header markup and replace with level N header.
2122 Otherwise, insert empty header markup and place the cursor in
2123 between.
2124 The style of the header will be atx (hash marks) unless
2125 SETEXT is non-nil, in which case a setext-style (underlined)
2126 header will be inserted."
2127 (interactive "p\nsHeader text: ")
2128 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2129 ;; Determine header text if not given
2130 (when (null text)
2131 (if (markdown-use-region-p)
2132 ;; Active region
2133 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2134 ;; No active region
2135 (markdown-remove-header)
2136 (setq text (delete-and-extract-region
2137 (line-beginning-position) (line-end-position)))
2138 (when (and setext (string-match "^[ \t]*$" text))
2139 (setq text (read-string "Header text: "))))
2140 (setq text (markdown-compress-whitespace-string text)))
2141 ;; Insertion with given text
2142 (markdown-ensure-blank-line-before)
2143 (let (hdr)
2144 (cond (setext
2145 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2146 (insert text "\n" hdr))
2148 (setq hdr (make-string level ?#))
2149 (insert hdr " " text " " hdr))))
2150 (markdown-ensure-blank-line-after)
2151 ;; Leave point at end of text
2152 (if setext
2153 (backward-char (1+ (length text)))
2154 (backward-char (1+ level))))
2156 (defun markdown-insert-header-dwim (&optional arg setext)
2157 "Insert or replace header markup.
2158 The level and type of the header are determined automatically by
2159 the type and level of the previous header, unless a prefix
2160 argument is given via ARG.
2161 With a numeric prefix valued 1 to 6, insert a header of the given
2162 level, with the type being determined automatically (note that
2163 only level 1 or 2 setext headers are possible).
2164 With \\[universal-argument], insert a level-one setext header.
2165 With \\[universal-argument] \\[universal-argument], insert a
2166 level two setext header.
2167 When SETEXT is non-nil, prefer setext-style headers when
2168 possible (levels one and two).
2170 When there is an active region, use it for the header text. When
2171 the point is at an existing header, change the type and level
2172 according to the rules above.
2173 Otherwise, if the line is not empty, create a header using the
2174 text on the current line as the header text.
2175 Finally, if the point is on a blank line, insert empty header
2176 markup (atx) or prompt for text (setext).
2177 See `markdown-insert-header' for more details about how the
2178 header text is determined."
2179 (interactive "*P")
2180 (let (level)
2181 (cond ((equal arg '(4)) ; level-one setext with C-u
2182 (setq setext t)
2183 (setq level 1))
2184 ((equal arg '(16)) ; level-two setext with C-u C-u
2185 (setq setext t)
2186 (setq level 2))
2187 (t ; automatic with numeric override
2188 (save-excursion
2189 (when (re-search-backward markdown-regex-header nil t)
2190 ;; level of previous header
2191 (setq level (markdown-outline-level))
2192 ;; match groups 1 and 2 indicate setext headers
2193 (setq setext (or setext (match-end 1) (match-end 3)))))
2194 ;; use prefix if given, or level of previous header
2195 (setq level (if arg (prefix-numeric-value arg) level))
2196 ;; setext headers must be level one or two
2197 (and level (setq setext (and setext (<= level 2))))))
2198 (markdown-insert-header level nil setext)))
2200 (defun markdown-insert-header-setext-dwim (&optional arg)
2201 "Insert or replace header markup, with preference for setext.
2202 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2203 (interactive "*P")
2204 (markdown-insert-header-dwim arg t))
2206 (defun markdown-insert-header-atx-1 ()
2207 "Insert a first level atx-style (hash mark) header.
2208 See `markdown-insert-header'."
2209 (interactive "*")
2210 (markdown-insert-header 1 nil nil))
2212 (defun markdown-insert-header-atx-2 ()
2213 "Insert a level two atx-style (hash mark) header.
2214 See `markdown-insert-header'."
2215 (interactive "*")
2216 (markdown-insert-header 2 nil nil))
2218 (defun markdown-insert-header-atx-3 ()
2219 "Insert a level three atx-style (hash mark) header.
2220 See `markdown-insert-header'."
2221 (interactive "*")
2222 (markdown-insert-header 3 nil nil))
2224 (defun markdown-insert-header-atx-4 ()
2225 "Insert a level four atx-style (hash mark) header.
2226 See `markdown-insert-header'."
2227 (interactive "*")
2228 (markdown-insert-header 4 nil nil))
2230 (defun markdown-insert-header-atx-5 ()
2231 "Insert a level five atx-style (hash mark) header.
2232 See `markdown-insert-header'."
2233 (interactive "*")
2234 (markdown-insert-header 5 nil nil))
2236 (defun markdown-insert-header-atx-6 ()
2237 "Insert a sixth level atx-style (hash mark) header.
2238 See `markdown-insert-header'."
2239 (interactive "*")
2240 (markdown-insert-header 6 nil nil))
2242 (defun markdown-insert-header-setext-1 ()
2243 "Insert a setext-style (underlined) first-level header.
2244 See `markdown-insert-header'."
2245 (interactive "*")
2246 (markdown-insert-header 1 nil t))
2248 (defun markdown-insert-header-setext-2 ()
2249 "Insert a setext-style (underlined) second-level header.
2250 See `markdown-insert-header'."
2251 (interactive "*")
2252 (markdown-insert-header 2 nil t))
2254 (defun markdown-blockquote-indentation (loc)
2255 "Return string containing necessary indentation for a blockquote at LOC.
2256 Also see `markdown-pre-indentation'."
2257 (save-excursion
2258 (goto-char loc)
2259 (let* ((list-level (length (markdown-calculate-list-levels)))
2260 (indent ""))
2261 (dotimes (count list-level indent)
2262 (setq indent (concat indent " "))))))
2264 (defun markdown-insert-blockquote ()
2265 "Start a blockquote section (or blockquote the region).
2266 If Transient Mark mode is on and a region is active, it is used as
2267 the blockquote text."
2268 (interactive)
2269 (if (markdown-use-region-p)
2270 (markdown-blockquote-region (region-beginning) (region-end))
2271 (markdown-ensure-blank-line-before)
2272 (insert (markdown-blockquote-indentation (point)) "> ")
2273 (markdown-ensure-blank-line-after)))
2275 (defun markdown-block-region (beg end prefix)
2276 "Format the region using a block prefix.
2277 Arguments BEG and END specify the beginning and end of the
2278 region. The characters PREFIX will appear at the beginning
2279 of each line."
2280 (save-excursion
2281 (let* ((end-marker (make-marker))
2282 (beg-marker (make-marker)))
2283 ;; Ensure blank line after and remove extra whitespace
2284 (goto-char end)
2285 (skip-syntax-backward "-")
2286 (set-marker end-marker (point))
2287 (delete-horizontal-space)
2288 (markdown-ensure-blank-line-after)
2289 ;; Ensure blank line before and remove extra whitespace
2290 (goto-char beg)
2291 (skip-syntax-forward "-")
2292 (delete-horizontal-space)
2293 (markdown-ensure-blank-line-before)
2294 (set-marker beg-marker (point))
2295 ;; Insert PREFIX before each line
2296 (goto-char beg-marker)
2297 (while (and (< (line-beginning-position) end-marker)
2298 (not (eobp)))
2299 (insert prefix)
2300 (forward-line)))))
2302 (defun markdown-blockquote-region (beg end)
2303 "Blockquote the region.
2304 Arguments BEG and END specify the beginning and end of the region."
2305 (interactive "*r")
2306 (markdown-block-region
2307 beg end (concat (markdown-blockquote-indentation
2308 (max (point-min) (1- beg))) "> ")))
2310 (defun markdown-pre-indentation (loc)
2311 "Return string containing necessary whitespace for a pre block at LOC.
2312 Also see `markdown-blockquote-indentation'."
2313 (save-excursion
2314 (goto-char loc)
2315 (let* ((list-level (length (markdown-calculate-list-levels)))
2316 indent)
2317 (dotimes (count (1+ list-level) indent)
2318 (setq indent (concat indent " "))))))
2320 (defun markdown-insert-pre ()
2321 "Start a preformatted section (or apply to the region).
2322 If Transient Mark mode is on and a region is active, it is marked
2323 as preformatted text."
2324 (interactive)
2325 (if (markdown-use-region-p)
2326 (markdown-pre-region (region-beginning) (region-end))
2327 (markdown-ensure-blank-line-before)
2328 (insert (markdown-pre-indentation (point)))
2329 (markdown-ensure-blank-line-after)))
2331 (defun markdown-pre-region (beg end)
2332 "Format the region as preformatted text.
2333 Arguments BEG and END specify the beginning and end of the region."
2334 (interactive "*r")
2335 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2336 (markdown-block-region beg end indent)))
2338 (defun markdown-insert-gfm-code-block (&optional lang)
2339 "Insert GFM code block for language LANG.
2340 If LANG is nil, the language will be queried from user. If a
2341 region is active, wrap this region with the markup instead. If
2342 the region boundaries are not on empty lines, these are added
2343 automatically in order to have the correct markup."
2344 (interactive "sProgramming language: ")
2345 (if (markdown-use-region-p)
2346 (let ((b (region-beginning)) (e (region-end)))
2347 (goto-char b)
2348 ;; if we're on a blank line, insert the quotes here, otherwise
2349 ;; add a new line first
2350 (unless (looking-at "\n")
2351 (newline)
2352 (forward-line -1)
2353 (setq e (1+ e)))
2354 (insert "```" lang)
2355 (goto-char (+ e 3 (length lang)))
2356 ;; if we're on a blank line, don't newline, otherwise the ```
2357 ;; should go on its own line
2358 (unless (looking-back "\n")
2359 (newline))
2360 (insert "```"))
2361 (insert "```" lang)
2362 (newline 2)
2363 (insert "```")
2364 (forward-line -1)))
2367 ;;; Footnotes ======================================================================
2369 (defun markdown-footnote-counter-inc ()
2370 "Increment `markdown-footnote-counter' and return the new value."
2371 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2372 (save-excursion
2373 (goto-char (point-min))
2374 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2375 (point-max) t)
2376 (let ((fn (string-to-number (match-string 1))))
2377 (when (> fn markdown-footnote-counter)
2378 (setq markdown-footnote-counter fn))))))
2379 (incf markdown-footnote-counter))
2381 (defun markdown-footnote-new ()
2382 "Insert footnote with a new number and move point to footnote definition."
2383 (interactive)
2384 (let ((fn (markdown-footnote-counter-inc)))
2385 (insert (format "[^%d]" fn))
2386 (markdown-footnote-text-find-new-location)
2387 (markdown-ensure-blank-line-before)
2388 (unless (markdown-cur-line-blank-p)
2389 (insert "\n"))
2390 (insert (format "[^%d]: " fn))
2391 (markdown-ensure-blank-line-after)))
2393 (defun markdown-footnote-text-find-new-location ()
2394 "Position the cursor at the proper location for a new footnote text."
2395 (cond
2396 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2397 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
2398 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2400 (defun markdown-footnote-kill ()
2401 "Kill the footnote at point.
2402 The footnote text is killed (and added to the kill ring), the
2403 footnote marker is deleted. Point has to be either at the
2404 footnote marker or in the footnote text."
2405 (interactive)
2406 (let (return-pos)
2407 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2408 (markdown-footnote-return) ; we first move to the marker
2409 (setq return-pos 'text)) ; and remember our return position
2410 (let ((marker (markdown-footnote-delete-marker)))
2411 (unless marker
2412 (error "Not at a footnote"))
2413 (let ((text-pos (markdown-footnote-find-text (car marker))))
2414 (unless text-pos
2415 (error "No text for footnote `%s'" (car marker)))
2416 (goto-char text-pos)
2417 (let ((pos (markdown-footnote-kill-text)))
2418 (setq return-pos
2419 (if (and pos (eq return-pos 'text))
2421 (cadr marker))))))
2422 (goto-char return-pos)))
2424 (defun markdown-footnote-delete-marker ()
2425 "Delete a footnote marker at point.
2426 Returns a list (ID START) containing the footnote ID and the
2427 start position of the marker before deletion. If no footnote
2428 marker was deleted, this function returns NIL."
2429 (let ((marker (markdown-footnote-marker-positions)))
2430 (when marker
2431 (delete-region (second marker) (third marker))
2432 (butlast marker))))
2434 (defun markdown-footnote-kill-text ()
2435 "Kill footnote text at point.
2436 Returns the start position of the footnote text before deletion,
2437 or NIL if point was not inside a footnote text.
2439 The killed text is placed in the kill ring (without the footnote
2440 number)."
2441 (let ((fn (markdown-footnote-text-positions)))
2442 (when fn
2443 (let ((text (delete-and-extract-region (second fn) (third fn))))
2444 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2445 (kill-new (match-string 1 text))
2446 (when (and (markdown-cur-line-blank-p)
2447 (markdown-prev-line-blank-p))
2448 (delete-region (1- (point)) (point)))
2449 (second fn)))))
2451 (defun markdown-footnote-goto-text ()
2452 "Jump to the text of the footnote at point."
2453 (interactive)
2454 (let ((fn (car (markdown-footnote-marker-positions))))
2455 (unless fn
2456 (error "Not at a footnote marker"))
2457 (let ((new-pos (markdown-footnote-find-text fn)))
2458 (unless new-pos
2459 (error "No definition found for footnote `%s'" fn))
2460 (goto-char new-pos))))
2462 (defun markdown-footnote-return ()
2463 "Return from a footnote to its footnote number in the main text."
2464 (interactive)
2465 (let ((fn (save-excursion
2466 (car (markdown-footnote-text-positions)))))
2467 (unless fn
2468 (error "Not in a footnote"))
2469 (let ((new-pos (markdown-footnote-find-marker fn)))
2470 (unless new-pos
2471 (error "Footnote marker `%s' not found" fn))
2472 (goto-char new-pos))))
2474 (defun markdown-footnote-find-marker (id)
2475 "Find the location of the footnote marker with ID.
2476 The actual buffer position returned is the position directly
2477 following the marker's closing bracket. If no marker is found,
2478 NIL is returned."
2479 (save-excursion
2480 (goto-char (point-min))
2481 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2482 (skip-chars-backward "^]")
2483 (point))))
2485 (defun markdown-footnote-find-text (id)
2486 "Find the location of the text of footnote ID.
2487 The actual buffer position returned is the position of the first
2488 character of the text, after the footnote's identifier. If no
2489 footnote text is found, NIL is returned."
2490 (save-excursion
2491 (goto-char (point-min))
2492 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2493 (skip-chars-forward "[ \t]")
2494 (point))))
2496 (defun markdown-footnote-marker-positions ()
2497 "Return the position and ID of the footnote marker point is on.
2498 The return value is a list (ID START END). If point is not on a
2499 footnote, NIL is returned."
2500 ;; first make sure we're at a footnote marker
2501 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2502 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2503 (save-excursion
2504 ;; move point between [ and ^:
2505 (if (looking-at "\\[")
2506 (forward-char 1)
2507 (skip-chars-backward "^["))
2508 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2509 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2511 (defun markdown-footnote-text-positions ()
2512 "Return the start and end positions of the footnote text point is in.
2513 The exact return value is a list of three elements: (ID START END).
2514 The start position is the position of the opening bracket
2515 of the footnote id. The end position is directly after the
2516 newline that ends the footnote. If point is not in a footnote,
2517 NIL is returned instead."
2518 (save-excursion
2519 (let ((fn (progn
2520 (backward-paragraph)
2521 ;; if we're in a multiparagraph footnote, we need to back up further
2522 (while (>= (markdown-next-line-indent) 4)
2523 (backward-paragraph))
2524 (forward-line)
2525 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2526 (list (match-string 1) (point))))))
2527 (when fn
2528 (while (progn
2529 (forward-paragraph)
2530 (>= (markdown-next-line-indent) 4)))
2531 (append fn (list (point)))))))
2534 ;;; Element Removal ===========================================================
2536 (defun markdown-kill-thing-at-point ()
2537 "Kill thing at point and add important text, without markup, to kill ring.
2538 Possible things to kill include (roughly in order of precedence):
2539 inline code, headers, horizonal rules, links (add link text to
2540 kill ring), images (add alt text to kill ring), angle uri, email
2541 addresses, bold, italics, reference definition (add URI to kill
2542 ring), footnote markers and text (kill both marker and text, add
2543 text to kill ring), and list items."
2544 (interactive "*")
2545 (let (val tmp)
2546 (cond
2547 ;; Inline code
2548 ((thing-at-point-looking-at markdown-regex-code)
2549 (kill-new (match-string 4))
2550 (delete-region (match-beginning 2) (match-end 2)))
2551 ;; ATX header
2552 ((thing-at-point-looking-at markdown-regex-header-atx)
2553 (kill-new (match-string 2))
2554 (delete-region (match-beginning 0) (match-end 0)))
2555 ;; Setext header
2556 ((thing-at-point-looking-at markdown-regex-header-setext)
2557 (kill-new (match-string 1))
2558 (delete-region (match-beginning 0) (match-end 0)))
2559 ;; Horizonal rule
2560 ((thing-at-point-looking-at markdown-regex-hr)
2561 (kill-new (match-string 0))
2562 (delete-region (match-beginning 0) (match-end 0)))
2563 ;; Inline link or image (add link or alt text to kill ring)
2564 ((thing-at-point-looking-at markdown-regex-link-inline)
2565 (kill-new (match-string 3))
2566 (delete-region (match-beginning 0) (match-end 0)))
2567 ;; Reference link or image (add link or alt text to kill ring)
2568 ((thing-at-point-looking-at markdown-regex-link-reference)
2569 (kill-new (match-string 3))
2570 (delete-region (match-beginning 0) (match-end 0)))
2571 ;; Angle URI (add URL to kill ring)
2572 ((thing-at-point-looking-at markdown-regex-angle-uri)
2573 (kill-new (match-string 2))
2574 (delete-region (match-beginning 0) (match-end 0)))
2575 ;; Email address in angle brackets (add email address to kill ring)
2576 ((thing-at-point-looking-at markdown-regex-email)
2577 (kill-new (match-string 1))
2578 (delete-region (match-beginning 0) (match-end 0)))
2579 ;; Wiki link (add alias text to kill ring)
2580 ((thing-at-point-looking-at markdown-regex-wiki-link)
2581 (kill-new (if markdown-wiki-link-alias-first
2582 (match-string-no-properties 2)
2583 (or (match-string-no-properties 2) (match-string-no-properties 4))))
2584 (delete-region (match-beginning 1) (match-end 1)))
2585 ;; Bold
2586 ((thing-at-point-looking-at markdown-regex-bold)
2587 (kill-new (match-string 4))
2588 (delete-region (match-beginning 2) (match-end 2)))
2589 ;; Italics
2590 ((thing-at-point-looking-at markdown-regex-italic)
2591 (kill-new (match-string 4))
2592 (delete-region (match-beginning 2) (match-end 2)))
2593 ;; Reference definition (add URL to kill ring)
2594 ((thing-at-point-looking-at markdown-regex-reference-definition)
2595 (kill-new (match-string 2))
2596 (delete-region (match-beginning 0) (match-end 0)))
2597 ;; Footnote marker (add footnote text to kill ring)
2598 ((thing-at-point-looking-at markdown-regex-footnote)
2599 (markdown-footnote-kill))
2600 ;; Footnote text (add footnote text to kill ring)
2601 ((setq val (markdown-footnote-text-positions))
2602 (markdown-footnote-kill))
2603 ;; List item
2604 ((setq val (markdown-cur-list-item-bounds))
2605 (kill-new (delete-and-extract-region (first val) (second val))))
2607 (error "Nothing found at point to kill")))))
2610 ;;; Indentation ====================================================================
2612 (defun markdown-indent-find-next-position (cur-pos positions)
2613 "Return the position after the index of CUR-POS in POSITIONS.
2614 Positions are calculated by `markdown-calc-indents'."
2615 (while (and positions
2616 (not (equal cur-pos (car positions))))
2617 (setq positions (cdr positions)))
2618 (or (cadr positions) 0))
2620 (defun markdown-exdent-find-next-position (cur-pos positions)
2621 "Return the maximal element that precedes CUR-POS from POSITIONS.
2622 Positions are calculated by `markdown-calc-indents'."
2623 (let ((result 0))
2624 (dolist (i positions)
2625 (when (< i cur-pos)
2626 (setq result (max result i))))
2627 result))
2629 (defun markdown-indent-line ()
2630 "Indent the current line using some heuristics.
2631 If the _previous_ command was either `markdown-enter-key' or
2632 `markdown-cycle', then we should cycle to the next
2633 reasonable indentation position. Otherwise, we could have been
2634 called directly by `markdown-enter-key', by an initial call of
2635 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2636 these cases, indent to the default position.
2637 Positions are calculated by `markdown-calc-indents'."
2638 (interactive)
2639 (let ((positions (markdown-calc-indents))
2640 (cur-pos (current-column)))
2641 (if (not (equal this-command 'markdown-cycle))
2642 (indent-line-to (car positions))
2643 (setq positions (sort (delete-dups positions) '<))
2644 (indent-line-to
2645 (markdown-indent-find-next-position cur-pos positions)))))
2647 (defun markdown-calc-indents ()
2648 "Return a list of indentation columns to cycle through.
2649 The first element in the returned list should be considered the
2650 default indentation level. This function does not worry about
2651 duplicate positions, which are handled up by calling functions."
2652 (let (pos prev-line-pos positions)
2654 ;; Indentation of previous line
2655 (setq prev-line-pos (markdown-prev-line-indent))
2656 (setq positions (cons prev-line-pos positions))
2658 ;; Indentation of previous non-list-marker text
2659 (when (setq pos (markdown-prev-non-list-indent))
2660 (setq positions (cons pos positions)))
2662 ;; Indentation required for a pre block in current context
2663 (setq pos (length (markdown-pre-indentation (point))))
2664 (setq positions (cons pos positions))
2666 ;; Indentation of the previous line + tab-width
2667 (if prev-line-pos
2668 (setq positions (cons (+ prev-line-pos tab-width) positions))
2669 (setq positions (cons tab-width positions)))
2671 ;; Indentation of the previous line - tab-width
2672 (if (and prev-line-pos (> prev-line-pos tab-width))
2673 (setq positions (cons (- prev-line-pos tab-width) positions)))
2675 ;; Indentation of all preceeding list markers (when in a list)
2676 (when (setq pos (markdown-calculate-list-levels))
2677 (setq positions (append pos positions)))
2679 ;; First column
2680 (setq positions (cons 0 positions))
2682 ;; Return reversed list
2683 (reverse positions)))
2685 (defun markdown-do-normal-return ()
2686 "Insert a newline and optionally indent the next line."
2687 (newline)
2688 (if markdown-indent-on-enter
2689 (funcall indent-line-function)))
2691 (defun markdown-enter-key ()
2692 "Handle RET according to context.
2693 If there is a wiki link at the point, follow it unless
2694 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2695 it in the usual way."
2696 (interactive)
2697 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2698 (markdown-follow-wiki-link-at-point)
2699 (markdown-do-normal-return)))
2701 (defun markdown-exdent-or-delete (arg)
2702 "Handle BACKSPACE by cycling through indentation points.
2703 When BACKSPACE is pressed, if there is only whitespace
2704 before the current point, then exdent the line one level.
2705 Otherwise, do normal delete by repeating
2706 `backward-delete-char-untabify' ARG times."
2707 (interactive "*p")
2708 (let ((cur-pos (current-column))
2709 (start-of-indention (save-excursion
2710 (back-to-indentation)
2711 (current-column)))
2712 (positions (markdown-calc-indents)))
2713 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2714 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
2715 (backward-delete-char-untabify arg))))
2717 (defun markdown-find-leftmost-column (beg end)
2718 "Find the leftmost column in the region from BEG to END."
2719 (let ((mincol 1000))
2720 (save-excursion
2721 (goto-char beg)
2722 (while (< (point) end)
2723 (back-to-indentation)
2724 (unless (looking-at "[ \t]*$")
2725 (setq mincol (min mincol (current-column))))
2726 (forward-line 1)
2728 mincol))
2730 (defun markdown-indent-region (beg end arg)
2731 "Indent the region from BEG to END using some heuristics.
2732 When ARG is non-nil, exdent the region instead.
2733 See `markdown-indent-line' and `markdown-indent-line'."
2734 (interactive "*r\nP")
2735 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2736 (leftmostcol (markdown-find-leftmost-column beg end))
2737 (next-pos (if arg
2738 (markdown-exdent-find-next-position leftmostcol positions)
2739 (markdown-indent-find-next-position leftmostcol positions))))
2740 (indent-rigidly beg end (- next-pos leftmostcol))
2741 (setq deactivate-mark nil)))
2744 ;;; Markup Completion =========================================================
2746 (defconst markdown-complete-alist
2747 '((markdown-regex-header-atx . markdown-complete-atx)
2748 (markdown-regex-header-setext . markdown-complete-setext)
2749 (markdown-regex-hr . markdown-complete-hr))
2750 "Association list of form (regexp . function) for markup completion.")
2752 (defun markdown-incomplete-atx-p ()
2753 "Return t if ATX header markup is incomplete and nil otherwise.
2754 Assumes match data is available for `markdown-regex-header-atx'.
2755 Checks that the number of trailing hash marks equals the number of leading
2756 hash marks, that there is only a single space before and after the text,
2757 and that there is no extraneous whitespace in the text."
2758 (save-match-data
2760 ;; Number of starting and ending hash marks differs
2761 (not (= (length (match-string 1)) (length (match-string 3))))
2762 ;; When the header text is not empty...
2763 (and (> (length (match-string 2)) 0)
2764 ;; ...if there are extra leading, trailing, or interior spaces
2765 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2766 (not (= (match-beginning 3) (1+ (match-end 2))))
2767 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2768 ;; When the header text is empty...
2769 (and (= (length (match-string 2)) 0)
2770 ;; ...if there are too many or too few spaces
2771 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2773 (defun markdown-complete-atx ()
2774 "Complete and normalize ATX headers.
2775 Add or remove hash marks to the end of the header to match the
2776 beginning. Ensure that there is only a single space between hash
2777 marks and header text. Removes extraneous whitespace from header text.
2778 Assumes match data is available for `markdown-regex-header-atx'."
2779 (when (markdown-incomplete-atx-p)
2780 (let* ((new-marker (make-marker))
2781 (new-marker (set-marker new-marker (match-end 2))))
2782 ;; Hash marks and spacing at end
2783 (goto-char (match-end 2))
2784 (delete-region (match-end 2) (match-end 3))
2785 (insert " " (match-string 1))
2786 ;; Remove extraneous whitespace from title
2787 (replace-match (markdown-compress-whitespace-string (match-string 2))
2788 t t nil 2)
2789 ;; Spacing at beginning
2790 (goto-char (match-end 1))
2791 (delete-region (match-end 1) (match-beginning 2))
2792 (insert " ")
2793 ;; Leave point at end of text
2794 (goto-char new-marker))))
2796 (defun markdown-incomplete-setext-p ()
2797 "Return t if setext header markup is incomplete and nil otherwise.
2798 Assumes match data is available for `markdown-regex-header-setext'.
2799 Checks that length of underline matches text and that there is no
2800 extraneous whitespace in the text."
2801 (save-match-data
2802 (or (not (= (length (match-string 1)) (length (match-string 2))))
2803 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2805 (defun markdown-complete-setext ()
2806 "Complete and normalize setext headers.
2807 Add or remove underline characters to match length of header
2808 text. Removes extraneous whitespace from header text. Assumes
2809 match data is available for `markdown-regex-header-setext'."
2810 (when (markdown-incomplete-setext-p)
2811 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2812 (char (char-after (match-beginning 2)))
2813 (level (if (char-equal char ?-) 2 1)))
2814 (goto-char (match-beginning 0))
2815 (delete-region (match-beginning 0) (match-end 0))
2816 (markdown-insert-header level text t))))
2818 (defun markdown-incomplete-hr-p ()
2819 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2820 Assumes match data is available for `markdown-regex-hr'."
2821 (not (member (match-string 0) markdown-hr-strings)))
2823 (defun markdown-complete-hr ()
2824 "Complete horizontal rules.
2825 If horizontal rule string is a member of `markdown-hr-strings',
2826 do nothing. Otherwise, replace with the car of
2827 `markdown-hr-strings'.
2828 Assumes match data is available for `markdown-regex-hr'."
2829 (replace-match (car markdown-hr-strings)))
2831 (defun markdown-complete ()
2832 "Complete markup of object near point or in region when active.
2833 Handle all objects in `markdown-complete-alist', in order.
2834 See `markdown-complete-at-point' and `markdown-complete-region'."
2835 (interactive "*")
2836 (if (markdown-use-region-p)
2837 (markdown-complete-region (region-beginning) (region-end))
2838 (markdown-complete-at-point)))
2840 (defun markdown-complete-at-point ()
2841 "Complete markup of object near point.
2842 Handle all objects in `markdown-complete-alist', in
2843 order."
2844 (interactive "*")
2845 (loop for (regexp . function) in markdown-complete-alist
2846 until (thing-at-point-looking-at (eval regexp))
2847 finally (funcall function)))
2849 (defun markdown-complete-region (beg end)
2850 "Complete markup of objects in region from BEG to END.
2851 Handle all objects in `markdown-complete-alist', in
2852 order."
2853 (interactive "*r")
2854 (let* ((end-marker (make-marker))
2855 (end-marker (set-marker end-marker end)))
2856 (loop for (regexp . function) in markdown-complete-alist
2857 do (save-excursion
2858 (goto-char beg)
2859 (while (re-search-forward (eval regexp) end-marker t)
2860 (funcall function))))))
2862 (defun markdown-complete-buffer ()
2863 "Complete markup for all objects in the current buffer."
2864 (interactive "*")
2865 (markdown-complete-region (point-min) (point-max)))
2868 ;;; Markup Cycling ============================================================
2870 (defun markdown-cycle-atx (arg &optional remove)
2871 "Cycle ATX header markup.
2872 Promote header (decrease level) when ARG is 1 and demote
2873 header (increase level) if arg is -1. When REMOVE is non-nil,
2874 remove the header when the level reaches zero and stop cycling
2875 when it reaches six. Otherwise, perform a proper cycling through
2876 levels one through six. Assumes match data is available for
2877 `markdown-regex-header-atx'."
2878 (let* ((old-level (length (match-string 1)))
2879 (new-level (+ old-level arg))
2880 (text (match-string 2)))
2881 (when (not remove)
2882 (setq new-level (% new-level 6))
2883 (setq new-level (cond ((= new-level 0) 6)
2884 ((< new-level 0) (+ new-level 6))
2885 (t new-level))))
2886 (cond
2887 ((= new-level 0)
2888 (markdown-unwrap-thing-at-point nil 0 2))
2889 ((<= new-level 6)
2890 (goto-char (match-beginning 0))
2891 (delete-region (match-beginning 0) (match-end 0))
2892 (markdown-insert-header new-level text nil)))))
2894 (defun markdown-cycle-setext (arg &optional remove)
2895 "Cycle setext header markup.
2896 Promote header (increase level) when ARG is 1 and demote
2897 header (decrease level or remove) if arg is -1. When demoting a
2898 level-two setext header, replace with a level-three atx header.
2899 When REMOVE is non-nil, remove the header when the level reaches
2900 zero. Otherwise, cycle back to a level six atx header. Assumes
2901 match data is available for `markdown-regex-header-setext'."
2902 (let* ((char (char-after (match-beginning 2)))
2903 (old-level (if (char-equal char ?=) 1 2))
2904 (new-level (+ old-level arg))
2905 (text (match-string 1)))
2906 (when (and (not remove) (= new-level 0))
2907 (setq new-level 6))
2908 (cond
2909 ((= new-level 0)
2910 (markdown-unwrap-thing-at-point nil 0 1))
2911 ((<= new-level 2)
2912 (markdown-insert-header new-level nil t))
2913 ((<= new-level 6)
2914 (markdown-insert-header new-level nil nil)))))
2916 (defun markdown-cycle-hr (arg &optional remove)
2917 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2918 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
2919 backwards (promote). When REMOVE is non-nil, remove the hr instead
2920 of cycling when the end of the list is reached.
2921 Assumes match data is available for `markdown-regex-hr'."
2922 (let* ((strings (if (= arg -1)
2923 (reverse markdown-hr-strings)
2924 markdown-hr-strings))
2925 (tail (member (match-string 0) strings))
2926 (new (or (cadr tail)
2927 (if remove
2928 (if (= arg 1)
2930 (car tail))
2931 (car strings)))))
2932 (replace-match new)))
2934 (defun markdown-cycle-bold ()
2935 "Cycle bold markup between underscores and asterisks.
2936 Assumes match data is available for `markdown-regex-bold'."
2937 (save-excursion
2938 (let* ((old-delim (match-string 3))
2939 (new-delim (if (string-equal old-delim "**") "__" "**")))
2940 (replace-match new-delim t t nil 3)
2941 (replace-match new-delim t t nil 5))))
2943 (defun markdown-cycle-italic ()
2944 "Cycle italic markup between underscores and asterisks.
2945 Assumes match data is available for `markdown-regex-italic'."
2946 (save-excursion
2947 (let* ((old-delim (match-string 3))
2948 (new-delim (if (string-equal old-delim "*") "_" "*")))
2949 (replace-match new-delim t t nil 3)
2950 (replace-match new-delim t t nil 5))))
2953 ;;; Keymap ====================================================================
2955 (defvar markdown-mode-map
2956 (let ((map (make-keymap)))
2957 ;; Element insertion
2958 (define-key map "\C-c\C-al" 'markdown-insert-link)
2959 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
2960 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
2961 (define-key map "\C-c\C-au" 'markdown-insert-uri)
2962 (define-key map "\C-c\C-ii" 'markdown-insert-image)
2963 (define-key map "\C-c\C-t0" 'markdown-remove-header)
2964 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
2965 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
2966 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
2967 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
2968 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
2969 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
2970 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
2971 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
2972 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
2973 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
2974 (define-key map "\C-c\C-se" 'markdown-insert-italic)
2975 (define-key map "\C-c\C-pf" 'markdown-insert-code)
2976 (define-key map "\C-c\C-sc" 'markdown-insert-code)
2977 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
2978 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
2979 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
2980 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
2981 (define-key map "\C-c-" 'markdown-insert-hr)
2982 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
2983 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
2984 ;; Element removal
2985 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
2986 ;; Footnotes
2987 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
2988 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
2989 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
2990 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
2991 ;; Promotion, Demotion, Completion, and Cycling
2992 (define-key map (kbd "M-<left>") 'markdown-promote)
2993 (define-key map (kbd "M-<right>") 'markdown-demote)
2994 (define-key map (kbd "C-c C-l") 'markdown-promote)
2995 (define-key map (kbd "C-c C-r") 'markdown-demote)
2996 (define-key map (kbd "C-c C-=") 'markdown-complete-or-cycle)
2997 (define-key map (kbd "C-c C-c =") 'markdown-complete-buffer)
2998 ;; Following and Jumping
2999 (define-key map "\C-c\C-o" 'markdown-follow-thing-at-point)
3000 (define-key map "\C-c\C-j" 'markdown-jump)
3001 ;; Indentation
3002 (define-key map (kbd "C-m") 'markdown-enter-key)
3003 (define-key map (kbd "<backspace>") 'markdown-exdent-or-delete)
3004 (define-key map (kbd "C-c >") 'markdown-indent-region)
3005 (define-key map (kbd "C-c <") (kbd "C-u C-c >"))
3006 ;; Visibility cycling
3007 (define-key map (kbd "<tab>") 'markdown-cycle)
3008 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
3009 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
3010 (define-key map (kbd "<backtab>") 'markdown-shifttab)
3011 ;; Header navigation
3012 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
3013 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
3014 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
3015 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
3016 (define-key map (kbd "C-M-u") 'outline-up-heading)
3017 ;; Markdown functions
3018 (define-key map "\C-c\C-cm" 'markdown-other-window)
3019 (define-key map "\C-c\C-cp" 'markdown-preview)
3020 (define-key map "\C-c\C-ce" 'markdown-export)
3021 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
3022 (define-key map "\C-c\C-co" 'markdown-open)
3023 (define-key map "\C-c\C-cw" 'markdown-kill-ring-save)
3024 ;; References
3025 (define-key map "\C-c\C-cc" 'markdown-check-refs)
3026 ;; Lists
3027 (define-key map "\C-c\C-cn" 'markdown-cleanup-list-numbers)
3028 (define-key map (kbd "M-<up>") 'markdown-move-up)
3029 (define-key map (kbd "M-<down>") 'markdown-move-down)
3030 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
3031 ;; Movement
3032 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
3033 (define-key map (kbd "M-]") 'markdown-end-of-block)
3034 (define-key map (kbd "M-n") 'markdown-next-link)
3035 (define-key map (kbd "M-p") 'markdown-previous-link)
3036 map)
3037 "Keymap for Markdown major mode.")
3039 (defvar gfm-mode-map
3040 (let ((map (make-sparse-keymap)))
3041 (set-keymap-parent map markdown-mode-map)
3042 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
3043 map)
3044 "Keymap for `gfm-mode'.
3045 See also `markdown-mode-map'.")
3048 ;;; Menu ==================================================================
3050 (easy-menu-define markdown-mode-menu markdown-mode-map
3051 "Menu for Markdown mode"
3052 '("Markdown"
3053 ("Show/Hide"
3054 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
3055 ["Cycle global visibility" markdown-shifttab])
3056 "---"
3057 ["Compile" markdown-other-window]
3058 ["Preview" markdown-preview]
3059 ["Export" markdown-export]
3060 ["Export & View" markdown-export-and-preview]
3061 ["Open" markdown-open]
3062 ["Kill ring save" markdown-kill-ring-save]
3063 "---"
3064 ("Headers (setext)"
3065 ["First level" markdown-insert-setext-header-1]
3066 ["Second level" markdown-insert-setext-header-2])
3067 ("Headers (atx)"
3068 ["First level" markdown-insert-header-atx-1]
3069 ["Second level" markdown-insert-header-atx-2]
3070 ["Third level" markdown-insert-header-atx-3]
3071 ["Fourth level" markdown-insert-header-atx-4]
3072 ["Fifth level" markdown-insert-header-atx-5]
3073 ["Sixth level" markdown-insert-header-atx-6])
3074 "---"
3075 ["Bold" markdown-insert-bold]
3076 ["Italic" markdown-insert-italic]
3077 ["Blockquote" markdown-insert-blockquote]
3078 ["Preformatted" markdown-insert-pre]
3079 ["Code" markdown-insert-code]
3080 "---"
3081 ["Insert inline link" markdown-insert-link]
3082 ["Insert reference link" markdown-insert-reference-link-dwim]
3083 ["Insert image" markdown-insert-image]
3084 ["Insert horizontal rule" markdown-insert-hr]
3085 "---"
3086 ("Footnotes"
3087 ["Insert footnote" markdown-footnote-new]
3088 ["Jump to footnote text" markdown-footnote-goto-text]
3089 ["Return from footnote" markdown-footnote-return])
3090 "---"
3091 ["Check references" markdown-check-refs]
3092 ["Clean up list numbering" markdown-cleanup-list-numbers]
3093 "---"
3094 ["Version" markdown-show-version]
3098 ;;; imenu =====================================================================
3100 (defun markdown-imenu-create-index ()
3101 "Create and return an imenu index alist for the current buffer.
3102 See `imenu-create-index-function' and `imenu--index-alist' for details."
3103 (let* ((root '(nil . nil))
3104 cur-alist
3105 (cur-level 0)
3106 (empty-heading "-")
3107 (self-heading ".")
3108 hashes pos level heading)
3109 (save-excursion
3110 (goto-char (point-min))
3111 (while (re-search-forward markdown-regex-header (point-max) t)
3112 (cond
3113 ((setq heading (match-string-no-properties 1))
3114 (setq pos (match-beginning 1)
3115 level 1))
3116 ((setq heading (match-string-no-properties 3))
3117 (setq pos (match-beginning 3)
3118 level 2))
3119 ((setq hashes (match-string-no-properties 5))
3120 (setq heading (match-string-no-properties 6)
3121 pos (match-beginning 5)
3122 level (length hashes))))
3123 (let ((alist (list (cons heading pos))))
3124 (cond
3125 ((= cur-level level) ; new sibling
3126 (setcdr cur-alist alist)
3127 (setq cur-alist alist))
3128 ((< cur-level level) ; first child
3129 (dotimes (i (- level cur-level 1))
3130 (setq alist (list (cons empty-heading alist))))
3131 (if cur-alist
3132 (let* ((parent (car cur-alist))
3133 (self-pos (cdr parent)))
3134 (setcdr parent (cons (cons self-heading self-pos) alist)))
3135 (setcdr root alist)) ; primogenitor
3136 (setq cur-alist alist)
3137 (setq cur-level level))
3138 (t ; new sibling of an ancestor
3139 (let ((sibling-alist (last (cdr root))))
3140 (dotimes (i (1- level))
3141 (setq sibling-alist (last (cdar sibling-alist))))
3142 (setcdr sibling-alist alist)
3143 (setq cur-alist alist))
3144 (setq cur-level level)))))
3145 (cdr root))))
3148 ;;; References ================================================================
3150 (defun markdown-insert-reference-definition (ref &optional buffer)
3151 "Add blank REF definition to the end of BUFFER.
3152 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3153 (or buffer (setq buffer (current-buffer)))
3154 (with-current-buffer buffer
3155 (goto-char (point-max))
3156 (indent-new-comment-line)
3157 (insert (concat ref ": "))))
3159 (defun markdown-reference-goto-definition ()
3160 "Jump to the definition of the reference at point or create it."
3161 (interactive)
3162 (when (thing-at-point-looking-at markdown-regex-link-reference)
3163 (let* ((text (match-string-no-properties 2))
3164 (reference (match-string-no-properties 4))
3165 (target (downcase (if (string= reference "[]") text reference)))
3166 (loc (cadr (markdown-reference-definition target))))
3167 (if loc
3168 (goto-char loc)
3169 (markdown-insert-reference-definition target (current-buffer))))))
3171 (defun markdown-reference-find-links (reference)
3172 "Return a list of all links for REFERENCE.
3173 REFERENCE should include the surrounding square brackets like [this].
3174 Elements of the list have the form (text start line), where
3175 text is the link text, start is the location at the beginning of
3176 the link, and line is the line number on which the link appears."
3177 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3178 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3179 ref-quote ref-quote))
3180 links)
3181 (save-excursion
3182 (goto-char (point-min))
3183 (while (re-search-forward regexp nil t)
3184 (let* ((text (or (match-string-no-properties 1)
3185 (match-string-no-properties 2)))
3186 (start (match-beginning 0))
3187 (line (markdown-line-number-at-pos)))
3188 (add-to-list 'links (list text start line)))))
3189 links))
3191 (defun markdown-get-undefined-refs ()
3192 "Return a list of undefined Markdown references.
3193 Result is an alist of pairs (reference . occurrences), where
3194 occurrences is itself another alist of pairs (label . line-number).
3195 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3196 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3197 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3198 (let ((missing))
3199 (save-excursion
3200 (goto-char (point-min))
3201 (while
3202 (re-search-forward markdown-regex-link-reference nil t)
3203 (let* ((text (match-string-no-properties 2))
3204 (reference (match-string-no-properties 4))
3205 (target (downcase (if (string= reference "[]") text reference))))
3206 (unless (markdown-reference-definition target)
3207 (let ((entry (assoc target missing)))
3208 (if (not entry)
3209 (add-to-list 'missing (cons target
3210 (list (cons text (markdown-line-number-at-pos)))) t)
3211 (setcdr entry
3212 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3213 missing)))
3215 (defconst markdown-reference-check-buffer
3216 "*Undefined references for %buffer%*"
3217 "Pattern for name of buffer for listing undefined references.
3218 The string %buffer% will be replaced by the corresponding
3219 `markdown-mode' buffer name.")
3221 (defun markdown-reference-check-buffer (&optional buffer-name)
3222 "Name and return buffer for reference checking.
3223 BUFFER-NAME is the name of the main buffer being visited."
3224 (or buffer-name (setq buffer-name (buffer-name)))
3225 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3226 "%buffer%" buffer-name
3227 markdown-reference-check-buffer))))
3228 (with-current-buffer refbuf
3229 (when view-mode
3230 (View-exit-and-edit))
3231 (use-local-map button-buffer-map)
3232 (erase-buffer))
3233 refbuf))
3235 (defconst markdown-reference-links-buffer
3236 "*Reference links for %buffer%*"
3237 "Pattern for name of buffer for listing references.
3238 The string %buffer% will be replaced by the corresponding buffer name.")
3240 (defun markdown-reference-links-buffer (&optional buffer-name)
3241 "Name, setup, and return a buffer for listing links.
3242 BUFFER-NAME is the name of the main buffer being visited."
3243 (or buffer-name (setq buffer-name (buffer-name)))
3244 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3245 "%buffer%" buffer-name
3246 markdown-reference-links-buffer))))
3247 (with-current-buffer linkbuf
3248 (when view-mode
3249 (View-exit-and-edit))
3250 (use-local-map button-buffer-map)
3251 (erase-buffer))
3252 linkbuf))
3254 (when (markdown-use-buttons-p)
3255 ;; Add an empty Markdown reference definition to the end of buffer
3256 ;; specified in the 'target-buffer property. The reference name is
3257 ;; the button's label.
3258 (define-button-type 'markdown-undefined-reference-button
3259 'help-echo "mouse-1, RET: create definition for undefined reference"
3260 'follow-link t
3261 'face 'bold
3262 'action (lambda (b)
3263 (let ((buffer (button-get b 'target-buffer)))
3264 (markdown-insert-reference-definition (button-label b) buffer)
3265 (switch-to-buffer-other-window buffer)
3266 (goto-char (point-max))
3267 (markdown-check-refs t))))
3269 ;; Jump to line in buffer specified by 'target-buffer property.
3270 ;; Line number is button's 'line property.
3271 (define-button-type 'markdown-goto-line-button
3272 'help-echo "mouse-1, RET: go to line"
3273 'follow-link t
3274 'face 'italic
3275 'action (lambda (b)
3276 (message (button-get b 'buffer))
3277 (switch-to-buffer-other-window (button-get b 'target-buffer))
3278 ;; use call-interactively to silence compiler
3279 (let ((current-prefix-arg (button-get b 'target-line)))
3280 (call-interactively 'goto-line))))
3282 ;; Jumps to a particular link at location given by 'target-char
3283 ;; property in buffer given by 'target-buffer property.
3284 (define-button-type 'markdown-link-button
3285 'help-echo "mouse-1, RET: jump to location of link"
3286 'follow-link t
3287 'face 'bold
3288 'action (lambda (b)
3289 (let ((target (button-get b 'target-buffer))
3290 (loc (button-get b 'target-char)))
3291 (kill-buffer-and-window)
3292 (switch-to-buffer target)
3293 (goto-char loc)))))
3295 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3296 "Insert a button for creating REFERENCE in buffer OLDBUF.
3297 REFERENCE should be a list of the form (reference . occurrences),
3298 as by `markdown-get-undefined-refs'."
3299 (let ((label (car reference)))
3300 (if (markdown-use-buttons-p)
3301 ;; Create a reference button in Emacs 22
3302 (insert-button label
3303 :type 'markdown-undefined-reference-button
3304 'target-buffer oldbuf)
3305 ;; Insert reference as text in Emacs < 22
3306 (insert label))
3307 (insert " (")
3308 (dolist (occurrence (cdr reference))
3309 (let ((line (cdr occurrence)))
3310 (if (markdown-use-buttons-p)
3311 ;; Create a line number button in Emacs 22
3312 (insert-button (number-to-string line)
3313 :type 'markdown-goto-line-button
3314 'target-buffer oldbuf
3315 'target-line line)
3316 ;; Insert line number as text in Emacs < 22
3317 (insert (number-to-string line)))
3318 (insert " ")))
3319 (delete-char -1)
3320 (insert ")")
3321 (newline)))
3323 (defun markdown-insert-link-button (link oldbuf)
3324 "Insert a button for jumping to LINK in buffer OLDBUF.
3325 LINK should be a list of the form (text char line) containing
3326 the link text, location, and line number."
3327 (let ((label (first link))
3328 (char (second link))
3329 (line (third link)))
3330 (if (markdown-use-buttons-p)
3331 ;; Create a reference button in Emacs 22
3332 (insert-button label
3333 :type 'markdown-link-button
3334 'target-buffer oldbuf
3335 'target-char char)
3336 ;; Insert reference as text in Emacs < 22
3337 (insert label))
3338 (insert (format " (line %d)\n" line))))
3340 (defun markdown-reference-goto-link (&optional reference)
3341 "Jump to the location of the first use of REFERENCE."
3342 (interactive)
3343 (unless reference
3344 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3345 (setq reference (match-string-no-properties 1))
3346 (error "No reference definition at point")))
3347 (let ((links (markdown-reference-find-links reference)))
3348 (cond ((= (length links) 1)
3349 (goto-char (cadr (car links))))
3350 ((> (length links) 1)
3351 (let ((oldbuf (current-buffer))
3352 (linkbuf (markdown-reference-links-buffer)))
3353 (with-current-buffer linkbuf
3354 (insert "Links using reference " reference ":\n\n")
3355 (dolist (link (reverse links))
3356 (markdown-insert-link-button link oldbuf)))
3357 (view-buffer-other-window linkbuf)
3358 (goto-char (point-min))
3359 (forward-line 2)))
3361 (error "No links for reference %s" reference)))))
3363 (defun markdown-check-refs (&optional silent)
3364 "Show all undefined Markdown references in current `markdown-mode' buffer.
3365 If SILENT is non-nil, do not message anything when no undefined
3366 references found.
3367 Links which have empty reference definitions are considered to be
3368 defined."
3369 (interactive "P")
3370 (when (not (eq major-mode 'markdown-mode))
3371 (error "Not available in current mode"))
3372 (let ((oldbuf (current-buffer))
3373 (refs (markdown-get-undefined-refs))
3374 (refbuf (markdown-reference-check-buffer)))
3375 (if (null refs)
3376 (progn
3377 (when (not silent)
3378 (message "No undefined references found"))
3379 (kill-buffer refbuf))
3380 (with-current-buffer refbuf
3381 (insert "The following references are undefined:\n\n")
3382 (dolist (ref refs)
3383 (markdown-insert-undefined-reference-button ref oldbuf))
3384 (view-buffer-other-window refbuf)
3385 (goto-char (point-min))
3386 (forward-line 2)))))
3389 ;;; Lists =====================================================================
3391 (defun markdown-insert-list-item (&optional arg)
3392 "Insert a new list item.
3393 If the point is inside unordered list, insert a bullet mark. If
3394 the point is inside ordered list, insert the next number followed
3395 by a period. Use the previous list item to determine the amount
3396 of whitespace to place before and after list markers.
3398 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3399 decrease the indentation by one level.
3401 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3402 increase the indentation by one level."
3403 (interactive "p")
3404 (let (bounds item-indent marker indent new-indent new-loc)
3405 (save-match-data
3406 ;; Look for a list item on current or previous non-blank line
3407 (save-excursion
3408 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3409 (not (bobp))
3410 (markdown-cur-line-blank-p))
3411 (forward-line -1)))
3412 (when bounds
3413 (cond ((save-excursion
3414 (skip-chars-backward " \t")
3415 (looking-at markdown-regex-list))
3416 (beginning-of-line)
3417 (insert "\n")
3418 (forward-line -1))
3419 ((not (markdown-cur-line-blank-p))
3420 (newline)))
3421 (setq new-loc (point)))
3422 ;; Look ahead for a list item on next non-blank line
3423 (unless bounds
3424 (save-excursion
3425 (while (and (null bounds)
3426 (not (eobp))
3427 (markdown-cur-line-blank-p))
3428 (forward-line)
3429 (setq bounds (markdown-cur-list-item-bounds))))
3430 (when bounds
3431 (setq new-loc (point))
3432 (unless (markdown-cur-line-blank-p)
3433 (newline))))
3434 (if (not bounds)
3435 ;; When not in a list, start a new unordered one
3436 (progn
3437 (unless (markdown-cur-line-blank-p)
3438 (insert "\n"))
3439 (insert "* "))
3440 ;; Compute indentation for a new list item
3441 (setq item-indent (nth 2 bounds))
3442 (setq marker (nth 4 bounds))
3443 (setq indent (cond
3444 ((= arg 4) (max (- item-indent 4) 0))
3445 ((= arg 16) (+ item-indent 4))
3446 (t item-indent)))
3447 (setq new-indent (make-string indent 32))
3448 (goto-char new-loc)
3449 (cond
3450 ;; Ordered list
3451 ((string-match "[0-9]" marker)
3452 (if (= arg 16) ;; starting a new column indented one more level
3453 (insert (concat new-indent "1. "))
3454 ;; travel up to the last item and pick the correct number. If
3455 ;; the argument was nil, "new-indent = item-indent" is the same,
3456 ;; so we don't need special treatment. Neat.
3457 (save-excursion
3458 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3459 (forward-line -1)))
3460 (insert (concat new-indent
3461 (int-to-string (1+ (string-to-number (match-string 1))))
3462 ". "))))
3463 ;; Unordered list
3464 ((string-match "[\\*\\+-]" marker)
3465 (insert new-indent marker)))))))
3467 (defun markdown-move-list-item-up ()
3468 "Move the current list item up in the list when possible."
3469 (interactive)
3470 (let (cur prev old)
3471 (when (setq cur (markdown-cur-list-item-bounds))
3472 (setq old (point))
3473 (goto-char (nth 0 cur))
3474 (if (markdown-prev-list-item (nth 3 cur))
3475 (progn
3476 (setq prev (markdown-cur-list-item-bounds))
3477 (condition-case nil
3478 (progn
3479 (transpose-regions (nth 0 prev) (nth 1 prev)
3480 (nth 0 cur) (nth 1 cur) t)
3481 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3482 ;; Catch error in case regions overlap.
3483 (error (goto-char old))))
3484 (goto-char old)))))
3486 (defun markdown-move-list-item-down ()
3487 "Move the current list item down in the list when possible."
3488 (interactive)
3489 (let (cur next old)
3490 (when (setq cur (markdown-cur-list-item-bounds))
3491 (setq old (point))
3492 (if (markdown-next-list-item (nth 3 cur))
3493 (progn
3494 (setq next (markdown-cur-list-item-bounds))
3495 (condition-case nil
3496 (progn
3497 (transpose-regions (nth 0 cur) (nth 1 cur)
3498 (nth 0 next) (nth 1 next) nil)
3499 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3500 ;; Catch error in case regions overlap.
3501 (error (goto-char old))))
3502 (goto-char old)))))
3504 (defun markdown-demote-list-item (&optional bounds)
3505 "Indent (or demote) the current list item.
3506 Optionally, BOUNDS of the current list item may be provided if available."
3507 (interactive)
3508 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3509 (save-excursion
3510 (save-match-data
3511 (let* ((end-marker (make-marker))
3512 (end-marker (set-marker end-marker (nth 1 bounds))))
3513 (goto-char (nth 0 bounds))
3514 (while (< (point) end-marker)
3515 (unless (markdown-cur-line-blank-p)
3516 (insert " "))
3517 (forward-line)))))))
3519 (defun markdown-promote-list-item (&optional bounds)
3520 "Unindent (or promote) the current list item.
3521 Optionally, BOUNDS of the current list item may be provided if available."
3522 (interactive)
3523 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3524 (save-excursion
3525 (save-match-data
3526 (let* ((end-marker (make-marker))
3527 (end-marker (set-marker end-marker (nth 1 bounds)))
3528 num regexp)
3529 (goto-char (nth 0 bounds))
3530 (when (looking-at "^[ ]\\{1,4\\}")
3531 (setq num (- (match-end 0) (match-beginning 0)))
3532 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3533 (while (and (< (point) end-marker)
3534 (re-search-forward regexp end-marker t))
3535 (replace-match "" nil nil)
3536 (forward-line))))))))
3538 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3539 "Update the numbering for level PFX (as a string of spaces).
3541 Assume that the previously found match was for a numbered item in
3542 a list."
3543 (let ((cpfx pfx)
3544 (idx 0)
3545 (continue t)
3546 (step t)
3547 (sep nil))
3548 (while (and continue (not (eobp)))
3549 (setq step t)
3550 (cond
3551 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3552 (setq cpfx (match-string-no-properties 1))
3553 (cond
3554 ((string= cpfx pfx)
3555 (replace-match
3556 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3557 (setq sep nil))
3558 ;; indented a level
3559 ((string< pfx cpfx)
3560 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3561 (setq step nil))
3562 ;; exit the loop
3564 (setq step nil)
3565 (setq continue nil))))
3567 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3568 (setq cpfx (match-string-no-properties 1))
3569 (cond
3570 ;; reset if separated before
3571 ((string= cpfx pfx) (when sep (setq idx 0)))
3572 ((string< cpfx pfx)
3573 (setq step nil)
3574 (setq continue nil))))
3575 (t (setq sep t)))
3577 (when step
3578 (beginning-of-line)
3579 (setq continue (= (forward-line) 0))))
3580 sep))
3582 (defun markdown-cleanup-list-numbers ()
3583 "Update the numbering of ordered lists."
3584 (interactive)
3585 (save-excursion
3586 (goto-char (point-min))
3587 (markdown--cleanup-list-numbers-level "")))
3590 ;;; Outline ===================================================================
3592 (defvar markdown-cycle-global-status 1)
3593 (defvar markdown-cycle-subtree-status nil)
3595 (defun markdown-end-of-subtree (&optional invisible-OK)
3596 "Move to the end of the current subtree.
3597 Only visible heading lines are considered, unless INVISIBLE-OK is
3598 non-nil.
3599 Derived from `org-end-of-subtree'."
3600 (outline-back-to-heading invisible-OK)
3601 (let ((first t)
3602 (level (funcall outline-level)))
3603 (while (and (not (eobp))
3604 (or first (> (funcall outline-level) level)))
3605 (setq first nil)
3606 (outline-next-heading))
3607 (if (memq (preceding-char) '(?\n ?\^M))
3608 (progn
3609 ;; Go to end of line before heading
3610 (forward-char -1)
3611 (if (memq (preceding-char) '(?\n ?\^M))
3612 ;; leave blank line before heading
3613 (forward-char -1)))))
3614 (point))
3616 (defun markdown-cycle (&optional arg)
3617 "Visibility cycling for Markdown mode.
3618 If ARG is t, perform global visibility cycling. If the point is
3619 at an atx-style header, cycle visibility of the corresponding
3620 subtree. Otherwise, insert a tab using `indent-relative'.
3621 Derived from `org-cycle'."
3622 (interactive "P")
3623 (cond
3624 ((eq arg t) ;; Global cycling
3625 (cond
3626 ((and (eq last-command this-command)
3627 (eq markdown-cycle-global-status 2))
3628 ;; Move from overview to contents
3629 (hide-sublevels 1)
3630 (message "CONTENTS")
3631 (setq markdown-cycle-global-status 3))
3633 ((and (eq last-command this-command)
3634 (eq markdown-cycle-global-status 3))
3635 ;; Move from contents to all
3636 (show-all)
3637 (message "SHOW ALL")
3638 (setq markdown-cycle-global-status 1))
3641 ;; Defaults to overview
3642 (hide-body)
3643 (message "OVERVIEW")
3644 (setq markdown-cycle-global-status 2))))
3646 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3647 ;; At a heading: rotate between three different views
3648 (outline-back-to-heading)
3649 (let ((goal-column 0) eoh eol eos)
3650 ;; Determine boundaries
3651 (save-excursion
3652 (outline-back-to-heading)
3653 (save-excursion
3654 (beginning-of-line 2)
3655 (while (and (not (eobp)) ;; this is like `next-line'
3656 (get-char-property (1- (point)) 'invisible))
3657 (beginning-of-line 2)) (setq eol (point)))
3658 (outline-end-of-heading) (setq eoh (point))
3659 (markdown-end-of-subtree t)
3660 (skip-chars-forward " \t\n")
3661 (beginning-of-line 1) ; in case this is an item
3662 (setq eos (1- (point))))
3663 ;; Find out what to do next and set `this-command'
3664 (cond
3665 ((= eos eoh)
3666 ;; Nothing is hidden behind this heading
3667 (message "EMPTY ENTRY")
3668 (setq markdown-cycle-subtree-status nil))
3669 ((>= eol eos)
3670 ;; Entire subtree is hidden in one line: open it
3671 (show-entry)
3672 (show-children)
3673 (message "CHILDREN")
3674 (setq markdown-cycle-subtree-status 'children))
3675 ((and (eq last-command this-command)
3676 (eq markdown-cycle-subtree-status 'children))
3677 ;; We just showed the children, now show everything.
3678 (show-subtree)
3679 (message "SUBTREE")
3680 (setq markdown-cycle-subtree-status 'subtree))
3682 ;; Default action: hide the subtree.
3683 (hide-subtree)
3684 (message "FOLDED")
3685 (setq markdown-cycle-subtree-status 'folded)))))
3688 (indent-for-tab-command))))
3690 (defun markdown-shifttab ()
3691 "Global visibility cycling.
3692 Calls `markdown-cycle' with argument t."
3693 (interactive)
3694 (markdown-cycle t))
3696 (defun markdown-outline-level ()
3697 "Return the depth to which a statement is nested in the outline."
3698 (cond
3699 ((match-end 1) 1)
3700 ((match-end 3) 2)
3701 ((- (match-end 5) (match-beginning 5)))))
3704 ;;; Movement ==================================================================
3706 (defun markdown-beginning-of-defun (&optional arg)
3707 "`beginning-of-defun-function' for Markdown.
3708 Move backward to the beginning of the current or previous section.
3709 When ARG is non-nil, repeat that many times. When ARG is negative,
3710 move forward to the ARG-th following section."
3711 (interactive "P")
3712 (or arg (setq arg 1))
3713 (or (re-search-backward markdown-regex-header nil t arg)
3714 (goto-char (point-min))))
3716 (defun markdown-end-of-defun (&optional arg)
3717 "`end-of-defun-function' for Markdown.
3718 Move forward to the end of the current or following section.
3719 When ARG is non-nil, repeat that many times. When ARG is negative,
3720 move back to the ARG-th preceding section."
3721 (interactive "P")
3722 (or arg (setq arg 1))
3723 (when (looking-at markdown-regex-header)
3724 (goto-char (match-beginning 0))
3725 (forward-char 1))
3726 (if (re-search-forward markdown-regex-header nil t arg)
3727 (goto-char (match-beginning 0))
3728 (goto-char (point-max)))
3729 (skip-syntax-backward "-"))
3731 (defun markdown-beginning-of-block ()
3732 "Move the point to the start of the previous text block."
3733 (interactive)
3734 (if (re-search-backward markdown-regex-block-separator nil t)
3735 (goto-char (or (match-end 2) (match-end 0)))
3736 (goto-char (point-min))))
3738 (defun markdown-end-of-block ()
3739 "Move the point to the start of the next text block."
3740 (interactive)
3741 (beginning-of-line)
3742 (skip-syntax-forward "-")
3743 (when (= (point) (point-min))
3744 (forward-char))
3745 (if (re-search-forward markdown-regex-block-separator nil t)
3746 (goto-char (or (match-end 2) (match-end 0)))
3747 (goto-char (point-max)))
3748 (skip-syntax-backward "-")
3749 (forward-line))
3751 (defun markdown-end-of-block-element ()
3752 "Move the point to the start of the next block unit.
3753 Stops at blank lines, list items, headers, and horizontal rules."
3754 (interactive)
3755 (forward-line)
3756 (while (and (or (not (markdown-prev-line-blank-p))
3757 (markdown-cur-line-blank-p))
3758 (not (or (looking-at markdown-regex-list)
3759 (looking-at markdown-regex-header)
3760 (looking-at markdown-regex-hr)))
3761 (not (eobp)))
3762 (forward-line)))
3764 (defun markdown-next-link ()
3765 "Jump to next inline, reference, or wiki link.
3766 If successful, return point. Otherwise, return nil.
3767 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3768 (interactive)
3769 (let ((opoint (point)))
3770 (when (or (markdown-link-p) (markdown-wiki-link-p))
3771 ;; At a link already, move past it.
3772 (goto-char (+ (match-end 0) 1)))
3773 ;; Search for the next wiki link and move to the beginning.
3774 (if (re-search-forward markdown-regex-link-generic nil t)
3775 ;; Group 1 will move past non-escape character in wiki link regexp.
3776 ;; Go to beginning of group zero for all other link types.
3777 (goto-char (or (match-beginning 1) (match-beginning 0)))
3778 (goto-char opoint)
3779 nil)))
3781 (defun markdown-previous-link ()
3782 "Jump to previous wiki link.
3783 If successful, return point. Otherwise, return nil.
3784 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3785 (interactive)
3786 (if (re-search-backward markdown-regex-link-generic nil t)
3787 (goto-char (or (match-beginning 1) (match-beginning 0)))
3788 nil))
3791 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3793 (defun markdown-move-up ()
3794 "Move list item up.
3795 Calls `markdown-move-list-item-up'."
3796 (interactive)
3797 (markdown-move-list-item-up))
3799 (defun markdown-move-down ()
3800 "Move list item down.
3801 Calls `markdown-move-list-item-down'."
3802 (interactive)
3803 (markdown-move-list-item-down))
3805 (defun markdown-promote ()
3806 "Either promote header or list item at point or cycle markup.
3807 See `markdown-cycle-atx', `markdown-cycle-setext', and
3808 `markdown-demote-list-item'."
3809 (interactive)
3810 (let (bounds)
3811 (cond
3812 ;; Promote atx header
3813 ((thing-at-point-looking-at markdown-regex-header-atx)
3814 (markdown-cycle-atx -1 t))
3815 ;; Promote setext header
3816 ((thing-at-point-looking-at markdown-regex-header-setext)
3817 (markdown-cycle-setext -1 t))
3818 ;; Promote horizonal rule
3819 ((thing-at-point-looking-at markdown-regex-hr)
3820 (markdown-cycle-hr -1 t))
3821 ;; Promote list item
3822 ((setq bounds (markdown-cur-list-item-bounds))
3823 (markdown-promote-list-item)))))
3825 (defun markdown-demote ()
3826 "Either demote header or list item at point or cycle or remove markup.
3827 See `markdown-cycle-atx', `markdown-cycle-setext', and
3828 `markdown-demote-list-item'."
3829 (interactive)
3830 (let (bounds)
3831 (cond
3832 ;; Demote atx header
3833 ((thing-at-point-looking-at markdown-regex-header-atx)
3834 (markdown-cycle-atx 1 t))
3835 ;; Demote setext header
3836 ((thing-at-point-looking-at markdown-regex-header-setext)
3837 (markdown-cycle-setext 1 t))
3838 ;; Demote horizonal rule
3839 ((thing-at-point-looking-at markdown-regex-hr)
3840 (markdown-cycle-hr 1 t))
3841 ;; Promote list item
3842 ((setq bounds (markdown-cur-list-item-bounds))
3843 (markdown-demote-list-item))
3844 ;; Create a new level one ATX header
3846 (markdown-insert-header-atx-1)))))
3848 (defun markdown-complete-or-cycle (arg)
3849 "Complete or cycle markup of object at point or complete objects in region.
3850 If there is an active region, complete markup in region.
3851 Otherwise, complete or cycle markup of object near point.
3852 When ARG is non-nil, cycle backwards when cycling."
3853 (interactive "*P")
3854 (if (markdown-use-region-p)
3855 ;; Complete markup in region
3856 (markdown-complete-region (region-beginning) (region-end))
3857 ;; Complete or cycle markup at point
3858 (let ((dir (if arg -1 1))
3859 bounds)
3860 (cond
3861 ;; atx header
3862 ((thing-at-point-looking-at markdown-regex-header-atx)
3863 (if (markdown-incomplete-atx-p)
3864 (markdown-complete-atx)
3865 (markdown-cycle-atx dir)))
3866 ;; setext header
3867 ((thing-at-point-looking-at markdown-regex-header-setext)
3868 (if (markdown-incomplete-setext-p)
3869 (markdown-complete-setext)
3870 (markdown-cycle-setext dir)))
3871 ;; horizonal rule
3872 ((thing-at-point-looking-at markdown-regex-hr)
3873 (if (markdown-incomplete-hr-p)
3874 (markdown-complete-hr)
3875 (markdown-cycle-hr dir)))
3876 ;; bold
3877 ((thing-at-point-looking-at markdown-regex-bold)
3878 (markdown-cycle-bold))
3879 ;; italic
3880 ((thing-at-point-looking-at markdown-regex-italic)
3881 (markdown-cycle-italic))))))
3884 ;;; Commands ==================================================================
3886 (defun markdown (&optional output-buffer-name)
3887 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3888 The output buffer name defaults to `markdown-output-buffer-name'.
3889 Return the name of the output buffer used."
3890 (interactive)
3891 (save-window-excursion
3892 (let ((begin-region)
3893 (end-region))
3894 (if (markdown-use-region-p)
3895 (setq begin-region (region-beginning)
3896 end-region (region-end))
3897 (setq begin-region (point-min)
3898 end-region (point-max)))
3900 (unless output-buffer-name
3901 (setq output-buffer-name markdown-output-buffer-name))
3903 (cond
3904 ;; Handle case when `markdown-command' does not read from stdin
3905 (markdown-command-needs-filename
3906 (if (not buffer-file-name)
3907 (error "Must be visiting a file")
3908 (shell-command (concat markdown-command " "
3909 (shell-quote-argument buffer-file-name))
3910 output-buffer-name)))
3911 ;; Pass region to `markdown-command' via stdin
3913 (shell-command-on-region begin-region end-region markdown-command
3914 output-buffer-name))))
3915 output-buffer-name))
3917 (defun markdown-standalone (&optional output-buffer-name)
3918 "Special function to provide standalone HTML output.
3919 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3920 (interactive)
3921 (setq output-buffer-name (markdown output-buffer-name))
3922 (with-current-buffer output-buffer-name
3923 (set-buffer output-buffer-name)
3924 (goto-char (point-min))
3925 (unless (markdown-output-standalone-p)
3926 (markdown-add-xhtml-header-and-footer output-buffer-name))
3927 (html-mode))
3928 output-buffer-name)
3930 (defun markdown-other-window (&optional output-buffer-name)
3931 "Run `markdown-command' on current buffer and display in other window.
3932 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3933 that name."
3934 (interactive)
3935 (display-buffer (markdown-standalone output-buffer-name)))
3937 (defun markdown-output-standalone-p ()
3938 "Determine whether `markdown-command' output is standalone XHTML.
3939 Standalone XHTML output is identified by an occurrence of
3940 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3941 (re-search-forward
3942 markdown-xhtml-standalone-regexp
3943 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3946 (defun markdown-add-xhtml-header-and-footer (title)
3947 "Wrap XHTML header and footer with given TITLE around current buffer."
3948 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3949 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3950 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3951 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3952 "<head>\n<title>")
3953 (insert title)
3954 (insert "</title>\n")
3955 (when (> (length markdown-content-type) 0)
3956 (insert
3957 (format
3958 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3959 markdown-content-type
3960 (or (and markdown-coding-system
3961 (fboundp 'coding-system-get)
3962 (coding-system-get markdown-coding-system
3963 'mime-charset))
3964 (and (fboundp 'coding-system-get)
3965 (coding-system-get buffer-file-coding-system
3966 'mime-charset))
3967 "iso-8859-1"))))
3968 (if (> (length markdown-css-path) 0)
3969 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3970 markdown-css-path
3971 "\" />\n"))
3972 (when (> (length markdown-xhtml-header-content) 0)
3973 (insert markdown-xhtml-header-content))
3974 (insert "\n</head>\n\n"
3975 "<body>\n\n")
3976 (goto-char (point-max))
3977 (insert "\n"
3978 "</body>\n"
3979 "</html>\n"))
3981 (defun markdown-preview (&optional output-buffer-name)
3982 "Run `markdown-command' on the current buffer and view output in browser.
3983 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3984 that name."
3985 (interactive)
3986 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3988 (defun markdown-export-file-name (&optional extension)
3989 "Attempt to generate a filename for Markdown output.
3990 The file extension will be EXTENSION if given, or .html by default.
3991 If the current buffer is visiting a file, we construct a new
3992 output filename based on that filename. Otherwise, return nil."
3993 (when (buffer-file-name)
3994 (unless extension
3995 (setq extension ".html"))
3996 (concat
3997 (cond
3998 ((buffer-file-name)
3999 (file-name-sans-extension (buffer-file-name)))
4000 (t (buffer-name)))
4001 extension)))
4003 (defun markdown-export (&optional output-file)
4004 "Run Markdown on the current buffer, save to file, and return the filename.
4005 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4006 generated by `markdown-export-file-name', which will be constructed using the
4007 current filename, but with the extension removed and replaced with .html."
4008 (interactive)
4009 (unless output-file
4010 (setq output-file (markdown-export-file-name ".html")))
4011 (when output-file
4012 (let ((output-buffer-name))
4013 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
4014 (run-hook-with-args 'markdown-before-export-hooks output-file)
4015 (markdown-standalone output-buffer-name)
4016 (with-current-buffer output-buffer-name
4017 (save-buffer))
4018 (run-hook-with-args 'markdown-after-export-hooks output-file)
4019 output-file)))
4021 (defun markdown-export-and-preview ()
4022 "Export to XHTML using `markdown-export' and browse the resulting file."
4023 (interactive)
4024 (browse-url (markdown-export)))
4026 (defun markdown-open ()
4027 "Open file for the current buffer with `markdown-open-command'."
4028 (interactive)
4029 (if (not markdown-open-command)
4030 (error "Variable `markdown-open-command' must be set")
4031 (if (not buffer-file-name)
4032 (error "Must be visiting a file")
4033 (call-process markdown-open-command
4034 nil nil nil buffer-file-name))))
4036 (defun markdown-kill-ring-save ()
4037 "Run Markdown on file and store output in the kill ring."
4038 (interactive)
4039 (save-window-excursion
4040 (markdown)
4041 (with-current-buffer markdown-output-buffer-name
4042 (kill-ring-save (point-min) (point-max)))))
4045 ;;; Links =====================================================================
4047 (require 'thingatpt)
4049 (defun markdown-link-p ()
4050 "Return non-nil when `point' is at a non-wiki link.
4051 See `markdown-wiki-link-p' for more information."
4052 (let ((case-fold-search nil))
4053 (and (not (markdown-wiki-link-p))
4054 (or (thing-at-point-looking-at markdown-regex-link-inline)
4055 (thing-at-point-looking-at markdown-regex-link-reference)
4056 (thing-at-point-looking-at markdown-regex-uri)
4057 (thing-at-point-looking-at markdown-regex-angle-uri)))))
4059 (defun markdown-link-link ()
4060 "Return the link part of the regular (non-wiki) link at point.
4061 Works with both inline and reference style links. If point is
4062 not at a link or the link reference is not defined returns nil."
4063 (cond
4064 ((thing-at-point-looking-at markdown-regex-link-inline)
4065 (match-string-no-properties 5))
4066 ((thing-at-point-looking-at markdown-regex-link-reference)
4067 (let* ((text (match-string-no-properties 2))
4068 (reference (match-string-no-properties 4))
4069 (target (downcase (if (string= reference "[]") text reference))))
4070 (car (markdown-reference-definition target))))
4071 ((thing-at-point-looking-at markdown-regex-uri)
4072 (match-string-no-properties 0))
4073 ((thing-at-point-looking-at markdown-regex-angle-uri)
4074 (match-string-no-properties 2))
4075 (t nil)))
4077 (defun markdown-follow-link-at-point ()
4078 "Open the current non-wiki link in a browser."
4079 (interactive)
4080 (if (markdown-link-p) (browse-url (markdown-link-link))
4081 (error "Point is not at a Markdown link or URI")))
4084 ;;; WikiLink Following/Markup =================================================
4086 (defun markdown-wiki-link-p ()
4087 "Return non-nil when `point' is at a true wiki link.
4088 A true wiki link name matches `markdown-regex-wiki-link' but does not
4089 match the current file name after conversion. This modifies the data
4090 returned by `match-data'. Note that the potential wiki link name must
4091 be available via `match-string'."
4092 (let ((case-fold-search nil))
4093 (and (thing-at-point-looking-at markdown-regex-wiki-link)
4094 (or (not buffer-file-name)
4095 (not (string-equal (buffer-file-name)
4096 (markdown-convert-wiki-link-to-filename
4097 (markdown-wiki-link-link)))))
4098 (not (save-match-data
4099 (save-excursion))))))
4101 (defun markdown-wiki-link-link ()
4102 "Return the link part of the wiki link using current match data.
4103 The location of the link component depends on the value of
4104 `markdown-wiki-link-alias-first'."
4105 (if markdown-wiki-link-alias-first
4106 (or (match-string-no-properties 4) (match-string-no-properties 2))
4107 (match-string-no-properties 2)))
4109 (defun markdown-convert-wiki-link-to-filename (name)
4110 "Generate a filename from the wiki link NAME.
4111 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4112 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4113 and [[test test]] both map to Test-test.ext."
4114 (let ((basename (markdown-replace-regexp-in-string
4115 "[[:space:]\n]" markdown-link-space-sub-char name)))
4116 (when (eq major-mode 'gfm-mode)
4117 (setq basename (concat (upcase (substring basename 0 1))
4118 (downcase (substring basename 1 nil)))))
4119 (concat basename
4120 (if (buffer-file-name)
4121 (concat "."
4122 (file-name-extension (buffer-file-name)))))))
4124 (defun markdown-follow-wiki-link (name &optional other)
4125 "Follow the wiki link NAME.
4126 Convert the name to a file name and call `find-file'. Ensure that
4127 the new buffer remains in `markdown-mode'. Open the link in another
4128 window when OTHER is non-nil."
4129 (let ((filename (markdown-convert-wiki-link-to-filename name))
4130 (wp (file-name-directory buffer-file-name)))
4131 (when other (other-window 1))
4132 (find-file (concat wp filename)))
4133 (when (not (eq major-mode 'markdown-mode))
4134 (markdown-mode)))
4136 (defun markdown-follow-wiki-link-at-point (&optional arg)
4137 "Find Wiki Link at point.
4138 With prefix argument ARG, open the file in other window.
4139 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4140 (interactive "P")
4141 (if (markdown-wiki-link-p)
4142 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4143 (error "Point is not at a Wiki Link")))
4145 (defun markdown-highlight-wiki-link (from to face)
4146 "Highlight the wiki link in the region between FROM and TO using FACE."
4147 (put-text-property from to 'font-lock-face face))
4149 (defun markdown-unfontify-region-wiki-links (from to)
4150 "Remove wiki link faces from the region specified by FROM and TO."
4151 (interactive "nfrom: \nnto: ")
4152 (remove-text-properties from to '(font-lock-face markdown-link-face))
4153 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4155 (defun markdown-fontify-region-wiki-links (from to)
4156 "Search region given by FROM and TO for wiki links and fontify them.
4157 If a wiki link is found check to see if the backing file exists
4158 and highlight accordingly."
4159 (goto-char from)
4160 (save-match-data
4161 (while (re-search-forward markdown-regex-wiki-link to t)
4162 (let ((highlight-beginning (match-beginning 1))
4163 (highlight-end (match-end 1))
4164 (file-name
4165 (markdown-convert-wiki-link-to-filename
4166 (markdown-wiki-link-link))))
4167 (if (file-exists-p file-name)
4168 (markdown-highlight-wiki-link
4169 highlight-beginning highlight-end markdown-link-face)
4170 (markdown-highlight-wiki-link
4171 highlight-beginning highlight-end markdown-link-face)
4172 (markdown-highlight-wiki-link
4173 highlight-beginning highlight-end markdown-missing-link-face))))))
4175 (defun markdown-extend-changed-region (from to)
4176 "Extend region given by FROM and TO so that we can fontify all links.
4177 The region is extended to the first newline before and the first
4178 newline after."
4179 ;; start looking for the first new line before 'from
4180 (goto-char from)
4181 (re-search-backward "\n" nil t)
4182 (let ((new-from (point-min))
4183 (new-to (point-max)))
4184 (if (not (= (point) from))
4185 (setq new-from (point)))
4186 ;; do the same thing for the first new line after 'to
4187 (goto-char to)
4188 (re-search-forward "\n" nil t)
4189 (if (not (= (point) to))
4190 (setq new-to (point)))
4191 (values new-from new-to)))
4193 (defun markdown-check-change-for-wiki-link (from to change)
4194 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4195 Designed to be used with the `after-change-functions' hook.
4196 CHANGE is the number of bytes of pre-change text replaced by the
4197 given range."
4198 (interactive "nfrom: \nnto: \nnchange: ")
4199 (let* ((modified (buffer-modified-p))
4200 (buffer-undo-list t)
4201 (inhibit-read-only t)
4202 (inhibit-point-motion-hooks t)
4203 deactivate-mark
4204 buffer-file-truename)
4205 (unwind-protect
4206 (save-excursion
4207 (save-match-data
4208 (save-restriction
4209 ;; Extend the region to fontify so that it starts
4210 ;; and ends at safe places.
4211 (multiple-value-bind (new-from new-to)
4212 (markdown-extend-changed-region from to)
4213 ;; Unfontify existing fontification (start from scratch)
4214 (markdown-unfontify-region-wiki-links new-from new-to)
4215 ;; Now do the fontification.
4216 (markdown-fontify-region-wiki-links new-from new-to)))))
4217 (and (not modified)
4218 (buffer-modified-p)
4219 (set-buffer-modified-p nil)))))
4221 (defun markdown-fontify-buffer-wiki-links ()
4222 "Refontify all wiki links in the buffer."
4223 (interactive)
4224 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4227 ;;; Following and Jumping =====================================================
4229 (defun markdown-follow-thing-at-point (arg)
4230 "Follow thing at point if possible, such as a reference link or wiki link.
4231 Opens inline and reference links in a browser. Opens wiki links
4232 to other files in the current window, or the another window if
4233 ARG is non-nil.
4234 See `markdown-follow-link-at-point' and
4235 `markdown-follow-wiki-link-at-point'."
4236 (interactive "P")
4237 (cond ((markdown-link-p)
4238 (markdown-follow-link-at-point))
4239 ((markdown-wiki-link-p)
4240 (markdown-follow-wiki-link-at-point arg))
4242 (error "Nothing to follow at point"))))
4244 (defun markdown-jump ()
4245 "Jump to another location based on context at point.
4246 Jumps between reference links and definitions; between footnote
4247 markers and footnote text."
4248 (interactive)
4249 (cond ((markdown-footnote-text-positions)
4250 (markdown-footnote-return))
4251 ((markdown-footnote-marker-positions)
4252 (markdown-footnote-goto-text))
4253 ((thing-at-point-looking-at markdown-regex-link-reference)
4254 (markdown-reference-goto-definition))
4255 ((thing-at-point-looking-at markdown-regex-reference-definition)
4256 (markdown-reference-goto-link (match-string-no-properties 1)))
4258 (error "Nothing to jump to from context at point"))))
4261 ;;; Miscellaneous =============================================================
4263 (defun markdown-compress-whitespace-string (str)
4264 "Compress whitespace in STR and return result.
4265 Leading and trailing whitespace is removed. Sequences of multiple
4266 spaces, tabs, and newlines are replaced with single spaces."
4267 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4268 (replace-regexp-in-string "[ \t\n]+" " " str)))
4270 (defun markdown-line-number-at-pos (&optional pos)
4271 "Return (narrowed) buffer line number at position POS.
4272 If POS is nil, use current buffer location.
4273 This is an exact copy of `line-number-at-pos' for use in emacs21."
4274 (let ((opoint (or pos (point))) start)
4275 (save-excursion
4276 (goto-char (point-min))
4277 (setq start (point))
4278 (goto-char opoint)
4279 (forward-line 0)
4280 (1+ (count-lines start (point))))))
4282 (defun markdown-nobreak-p ()
4283 "Return nil if it is acceptable to break the current line at the point."
4284 ;; inside in square brackets (e.g., link anchor text)
4285 (looking-back "\\[[^]]*"))
4287 (defun markdown-adaptive-fill-function ()
4288 "Return prefix for filling paragraph or nil if not determined."
4289 (cond
4290 ;; List item inside blockquote
4291 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4292 (replace-regexp-in-string
4293 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4294 ;; Blockquote
4295 ((looking-at "^[ \t]*>[ \t]*")
4296 (match-string-no-properties 0))
4297 ;; List items
4298 ((looking-at markdown-regex-list)
4299 (match-string-no-properties 0))
4300 ;; No match
4301 (t nil)))
4304 ;;; Mode Definition ==========================================================
4306 (defun markdown-show-version ()
4307 "Show the version number in the minibuffer."
4308 (interactive)
4309 (message "markdown-mode, version %s" markdown-mode-version))
4311 ;;;###autoload
4312 (define-derived-mode markdown-mode text-mode "Markdown"
4313 "Major mode for editing Markdown files."
4314 ;; Natural Markdown tab width
4315 (setq tab-width 4)
4316 ;; Comments
4317 (make-local-variable 'comment-start)
4318 (setq comment-start "<!-- ")
4319 (make-local-variable 'comment-end)
4320 (setq comment-end " -->")
4321 (make-local-variable 'comment-start-skip)
4322 (setq comment-start-skip "<!--[ \t]*")
4323 (make-local-variable 'comment-column)
4324 (setq comment-column 0)
4325 ;; Font lock.
4326 (set (make-local-variable 'font-lock-defaults)
4327 '(markdown-mode-font-lock-keywords))
4328 (set (make-local-variable 'font-lock-multiline) t)
4329 ;; For imenu support
4330 (setq imenu-create-index-function 'markdown-imenu-create-index)
4331 ;; For menu support in XEmacs
4332 (easy-menu-add markdown-mode-menu markdown-mode-map)
4333 ;; Defun movement
4334 (set (make-local-variable 'beginning-of-defun-function)
4335 'markdown-beginning-of-defun)
4336 (set (make-local-variable 'end-of-defun-function)
4337 'markdown-end-of-defun)
4338 ;; Paragraph filling
4339 (set (make-local-variable 'paragraph-start)
4340 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4341 (set (make-local-variable 'paragraph-separate)
4342 "\\(?:[ \t\f]\\|.* \\)*$")
4343 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4344 "\\`[ \t]*>[ \t]*?\\'")
4345 (set (make-local-variable 'adaptive-fill-function)
4346 'markdown-adaptive-fill-function)
4347 ;; Outline mode
4348 (make-local-variable 'outline-regexp)
4349 (setq outline-regexp markdown-regex-header)
4350 (make-local-variable 'outline-level)
4351 (setq outline-level 'markdown-outline-level)
4352 ;; Cause use of ellipses for invisible text.
4353 (add-to-invisibility-spec '(outline . t))
4354 ;; Indentation and filling
4355 (make-local-variable 'fill-nobreak-predicate)
4356 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4357 (setq indent-line-function markdown-indent-function)
4359 ;; Prepare hooks for XEmacs compatibility
4360 (when (featurep 'xemacs)
4361 (make-local-hook 'after-change-functions)
4362 (make-local-hook 'font-lock-extend-region-functions)
4363 (make-local-hook 'window-configuration-change-hook))
4365 ;; Multiline font lock
4366 (add-hook 'font-lock-extend-region-functions
4367 'markdown-font-lock-extend-region)
4369 ;; Anytime text changes make sure it gets fontified correctly
4370 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4372 ;; If we left the buffer there is a really good chance we were
4373 ;; creating one of the wiki link documents. Make sure we get
4374 ;; refontified when we come back.
4375 (add-hook 'window-configuration-change-hook
4376 'markdown-fontify-buffer-wiki-links t t)
4378 ;; do the initial link fontification
4379 (markdown-fontify-buffer-wiki-links))
4381 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4384 ;;; GitHub Flavored Markdown Mode ============================================
4386 (defvar gfm-font-lock-keywords
4387 (append
4388 ;; GFM features to match first
4389 (list
4390 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4391 (2 markdown-language-keyword-face)
4392 (3 markdown-pre-face)
4393 (4 markdown-pre-face))))
4394 ;; Basic Markdown features (excluding possibly overridden ones)
4395 markdown-mode-font-lock-keywords-basic
4396 ;; GFM features to match last
4397 (list
4398 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4399 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4401 ;;;###autoload
4402 (define-derived-mode gfm-mode markdown-mode "GFM"
4403 "Major mode for editing GitHub Flavored Markdown files."
4404 (setq markdown-link-space-sub-char "-")
4405 (set (make-local-variable 'font-lock-defaults)
4406 '(gfm-font-lock-keywords))
4407 (auto-fill-mode 0)
4408 ;; Use visual-line-mode if available, fall back to longlines-mode:
4409 (if (fboundp 'visual-line-mode)
4410 (visual-line-mode 1)
4411 (longlines-mode 1))
4412 ;; do the initial link fontification
4413 (markdown-fontify-buffer-wiki-links))
4416 (provide 'markdown-mode)
4418 ;;; markdown-mode.el ends here