Extract wiki link alias text with function
[markdown-mode.git] / markdown-mode.el
blob99dd5c93d139d741355bc6d22f39a060eef033d7
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 ;; 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-math t)`
459 ;; in `.emacs`, and then restarting Emacs or calling
460 ;; `markdown-reload-extensions'.
462 ;;; GitHub Flavored Markdown:
464 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
465 ;; available. The GitHub implementation of differs slightly from
466 ;; standard Markdown. The most important differences are that
467 ;; newlines are significant, triggering hard line breaks, and that
468 ;; underscores inside of words (e.g., variable names) need not be
469 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
470 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
471 ;; not available). Underscores inside of words (such as
472 ;; test_variable) will not trigger emphasis.
474 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
475 ;; replacing spaces in filenames and where the first letter of the
476 ;; filename capitalized. For example, `[[wiki link]]' will map to a
477 ;; file named `Wiki-link` with the same extension as the current file.
479 ;; GFM code blocks, with optional programming language keywords, will
480 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
481 ;; is an active region, the text in the region will be placed inside
482 ;; the code block. You will be prompted for the name of the language,
483 ;; but may press enter to continue without naming a language.
485 ;; For a more complete GitHub-flavored markdown experience, consider
486 ;; adding README.md to your `auto-mode-alist':
488 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
490 ;; For GFM preview can be powered by setting `markdown-command' to
491 ;; use [Docter][]. This may also be configured to work with [Marked][]
492 ;; for `markdown-open-command'.
494 ;; [GFM]: http://github.github.com/github-flavored-markdown/
495 ;; [Docter]: https://github.com/alampros/Docter
497 ;;; Acknowledgments:
499 ;; markdown-mode has benefited greatly from the efforts of the
500 ;; following people:
502 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
503 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
504 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
505 ;; GitHub Flavored Markdown mode (`gfm-mode').
506 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
507 ;; `markdown' with an active region.
508 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
509 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
510 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
511 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
512 ;; visibility cycling functionality was derived, and for a bug fix
513 ;; related to `orgtbl-mode'.
514 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
515 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
516 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
517 ;; compatibility and custom CSS.
518 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
519 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
520 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
521 ;; comment matching functions were derived.
522 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
523 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
524 ;; functions, bug reports regarding indentation, and
525 ;; fixes for byte-compilation warnings.
526 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
527 ;; enhancements.
528 ;; * George Ogata <george.ogata@gmail.com> for fixing several
529 ;; byte-compilation warnings.
530 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
531 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
532 ;; customizations and XHTML export.
533 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
534 ;; Markdown processors which do not accept input from stdin.
535 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
536 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
537 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
538 ;; substitution character for mapping wiki links to filenames.
539 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
540 ;; escape shell commands.
541 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
542 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
543 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
544 ;; Emacs Lisp coding conventions.
545 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
546 ;; regexp, refactoring the compilation and preview functions,
547 ;; heading font-lock generalizations, list renumbering,
548 ;; and kill ring save.
549 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
550 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
551 ;; for an autoload token for `gfm-mode'.
552 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
553 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
554 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
555 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
556 ;; declaration in XHTML output.
557 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
558 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
559 ;; and GFM code block insertion.
560 ;; * Peter Jones <pjones@pmade.com> for link following functions.
561 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
562 ;; externally modified files.
563 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
564 ;; related to `orgtbl-mode'.
565 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
566 ;; export hooks and unit test improvements.
567 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
568 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
569 ;; completion.
571 ;;; Bugs:
573 ;; Although markdown-mode is developed and tested primarily using
574 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
575 ;; priority.
577 ;; If you find any bugs in markdown-mode, please construct a test case
578 ;; or a patch and email me at <jrblevin@sdf.org>.
580 ;;; History:
582 ;; markdown-mode was written and is maintained by Jason Blevins. The
583 ;; first version was released on May 24, 2007.
585 ;; * 2007-05-24: Version 1.1
586 ;; * 2007-05-25: Version 1.2
587 ;; * 2007-06-05: [Version 1.3][]
588 ;; * 2007-06-29: Version 1.4
589 ;; * 2007-10-11: [Version 1.5][]
590 ;; * 2008-06-04: [Version 1.6][]
591 ;; * 2009-10-01: [Version 1.7][]
592 ;; * 2011-08-12: [Version 1.8][]
593 ;; * 2011-08-15: [Version 1.8.1][]
594 ;; * 2013-01-25: [Version 1.9][]
596 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
597 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
598 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
599 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
600 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
601 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
602 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
605 ;;; Code:
607 (require 'easymenu)
608 (require 'outline)
609 (eval-when-compile (require 'cl))
612 ;;; Constants =================================================================
614 (defconst markdown-mode-version "2.0-pre"
615 "Markdown mode version number.")
617 (defconst markdown-output-buffer-name "*markdown-output*"
618 "Name of temporary buffer for markdown command output.")
621 ;;; Global Variables ==========================================================
623 (defvar markdown-reference-label-history nil
624 "History of used reference labels.")
627 ;;; Customizable Variables ====================================================
629 (defvar markdown-mode-hook nil
630 "Hook run when entering Markdown mode.")
632 (defvar markdown-before-export-hooks nil
633 "Hook run before output XHTML.
634 This hook is abnormal and registered functions are given an argument that is output filename.")
636 (defvar markdown-after-export-hooks nil
637 "Hook run after output XHTML.
638 This hook is abnormal and registered functions are given an argument that is output filename.")
640 (defgroup markdown nil
641 "Major mode for editing text files in Markdown format."
642 :prefix "markdown-"
643 :group 'wp
644 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
646 (defcustom markdown-command "markdown"
647 "Command to run markdown."
648 :group 'markdown
649 :type 'string)
651 (defcustom markdown-command-needs-filename nil
652 "Set to non-nil if `markdown-command' does not accept input from stdin.
653 Instead, it will be passed a filename as the final command line
654 option. As a result, you will only be able to run Markdown from
655 buffers which are visiting a file."
656 :group 'markdown
657 :type 'boolean)
659 (defcustom markdown-open-command nil
660 "Command used for opening Markdown files directly.
661 For example, a standalone Markdown previewer. This command will
662 be called with a single argument: the filename of the current
663 buffer."
664 :group 'markdown
665 :type 'string)
667 (defcustom markdown-hr-strings
668 '("-------------------------------------------------------------------------------"
669 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
670 "---------------------------------------"
671 "* * * * * * * * * * * * * * * * * * * *"
672 "---------"
673 "* * * * *")
674 "Strings to use when inserting horizontal rules.
675 The first string in the list will be the default when inserting a
676 horizontal rule. Strings should be listed in decreasing order of
677 prominence (as in headers from level one to six) for use with
678 promotion and demotion functions."
679 :group 'markdown
680 :type 'list)
682 (defcustom markdown-bold-underscore nil
683 "Use two underscores for bold instead of two asterisks."
684 :group 'markdown
685 :type 'boolean)
687 (defcustom markdown-italic-underscore nil
688 "Use underscores for italic instead of asterisks."
689 :group 'markdown
690 :type 'boolean)
692 (defcustom markdown-indent-function 'markdown-indent-line
693 "Function to use to indent."
694 :group 'markdown
695 :type 'function)
697 (defcustom markdown-indent-on-enter t
698 "Automatically indent new lines when enter key is pressed."
699 :group 'markdown
700 :type 'boolean)
702 (defcustom markdown-follow-wiki-link-on-enter t
703 "Follow wiki link at point (if any) when the enter key is pressed."
704 :group 'markdown
705 :type 'boolean)
707 (defcustom markdown-wiki-link-alias-first t
708 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
709 Otherwise, they will be treated as [[PageName|alias text]]."
710 :group 'markdown
711 :type 'boolean)
713 (defcustom markdown-uri-types
714 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
715 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
716 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
717 "Link types for syntax highlighting of URIs."
718 :group 'markdown
719 :type 'list)
721 (defcustom markdown-enable-math nil
722 "Syntax highlighting for inline LaTeX and itex expressions.
723 Set this to a non-nil value to turn on math support by default.
724 Math support can be toggled later using `markdown-enable-math'
725 or \\[markdown-enable-math]."
726 :group 'markdown
727 :type 'boolean
728 :safe 'booleanp)
730 (defcustom markdown-css-path ""
731 "URL of CSS file to link to in the output XHTML."
732 :group 'markdown
733 :type 'string)
735 (defcustom markdown-content-type ""
736 "Content type string for the http-equiv header in XHTML output.
737 When set to a non-empty string, insert the http-equiv attribute.
738 Otherwise, this attribute is omitted."
739 :group 'markdown
740 :type 'string)
742 (defcustom markdown-coding-system nil
743 "Character set string for the http-equiv header in XHTML output.
744 Defaults to `buffer-file-coding-system' (and falling back to
745 `iso-8859-1' when not available). Common settings are `utf-8'
746 and `iso-latin-1'. Use `list-coding-systems' for more choices."
747 :group 'markdown
748 :type 'coding-system)
750 (defcustom markdown-xhtml-header-content ""
751 "Additional content to include in the XHTML <head> block."
752 :group 'markdown
753 :type 'string)
755 (defcustom markdown-xhtml-standalone-regexp
756 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
757 "Regexp indicating whether `markdown-command' output is standalone XHTML."
758 :group 'markdown
759 :type 'regexp)
761 (defcustom markdown-link-space-sub-char
763 "Character to use instead of spaces when mapping wiki links to filenames."
764 :group 'markdown
765 :type 'string)
767 (defcustom markdown-reference-location 'header
768 "Position where new reference definitions are inserted in the document."
769 :group 'markdown
770 :type '(choice (const :tag "At the end of the document" end)
771 (const :tag "Immediately after the current block" immediately)
772 (const :tag "Before next header" header)))
774 (defcustom markdown-footnote-location 'end
775 "Position where new footnotes are inserted in the document."
776 :group 'markdown
777 :type '(choice (const :tag "At the end of the document" end)
778 (const :tag "Immediately after the current block" immediately)
779 (const :tag "Before next header" header)))
782 ;;; Font Lock =================================================================
784 (require 'font-lock)
786 (defvar markdown-italic-face 'markdown-italic-face
787 "Face name to use for italic text.")
789 (defvar markdown-bold-face 'markdown-bold-face
790 "Face name to use for bold text.")
792 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
793 "Face name to use as a base for header delimiters.")
795 (defvar markdown-header-rule-face 'markdown-header-rule-face
796 "Face name to use as a base for header rules.")
798 (defvar markdown-header-face 'markdown-header-face
799 "Face name to use as a base for headers.")
801 (defvar markdown-header-face-1 'markdown-header-face-1
802 "Face name to use for level-1 headers.")
804 (defvar markdown-header-face-2 'markdown-header-face-2
805 "Face name to use for level-2 headers.")
807 (defvar markdown-header-face-3 'markdown-header-face-3
808 "Face name to use for level-3 headers.")
810 (defvar markdown-header-face-4 'markdown-header-face-4
811 "Face name to use for level-4 headers.")
813 (defvar markdown-header-face-5 'markdown-header-face-5
814 "Face name to use for level-5 headers.")
816 (defvar markdown-header-face-6 'markdown-header-face-6
817 "Face name to use for level-6 headers.")
819 (defvar markdown-inline-code-face 'markdown-inline-code-face
820 "Face name to use for inline code.")
822 (defvar markdown-list-face 'markdown-list-face
823 "Face name to use for list markers.")
825 (defvar markdown-blockquote-face 'markdown-blockquote-face
826 "Face name to use for blockquote.")
828 (defvar markdown-pre-face 'markdown-pre-face
829 "Face name to use for preformatted text.")
831 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
832 "Face name to use for programming language identifiers.")
834 (defvar markdown-link-face 'markdown-link-face
835 "Face name to use for links.")
837 (defvar markdown-missing-link-face 'markdown-missing-link-face
838 "Face name to use for links where the linked file does not exist.")
840 (defvar markdown-reference-face 'markdown-reference-face
841 "Face name to use for reference.")
843 (defvar markdown-footnote-face 'markdown-footnote-face
844 "Face name to use for footnote identifiers.")
846 (defvar markdown-url-face 'markdown-url-face
847 "Face name to use for URLs.")
849 (defvar markdown-link-title-face 'markdown-link-title-face
850 "Face name to use for reference link titles.")
852 (defvar markdown-line-break-face 'markdown-line-break-face
853 "Face name to use for hard line breaks.")
855 (defvar markdown-comment-face 'markdown-comment-face
856 "Face name to use for HTML comments.")
858 (defvar markdown-math-face 'markdown-math-face
859 "Face name to use for LaTeX expressions.")
861 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
862 "Face name to use for metadata keys.")
864 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
865 "Face name to use for metadata values.")
867 (defgroup markdown-faces nil
868 "Faces used in Markdown Mode"
869 :group 'markdown
870 :group 'faces)
872 (defface markdown-italic-face
873 '((t (:inherit font-lock-variable-name-face :slant italic)))
874 "Face for italic text."
875 :group 'markdown-faces)
877 (defface markdown-bold-face
878 '((t (:inherit font-lock-variable-name-face :weight bold)))
879 "Face for bold text."
880 :group 'markdown-faces)
882 (defface markdown-header-rule-face
883 '((t (:inherit font-lock-function-name-face :weight bold)))
884 "Base face for headers rules."
885 :group 'markdown-faces)
887 (defface markdown-header-delimiter-face
888 '((t (:inherit font-lock-function-name-face :weight bold)))
889 "Base face for headers hash delimiter."
890 :group 'markdown-faces)
892 (defface markdown-header-face
893 '((t (:inherit font-lock-function-name-face :weight bold)))
894 "Base face for headers."
895 :group 'markdown-faces)
897 (defface markdown-header-face-1
898 '((t (:inherit markdown-header-face)))
899 "Face for level-1 headers."
900 :group 'markdown-faces)
902 (defface markdown-header-face-2
903 '((t (:inherit markdown-header-face)))
904 "Face for level-2 headers."
905 :group 'markdown-faces)
907 (defface markdown-header-face-3
908 '((t (:inherit markdown-header-face)))
909 "Face for level-3 headers."
910 :group 'markdown-faces)
912 (defface markdown-header-face-4
913 '((t (:inherit markdown-header-face)))
914 "Face for level-4 headers."
915 :group 'markdown-faces)
917 (defface markdown-header-face-5
918 '((t (:inherit markdown-header-face)))
919 "Face for level-5 headers."
920 :group 'markdown-faces)
922 (defface markdown-header-face-6
923 '((t (:inherit markdown-header-face)))
924 "Face for level-6 headers."
925 :group 'markdown-faces)
927 (defface markdown-inline-code-face
928 '((t (:inherit font-lock-constant-face)))
929 "Face for inline code."
930 :group 'markdown-faces)
932 (defface markdown-list-face
933 '((t (:inherit font-lock-builtin-face)))
934 "Face for list item markers."
935 :group 'markdown-faces)
937 (defface markdown-blockquote-face
938 '((t (:inherit font-lock-doc-face)))
939 "Face for blockquote sections."
940 :group 'markdown-faces)
942 (defface markdown-pre-face
943 '((t (:inherit font-lock-constant-face)))
944 "Face for preformatted text."
945 :group 'markdown-faces)
947 (defface markdown-language-keyword-face
948 '((t (:inherit font-lock-type-face)))
949 "Face for programming language identifiers."
950 :group 'markdown-faces)
952 (defface markdown-link-face
953 '((t (:inherit font-lock-keyword-face)))
954 "Face for links."
955 :group 'markdown-faces)
957 (defface markdown-missing-link-face
958 '((t (:inherit font-lock-warning-face)))
959 "Face for missing links."
960 :group 'markdown-faces)
962 (defface markdown-reference-face
963 '((t (:inherit font-lock-type-face)))
964 "Face for link references."
965 :group 'markdown-faces)
967 (defface markdown-footnote-face
968 '((t (:inherit font-lock-keyword-face)))
969 "Face for footnote markers."
970 :group 'markdown-faces)
972 (defface markdown-url-face
973 '((t (:inherit font-lock-string-face)))
974 "Face for URLs."
975 :group 'markdown-faces)
977 (defface markdown-link-title-face
978 '((t (:inherit font-lock-comment-face)))
979 "Face for reference link titles."
980 :group 'markdown-faces)
982 (defface markdown-line-break-face
983 '((t (:inherit font-lock-constant-face :underline t)))
984 "Face for hard line breaks."
985 :group 'markdown-faces)
987 (defface markdown-comment-face
988 '((t (:inherit font-lock-comment-face)))
989 "Face for HTML comments."
990 :group 'markdown-faces)
992 (defface markdown-math-face
993 '((t (:inherit font-lock-string-face)))
994 "Face for LaTeX expressions."
995 :group 'markdown-faces)
997 (defface markdown-metadata-key-face
998 '((t (:inherit font-lock-variable-name-face)))
999 "Face for metadata keys."
1000 :group 'markdown-faces)
1002 (defface markdown-metadata-value-face
1003 '((t (:inherit font-lock-string-face)))
1004 "Face for metadata values."
1005 :group 'markdown-faces)
1007 (defconst markdown-regex-link-inline
1008 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
1009 "Regular expression for a [text](file) or an image link ![text](file).
1010 Group 1 matches the leading exclamation point, if any.
1011 Group 2 matchs the entire square bracket term, including the text.
1012 Group 3 matches the text inside the square brackets.
1013 Group 4 matches the entire parenthesis term, including the URL and title.
1014 Group 5 matches the URL.
1015 Group 6 matches (optional) title.")
1017 (defconst markdown-regex-link-reference
1018 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
1019 "Regular expression for a reference link [text][id].
1020 Group 1 matches the leading exclamation point, if any.
1021 Group 2 matchs the entire first square bracket term, including the text.
1022 Group 3 matches the text inside the square brackets.
1023 Group 4 matches the entire second square bracket term.
1024 Group 5 matches the reference label.")
1026 (defconst markdown-regex-reference-definition
1027 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1028 "Regular expression for a link definition [id]: ...")
1030 (defconst markdown-regex-footnote
1031 "\\(\\[\\^.+?\\]\\)"
1032 "Regular expression for a footnote marker [^fn].")
1034 (defconst markdown-regex-header
1035 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1036 "Regexp identifying Markdown headers.")
1038 (defconst markdown-regex-header-1-atx
1039 "^\\(#\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1040 "Regular expression for level 1 atx-style (hash mark) headers.")
1042 (defconst markdown-regex-header-2-atx
1043 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1044 "Regular expression for level 2 atx-style (hash mark) headers.")
1046 (defconst markdown-regex-header-3-atx
1047 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1048 "Regular expression for level 3 atx-style (hash mark) headers.")
1050 (defconst markdown-regex-header-4-atx
1051 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1052 "Regular expression for level 4 atx-style (hash mark) headers.")
1054 (defconst markdown-regex-header-5-atx
1055 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1056 "Regular expression for level 5 atx-style (hash mark) headers.")
1058 (defconst markdown-regex-header-6-atx
1059 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1060 "Regular expression for level 6 atx-style (hash mark) headers.")
1062 (defconst markdown-regex-header-1-setext
1063 "^\\(.*\\)\n\\(=+\\)$"
1064 "Regular expression for level 1 setext-style (underline) headers.")
1066 (defconst markdown-regex-header-2-setext
1067 "^\\(.*\\)\n\\(-+\\)$"
1068 "Regular expression for level 2 setext-style (underline) headers.")
1070 (defconst markdown-regex-header-setext
1071 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1072 "Regular expression for generic setext-style (underline) headers.")
1074 (defconst markdown-regex-header-atx
1075 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1076 "Regular expression for generic atx-style (hash mark) headers.")
1078 (defconst markdown-regex-hr
1079 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1080 "Regular expression for matching Markdown horizontal rules.")
1082 (defconst markdown-regex-code
1083 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1084 "Regular expression for matching inline code fragments.
1086 The first group ensures that the leading backquote character
1087 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1088 character, including newlines, but not two newlines in a row.
1089 The final group requires that the character following the code
1090 fragment is not a backquote.")
1092 (defconst markdown-regex-pre
1093 "^\\( \\|\t\\).*$"
1094 "Regular expression for matching preformatted text sections.")
1096 (defconst markdown-regex-list
1097 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1098 "Regular expression for matching list items.")
1100 (defconst markdown-regex-bold
1101 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1102 "Regular expression for matching bold text.
1103 Group 1 matches the character before the opening asterisk or
1104 underscore, if any, ensuring that it is not a backslash escape.
1105 Group 2 matches the entire expression, including delimiters.
1106 Groups 3 and 5 matches the opening and closing delimiters.
1107 Group 4 matches the text inside the delimiters.")
1109 (defconst markdown-regex-italic
1110 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1111 "Regular expression for matching italic text.
1112 Group 1 matches the character before the opening asterisk or
1113 underscore, if any, ensuring that it is not a backslash escape.
1114 Group 2 matches the entire expression, including delimiters.
1115 Groups 3 and 5 matches the opening and closing delimiters.
1116 Group 4 matches the text inside the delimiters.")
1118 (defconst markdown-regex-gfm-italic
1119 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1120 "Regular expression for matching italic text in GitHub-flavored Markdown.
1121 Underscores in words are not treated as special.")
1123 (defconst markdown-regex-blockquote
1124 "^[ \t]*\\(>\\).*$"
1125 "Regular expression for matching blockquote lines.")
1127 (defconst markdown-regex-line-break
1128 "[^ \n\t][ \t]*\\( \\)$"
1129 "Regular expression for matching line breaks.")
1131 (defconst markdown-regex-wiki-link
1132 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1133 "Regular expression for matching wiki links.
1134 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1135 wiki links of the form [[PageName|link text]]. In this regular
1136 expression, group 1 matches the entire link, including square
1137 brackets, group 2 matches the first component of the wiki link
1138 and group 4 matches the second component, after the pipe, when
1139 present. The meanings of the first and second components depend
1140 on the value of `markdown-wiki-link-alias-first'.")
1142 (defconst markdown-regex-uri
1143 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1144 "Regular expression for matching inline URIs.")
1146 (defconst markdown-regex-angle-uri
1147 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1148 "Regular expression for matching inline URIs in angle brackets.")
1150 (defconst markdown-regex-email
1151 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1152 "Regular expression for matching inline email addresses.")
1154 (defconst markdown-regex-link-generic
1155 (concat "\\(?:" markdown-regex-wiki-link
1156 "\\|" markdown-regex-link-inline
1157 "\\|" markdown-regex-link-reference
1158 "\\|" markdown-regex-angle-uri "\\)")
1159 "Regular expression for matching any recognized link.")
1161 (defconst markdown-regex-block-separator
1162 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1163 "Regular expression for matching block boundaries.")
1165 (defconst markdown-regex-math-inline
1166 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1167 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1169 (defconst markdown-regex-math-display
1170 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1171 "Regular expression for itex \[..\] display mode expressions.")
1173 (defconst markdown-regex-multimarkdown-metadata
1174 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1175 "Regular expression for matching MultiMarkdown metadata.")
1177 (defconst markdown-regex-pandoc-metadata
1178 "^\\(%\\)[ \t]*\\(.*\\)$"
1179 "Regular expression for matching Pandoc metadata.")
1181 (defvar markdown-mode-font-lock-keywords-basic
1182 (list
1183 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1184 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1185 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1186 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1187 (2 markdown-header-rule-face)))
1188 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1189 (2 markdown-header-rule-face)))
1190 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1191 (2 markdown-header-face-6)
1192 (3 markdown-header-delimiter-face)))
1193 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1194 (2 markdown-header-face-5)
1195 (3 markdown-header-delimiter-face)))
1196 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1197 (2 markdown-header-face-4)
1198 (3 markdown-header-delimiter-face)))
1199 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1200 (2 markdown-header-face-3)
1201 (3 markdown-header-delimiter-face)))
1202 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1203 (2 markdown-header-face-2)
1204 (3 markdown-header-delimiter-face)))
1205 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1206 (2 markdown-header-face-1)
1207 (3 markdown-header-delimiter-face)))
1208 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1209 (2 markdown-metadata-value-face)))
1210 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1211 (2 markdown-metadata-value-face)))
1212 (cons markdown-regex-hr 'markdown-header-face)
1213 (cons 'markdown-match-comments '((0 markdown-comment-face)))
1214 (cons 'markdown-match-code '((0 markdown-inline-code-face)))
1215 (cons markdown-regex-angle-uri 'markdown-link-face)
1216 (cons markdown-regex-uri 'markdown-link-face)
1217 (cons markdown-regex-email 'markdown-link-face)
1218 (cons markdown-regex-list '(2 markdown-list-face))
1219 (cons markdown-regex-footnote 'markdown-footnote-face)
1220 (cons markdown-regex-link-inline '((1 markdown-link-face t t)
1221 (2 markdown-link-face t)
1222 (4 markdown-url-face t)
1223 (6 markdown-link-title-face t t)))
1224 (cons markdown-regex-link-reference '((1 markdown-link-face t t)
1225 (2 markdown-link-face t)
1226 (4 markdown-reference-face t)))
1227 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1228 (2 markdown-url-face t)
1229 (3 markdown-link-title-face t)))
1230 (cons markdown-regex-bold '(2 markdown-bold-face))
1231 (cons markdown-regex-line-break '(1 markdown-line-break-face prepend))
1233 "Syntax highlighting for Markdown files.")
1235 (defvar markdown-mode-font-lock-keywords-core
1236 (list
1237 (cons markdown-regex-italic '(2 markdown-italic-face))
1239 "Additional syntax highlighting for Markdown files.
1240 Includes features which are overridden by some variants.")
1242 (defconst markdown-mode-font-lock-keywords-math
1243 (list
1244 ;; Math mode $..$ or $$..$$
1245 (cons markdown-regex-math-inline '(2 markdown-math-face))
1246 ;; Display mode equations with brackets: \[ \]
1247 (cons markdown-regex-math-display 'markdown-math-face)
1248 ;; Equation reference (eq:foo)
1249 (cons "(eq:[[:alnum:]:_]+)" 'markdown-reference-face)
1250 ;; Equation reference \eqref{foo}
1251 (cons "\\\\eqref{[[:alnum:]:_]+}" 'markdown-reference-face))
1252 "Syntax highlighting for LaTeX and itex fragments.")
1254 (defvar markdown-mode-font-lock-keywords nil
1255 "Default highlighting expressions for Markdown mode.
1256 This variable is defined as a buffer-local variable for dynamic
1257 extension support.")
1259 ;; Footnotes
1260 (defvar markdown-footnote-counter 0
1261 "Counter for footnote numbers.")
1262 (make-variable-buffer-local 'markdown-footnote-counter)
1264 (defconst markdown-footnote-chars
1265 "[[:alnum:]-]"
1266 "Regular expression maching any character that is allowed in a footnote identifier.")
1269 ;;; Compatibility =============================================================
1271 (defun markdown-replace-regexp-in-string (regexp rep string)
1272 "Replace ocurrences of REGEXP with REP in STRING.
1273 This is a compatibility wrapper to provide `replace-regexp-in-string'
1274 in XEmacs 21."
1275 (if (featurep 'xemacs)
1276 (replace-in-string string regexp rep)
1277 (replace-regexp-in-string regexp rep string)))
1279 ;; `markdown-use-region-p' is a compatibility function which checks
1280 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1281 (eval-and-compile
1282 (cond
1283 ;; Emacs 23 and newer
1284 ((fboundp 'use-region-p)
1285 (defalias 'markdown-use-region-p 'use-region-p))
1286 ;; Older Emacsen
1287 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1288 (defun markdown-use-region-p ()
1289 "Compatibility wrapper to provide `use-region-p'."
1290 (and transient-mark-mode mark-active)))
1291 ;; XEmacs
1292 ((fboundp 'region-active-p)
1293 (defalias 'markdown-use-region-p 'region-active-p))))
1295 (defun markdown-use-buttons-p ()
1296 "Determine whether this Emacs supports buttons."
1297 (or (featurep 'button) (locate-library "button")))
1300 ;;; Markdown Parsing Functions ================================================
1302 (defun markdown-cur-line-blank-p ()
1303 "Return t if the current line is blank and nil otherwise."
1304 (save-excursion
1305 (beginning-of-line)
1306 (re-search-forward "^\\s *$" (line-end-position) t)))
1308 (defun markdown-prev-line-blank-p ()
1309 "Return t if the previous line is blank and nil otherwise.
1310 If we are at the first line, then consider the previous line to be blank."
1311 (or (= (line-beginning-position) (point-min))
1312 (save-excursion
1313 (forward-line -1)
1314 (markdown-cur-line-blank-p))))
1316 (defun markdown-next-line-blank-p ()
1317 "Return t if the next line is blank and nil otherwise.
1318 If we are at the last line, then consider the next line to be blank."
1319 (or (= (line-end-position) (point-max))
1320 (save-excursion
1321 (forward-line 1)
1322 (markdown-cur-line-blank-p))))
1324 (defun markdown-prev-line-indent-p ()
1325 "Return t if the previous line is indented and nil otherwise."
1326 (save-excursion
1327 (forward-line -1)
1328 (goto-char (line-beginning-position))
1329 (if (re-search-forward "^\\s " (line-end-position) t) t)))
1331 (defun markdown-cur-line-indent ()
1332 "Return the number of leading whitespace characters in the current line."
1333 (save-match-data
1334 (save-excursion
1335 (goto-char (line-beginning-position))
1336 (re-search-forward "^[ \t]+" (line-end-position) t)
1337 (current-column))))
1339 (defun markdown-prev-line-indent ()
1340 "Return the number of leading whitespace characters in the previous line."
1341 (save-excursion
1342 (forward-line -1)
1343 (markdown-cur-line-indent)))
1345 (defun markdown-next-line-indent ()
1346 "Return the number of leading whitespace characters in the next line."
1347 (save-excursion
1348 (forward-line 1)
1349 (markdown-cur-line-indent)))
1351 (defun markdown-cur-non-list-indent ()
1352 "Return beginning position of list item text (not including the list marker).
1353 Return nil if the current line is not the beginning of a list item."
1354 (save-match-data
1355 (save-excursion
1356 (beginning-of-line)
1357 (when (re-search-forward markdown-regex-list (line-end-position) t)
1358 (current-column)))))
1360 (defun markdown-prev-non-list-indent ()
1361 "Return position of the first non-list-marker on the previous line."
1362 (save-excursion
1363 (forward-line -1)
1364 (markdown-cur-non-list-indent)))
1366 (defun markdown-new-baseline-p ()
1367 "Determine if the current line begins a new baseline level."
1368 (save-excursion
1369 (beginning-of-line)
1370 (save-match-data
1371 (or (looking-at markdown-regex-header)
1372 (looking-at markdown-regex-hr)
1373 (and (null (markdown-cur-non-list-indent))
1374 (= (markdown-cur-line-indent) 0)
1375 (markdown-prev-line-blank-p))))))
1377 (defun markdown-search-backward-baseline ()
1378 "Search backward baseline point with no indentation and not a list item."
1379 (end-of-line)
1380 (let (stop)
1381 (while (not (or stop (bobp)))
1382 (re-search-backward markdown-regex-block-separator nil t)
1383 (when (match-end 2)
1384 (goto-char (match-end 2))
1385 (cond
1386 ((markdown-new-baseline-p)
1387 (setq stop t))
1388 ((looking-at markdown-regex-list)
1389 (setq stop nil))
1390 (t (setq stop t)))))))
1392 (defun markdown-update-list-levels (marker indent levels)
1393 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1394 Here, MARKER is a string representing the type of list, INDENT is an integer
1395 giving the indentation, in spaces, of the current block, and LEVELS is a
1396 list of the indentation levels of parent list items. When LEVELS is nil,
1397 it means we are at baseline (not inside of a nested list)."
1398 (cond
1399 ;; New list item at baseline.
1400 ((and marker (null levels))
1401 (setq levels (list indent)))
1402 ;; List item with greater indentation (four or more spaces).
1403 ;; Increase list level.
1404 ((and marker (>= indent (+ (car levels) 4)))
1405 (setq levels (cons indent levels)))
1406 ;; List item with greater or equal indentation (less than four spaces).
1407 ;; Do not increase list level.
1408 ((and marker (>= indent (car levels)))
1409 levels)
1410 ;; Lesser indentation level.
1411 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1412 ;; indentation could move back more than one list level). Note
1413 ;; that this block need not be the beginning of list item.
1414 ((< indent (car levels))
1415 (while (and (> (length levels) 1)
1416 (< indent (+ (cadr levels) 4)))
1417 (setq levels (cdr levels)))
1418 levels)
1419 ;; Otherwise, do nothing.
1420 (t levels)))
1422 (defun markdown-calculate-list-levels ()
1423 "Calculate list levels at point.
1424 Return a list of the form (n1 n2 n3 ...) where n1 is the
1425 indentation of the deepest nested list item in the branch of
1426 the list at the point, n2 is the indentation of the parent
1427 list item, and so on. The depth of the list item is therefore
1428 the length of the returned list. If the point is not at or
1429 immediately after a list item, return nil."
1430 (save-excursion
1431 (let ((first (point)) levels indent pre-regexp)
1432 ;; Find a baseline point with zero list indentation
1433 (markdown-search-backward-baseline)
1434 ;; Search for all list items between baseline and LOC
1435 (while (and (< (point) first)
1436 (re-search-forward markdown-regex-list first t))
1437 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1438 (beginning-of-line)
1439 (cond
1440 ;; Make sure this is not a header or hr
1441 ((markdown-new-baseline-p) (setq levels nil))
1442 ;; Make sure this is not a line from a pre block
1443 ((looking-at pre-regexp))
1444 ;; If not, then update levels
1446 (setq indent (markdown-cur-line-indent))
1447 (setq levels (markdown-update-list-levels (match-string 2)
1448 indent levels))))
1449 (end-of-line))
1450 levels)))
1452 (defun markdown-prev-list-item (level)
1453 "Search backward from point for a list item with indentation LEVEL.
1454 Set point to the beginning of the item, and return point, or nil
1455 upon failure."
1456 (let (bounds indent prev)
1457 (setq prev (point))
1458 (forward-line -1)
1459 (setq indent (markdown-cur-line-indent))
1460 (while
1461 (cond
1462 ;; Stop at beginning of buffer
1463 ((bobp) (setq prev nil))
1464 ;; Continue if current line is blank
1465 ((markdown-cur-line-blank-p) t)
1466 ;; List item
1467 ((and (looking-at markdown-regex-list)
1468 (setq bounds (markdown-cur-list-item-bounds)))
1469 (cond
1470 ;; Continue at item with greater indentation
1471 ((> (nth 3 bounds) level) t)
1472 ;; Stop and return point at item of equal indentation
1473 ((= (nth 3 bounds) level)
1474 (setq prev (point))
1475 nil)
1476 ;; Stop and return nil at item with lesser indentation
1477 ((< (nth 3 bounds) level)
1478 (setq prev nil)
1479 nil)))
1480 ;; Continue while indentation is the same or greater
1481 ((>= indent level) t)
1482 ;; Stop if current indentation is less than list item
1483 ;; and the next is blank
1484 ((and (< indent level)
1485 (markdown-next-line-blank-p))
1486 (setq prev nil))
1487 ;; Stop at a header
1488 ((looking-at markdown-regex-header) (setq prev nil))
1489 ;; Stop at a horizontal rule
1490 ((looking-at markdown-regex-hr) (setq prev nil))
1491 ;; Otherwise, continue.
1492 (t t))
1493 (forward-line -1)
1494 (setq indent (markdown-cur-line-indent)))
1495 prev))
1497 (defun markdown-next-list-item (level)
1498 "Search forward from point for the next list item with indentation LEVEL.
1499 Set point to the beginning of the item, and return point, or nil
1500 upon failure."
1501 (let (bounds indent prev next)
1502 (setq next (point))
1503 (forward-line)
1504 (setq indent (markdown-cur-line-indent))
1505 (while
1506 (cond
1507 ;; Stop at end of the buffer.
1508 ((eobp) (setq prev nil))
1509 ;; Continue if the current line is blank
1510 ((markdown-cur-line-blank-p) t)
1511 ;; List item
1512 ((and (looking-at markdown-regex-list)
1513 (setq bounds (markdown-cur-list-item-bounds)))
1514 (cond
1515 ;; Continue at item with greater indentation
1516 ((> (nth 3 bounds) level) t)
1517 ;; Stop and return point at item of equal indentation
1518 ((= (nth 3 bounds) level)
1519 (setq next (point))
1520 nil)
1521 ;; Stop and return nil at item with lesser indentation
1522 ((< (nth 3 bounds) level)
1523 (setq next nil)
1524 nil)))
1525 ;; Continue while indentation is the same or greater
1526 ((>= indent level) t)
1527 ;; Stop if current indentation is less than list item
1528 ;; and the previous line was blank.
1529 ((and (< indent level)
1530 (markdown-prev-line-blank-p))
1531 (setq next nil))
1532 ;; Stop at a header
1533 ((looking-at markdown-regex-header) (setq next nil))
1534 ;; Stop at a horizontal rule
1535 ((looking-at markdown-regex-hr) (setq next nil))
1536 ;; Otherwise, continue.
1537 (t t))
1538 (forward-line)
1539 (setq indent (markdown-cur-line-indent)))
1540 next))
1542 (defun markdown-cur-list-item-end (level)
1543 "Move to the end of the current list item with nonlist indentation LEVEL.
1544 If the point is not in a list item, do nothing."
1545 (let (indent)
1546 (forward-line)
1547 (setq indent (markdown-cur-line-indent))
1548 (while
1549 (cond
1550 ;; Stop at end of the buffer.
1551 ((eobp) nil)
1552 ;; Continue if the current line is blank
1553 ((markdown-cur-line-blank-p) t)
1554 ;; Continue while indentation is the same or greater
1555 ((>= indent level) t)
1556 ;; Stop if current indentation is less than list item
1557 ;; and the previous line was blank.
1558 ((and (< indent level)
1559 (markdown-prev-line-blank-p))
1560 nil)
1561 ;; Stop at a new list item of the same or lesser indentation
1562 ((looking-at markdown-regex-list) nil)
1563 ;; Stop at a header
1564 ((looking-at markdown-regex-header) nil)
1565 ;; Stop at a horizontal rule
1566 ((looking-at markdown-regex-hr) nil)
1567 ;; Otherwise, continue.
1568 (t t))
1569 (forward-line)
1570 (setq indent (markdown-cur-line-indent)))
1571 ;; Don't skip over whitespace for empty list items (marker and
1572 ;; whitespace only), just move to end of whitespace.
1573 (if (looking-back (concat markdown-regex-list "\\s-*"))
1574 (goto-char (match-end 3))
1575 (skip-syntax-backward "-"))))
1577 (defun markdown-cur-list-item-bounds ()
1578 "Return bounds and indentation of the current list item.
1579 Return a list of the form (begin end indent nonlist-indent marker).
1580 If the point is not inside a list item, return nil.
1581 Leave match data intact for `markdown-regex-list'."
1582 (let (cur prev-begin prev-end indent nonlist-indent marker)
1583 ;; Store current location
1584 (setq cur (point))
1585 ;; Verify that cur is between beginning and end of item
1586 (save-excursion
1587 (end-of-line)
1588 (when (re-search-backward markdown-regex-list nil t)
1589 (setq prev-begin (match-beginning 0))
1590 (setq indent (length (match-string 1)))
1591 (setq nonlist-indent (length (match-string 0)))
1592 (setq marker (concat (match-string 2) (match-string 3)))
1593 (save-match-data
1594 (markdown-cur-list-item-end nonlist-indent)
1595 (setq prev-end (point)))
1596 (when (and (>= cur prev-begin)
1597 (<= cur prev-end)
1598 nonlist-indent)
1599 (list prev-begin prev-end indent nonlist-indent marker))))))
1601 (defun markdown-bounds-of-thing-at-point (thing)
1602 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1603 Does not include trailing newlines when THING is 'line. Handles the
1604 end of buffer case by setting both endpoints equal to the value of
1605 `point-max', since an empty region will trigger empty markup insertion.
1606 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1607 (let* ((bounds (bounds-of-thing-at-point thing))
1608 (a (car bounds))
1609 (b (cdr bounds)))
1610 (when bounds
1611 (when (eq thing 'line)
1612 (cond ((and (eobp) (markdown-cur-line-blank-p))
1613 (setq a b))
1614 ((char-equal (char-before b) ?\^J)
1615 (setq b (1- b)))))
1616 (cons a b))))
1618 (defun markdown-reference-definition (reference)
1619 "Find out whether Markdown REFERENCE is defined.
1620 REFERENCE should include the square brackets, like [this].
1621 When REFERENCE is defined, return a list of the form (text start end)
1622 containing the definition text itself followed by the start and end
1623 locations of the text. Otherwise, return nil.
1624 Leave match data for `markdown-regex-reference-definition'
1625 intact additional processing."
1626 (let ((reference (downcase reference)))
1627 (save-excursion
1628 (goto-char (point-min))
1629 (catch 'found
1630 (while (re-search-forward markdown-regex-reference-definition nil t)
1631 (when (string= reference (downcase (match-string-no-properties 1)))
1632 (throw 'found
1633 (list (match-string-no-properties 2)
1634 (match-beginning 2) (match-end 2)))))))))
1636 (defun markdown-get-defined-references ()
1637 "Return a list of all defined reference labels (including square brackets)."
1638 (save-excursion
1639 (goto-char (point-min))
1640 (let (refs)
1641 (while (re-search-forward markdown-regex-reference-definition nil t)
1642 (let ((target (match-string-no-properties 1)))
1643 (add-to-list 'refs target t)))
1644 refs)))
1647 ;;; Markdown Font Lock Matching Functions =====================================
1649 (defun markdown-match-comments (last)
1650 "Match HTML comments from the point to LAST."
1651 (cond ((search-forward "<!--" last t)
1652 (backward-char 4)
1653 (let ((beg (point)))
1654 (cond ((search-forward-regexp "--[ \t]*>" last t)
1655 (set-match-data (list beg (point)))
1657 (t nil))))
1658 (t nil)))
1660 (defun markdown-match-code (last)
1661 "Match inline code from the point to LAST."
1662 (unless (bobp)
1663 (backward-char 1))
1664 (cond ((re-search-forward markdown-regex-code last t)
1665 (set-match-data (list (match-beginning 2) (match-end 2)))
1666 (goto-char (match-end 0))
1668 (t (forward-char 2) nil)))
1670 (defun markdown-match-pre-blocks (last)
1671 "Match Markdown pre blocks from point to LAST."
1672 (let ((levels (markdown-calculate-list-levels))
1673 indent pre-regexp end-regexp begin end stop)
1674 (while (and (< (point) last) (not end))
1675 ;; Search for a region with sufficient indentation
1676 (if (null levels)
1677 (setq indent 1)
1678 (setq indent (1+ (length levels))))
1679 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1680 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1682 (cond
1683 ;; If not at the beginning of a line, move forward
1684 ((not (bolp)) (forward-line))
1685 ;; Move past blank lines
1686 ((markdown-cur-line-blank-p) (forward-line))
1687 ;; At headers and horizontal rules, reset levels
1688 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1689 ;; If the current line has sufficient indentation, mark out pre block
1690 ((looking-at pre-regexp)
1691 (setq begin (match-beginning 0))
1692 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1693 (not (eobp)))
1694 (forward-line))
1695 (setq end (point)))
1696 ;; If current line has a list marker, update levels, move to end of block
1697 ((looking-at markdown-regex-list)
1698 (setq levels (markdown-update-list-levels
1699 (match-string 2) (markdown-cur-line-indent) levels))
1700 (markdown-end-of-block-element))
1701 ;; If this is the end of the indentation level, adjust levels accordingly.
1702 ;; Only match end of indentation level if levels is not the empty list.
1703 ((and (car levels) (looking-at end-regexp))
1704 (setq levels (markdown-update-list-levels
1705 nil (markdown-cur-line-indent) levels))
1706 (markdown-end-of-block-element))
1707 (t (markdown-end-of-block-element))))
1709 (if (not (and begin end))
1710 ;; Return nil if no pre block was found
1712 ;; Set match data and return t upon success
1713 (set-match-data (list begin end))
1714 t)))
1716 (defun markdown-match-fenced-code-blocks (last)
1717 "Match fenced code blocks from the point to LAST."
1718 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1719 (beginning-of-line)
1720 (let ((beg (point)))
1721 (forward-line)
1722 (cond ((search-forward-regexp
1723 (concat "^" (match-string 1) "~*") last t)
1724 (set-match-data (list beg (point)))
1726 (t nil))))
1727 (t nil)))
1729 (defun markdown-match-gfm-code-blocks (last)
1730 "Match GFM quoted code blocks from point to LAST."
1731 (let (open lang body close all)
1732 (cond ((and (eq major-mode 'gfm-mode)
1733 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1734 (beginning-of-line)
1735 (setq open (list (match-beginning 1) (match-end 1))
1736 lang (list (match-beginning 2) (match-end 2)))
1737 (forward-line)
1738 (setq body (list (point)))
1739 (cond ((search-forward-regexp "^```$" last t)
1740 (setq body (reverse (cons (1- (match-beginning 0)) body))
1741 close (list (match-beginning 0) (match-end 0))
1742 all (list (car open) (match-end 0)))
1743 (set-match-data (append all open lang body close))
1745 (t nil)))
1746 (t nil))))
1748 (defun markdown-match-generic-metadata (regexp last)
1749 "Match generic metadata specified by REGEXP from the point to LAST."
1750 (let ((header-end (save-excursion
1751 (goto-char (point-min))
1752 (if (re-search-forward "\n\n" (point-max) t)
1753 (match-beginning 0)
1754 (point-max)))))
1755 (cond ((>= (point) header-end)
1756 ;; Don't match anything outside of the header.
1757 nil)
1758 ((re-search-forward regexp (min last header-end) t)
1759 ;; If a metadata item is found, it may span several lines.
1760 (let ((key-beginning (match-beginning 1))
1761 (key-end (match-end 1))
1762 (value-beginning (match-beginning 2)))
1763 (while (and (not (looking-at regexp))
1764 (not (> (point) (min last header-end)))
1765 (not (eobp)))
1766 (forward-line))
1767 (unless (eobp)
1768 (forward-line -1)
1769 (end-of-line))
1770 (set-match-data (list key-beginning (point) ; complete metadata
1771 key-beginning key-end ; key
1772 value-beginning (point))) ; value
1774 (t nil))))
1776 (defun markdown-match-multimarkdown-metadata (last)
1777 "Match MultiMarkdown metadata from the point to LAST."
1778 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1780 (defun markdown-match-pandoc-metadata (last)
1781 "Match Pandoc metadata from the point to LAST."
1782 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1784 (defun markdown-font-lock-extend-region ()
1785 "Extend the search region to include an entire block of text.
1786 This helps improve font locking for block constructs such as pre blocks."
1787 ;; Avoid compiler warnings about these global variables from font-lock.el.
1788 ;; See the documentation for variable `font-lock-extend-region-functions'.
1789 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1790 (save-excursion
1791 (goto-char font-lock-beg)
1792 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1793 (goto-char font-lock-end)
1794 (when (re-search-forward "\n\n" nil t)
1795 (beginning-of-line)
1796 (setq font-lock-end (point)))
1797 (setq font-lock-beg found))))
1800 ;;; Syntax Table ==============================================================
1802 (defvar markdown-mode-syntax-table
1803 (let ((tab (make-syntax-table text-mode-syntax-table)))
1804 (modify-syntax-entry ?\" "." tab)
1805 tab)
1806 "Syntax table for `markdown-mode'.")
1809 ;;; Element Insertion =========================================================
1811 (defun markdown-ensure-blank-line-before ()
1812 "If previous line is not already blank, insert a blank line before point."
1813 (unless (bolp) (insert "\n"))
1814 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1816 (defun markdown-ensure-blank-line-after ()
1817 "If following line is not already blank, insert a blank line after point.
1818 Return the point where it was originally."
1819 (save-excursion
1820 (unless (eolp) (insert "\n"))
1821 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1823 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1824 "Insert the strings S1 and S2, wrapping around region or THING.
1825 If a region is specified by the optional BEG and END arguments,
1826 wrap the strings S1 and S2 around that region.
1827 If there is an active region, wrap the strings S1 and S2 around
1828 the region. If there is not an active region but the point is at
1829 THING, wrap that thing (which defaults to word). Otherwise, just
1830 insert S1 and S2 and place the cursor in between. Return the
1831 bounds of the entire wrapped string, or nil if nothing was wrapped
1832 and S1 and S2 were only inserted."
1833 (let (a b bounds new-point)
1834 (cond
1835 ;; Given region
1836 ((and beg end)
1837 (setq a beg
1838 b end
1839 new-point (+ (point) (length s1))))
1840 ;; Active region
1841 ((markdown-use-region-p)
1842 (setq a (region-beginning)
1843 b (region-end)
1844 new-point (+ (point) (length s1))))
1845 ;; Thing (word) at point
1846 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1847 (setq a (car bounds)
1848 b (cdr bounds)
1849 new-point (+ (point) (length s1))))
1850 ;; No active region and no word
1852 (setq a (point)
1853 b (point))))
1854 (goto-char b)
1855 (insert s2)
1856 (goto-char a)
1857 (insert s1)
1858 (when new-point (goto-char new-point))
1859 (if (= a b)
1861 (setq b (+ b (length s1) (length s2)))
1862 (cons a b))))
1864 (defun markdown-point-after-unwrap (cur prefix suffix)
1865 "Return desired position of point after an unwrapping operation.
1866 CUR gives the position of the point before the operation.
1867 Additionally, two cons cells must be provided. PREFIX gives the
1868 bounds of the prefix string and SUFFIX gives the bounds of the
1869 suffix string."
1870 (cond ((< cur (cdr prefix)) (car prefix))
1871 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1872 ((<= cur (cdr suffix))
1873 (- cur (+ (- (cdr prefix) (car prefix))
1874 (- cur (car suffix)))))
1875 (t cur)))
1877 (defun markdown-unwrap-thing-at-point (regexp all text)
1878 "Remove prefix and suffix of thing at point and reposition the point.
1879 When the thing at point matches REGEXP, replace the subexpression
1880 ALL with the string in subexpression TEXT. Reposition the point
1881 in an appropriate location accounting for the removal of prefix
1882 and suffix strings. Return new bounds of string from group TEXT.
1883 When REGEXP is nil, assumes match data is already set."
1884 (when (or (null regexp)
1885 (thing-at-point-looking-at regexp))
1886 (let ((cur (point))
1887 (prefix (cons (match-beginning all) (match-beginning text)))
1888 (suffix (cons (match-end text) (match-end all)))
1889 (bounds (cons (match-beginning text) (match-end text))))
1890 ;; Replace the thing at point
1891 (replace-match (match-string text) t t nil all)
1892 ;; Reposition the point
1893 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1894 ;; Adjust bounds
1895 (setq bounds (cons (car prefix)
1896 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1898 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1899 "Remove prefix and suffix of all things in region from BEG to END.
1900 When a thing in the region matches REGEXP, replace the
1901 subexpression ALL with the string in subexpression TEXT.
1902 Return a cons cell containing updated bounds for the region."
1903 (save-excursion
1904 (goto-char beg)
1905 (let ((removed 0) len-all len-text)
1906 (while (re-search-forward regexp (- end removed) t)
1907 (setq len-all (length (match-string-no-properties all)))
1908 (setq len-text (length (match-string-no-properties text)))
1909 (setq removed (+ removed (- len-all len-text)))
1910 (replace-match (match-string text) t t nil all))
1911 (cons beg (- end removed)))))
1913 (defun markdown-insert-hr (arg)
1914 "Insert or replace a horizonal rule.
1915 By default, use the first element of `markdown-hr-strings'. When
1916 ARG is non-nil, as when given a prefix, select a different
1917 element as follows. When prefixed with \\[universal-argument],
1918 use the last element of `markdown-hr-strings' instead. When
1919 prefixed with an integer from 1 to the length of
1920 `markdown-hr-strings', use the element in that position instead."
1921 (interactive "*P")
1922 (when (thing-at-point-looking-at markdown-regex-hr)
1923 (delete-region (match-beginning 0) (match-end 0)))
1924 (markdown-ensure-blank-line-before)
1925 (cond ((equal arg '(4))
1926 (insert (car (reverse markdown-hr-strings))))
1927 ((and (integerp arg) (> arg 0)
1928 (<= arg (length markdown-hr-strings)))
1929 (insert (nth (1- arg) markdown-hr-strings)))
1931 (insert (car markdown-hr-strings))))
1932 (markdown-ensure-blank-line-after))
1934 (defun markdown-insert-bold ()
1935 "Insert markup to make a region or word bold.
1936 If there is an active region, make the region bold. If the point
1937 is at a non-bold word, make the word bold. If the point is at a
1938 bold word or phrase, remove the bold markup. Otherwise, simply
1939 insert bold delimiters and place the cursor in between them."
1940 (interactive)
1941 (let ((delim (if markdown-bold-underscore "__" "**")))
1942 (if (markdown-use-region-p)
1943 ;; Active region
1944 (let ((bounds (markdown-unwrap-things-in-region
1945 (region-beginning) (region-end)
1946 markdown-regex-bold 2 4)))
1947 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1948 ;; Bold markup removal, bold word at point, or empty markup insertion
1949 (if (thing-at-point-looking-at markdown-regex-bold)
1950 (markdown-unwrap-thing-at-point nil 2 4)
1951 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1953 (defun markdown-insert-italic ()
1954 "Insert markup to make a region or word italic.
1955 If there is an active region, make the region italic. If the point
1956 is at a non-italic word, make the word italic. If the point is at an
1957 italic word or phrase, remove the italic markup. Otherwise, simply
1958 insert italic delimiters and place the cursor in between them."
1959 (interactive)
1960 (let ((delim (if markdown-italic-underscore "_" "*")))
1961 (if (markdown-use-region-p)
1962 ;; Active region
1963 (let ((bounds (markdown-unwrap-things-in-region
1964 (region-beginning) (region-end)
1965 markdown-regex-italic 2 4)))
1966 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1967 ;; Italic markup removal, italic word at point, or empty markup insertion
1968 (if (thing-at-point-looking-at markdown-regex-italic)
1969 (markdown-unwrap-thing-at-point nil 2 4)
1970 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1972 (defun markdown-insert-code ()
1973 "Insert markup to make a region or word an inline code fragment.
1974 If there is an active region, make the region an inline code
1975 fragment. If the point is at a word, make the word an inline
1976 code fragment. Otherwise, simply insert code delimiters and
1977 place the cursor in between them."
1978 (interactive)
1979 (if (markdown-use-region-p)
1980 ;; Active region
1981 (let ((bounds (markdown-unwrap-things-in-region
1982 (region-beginning) (region-end)
1983 markdown-regex-code 2 4)))
1984 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1985 ;; Code markup removal, code markup for word, or empty markup insertion
1986 (if (thing-at-point-looking-at markdown-regex-code)
1987 (markdown-unwrap-thing-at-point nil 2 4)
1988 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1990 (defun markdown-insert-link ()
1991 "Insert an inline link, using region or word as link text if possible.
1992 If there is an active region, use the region as the link text. If the
1993 point is at a word, use the word as the link text. In these cases, the
1994 point will be left at the position for inserting a URL. If there is no
1995 active region and the point is not at word, simply insert link markup and
1996 place the point in the position to enter link text."
1997 (interactive)
1998 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1999 (when bounds
2000 (goto-char (- (cdr bounds) 1)))))
2002 (defun markdown-insert-reference-link (text label &optional url title)
2003 "Insert a reference link and, optionally, a reference definition.
2004 The link TEXT will be inserted followed by the optional LABEL.
2005 If a URL is given, also insert a definition for the reference
2006 LABEL after the end of the paragraph. If a TITLE is given, it
2007 will be added to the end of the reference definition and will be
2008 used to populate the title attribute when converted to XHTML. If
2009 URL is nil, insert only the link portion (for example, when a
2010 reference label is already defined)."
2011 (insert (concat "[" text "][" label "]"))
2012 (when url
2013 (let ((end (point))
2014 (label (if (> (length label) 0) label text)))
2015 (cond
2016 ((eq markdown-reference-location 'end) (goto-char (point-max)))
2017 ((eq markdown-reference-location 'immediately) (markdown-end-of-block))
2018 ((eq markdown-reference-location 'header) (markdown-end-of-defun)))
2019 (unless (markdown-cur-line-blank-p) (insert "\n"))
2020 (insert "\n[" label "]: " url)
2021 (unless (> (length url) 0)
2022 (setq end (point)))
2023 (when (> (length title) 0)
2024 (insert " \"" title "\""))
2025 (insert "\n")
2026 (unless (or (eobp) (looking-at "\n"))
2027 (insert "\n"))
2028 (goto-char end)
2029 (when (> (length url) 0)
2030 (message
2031 (substitute-command-keys
2032 "Defined reference [%s], press \\[markdown-jump] to jump there")
2033 (or label text))))))
2035 (defun markdown-insert-reference-link-dwim ()
2036 "Insert a reference link of the form [text][label] at point.
2037 If there is an active region, the text in the region will be used
2038 as the link text. If the point is at a word, it will be used as
2039 the link text. Otherwise, the link text will be read from the
2040 minibuffer. The link label will be read from the minibuffer in
2041 both cases, with completion from the set of currently defined
2042 references. To create an implicit reference link, press RET to
2043 accept the default, an empty label. If the entered referenced
2044 label is not defined, additionally prompt for the URL
2045 and (optional) title. The reference definition is placed at the
2046 end of the current paragraph."
2047 (interactive)
2048 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2049 (markdown-get-defined-references)))
2050 (bounds (or (and (markdown-use-region-p)
2051 (cons (region-beginning) (region-end)))
2052 (markdown-bounds-of-thing-at-point 'word)))
2053 (text (if bounds
2054 (buffer-substring (car bounds) (cdr bounds))
2055 (read-string "Link Text: ")))
2056 (label (completing-read
2057 "Link Label (default: none): " defined-labels
2058 nil nil nil 'markdown-reference-label-history nil))
2059 (ref (markdown-reference-definition
2060 (concat "[" (if (> (length label) 0) label text) "]")))
2061 (url (unless ref (read-string "Link URL: ")))
2062 (title (when (> (length url) 0)
2063 (read-string "Link Title (optional): "))))
2064 (when bounds (delete-region (car bounds) (cdr bounds)))
2065 (markdown-insert-reference-link text label url title)))
2067 (defun markdown-insert-uri ()
2068 "Insert markup for an inline URI.
2069 If there is an active region, use it as the URI. If the point is
2070 at a URI, wrap it with angle brackets. If the point is at an
2071 inline URI, remove the angle brackets. Otherwise, simply insert
2072 angle brackets place the point between them."
2073 (interactive)
2074 (if (markdown-use-region-p)
2075 ;; Active region
2076 (let ((bounds (markdown-unwrap-things-in-region
2077 (region-beginning) (region-end)
2078 markdown-regex-angle-uri 0 2)))
2079 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
2080 ;; Markup removal, URI at point, or empty markup insertion
2081 (if (thing-at-point-looking-at markdown-regex-angle-uri)
2082 (markdown-unwrap-thing-at-point nil 0 2)
2083 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
2085 (defun markdown-insert-wiki-link ()
2086 "Insert a wiki link of the form [[WikiLink]].
2087 If Transient Mark mode is on and a region is active, it is used
2088 as the link text."
2089 (interactive)
2090 (markdown-wrap-or-insert "[[" "]]")
2091 (backward-char 2))
2093 (defun markdown-insert-image (&optional arg)
2094 "Insert image markup using region or word as alt text if possible.
2095 If there is an active region, use the region as the alt text. If the
2096 point is at a word, use the word as the alt text. In these cases, the
2097 point will be left at the position for inserting a URL. If there is no
2098 active region and the point is not at word, simply insert image markup and
2099 place the point in the position to enter alt text. If ARG is nil, insert
2100 inline image markup. Otherwise, insert reference image markup."
2101 (interactive "*P")
2102 (let ((bounds (if arg
2103 (markdown-wrap-or-insert "![" "][]")
2104 (markdown-wrap-or-insert "![" "]()"))))
2105 (when bounds
2106 (goto-char (- (cdr bounds) 1)))))
2108 (defun markdown-insert-reference-image ()
2109 "Insert reference-style image markup using region or word as alt text.
2110 Calls `markdown-insert-image' with prefix argument."
2111 (interactive)
2112 (markdown-insert-image t))
2114 (defun markdown-remove-header ()
2115 "Remove header markup if point is at a header.
2116 Return bounds of remaining header text if a header was removed
2117 and nil otherwise."
2118 (interactive "*")
2119 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2120 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2122 (defun markdown-insert-header (&optional level text setext)
2123 "Insert or replace header markup.
2124 The level of the header is specified by LEVEL and header text is
2125 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2126 default value is 1.
2127 When TEXT is nil, the header text is obtained as follows.
2128 If there is an active region, it is used as the header text.
2129 Otherwise, the current line will be used as the header text.
2130 If there is not an active region and the point is at a header,
2131 remove the header markup and replace with level N header.
2132 Otherwise, insert empty header markup and place the cursor in
2133 between.
2134 The style of the header will be atx (hash marks) unless
2135 SETEXT is non-nil, in which case a setext-style (underlined)
2136 header will be inserted."
2137 (interactive "p\nsHeader text: ")
2138 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2139 ;; Determine header text if not given
2140 (when (null text)
2141 (if (markdown-use-region-p)
2142 ;; Active region
2143 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2144 ;; No active region
2145 (markdown-remove-header)
2146 (setq text (delete-and-extract-region
2147 (line-beginning-position) (line-end-position)))
2148 (when (and setext (string-match "^[ \t]*$" text))
2149 (setq text (read-string "Header text: "))))
2150 (setq text (markdown-compress-whitespace-string text)))
2151 ;; Insertion with given text
2152 (markdown-ensure-blank-line-before)
2153 (let (hdr)
2154 (cond (setext
2155 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2156 (insert text "\n" hdr))
2158 (setq hdr (make-string level ?#))
2159 (insert hdr " " text " " hdr))))
2160 (markdown-ensure-blank-line-after)
2161 ;; Leave point at end of text
2162 (if setext
2163 (backward-char (1+ (length text)))
2164 (backward-char (1+ level))))
2166 (defun markdown-insert-header-dwim (&optional arg setext)
2167 "Insert or replace header markup.
2168 The level and type of the header are determined automatically by
2169 the type and level of the previous header, unless a prefix
2170 argument is given via ARG.
2171 With a numeric prefix valued 1 to 6, insert a header of the given
2172 level, with the type being determined automatically (note that
2173 only level 1 or 2 setext headers are possible).
2174 With \\[universal-argument], insert a level-one setext header.
2175 With \\[universal-argument] \\[universal-argument], insert a
2176 level two setext header.
2177 When SETEXT is non-nil, prefer setext-style headers when
2178 possible (levels one and two).
2180 When there is an active region, use it for the header text. When
2181 the point is at an existing header, change the type and level
2182 according to the rules above.
2183 Otherwise, if the line is not empty, create a header using the
2184 text on the current line as the header text.
2185 Finally, if the point is on a blank line, insert empty header
2186 markup (atx) or prompt for text (setext).
2187 See `markdown-insert-header' for more details about how the
2188 header text is determined."
2189 (interactive "*P")
2190 (let (level)
2191 (cond ((equal arg '(4)) ; level-one setext with C-u
2192 (setq setext t)
2193 (setq level 1))
2194 ((equal arg '(16)) ; level-two setext with C-u C-u
2195 (setq setext t)
2196 (setq level 2))
2197 (t ; automatic with numeric override
2198 (save-excursion
2199 (when (re-search-backward markdown-regex-header nil t)
2200 ;; level of previous header
2201 (setq level (markdown-outline-level))
2202 ;; match groups 1 and 2 indicate setext headers
2203 (setq setext (or setext (match-end 1) (match-end 3)))))
2204 ;; use prefix if given, or level of previous header
2205 (setq level (if arg (prefix-numeric-value arg) level))
2206 ;; setext headers must be level one or two
2207 (and level (setq setext (and setext (<= level 2))))))
2208 (markdown-insert-header level nil setext)))
2210 (defun markdown-insert-header-setext-dwim (&optional arg)
2211 "Insert or replace header markup, with preference for setext.
2212 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2213 (interactive "*P")
2214 (markdown-insert-header-dwim arg t))
2216 (defun markdown-insert-header-atx-1 ()
2217 "Insert a first level atx-style (hash mark) header.
2218 See `markdown-insert-header'."
2219 (interactive "*")
2220 (markdown-insert-header 1 nil nil))
2222 (defun markdown-insert-header-atx-2 ()
2223 "Insert a level two atx-style (hash mark) header.
2224 See `markdown-insert-header'."
2225 (interactive "*")
2226 (markdown-insert-header 2 nil nil))
2228 (defun markdown-insert-header-atx-3 ()
2229 "Insert a level three atx-style (hash mark) header.
2230 See `markdown-insert-header'."
2231 (interactive "*")
2232 (markdown-insert-header 3 nil nil))
2234 (defun markdown-insert-header-atx-4 ()
2235 "Insert a level four atx-style (hash mark) header.
2236 See `markdown-insert-header'."
2237 (interactive "*")
2238 (markdown-insert-header 4 nil nil))
2240 (defun markdown-insert-header-atx-5 ()
2241 "Insert a level five atx-style (hash mark) header.
2242 See `markdown-insert-header'."
2243 (interactive "*")
2244 (markdown-insert-header 5 nil nil))
2246 (defun markdown-insert-header-atx-6 ()
2247 "Insert a sixth level atx-style (hash mark) header.
2248 See `markdown-insert-header'."
2249 (interactive "*")
2250 (markdown-insert-header 6 nil nil))
2252 (defun markdown-insert-header-setext-1 ()
2253 "Insert a setext-style (underlined) first-level header.
2254 See `markdown-insert-header'."
2255 (interactive "*")
2256 (markdown-insert-header 1 nil t))
2258 (defun markdown-insert-header-setext-2 ()
2259 "Insert a setext-style (underlined) second-level header.
2260 See `markdown-insert-header'."
2261 (interactive "*")
2262 (markdown-insert-header 2 nil t))
2264 (defun markdown-blockquote-indentation (loc)
2265 "Return string containing necessary indentation for a blockquote at LOC.
2266 Also see `markdown-pre-indentation'."
2267 (save-excursion
2268 (goto-char loc)
2269 (let* ((list-level (length (markdown-calculate-list-levels)))
2270 (indent ""))
2271 (dotimes (count list-level indent)
2272 (setq indent (concat indent " "))))))
2274 (defun markdown-insert-blockquote ()
2275 "Start a blockquote section (or blockquote the region).
2276 If Transient Mark mode is on and a region is active, it is used as
2277 the blockquote text."
2278 (interactive)
2279 (if (markdown-use-region-p)
2280 (markdown-blockquote-region (region-beginning) (region-end))
2281 (markdown-ensure-blank-line-before)
2282 (insert (markdown-blockquote-indentation (point)) "> ")
2283 (markdown-ensure-blank-line-after)))
2285 (defun markdown-block-region (beg end prefix)
2286 "Format the region using a block prefix.
2287 Arguments BEG and END specify the beginning and end of the
2288 region. The characters PREFIX will appear at the beginning
2289 of each line."
2290 (save-excursion
2291 (let* ((end-marker (make-marker))
2292 (beg-marker (make-marker)))
2293 ;; Ensure blank line after and remove extra whitespace
2294 (goto-char end)
2295 (skip-syntax-backward "-")
2296 (set-marker end-marker (point))
2297 (delete-horizontal-space)
2298 (markdown-ensure-blank-line-after)
2299 ;; Ensure blank line before and remove extra whitespace
2300 (goto-char beg)
2301 (skip-syntax-forward "-")
2302 (delete-horizontal-space)
2303 (markdown-ensure-blank-line-before)
2304 (set-marker beg-marker (point))
2305 ;; Insert PREFIX before each line
2306 (goto-char beg-marker)
2307 (while (and (< (line-beginning-position) end-marker)
2308 (not (eobp)))
2309 (insert prefix)
2310 (forward-line)))))
2312 (defun markdown-blockquote-region (beg end)
2313 "Blockquote the region.
2314 Arguments BEG and END specify the beginning and end of the region."
2315 (interactive "*r")
2316 (markdown-block-region
2317 beg end (concat (markdown-blockquote-indentation
2318 (max (point-min) (1- beg))) "> ")))
2320 (defun markdown-pre-indentation (loc)
2321 "Return string containing necessary whitespace for a pre block at LOC.
2322 Also see `markdown-blockquote-indentation'."
2323 (save-excursion
2324 (goto-char loc)
2325 (let* ((list-level (length (markdown-calculate-list-levels)))
2326 indent)
2327 (dotimes (count (1+ list-level) indent)
2328 (setq indent (concat indent " "))))))
2330 (defun markdown-insert-pre ()
2331 "Start a preformatted section (or apply to the region).
2332 If Transient Mark mode is on and a region is active, it is marked
2333 as preformatted text."
2334 (interactive)
2335 (if (markdown-use-region-p)
2336 (markdown-pre-region (region-beginning) (region-end))
2337 (markdown-ensure-blank-line-before)
2338 (insert (markdown-pre-indentation (point)))
2339 (markdown-ensure-blank-line-after)))
2341 (defun markdown-pre-region (beg end)
2342 "Format the region as preformatted text.
2343 Arguments BEG and END specify the beginning and end of the region."
2344 (interactive "*r")
2345 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2346 (markdown-block-region beg end indent)))
2348 (defun markdown-insert-gfm-code-block (&optional lang)
2349 "Insert GFM code block for language LANG.
2350 If LANG is nil, the language will be queried from user. If a
2351 region is active, wrap this region with the markup instead. If
2352 the region boundaries are not on empty lines, these are added
2353 automatically in order to have the correct markup."
2354 (interactive "sProgramming language: ")
2355 (if (markdown-use-region-p)
2356 (let ((b (region-beginning)) (e (region-end)))
2357 (goto-char b)
2358 ;; if we're on a blank line, insert the quotes here, otherwise
2359 ;; add a new line first
2360 (unless (looking-at "\n")
2361 (newline)
2362 (forward-line -1)
2363 (setq e (1+ e)))
2364 (insert "```" lang)
2365 (goto-char (+ e 3 (length lang)))
2366 ;; if we're on a blank line, don't newline, otherwise the ```
2367 ;; should go on its own line
2368 (unless (looking-back "\n")
2369 (newline))
2370 (insert "```"))
2371 (insert "```" lang)
2372 (newline 2)
2373 (insert "```")
2374 (forward-line -1)))
2377 ;;; Footnotes ======================================================================
2379 (defun markdown-footnote-counter-inc ()
2380 "Increment `markdown-footnote-counter' and return the new value."
2381 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2382 (save-excursion
2383 (goto-char (point-min))
2384 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2385 (point-max) t)
2386 (let ((fn (string-to-number (match-string 1))))
2387 (when (> fn markdown-footnote-counter)
2388 (setq markdown-footnote-counter fn))))))
2389 (incf markdown-footnote-counter))
2391 (defun markdown-footnote-new ()
2392 "Insert footnote with a new number and move point to footnote definition."
2393 (interactive)
2394 (let ((fn (markdown-footnote-counter-inc)))
2395 (insert (format "[^%d]" fn))
2396 (markdown-footnote-text-find-new-location)
2397 (markdown-ensure-blank-line-before)
2398 (unless (markdown-cur-line-blank-p)
2399 (insert "\n"))
2400 (insert (format "[^%d]: " fn))
2401 (markdown-ensure-blank-line-after)))
2403 (defun markdown-footnote-text-find-new-location ()
2404 "Position the cursor at the proper location for a new footnote text."
2405 (cond
2406 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2407 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
2408 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2410 (defun markdown-footnote-kill ()
2411 "Kill the footnote at point.
2412 The footnote text is killed (and added to the kill ring), the
2413 footnote marker is deleted. Point has to be either at the
2414 footnote marker or in the footnote text."
2415 (interactive)
2416 (let (return-pos)
2417 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2418 (markdown-footnote-return) ; we first move to the marker
2419 (setq return-pos 'text)) ; and remember our return position
2420 (let ((marker (markdown-footnote-delete-marker)))
2421 (unless marker
2422 (error "Not at a footnote"))
2423 (let ((text-pos (markdown-footnote-find-text (car marker))))
2424 (unless text-pos
2425 (error "No text for footnote `%s'" (car marker)))
2426 (goto-char text-pos)
2427 (let ((pos (markdown-footnote-kill-text)))
2428 (setq return-pos
2429 (if (and pos (eq return-pos 'text))
2431 (cadr marker))))))
2432 (goto-char return-pos)))
2434 (defun markdown-footnote-delete-marker ()
2435 "Delete a footnote marker at point.
2436 Returns a list (ID START) containing the footnote ID and the
2437 start position of the marker before deletion. If no footnote
2438 marker was deleted, this function returns NIL."
2439 (let ((marker (markdown-footnote-marker-positions)))
2440 (when marker
2441 (delete-region (second marker) (third marker))
2442 (butlast marker))))
2444 (defun markdown-footnote-kill-text ()
2445 "Kill footnote text at point.
2446 Returns the start position of the footnote text before deletion,
2447 or NIL if point was not inside a footnote text.
2449 The killed text is placed in the kill ring (without the footnote
2450 number)."
2451 (let ((fn (markdown-footnote-text-positions)))
2452 (when fn
2453 (let ((text (delete-and-extract-region (second fn) (third fn))))
2454 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2455 (kill-new (match-string 1 text))
2456 (when (and (markdown-cur-line-blank-p)
2457 (markdown-prev-line-blank-p))
2458 (delete-region (1- (point)) (point)))
2459 (second fn)))))
2461 (defun markdown-footnote-goto-text ()
2462 "Jump to the text of the footnote at point."
2463 (interactive)
2464 (let ((fn (car (markdown-footnote-marker-positions))))
2465 (unless fn
2466 (error "Not at a footnote marker"))
2467 (let ((new-pos (markdown-footnote-find-text fn)))
2468 (unless new-pos
2469 (error "No definition found for footnote `%s'" fn))
2470 (goto-char new-pos))))
2472 (defun markdown-footnote-return ()
2473 "Return from a footnote to its footnote number in the main text."
2474 (interactive)
2475 (let ((fn (save-excursion
2476 (car (markdown-footnote-text-positions)))))
2477 (unless fn
2478 (error "Not in a footnote"))
2479 (let ((new-pos (markdown-footnote-find-marker fn)))
2480 (unless new-pos
2481 (error "Footnote marker `%s' not found" fn))
2482 (goto-char new-pos))))
2484 (defun markdown-footnote-find-marker (id)
2485 "Find the location of the footnote marker with ID.
2486 The actual buffer position returned is the position directly
2487 following the marker's closing bracket. If no marker is found,
2488 NIL is returned."
2489 (save-excursion
2490 (goto-char (point-min))
2491 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2492 (skip-chars-backward "^]")
2493 (point))))
2495 (defun markdown-footnote-find-text (id)
2496 "Find the location of the text of footnote ID.
2497 The actual buffer position returned is the position of the first
2498 character of the text, after the footnote's identifier. If no
2499 footnote text is found, NIL is returned."
2500 (save-excursion
2501 (goto-char (point-min))
2502 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2503 (skip-chars-forward "[ \t]")
2504 (point))))
2506 (defun markdown-footnote-marker-positions ()
2507 "Return the position and ID of the footnote marker point is on.
2508 The return value is a list (ID START END). If point is not on a
2509 footnote, NIL is returned."
2510 ;; first make sure we're at a footnote marker
2511 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2512 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2513 (save-excursion
2514 ;; move point between [ and ^:
2515 (if (looking-at "\\[")
2516 (forward-char 1)
2517 (skip-chars-backward "^["))
2518 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2519 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2521 (defun markdown-footnote-text-positions ()
2522 "Return the start and end positions of the footnote text point is in.
2523 The exact return value is a list of three elements: (ID START END).
2524 The start position is the position of the opening bracket
2525 of the footnote id. The end position is directly after the
2526 newline that ends the footnote. If point is not in a footnote,
2527 NIL is returned instead."
2528 (save-excursion
2529 (let ((fn (progn
2530 (backward-paragraph)
2531 ;; if we're in a multiparagraph footnote, we need to back up further
2532 (while (>= (markdown-next-line-indent) 4)
2533 (backward-paragraph))
2534 (forward-line)
2535 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2536 (list (match-string 1) (point))))))
2537 (when fn
2538 (while (progn
2539 (forward-paragraph)
2540 (>= (markdown-next-line-indent) 4)))
2541 (append fn (list (point)))))))
2544 ;;; Element Removal ===========================================================
2546 (defun markdown-kill-thing-at-point ()
2547 "Kill thing at point and add important text, without markup, to kill ring.
2548 Possible things to kill include (roughly in order of precedence):
2549 inline code, headers, horizonal rules, links (add link text to
2550 kill ring), images (add alt text to kill ring), angle uri, email
2551 addresses, bold, italics, reference definition (add URI to kill
2552 ring), footnote markers and text (kill both marker and text, add
2553 text to kill ring), and list items."
2554 (interactive "*")
2555 (let (val tmp)
2556 (cond
2557 ;; Inline code
2558 ((thing-at-point-looking-at markdown-regex-code)
2559 (kill-new (match-string 4))
2560 (delete-region (match-beginning 2) (match-end 2)))
2561 ;; ATX header
2562 ((thing-at-point-looking-at markdown-regex-header-atx)
2563 (kill-new (match-string 2))
2564 (delete-region (match-beginning 0) (match-end 0)))
2565 ;; Setext header
2566 ((thing-at-point-looking-at markdown-regex-header-setext)
2567 (kill-new (match-string 1))
2568 (delete-region (match-beginning 0) (match-end 0)))
2569 ;; Horizonal rule
2570 ((thing-at-point-looking-at markdown-regex-hr)
2571 (kill-new (match-string 0))
2572 (delete-region (match-beginning 0) (match-end 0)))
2573 ;; Inline link or image (add link or alt text to kill ring)
2574 ((thing-at-point-looking-at markdown-regex-link-inline)
2575 (kill-new (match-string 3))
2576 (delete-region (match-beginning 0) (match-end 0)))
2577 ;; Reference link or image (add link or alt text to kill ring)
2578 ((thing-at-point-looking-at markdown-regex-link-reference)
2579 (kill-new (match-string 3))
2580 (delete-region (match-beginning 0) (match-end 0)))
2581 ;; Angle URI (add URL to kill ring)
2582 ((thing-at-point-looking-at markdown-regex-angle-uri)
2583 (kill-new (match-string 2))
2584 (delete-region (match-beginning 0) (match-end 0)))
2585 ;; Email address in angle brackets (add email address to kill ring)
2586 ((thing-at-point-looking-at markdown-regex-email)
2587 (kill-new (match-string 1))
2588 (delete-region (match-beginning 0) (match-end 0)))
2589 ;; Wiki link (add alias text to kill ring)
2590 ((thing-at-point-looking-at markdown-regex-wiki-link)
2591 (kill-new (markdown-wiki-link-alias))
2592 (delete-region (match-beginning 1) (match-end 1)))
2593 ;; Bold
2594 ((thing-at-point-looking-at markdown-regex-bold)
2595 (kill-new (match-string 4))
2596 (delete-region (match-beginning 2) (match-end 2)))
2597 ;; Italics
2598 ((thing-at-point-looking-at markdown-regex-italic)
2599 (kill-new (match-string 4))
2600 (delete-region (match-beginning 2) (match-end 2)))
2601 ;; Footnote marker (add footnote text to kill ring)
2602 ((thing-at-point-looking-at markdown-regex-footnote)
2603 (markdown-footnote-kill))
2604 ;; Footnote text (add footnote text to kill ring)
2605 ((setq val (markdown-footnote-text-positions))
2606 (markdown-footnote-kill))
2607 ;; Reference definition (add URL to kill ring)
2608 ((thing-at-point-looking-at markdown-regex-reference-definition)
2609 (kill-new (match-string 2))
2610 (delete-region (match-beginning 0) (match-end 0)))
2611 ;; List item
2612 ((setq val (markdown-cur-list-item-bounds))
2613 (kill-new (delete-and-extract-region (first val) (second val))))
2615 (error "Nothing found at point to kill")))))
2618 ;;; Indentation ====================================================================
2620 (defun markdown-indent-find-next-position (cur-pos positions)
2621 "Return the position after the index of CUR-POS in POSITIONS.
2622 Positions are calculated by `markdown-calc-indents'."
2623 (while (and positions
2624 (not (equal cur-pos (car positions))))
2625 (setq positions (cdr positions)))
2626 (or (cadr positions) 0))
2628 (defun markdown-exdent-find-next-position (cur-pos positions)
2629 "Return the maximal element that precedes CUR-POS from POSITIONS.
2630 Positions are calculated by `markdown-calc-indents'."
2631 (let ((result 0))
2632 (dolist (i positions)
2633 (when (< i cur-pos)
2634 (setq result (max result i))))
2635 result))
2637 (defun markdown-indent-line ()
2638 "Indent the current line using some heuristics.
2639 If the _previous_ command was either `markdown-enter-key' or
2640 `markdown-cycle', then we should cycle to the next
2641 reasonable indentation position. Otherwise, we could have been
2642 called directly by `markdown-enter-key', by an initial call of
2643 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2644 these cases, indent to the default position.
2645 Positions are calculated by `markdown-calc-indents'."
2646 (interactive)
2647 (let ((positions (markdown-calc-indents))
2648 (cur-pos (current-column)))
2649 (if (not (equal this-command 'markdown-cycle))
2650 (indent-line-to (car positions))
2651 (setq positions (sort (delete-dups positions) '<))
2652 (indent-line-to
2653 (markdown-indent-find-next-position cur-pos positions)))))
2655 (defun markdown-calc-indents ()
2656 "Return a list of indentation columns to cycle through.
2657 The first element in the returned list should be considered the
2658 default indentation level. This function does not worry about
2659 duplicate positions, which are handled up by calling functions."
2660 (let (pos prev-line-pos positions)
2662 ;; Indentation of previous line
2663 (setq prev-line-pos (markdown-prev-line-indent))
2664 (setq positions (cons prev-line-pos positions))
2666 ;; Indentation of previous non-list-marker text
2667 (when (setq pos (markdown-prev-non-list-indent))
2668 (setq positions (cons pos positions)))
2670 ;; Indentation required for a pre block in current context
2671 (setq pos (length (markdown-pre-indentation (point))))
2672 (setq positions (cons pos positions))
2674 ;; Indentation of the previous line + tab-width
2675 (if prev-line-pos
2676 (setq positions (cons (+ prev-line-pos tab-width) positions))
2677 (setq positions (cons tab-width positions)))
2679 ;; Indentation of the previous line - tab-width
2680 (if (and prev-line-pos (> prev-line-pos tab-width))
2681 (setq positions (cons (- prev-line-pos tab-width) positions)))
2683 ;; Indentation of all preceeding list markers (when in a list)
2684 (when (setq pos (markdown-calculate-list-levels))
2685 (setq positions (append pos positions)))
2687 ;; First column
2688 (setq positions (cons 0 positions))
2690 ;; Return reversed list
2691 (reverse positions)))
2693 (defun markdown-do-normal-return ()
2694 "Insert a newline and optionally indent the next line."
2695 (newline)
2696 (if markdown-indent-on-enter
2697 (funcall indent-line-function)))
2699 (defun markdown-enter-key ()
2700 "Handle RET according to context.
2701 If there is a wiki link at the point, follow it unless
2702 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2703 it in the usual way."
2704 (interactive)
2705 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2706 (markdown-follow-wiki-link-at-point)
2707 (markdown-do-normal-return)))
2709 (defun markdown-exdent-or-delete (arg)
2710 "Handle BACKSPACE by cycling through indentation points.
2711 When BACKSPACE is pressed, if there is only whitespace
2712 before the current point, then exdent the line one level.
2713 Otherwise, do normal delete by repeating
2714 `backward-delete-char-untabify' ARG times."
2715 (interactive "*p")
2716 (let ((cur-pos (current-column))
2717 (start-of-indention (save-excursion
2718 (back-to-indentation)
2719 (current-column)))
2720 (positions (markdown-calc-indents)))
2721 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2722 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
2723 (backward-delete-char-untabify arg))))
2725 (defun markdown-find-leftmost-column (beg end)
2726 "Find the leftmost column in the region from BEG to END."
2727 (let ((mincol 1000))
2728 (save-excursion
2729 (goto-char beg)
2730 (while (< (point) end)
2731 (back-to-indentation)
2732 (unless (looking-at "[ \t]*$")
2733 (setq mincol (min mincol (current-column))))
2734 (forward-line 1)
2736 mincol))
2738 (defun markdown-indent-region (beg end arg)
2739 "Indent the region from BEG to END using some heuristics.
2740 When ARG is non-nil, exdent the region instead.
2741 See `markdown-indent-line' and `markdown-indent-line'."
2742 (interactive "*r\nP")
2743 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2744 (leftmostcol (markdown-find-leftmost-column beg end))
2745 (next-pos (if arg
2746 (markdown-exdent-find-next-position leftmostcol positions)
2747 (markdown-indent-find-next-position leftmostcol positions))))
2748 (indent-rigidly beg end (- next-pos leftmostcol))
2749 (setq deactivate-mark nil)))
2752 ;;; Markup Completion =========================================================
2754 (defconst markdown-complete-alist
2755 '((markdown-regex-header-atx . markdown-complete-atx)
2756 (markdown-regex-header-setext . markdown-complete-setext)
2757 (markdown-regex-hr . markdown-complete-hr))
2758 "Association list of form (regexp . function) for markup completion.")
2760 (defun markdown-incomplete-atx-p ()
2761 "Return t if ATX header markup is incomplete and nil otherwise.
2762 Assumes match data is available for `markdown-regex-header-atx'.
2763 Checks that the number of trailing hash marks equals the number of leading
2764 hash marks, that there is only a single space before and after the text,
2765 and that there is no extraneous whitespace in the text."
2766 (save-match-data
2768 ;; Number of starting and ending hash marks differs
2769 (not (= (length (match-string 1)) (length (match-string 3))))
2770 ;; When the header text is not empty...
2771 (and (> (length (match-string 2)) 0)
2772 ;; ...if there are extra leading, trailing, or interior spaces
2773 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2774 (not (= (match-beginning 3) (1+ (match-end 2))))
2775 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2776 ;; When the header text is empty...
2777 (and (= (length (match-string 2)) 0)
2778 ;; ...if there are too many or too few spaces
2779 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2781 (defun markdown-complete-atx ()
2782 "Complete and normalize ATX headers.
2783 Add or remove hash marks to the end of the header to match the
2784 beginning. Ensure that there is only a single space between hash
2785 marks and header text. Removes extraneous whitespace from header text.
2786 Assumes match data is available for `markdown-regex-header-atx'."
2787 (when (markdown-incomplete-atx-p)
2788 (let* ((new-marker (make-marker))
2789 (new-marker (set-marker new-marker (match-end 2))))
2790 ;; Hash marks and spacing at end
2791 (goto-char (match-end 2))
2792 (delete-region (match-end 2) (match-end 3))
2793 (insert " " (match-string 1))
2794 ;; Remove extraneous whitespace from title
2795 (replace-match (markdown-compress-whitespace-string (match-string 2))
2796 t t nil 2)
2797 ;; Spacing at beginning
2798 (goto-char (match-end 1))
2799 (delete-region (match-end 1) (match-beginning 2))
2800 (insert " ")
2801 ;; Leave point at end of text
2802 (goto-char new-marker))))
2804 (defun markdown-incomplete-setext-p ()
2805 "Return t if setext header markup is incomplete and nil otherwise.
2806 Assumes match data is available for `markdown-regex-header-setext'.
2807 Checks that length of underline matches text and that there is no
2808 extraneous whitespace in the text."
2809 (save-match-data
2810 (or (not (= (length (match-string 1)) (length (match-string 2))))
2811 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2813 (defun markdown-complete-setext ()
2814 "Complete and normalize setext headers.
2815 Add or remove underline characters to match length of header
2816 text. Removes extraneous whitespace from header text. Assumes
2817 match data is available for `markdown-regex-header-setext'."
2818 (when (markdown-incomplete-setext-p)
2819 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2820 (char (char-after (match-beginning 2)))
2821 (level (if (char-equal char ?-) 2 1)))
2822 (goto-char (match-beginning 0))
2823 (delete-region (match-beginning 0) (match-end 0))
2824 (markdown-insert-header level text t))))
2826 (defun markdown-incomplete-hr-p ()
2827 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2828 Assumes match data is available for `markdown-regex-hr'."
2829 (not (member (match-string 0) markdown-hr-strings)))
2831 (defun markdown-complete-hr ()
2832 "Complete horizontal rules.
2833 If horizontal rule string is a member of `markdown-hr-strings',
2834 do nothing. Otherwise, replace with the car of
2835 `markdown-hr-strings'.
2836 Assumes match data is available for `markdown-regex-hr'."
2837 (replace-match (car markdown-hr-strings)))
2839 (defun markdown-complete ()
2840 "Complete markup of object near point or in region when active.
2841 Handle all objects in `markdown-complete-alist', in order.
2842 See `markdown-complete-at-point' and `markdown-complete-region'."
2843 (interactive "*")
2844 (if (markdown-use-region-p)
2845 (markdown-complete-region (region-beginning) (region-end))
2846 (markdown-complete-at-point)))
2848 (defun markdown-complete-at-point ()
2849 "Complete markup of object near point.
2850 Handle all objects in `markdown-complete-alist', in
2851 order."
2852 (interactive "*")
2853 (loop for (regexp . function) in markdown-complete-alist
2854 until (thing-at-point-looking-at (eval regexp))
2855 finally (funcall function)))
2857 (defun markdown-complete-region (beg end)
2858 "Complete markup of objects in region from BEG to END.
2859 Handle all objects in `markdown-complete-alist', in
2860 order."
2861 (interactive "*r")
2862 (let* ((end-marker (make-marker))
2863 (end-marker (set-marker end-marker end)))
2864 (loop for (regexp . function) in markdown-complete-alist
2865 do (save-excursion
2866 (goto-char beg)
2867 (while (re-search-forward (eval regexp) end-marker t)
2868 (funcall function))))))
2870 (defun markdown-complete-buffer ()
2871 "Complete markup for all objects in the current buffer."
2872 (interactive "*")
2873 (markdown-complete-region (point-min) (point-max)))
2876 ;;; Markup Cycling ============================================================
2878 (defun markdown-cycle-atx (arg &optional remove)
2879 "Cycle ATX header markup.
2880 Promote header (decrease level) when ARG is 1 and demote
2881 header (increase level) if arg is -1. When REMOVE is non-nil,
2882 remove the header when the level reaches zero and stop cycling
2883 when it reaches six. Otherwise, perform a proper cycling through
2884 levels one through six. Assumes match data is available for
2885 `markdown-regex-header-atx'."
2886 (let* ((old-level (length (match-string 1)))
2887 (new-level (+ old-level arg))
2888 (text (match-string 2)))
2889 (when (not remove)
2890 (setq new-level (% new-level 6))
2891 (setq new-level (cond ((= new-level 0) 6)
2892 ((< new-level 0) (+ new-level 6))
2893 (t new-level))))
2894 (cond
2895 ((= new-level 0)
2896 (markdown-unwrap-thing-at-point nil 0 2))
2897 ((<= new-level 6)
2898 (goto-char (match-beginning 0))
2899 (delete-region (match-beginning 0) (match-end 0))
2900 (markdown-insert-header new-level text nil)))))
2902 (defun markdown-cycle-setext (arg &optional remove)
2903 "Cycle setext header markup.
2904 Promote header (increase level) when ARG is 1 and demote
2905 header (decrease level or remove) if arg is -1. When demoting a
2906 level-two setext header, replace with a level-three atx header.
2907 When REMOVE is non-nil, remove the header when the level reaches
2908 zero. Otherwise, cycle back to a level six atx header. Assumes
2909 match data is available for `markdown-regex-header-setext'."
2910 (let* ((char (char-after (match-beginning 2)))
2911 (old-level (if (char-equal char ?=) 1 2))
2912 (new-level (+ old-level arg))
2913 (text (match-string 1)))
2914 (when (and (not remove) (= new-level 0))
2915 (setq new-level 6))
2916 (cond
2917 ((= new-level 0)
2918 (markdown-unwrap-thing-at-point nil 0 1))
2919 ((<= new-level 2)
2920 (markdown-insert-header new-level nil t))
2921 ((<= new-level 6)
2922 (markdown-insert-header new-level nil nil)))))
2924 (defun markdown-cycle-hr (arg &optional remove)
2925 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2926 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
2927 backwards (promote). When REMOVE is non-nil, remove the hr instead
2928 of cycling when the end of the list is reached.
2929 Assumes match data is available for `markdown-regex-hr'."
2930 (let* ((strings (if (= arg -1)
2931 (reverse markdown-hr-strings)
2932 markdown-hr-strings))
2933 (tail (member (match-string 0) strings))
2934 (new (or (cadr tail)
2935 (if remove
2936 (if (= arg 1)
2938 (car tail))
2939 (car strings)))))
2940 (replace-match new)))
2942 (defun markdown-cycle-bold ()
2943 "Cycle bold markup between underscores and asterisks.
2944 Assumes match data is available for `markdown-regex-bold'."
2945 (save-excursion
2946 (let* ((old-delim (match-string 3))
2947 (new-delim (if (string-equal old-delim "**") "__" "**")))
2948 (replace-match new-delim t t nil 3)
2949 (replace-match new-delim t t nil 5))))
2951 (defun markdown-cycle-italic ()
2952 "Cycle italic markup between underscores and asterisks.
2953 Assumes match data is available for `markdown-regex-italic'."
2954 (save-excursion
2955 (let* ((old-delim (match-string 3))
2956 (new-delim (if (string-equal old-delim "*") "_" "*")))
2957 (replace-match new-delim t t nil 3)
2958 (replace-match new-delim t t nil 5))))
2961 ;;; Keymap ====================================================================
2963 (defvar markdown-mode-map
2964 (let ((map (make-keymap)))
2965 ;; Element insertion
2966 (define-key map (kbd "C-c l") 'markdown-insert-link)
2967 (define-key map (kbd "C-c L") 'markdown-insert-reference-link-dwim)
2968 (define-key map (kbd "C-c u") 'markdown-insert-uri)
2969 (define-key map (kbd "C-c w") 'markdown-insert-wiki-link)
2970 (define-key map (kbd "C-c i") 'markdown-insert-image)
2971 (define-key map (kbd "C-c I") 'markdown-insert-reference-image)
2972 (define-key map (kbd "C-c 1") 'markdown-insert-header-atx-1)
2973 (define-key map (kbd "C-c 2") 'markdown-insert-header-atx-2)
2974 (define-key map (kbd "C-c 3") 'markdown-insert-header-atx-3)
2975 (define-key map (kbd "C-c 4") 'markdown-insert-header-atx-4)
2976 (define-key map (kbd "C-c 5") 'markdown-insert-header-atx-5)
2977 (define-key map (kbd "C-c 6") 'markdown-insert-header-atx-6)
2978 (define-key map (kbd "C-c !") 'markdown-insert-header-setext-1)
2979 (define-key map (kbd "C-c @") 'markdown-insert-header-setext-2)
2980 (define-key map (kbd "C-c h") 'markdown-insert-header-dwim)
2981 (define-key map (kbd "C-c H") 'markdown-insert-header-setext-dwim)
2982 (define-key map (kbd "C-c s") 'markdown-insert-bold)
2983 (define-key map (kbd "C-c e") 'markdown-insert-italic)
2984 (define-key map (kbd "C-c c") 'markdown-insert-code)
2985 (define-key map (kbd "C-c b") 'markdown-insert-blockquote)
2986 (define-key map (kbd "C-c B") 'markdown-blockquote-region)
2987 (define-key map (kbd "C-c p") 'markdown-insert-pre)
2988 (define-key map (kbd "C-c P") 'markdown-pre-region)
2989 (define-key map (kbd "C-c -") 'markdown-insert-hr)
2990 (define-key map (kbd "C-c f") 'markdown-footnote-new)
2991 ;; Element removal
2992 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
2993 ;; Promotion, Demotion, Completion, and Cycling
2994 (define-key map (kbd "C-c C--") 'markdown-promote)
2995 (define-key map (kbd "C-c C-=") 'markdown-demote)
2996 (define-key map (kbd "M-<left>") 'markdown-promote)
2997 (define-key map (kbd "M-<right>") 'markdown-demote)
2998 (define-key map (kbd "C-c C-]") 'markdown-complete-or-cycle)
2999 (define-key map (kbd "C-c C-[") (kbd "C-u C-c C-]"))
3000 ;; Following and Jumping
3001 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
3002 (define-key map (kbd "C-c C-j") 'markdown-jump)
3003 ;; Indentation
3004 (define-key map (kbd "C-m") 'markdown-enter-key)
3005 (define-key map (kbd "<backspace>") 'markdown-exdent-or-delete)
3006 (define-key map (kbd "C-c >") 'markdown-indent-region)
3007 (define-key map (kbd "C-c <") (kbd "C-u C-c >"))
3008 ;; Visibility cycling
3009 (define-key map (kbd "<tab>") 'markdown-cycle)
3010 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
3011 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
3012 (define-key map (kbd "<backtab>") 'markdown-shifttab)
3013 ;; Header navigation
3014 (define-key map (kbd "C-c C-n") 'outline-next-visible-heading)
3015 (define-key map (kbd "C-c C-p") 'outline-previous-visible-heading)
3016 (define-key map (kbd "C-c C-f") 'outline-forward-same-level)
3017 (define-key map (kbd "C-c C-b") 'outline-backward-same-level)
3018 (define-key map (kbd "C-c C-u") 'outline-up-heading)
3019 ;; Buffer-wide commands
3020 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
3021 (define-key map (kbd "C-c C-c p") 'markdown-preview)
3022 (define-key map (kbd "C-c C-c e") 'markdown-export)
3023 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
3024 (define-key map (kbd "C-c C-c o") 'markdown-open)
3025 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
3026 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
3027 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
3028 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
3029 ;; List editing
3030 (define-key map (kbd "M-<up>") 'markdown-move-up)
3031 (define-key map (kbd "M-<down>") 'markdown-move-down)
3032 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
3033 ;; Movement
3034 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
3035 (define-key map (kbd "M-]") 'markdown-end-of-block)
3036 (define-key map (kbd "M-n") 'markdown-next-link)
3037 (define-key map (kbd "M-p") 'markdown-previous-link)
3038 map)
3039 "Keymap for Markdown major mode.")
3041 (defvar gfm-mode-map
3042 (let ((map (make-sparse-keymap)))
3043 (set-keymap-parent map markdown-mode-map)
3044 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
3045 map)
3046 "Keymap for `gfm-mode'.
3047 See also `markdown-mode-map'.")
3050 ;;; Menu ==================================================================
3052 (easy-menu-define markdown-mode-menu markdown-mode-map
3053 "Menu for Markdown mode"
3054 '("Markdown"
3055 ("Show/Hide"
3056 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
3057 ["Cycle global visibility" markdown-shifttab])
3058 "---"
3059 ["Compile" markdown-other-window]
3060 ["Preview" markdown-preview]
3061 ["Export" markdown-export]
3062 ["Export & View" markdown-export-and-preview]
3063 ["Open" markdown-open]
3064 ["Kill ring save" markdown-kill-ring-save]
3065 "---"
3066 ("Headers (setext)"
3067 ["First level" markdown-insert-setext-header-1]
3068 ["Second level" markdown-insert-setext-header-2])
3069 ("Headers (atx)"
3070 ["First level" markdown-insert-header-atx-1]
3071 ["Second level" markdown-insert-header-atx-2]
3072 ["Third level" markdown-insert-header-atx-3]
3073 ["Fourth level" markdown-insert-header-atx-4]
3074 ["Fifth level" markdown-insert-header-atx-5]
3075 ["Sixth level" markdown-insert-header-atx-6])
3076 "---"
3077 ["Bold" markdown-insert-bold]
3078 ["Italic" markdown-insert-italic]
3079 ["Blockquote" markdown-insert-blockquote]
3080 ["Preformatted" markdown-insert-pre]
3081 ["Code" markdown-insert-code]
3082 "---"
3083 ["Insert inline link" markdown-insert-link]
3084 ["Insert reference link" markdown-insert-reference-link-dwim]
3085 ["Insert image" markdown-insert-image]
3086 ["Insert horizontal rule" markdown-insert-hr]
3087 "---"
3088 ("Footnotes"
3089 ["Insert footnote" markdown-footnote-new]
3090 ["Jump to footnote text" markdown-footnote-goto-text]
3091 ["Return from footnote" markdown-footnote-return])
3092 "---"
3093 ["Check references" markdown-check-refs]
3094 ["Clean up list numbering" markdown-cleanup-list-numbers]
3095 "---"
3096 ["Version" markdown-show-version]
3100 ;;; imenu =====================================================================
3102 (defun markdown-imenu-create-index ()
3103 "Create and return an imenu index alist for the current buffer.
3104 See `imenu-create-index-function' and `imenu--index-alist' for details."
3105 (let* ((root '(nil . nil))
3106 cur-alist
3107 (cur-level 0)
3108 (empty-heading "-")
3109 (self-heading ".")
3110 hashes pos level heading)
3111 (save-excursion
3112 (goto-char (point-min))
3113 (while (re-search-forward markdown-regex-header (point-max) t)
3114 (cond
3115 ((setq heading (match-string-no-properties 1))
3116 (setq pos (match-beginning 1)
3117 level 1))
3118 ((setq heading (match-string-no-properties 3))
3119 (setq pos (match-beginning 3)
3120 level 2))
3121 ((setq hashes (match-string-no-properties 5))
3122 (setq heading (match-string-no-properties 6)
3123 pos (match-beginning 5)
3124 level (length hashes))))
3125 (let ((alist (list (cons heading pos))))
3126 (cond
3127 ((= cur-level level) ; new sibling
3128 (setcdr cur-alist alist)
3129 (setq cur-alist alist))
3130 ((< cur-level level) ; first child
3131 (dotimes (i (- level cur-level 1))
3132 (setq alist (list (cons empty-heading alist))))
3133 (if cur-alist
3134 (let* ((parent (car cur-alist))
3135 (self-pos (cdr parent)))
3136 (setcdr parent (cons (cons self-heading self-pos) alist)))
3137 (setcdr root alist)) ; primogenitor
3138 (setq cur-alist alist)
3139 (setq cur-level level))
3140 (t ; new sibling of an ancestor
3141 (let ((sibling-alist (last (cdr root))))
3142 (dotimes (i (1- level))
3143 (setq sibling-alist (last (cdar sibling-alist))))
3144 (setcdr sibling-alist alist)
3145 (setq cur-alist alist))
3146 (setq cur-level level)))))
3147 (cdr root))))
3150 ;;; References ================================================================
3152 (defun markdown-insert-reference-definition (ref &optional buffer)
3153 "Add blank REF definition to the end of BUFFER.
3154 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3155 (or buffer (setq buffer (current-buffer)))
3156 (with-current-buffer buffer
3157 (goto-char (point-max))
3158 (indent-new-comment-line)
3159 (insert (concat ref ": "))))
3161 (defun markdown-reference-goto-definition ()
3162 "Jump to the definition of the reference at point or create it."
3163 (interactive)
3164 (when (thing-at-point-looking-at markdown-regex-link-reference)
3165 (let* ((text (match-string-no-properties 2))
3166 (reference (match-string-no-properties 4))
3167 (target (downcase (if (string= reference "[]") text reference)))
3168 (loc (cadr (markdown-reference-definition target))))
3169 (if loc
3170 (goto-char loc)
3171 (markdown-insert-reference-definition target (current-buffer))))))
3173 (defun markdown-reference-find-links (reference)
3174 "Return a list of all links for REFERENCE.
3175 REFERENCE should include the surrounding square brackets like [this].
3176 Elements of the list have the form (text start line), where
3177 text is the link text, start is the location at the beginning of
3178 the link, and line is the line number on which the link appears."
3179 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3180 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3181 ref-quote ref-quote))
3182 links)
3183 (save-excursion
3184 (goto-char (point-min))
3185 (while (re-search-forward regexp nil t)
3186 (let* ((text (or (match-string-no-properties 1)
3187 (match-string-no-properties 2)))
3188 (start (match-beginning 0))
3189 (line (markdown-line-number-at-pos)))
3190 (add-to-list 'links (list text start line)))))
3191 links))
3193 (defun markdown-get-undefined-refs ()
3194 "Return a list of undefined Markdown references.
3195 Result is an alist of pairs (reference . occurrences), where
3196 occurrences is itself another alist of pairs (label . line-number).
3197 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3198 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3199 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3200 (let ((missing))
3201 (save-excursion
3202 (goto-char (point-min))
3203 (while
3204 (re-search-forward markdown-regex-link-reference nil t)
3205 (let* ((text (match-string-no-properties 2))
3206 (reference (match-string-no-properties 4))
3207 (target (downcase (if (string= reference "[]") text reference))))
3208 (unless (markdown-reference-definition target)
3209 (let ((entry (assoc target missing)))
3210 (if (not entry)
3211 (add-to-list 'missing (cons target
3212 (list (cons text (markdown-line-number-at-pos)))) t)
3213 (setcdr entry
3214 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3215 missing)))
3217 (defconst markdown-reference-check-buffer
3218 "*Undefined references for %buffer%*"
3219 "Pattern for name of buffer for listing undefined references.
3220 The string %buffer% will be replaced by the corresponding
3221 `markdown-mode' buffer name.")
3223 (defun markdown-reference-check-buffer (&optional buffer-name)
3224 "Name and return buffer for reference checking.
3225 BUFFER-NAME is the name of the main buffer being visited."
3226 (or buffer-name (setq buffer-name (buffer-name)))
3227 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3228 "%buffer%" buffer-name
3229 markdown-reference-check-buffer))))
3230 (with-current-buffer refbuf
3231 (when view-mode
3232 (View-exit-and-edit))
3233 (use-local-map button-buffer-map)
3234 (erase-buffer))
3235 refbuf))
3237 (defconst markdown-reference-links-buffer
3238 "*Reference links for %buffer%*"
3239 "Pattern for name of buffer for listing references.
3240 The string %buffer% will be replaced by the corresponding buffer name.")
3242 (defun markdown-reference-links-buffer (&optional buffer-name)
3243 "Name, setup, and return a buffer for listing links.
3244 BUFFER-NAME is the name of the main buffer being visited."
3245 (or buffer-name (setq buffer-name (buffer-name)))
3246 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3247 "%buffer%" buffer-name
3248 markdown-reference-links-buffer))))
3249 (with-current-buffer linkbuf
3250 (when view-mode
3251 (View-exit-and-edit))
3252 (use-local-map button-buffer-map)
3253 (erase-buffer))
3254 linkbuf))
3256 (when (markdown-use-buttons-p)
3257 ;; Add an empty Markdown reference definition to the end of buffer
3258 ;; specified in the 'target-buffer property. The reference name is
3259 ;; the button's label.
3260 (define-button-type 'markdown-undefined-reference-button
3261 'help-echo "mouse-1, RET: create definition for undefined reference"
3262 'follow-link t
3263 'face 'bold
3264 'action (lambda (b)
3265 (let ((buffer (button-get b 'target-buffer)))
3266 (markdown-insert-reference-definition (button-label b) buffer)
3267 (switch-to-buffer-other-window buffer)
3268 (goto-char (point-max))
3269 (markdown-check-refs t))))
3271 ;; Jump to line in buffer specified by 'target-buffer property.
3272 ;; Line number is button's 'line property.
3273 (define-button-type 'markdown-goto-line-button
3274 'help-echo "mouse-1, RET: go to line"
3275 'follow-link t
3276 'face 'italic
3277 'action (lambda (b)
3278 (message (button-get b 'buffer))
3279 (switch-to-buffer-other-window (button-get b 'target-buffer))
3280 ;; use call-interactively to silence compiler
3281 (let ((current-prefix-arg (button-get b 'target-line)))
3282 (call-interactively 'goto-line))))
3284 ;; Jumps to a particular link at location given by 'target-char
3285 ;; property in buffer given by 'target-buffer property.
3286 (define-button-type 'markdown-link-button
3287 'help-echo "mouse-1, RET: jump to location of link"
3288 'follow-link t
3289 'face 'bold
3290 'action (lambda (b)
3291 (let ((target (button-get b 'target-buffer))
3292 (loc (button-get b 'target-char)))
3293 (kill-buffer-and-window)
3294 (switch-to-buffer target)
3295 (goto-char loc)))))
3297 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3298 "Insert a button for creating REFERENCE in buffer OLDBUF.
3299 REFERENCE should be a list of the form (reference . occurrences),
3300 as by `markdown-get-undefined-refs'."
3301 (let ((label (car reference)))
3302 (if (markdown-use-buttons-p)
3303 ;; Create a reference button in Emacs 22
3304 (insert-button label
3305 :type 'markdown-undefined-reference-button
3306 'target-buffer oldbuf)
3307 ;; Insert reference as text in Emacs < 22
3308 (insert label))
3309 (insert " (")
3310 (dolist (occurrence (cdr reference))
3311 (let ((line (cdr occurrence)))
3312 (if (markdown-use-buttons-p)
3313 ;; Create a line number button in Emacs 22
3314 (insert-button (number-to-string line)
3315 :type 'markdown-goto-line-button
3316 'target-buffer oldbuf
3317 'target-line line)
3318 ;; Insert line number as text in Emacs < 22
3319 (insert (number-to-string line)))
3320 (insert " ")))
3321 (delete-char -1)
3322 (insert ")")
3323 (newline)))
3325 (defun markdown-insert-link-button (link oldbuf)
3326 "Insert a button for jumping to LINK in buffer OLDBUF.
3327 LINK should be a list of the form (text char line) containing
3328 the link text, location, and line number."
3329 (let ((label (first link))
3330 (char (second link))
3331 (line (third link)))
3332 (if (markdown-use-buttons-p)
3333 ;; Create a reference button in Emacs 22
3334 (insert-button label
3335 :type 'markdown-link-button
3336 'target-buffer oldbuf
3337 'target-char char)
3338 ;; Insert reference as text in Emacs < 22
3339 (insert label))
3340 (insert (format " (line %d)\n" line))))
3342 (defun markdown-reference-goto-link (&optional reference)
3343 "Jump to the location of the first use of REFERENCE."
3344 (interactive)
3345 (unless reference
3346 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3347 (setq reference (match-string-no-properties 1))
3348 (error "No reference definition at point")))
3349 (let ((links (markdown-reference-find-links reference)))
3350 (cond ((= (length links) 1)
3351 (goto-char (cadr (car links))))
3352 ((> (length links) 1)
3353 (let ((oldbuf (current-buffer))
3354 (linkbuf (markdown-reference-links-buffer)))
3355 (with-current-buffer linkbuf
3356 (insert "Links using reference " reference ":\n\n")
3357 (dolist (link (reverse links))
3358 (markdown-insert-link-button link oldbuf)))
3359 (view-buffer-other-window linkbuf)
3360 (goto-char (point-min))
3361 (forward-line 2)))
3363 (error "No links for reference %s" reference)))))
3365 (defun markdown-check-refs (&optional silent)
3366 "Show all undefined Markdown references in current `markdown-mode' buffer.
3367 If SILENT is non-nil, do not message anything when no undefined
3368 references found.
3369 Links which have empty reference definitions are considered to be
3370 defined."
3371 (interactive "P")
3372 (when (not (eq major-mode 'markdown-mode))
3373 (error "Not available in current mode"))
3374 (let ((oldbuf (current-buffer))
3375 (refs (markdown-get-undefined-refs))
3376 (refbuf (markdown-reference-check-buffer)))
3377 (if (null refs)
3378 (progn
3379 (when (not silent)
3380 (message "No undefined references found"))
3381 (kill-buffer refbuf))
3382 (with-current-buffer refbuf
3383 (insert "The following references are undefined:\n\n")
3384 (dolist (ref refs)
3385 (markdown-insert-undefined-reference-button ref oldbuf))
3386 (view-buffer-other-window refbuf)
3387 (goto-char (point-min))
3388 (forward-line 2)))))
3391 ;;; Lists =====================================================================
3393 (defun markdown-insert-list-item (&optional arg)
3394 "Insert a new list item.
3395 If the point is inside unordered list, insert a bullet mark. If
3396 the point is inside ordered list, insert the next number followed
3397 by a period. Use the previous list item to determine the amount
3398 of whitespace to place before and after list markers.
3400 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3401 decrease the indentation by one level.
3403 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3404 increase the indentation by one level."
3405 (interactive "p")
3406 (let (bounds item-indent marker indent new-indent new-loc)
3407 (save-match-data
3408 ;; Look for a list item on current or previous non-blank line
3409 (save-excursion
3410 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3411 (not (bobp))
3412 (markdown-cur-line-blank-p))
3413 (forward-line -1)))
3414 (when bounds
3415 (cond ((save-excursion
3416 (skip-chars-backward " \t")
3417 (looking-at markdown-regex-list))
3418 (beginning-of-line)
3419 (insert "\n")
3420 (forward-line -1))
3421 ((not (markdown-cur-line-blank-p))
3422 (newline)))
3423 (setq new-loc (point)))
3424 ;; Look ahead for a list item on next non-blank line
3425 (unless bounds
3426 (save-excursion
3427 (while (and (null bounds)
3428 (not (eobp))
3429 (markdown-cur-line-blank-p))
3430 (forward-line)
3431 (setq bounds (markdown-cur-list-item-bounds))))
3432 (when bounds
3433 (setq new-loc (point))
3434 (unless (markdown-cur-line-blank-p)
3435 (newline))))
3436 (if (not bounds)
3437 ;; When not in a list, start a new unordered one
3438 (progn
3439 (unless (markdown-cur-line-blank-p)
3440 (insert "\n"))
3441 (insert "* "))
3442 ;; Compute indentation for a new list item
3443 (setq item-indent (nth 2 bounds))
3444 (setq marker (nth 4 bounds))
3445 (setq indent (cond
3446 ((= arg 4) (max (- item-indent 4) 0))
3447 ((= arg 16) (+ item-indent 4))
3448 (t item-indent)))
3449 (setq new-indent (make-string indent 32))
3450 (goto-char new-loc)
3451 (cond
3452 ;; Ordered list
3453 ((string-match "[0-9]" marker)
3454 (if (= arg 16) ;; starting a new column indented one more level
3455 (insert (concat new-indent "1. "))
3456 ;; travel up to the last item and pick the correct number. If
3457 ;; the argument was nil, "new-indent = item-indent" is the same,
3458 ;; so we don't need special treatment. Neat.
3459 (save-excursion
3460 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3461 (forward-line -1)))
3462 (insert (concat new-indent
3463 (int-to-string (1+ (string-to-number (match-string 1))))
3464 ". "))))
3465 ;; Unordered list
3466 ((string-match "[\\*\\+-]" marker)
3467 (insert new-indent marker)))))))
3469 (defun markdown-move-list-item-up ()
3470 "Move the current list item up in the list when possible."
3471 (interactive)
3472 (let (cur prev old)
3473 (when (setq cur (markdown-cur-list-item-bounds))
3474 (setq old (point))
3475 (goto-char (nth 0 cur))
3476 (if (markdown-prev-list-item (nth 3 cur))
3477 (progn
3478 (setq prev (markdown-cur-list-item-bounds))
3479 (condition-case nil
3480 (progn
3481 (transpose-regions (nth 0 prev) (nth 1 prev)
3482 (nth 0 cur) (nth 1 cur) t)
3483 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3484 ;; Catch error in case regions overlap.
3485 (error (goto-char old))))
3486 (goto-char old)))))
3488 (defun markdown-move-list-item-down ()
3489 "Move the current list item down in the list when possible."
3490 (interactive)
3491 (let (cur next old)
3492 (when (setq cur (markdown-cur-list-item-bounds))
3493 (setq old (point))
3494 (if (markdown-next-list-item (nth 3 cur))
3495 (progn
3496 (setq next (markdown-cur-list-item-bounds))
3497 (condition-case nil
3498 (progn
3499 (transpose-regions (nth 0 cur) (nth 1 cur)
3500 (nth 0 next) (nth 1 next) nil)
3501 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3502 ;; Catch error in case regions overlap.
3503 (error (goto-char old))))
3504 (goto-char old)))))
3506 (defun markdown-demote-list-item (&optional bounds)
3507 "Indent (or demote) the current list item.
3508 Optionally, BOUNDS of the current list item may be provided if available."
3509 (interactive)
3510 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3511 (save-excursion
3512 (save-match-data
3513 (let* ((end-marker (make-marker))
3514 (end-marker (set-marker end-marker (nth 1 bounds))))
3515 (goto-char (nth 0 bounds))
3516 (while (< (point) end-marker)
3517 (unless (markdown-cur-line-blank-p)
3518 (insert " "))
3519 (forward-line)))))))
3521 (defun markdown-promote-list-item (&optional bounds)
3522 "Unindent (or promote) the current list item.
3523 Optionally, BOUNDS of the current list item may be provided if available."
3524 (interactive)
3525 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3526 (save-excursion
3527 (save-match-data
3528 (let* ((end-marker (make-marker))
3529 (end-marker (set-marker end-marker (nth 1 bounds)))
3530 num regexp)
3531 (goto-char (nth 0 bounds))
3532 (when (looking-at "^[ ]\\{1,4\\}")
3533 (setq num (- (match-end 0) (match-beginning 0)))
3534 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3535 (while (and (< (point) end-marker)
3536 (re-search-forward regexp end-marker t))
3537 (replace-match "" nil nil)
3538 (forward-line))))))))
3540 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3541 "Update the numbering for level PFX (as a string of spaces).
3543 Assume that the previously found match was for a numbered item in
3544 a list."
3545 (let ((cpfx pfx)
3546 (idx 0)
3547 (continue t)
3548 (step t)
3549 (sep nil))
3550 (while (and continue (not (eobp)))
3551 (setq step t)
3552 (cond
3553 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3554 (setq cpfx (match-string-no-properties 1))
3555 (cond
3556 ((string= cpfx pfx)
3557 (replace-match
3558 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3559 (setq sep nil))
3560 ;; indented a level
3561 ((string< pfx cpfx)
3562 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3563 (setq step nil))
3564 ;; exit the loop
3566 (setq step nil)
3567 (setq continue nil))))
3569 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3570 (setq cpfx (match-string-no-properties 1))
3571 (cond
3572 ;; reset if separated before
3573 ((string= cpfx pfx) (when sep (setq idx 0)))
3574 ((string< cpfx pfx)
3575 (setq step nil)
3576 (setq continue nil))))
3577 (t (setq sep t)))
3579 (when step
3580 (beginning-of-line)
3581 (setq continue (= (forward-line) 0))))
3582 sep))
3584 (defun markdown-cleanup-list-numbers ()
3585 "Update the numbering of ordered lists."
3586 (interactive)
3587 (save-excursion
3588 (goto-char (point-min))
3589 (markdown--cleanup-list-numbers-level "")))
3592 ;;; Outline ===================================================================
3594 (defvar markdown-cycle-global-status 1)
3595 (defvar markdown-cycle-subtree-status nil)
3597 (defun markdown-end-of-subtree (&optional invisible-OK)
3598 "Move to the end of the current subtree.
3599 Only visible heading lines are considered, unless INVISIBLE-OK is
3600 non-nil.
3601 Derived from `org-end-of-subtree'."
3602 (outline-back-to-heading invisible-OK)
3603 (let ((first t)
3604 (level (funcall outline-level)))
3605 (while (and (not (eobp))
3606 (or first (> (funcall outline-level) level)))
3607 (setq first nil)
3608 (outline-next-heading))
3609 (if (memq (preceding-char) '(?\n ?\^M))
3610 (progn
3611 ;; Go to end of line before heading
3612 (forward-char -1)
3613 (if (memq (preceding-char) '(?\n ?\^M))
3614 ;; leave blank line before heading
3615 (forward-char -1)))))
3616 (point))
3618 (defun markdown-cycle (&optional arg)
3619 "Visibility cycling for Markdown mode.
3620 If ARG is t, perform global visibility cycling. If the point is
3621 at an atx-style header, cycle visibility of the corresponding
3622 subtree. Otherwise, insert a tab using `indent-relative'.
3623 Derived from `org-cycle'."
3624 (interactive "P")
3625 (cond
3626 ((eq arg t) ;; Global cycling
3627 (cond
3628 ((and (eq last-command this-command)
3629 (eq markdown-cycle-global-status 2))
3630 ;; Move from overview to contents
3631 (hide-sublevels 1)
3632 (message "CONTENTS")
3633 (setq markdown-cycle-global-status 3))
3635 ((and (eq last-command this-command)
3636 (eq markdown-cycle-global-status 3))
3637 ;; Move from contents to all
3638 (show-all)
3639 (message "SHOW ALL")
3640 (setq markdown-cycle-global-status 1))
3643 ;; Defaults to overview
3644 (hide-body)
3645 (message "OVERVIEW")
3646 (setq markdown-cycle-global-status 2))))
3648 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3649 ;; At a heading: rotate between three different views
3650 (outline-back-to-heading)
3651 (let ((goal-column 0) eoh eol eos)
3652 ;; Determine boundaries
3653 (save-excursion
3654 (outline-back-to-heading)
3655 (save-excursion
3656 (beginning-of-line 2)
3657 (while (and (not (eobp)) ;; this is like `next-line'
3658 (get-char-property (1- (point)) 'invisible))
3659 (beginning-of-line 2)) (setq eol (point)))
3660 (outline-end-of-heading) (setq eoh (point))
3661 (markdown-end-of-subtree t)
3662 (skip-chars-forward " \t\n")
3663 (beginning-of-line 1) ; in case this is an item
3664 (setq eos (1- (point))))
3665 ;; Find out what to do next and set `this-command'
3666 (cond
3667 ((= eos eoh)
3668 ;; Nothing is hidden behind this heading
3669 (message "EMPTY ENTRY")
3670 (setq markdown-cycle-subtree-status nil))
3671 ((>= eol eos)
3672 ;; Entire subtree is hidden in one line: open it
3673 (show-entry)
3674 (show-children)
3675 (message "CHILDREN")
3676 (setq markdown-cycle-subtree-status 'children))
3677 ((and (eq last-command this-command)
3678 (eq markdown-cycle-subtree-status 'children))
3679 ;; We just showed the children, now show everything.
3680 (show-subtree)
3681 (message "SUBTREE")
3682 (setq markdown-cycle-subtree-status 'subtree))
3684 ;; Default action: hide the subtree.
3685 (hide-subtree)
3686 (message "FOLDED")
3687 (setq markdown-cycle-subtree-status 'folded)))))
3690 (indent-for-tab-command))))
3692 (defun markdown-shifttab ()
3693 "Global visibility cycling.
3694 Calls `markdown-cycle' with argument t."
3695 (interactive)
3696 (markdown-cycle t))
3698 (defun markdown-outline-level ()
3699 "Return the depth to which a statement is nested in the outline."
3700 (cond
3701 ((match-end 1) 1)
3702 ((match-end 3) 2)
3703 ((- (match-end 5) (match-beginning 5)))))
3706 ;;; Movement ==================================================================
3708 (defun markdown-beginning-of-defun (&optional arg)
3709 "`beginning-of-defun-function' for Markdown.
3710 Move backward to the beginning of the current or previous section.
3711 When ARG is non-nil, repeat that many times. When ARG is negative,
3712 move forward to the ARG-th following section."
3713 (interactive "P")
3714 (or arg (setq arg 1))
3715 (or (re-search-backward markdown-regex-header nil t arg)
3716 (goto-char (point-min))))
3718 (defun markdown-end-of-defun (&optional arg)
3719 "`end-of-defun-function' for Markdown.
3720 Move forward to the end of the current or following section.
3721 When ARG is non-nil, repeat that many times. When ARG is negative,
3722 move back to the ARG-th preceding section."
3723 (interactive "P")
3724 (or arg (setq arg 1))
3725 (when (looking-at markdown-regex-header)
3726 (goto-char (match-beginning 0))
3727 (forward-char 1))
3728 (if (re-search-forward markdown-regex-header nil t arg)
3729 (goto-char (match-beginning 0))
3730 (goto-char (point-max)))
3731 (skip-syntax-backward "-"))
3733 (defun markdown-beginning-of-block ()
3734 "Move the point to the start of the previous text block."
3735 (interactive)
3736 (if (re-search-backward markdown-regex-block-separator nil t)
3737 (goto-char (or (match-end 2) (match-end 0)))
3738 (goto-char (point-min))))
3740 (defun markdown-end-of-block ()
3741 "Move the point to the start of the next text block."
3742 (interactive)
3743 (beginning-of-line)
3744 (skip-syntax-forward "-")
3745 (when (= (point) (point-min))
3746 (forward-char))
3747 (if (re-search-forward markdown-regex-block-separator nil t)
3748 (goto-char (or (match-end 2) (match-end 0)))
3749 (goto-char (point-max)))
3750 (skip-syntax-backward "-")
3751 (forward-line))
3753 (defun markdown-end-of-block-element ()
3754 "Move the point to the start of the next block unit.
3755 Stops at blank lines, list items, headers, and horizontal rules."
3756 (interactive)
3757 (forward-line)
3758 (while (and (or (not (markdown-prev-line-blank-p))
3759 (markdown-cur-line-blank-p))
3760 (not (or (looking-at markdown-regex-list)
3761 (looking-at markdown-regex-header)
3762 (looking-at markdown-regex-hr)))
3763 (not (eobp)))
3764 (forward-line)))
3766 (defun markdown-next-link ()
3767 "Jump to next inline, reference, or wiki link.
3768 If successful, return point. Otherwise, return nil.
3769 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3770 (interactive)
3771 (let ((opoint (point)))
3772 (when (or (markdown-link-p) (markdown-wiki-link-p))
3773 ;; At a link already, move past it.
3774 (goto-char (+ (match-end 0) 1)))
3775 ;; Search for the next wiki link and move to the beginning.
3776 (if (re-search-forward markdown-regex-link-generic nil t)
3777 ;; Group 1 will move past non-escape character in wiki link regexp.
3778 ;; Go to beginning of group zero for all other link types.
3779 (goto-char (or (match-beginning 1) (match-beginning 0)))
3780 (goto-char opoint)
3781 nil)))
3783 (defun markdown-previous-link ()
3784 "Jump to previous wiki link.
3785 If successful, return point. Otherwise, return nil.
3786 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3787 (interactive)
3788 (if (re-search-backward markdown-regex-link-generic nil t)
3789 (goto-char (or (match-beginning 1) (match-beginning 0)))
3790 nil))
3793 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3795 (defun markdown-move-up ()
3796 "Move list item up.
3797 Calls `markdown-move-list-item-up'."
3798 (interactive)
3799 (markdown-move-list-item-up))
3801 (defun markdown-move-down ()
3802 "Move list item down.
3803 Calls `markdown-move-list-item-down'."
3804 (interactive)
3805 (markdown-move-list-item-down))
3807 (defun markdown-promote ()
3808 "Either promote header or list item at point or cycle markup.
3809 See `markdown-cycle-atx', `markdown-cycle-setext', and
3810 `markdown-demote-list-item'."
3811 (interactive)
3812 (let (bounds)
3813 (cond
3814 ;; Promote atx header
3815 ((thing-at-point-looking-at markdown-regex-header-atx)
3816 (markdown-cycle-atx -1 t))
3817 ;; Promote setext header
3818 ((thing-at-point-looking-at markdown-regex-header-setext)
3819 (markdown-cycle-setext -1 t))
3820 ;; Promote horizonal rule
3821 ((thing-at-point-looking-at markdown-regex-hr)
3822 (markdown-cycle-hr -1 t))
3823 ;; Promote list item
3824 ((setq bounds (markdown-cur-list-item-bounds))
3825 (markdown-promote-list-item)))))
3827 (defun markdown-demote ()
3828 "Either demote header or list item at point or cycle or remove markup.
3829 See `markdown-cycle-atx', `markdown-cycle-setext', and
3830 `markdown-demote-list-item'."
3831 (interactive)
3832 (let (bounds)
3833 (cond
3834 ;; Demote atx header
3835 ((thing-at-point-looking-at markdown-regex-header-atx)
3836 (markdown-cycle-atx 1 t))
3837 ;; Demote setext header
3838 ((thing-at-point-looking-at markdown-regex-header-setext)
3839 (markdown-cycle-setext 1 t))
3840 ;; Demote horizonal rule
3841 ((thing-at-point-looking-at markdown-regex-hr)
3842 (markdown-cycle-hr 1 t))
3843 ;; Promote list item
3844 ((setq bounds (markdown-cur-list-item-bounds))
3845 (markdown-demote-list-item))
3846 ;; Create a new level one ATX header
3848 (markdown-insert-header-atx-1)))))
3850 (defun markdown-complete-or-cycle (arg)
3851 "Complete or cycle markup of object at point or complete objects in region.
3852 If there is an active region, complete markup in region.
3853 Otherwise, complete or cycle markup of object near point.
3854 When ARG is non-nil, cycle backwards when cycling."
3855 (interactive "*P")
3856 (if (markdown-use-region-p)
3857 ;; Complete markup in region
3858 (markdown-complete-region (region-beginning) (region-end))
3859 ;; Complete or cycle markup at point
3860 (let ((dir (if arg -1 1))
3861 bounds)
3862 (cond
3863 ;; atx header
3864 ((thing-at-point-looking-at markdown-regex-header-atx)
3865 (if (markdown-incomplete-atx-p)
3866 (markdown-complete-atx)
3867 (markdown-cycle-atx dir)))
3868 ;; setext header
3869 ((thing-at-point-looking-at markdown-regex-header-setext)
3870 (if (markdown-incomplete-setext-p)
3871 (markdown-complete-setext)
3872 (markdown-cycle-setext dir)))
3873 ;; horizonal rule
3874 ((thing-at-point-looking-at markdown-regex-hr)
3875 (if (markdown-incomplete-hr-p)
3876 (markdown-complete-hr)
3877 (markdown-cycle-hr dir)))
3878 ;; bold
3879 ((thing-at-point-looking-at markdown-regex-bold)
3880 (markdown-cycle-bold))
3881 ;; italic
3882 ((thing-at-point-looking-at markdown-regex-italic)
3883 (markdown-cycle-italic))))))
3886 ;;; Commands ==================================================================
3888 (defun markdown (&optional output-buffer-name)
3889 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3890 The output buffer name defaults to `markdown-output-buffer-name'.
3891 Return the name of the output buffer used."
3892 (interactive)
3893 (save-window-excursion
3894 (let ((begin-region)
3895 (end-region))
3896 (if (markdown-use-region-p)
3897 (setq begin-region (region-beginning)
3898 end-region (region-end))
3899 (setq begin-region (point-min)
3900 end-region (point-max)))
3902 (unless output-buffer-name
3903 (setq output-buffer-name markdown-output-buffer-name))
3905 (cond
3906 ;; Handle case when `markdown-command' does not read from stdin
3907 (markdown-command-needs-filename
3908 (if (not buffer-file-name)
3909 (error "Must be visiting a file")
3910 (shell-command (concat markdown-command " "
3911 (shell-quote-argument buffer-file-name))
3912 output-buffer-name)))
3913 ;; Pass region to `markdown-command' via stdin
3915 (shell-command-on-region begin-region end-region markdown-command
3916 output-buffer-name))))
3917 output-buffer-name))
3919 (defun markdown-standalone (&optional output-buffer-name)
3920 "Special function to provide standalone HTML output.
3921 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3922 (interactive)
3923 (setq output-buffer-name (markdown output-buffer-name))
3924 (with-current-buffer output-buffer-name
3925 (set-buffer output-buffer-name)
3926 (goto-char (point-min))
3927 (unless (markdown-output-standalone-p)
3928 (markdown-add-xhtml-header-and-footer output-buffer-name))
3929 (html-mode))
3930 output-buffer-name)
3932 (defun markdown-other-window (&optional output-buffer-name)
3933 "Run `markdown-command' on current buffer and display in other window.
3934 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3935 that name."
3936 (interactive)
3937 (display-buffer (markdown-standalone output-buffer-name)))
3939 (defun markdown-output-standalone-p ()
3940 "Determine whether `markdown-command' output is standalone XHTML.
3941 Standalone XHTML output is identified by an occurrence of
3942 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3943 (re-search-forward
3944 markdown-xhtml-standalone-regexp
3945 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3948 (defun markdown-add-xhtml-header-and-footer (title)
3949 "Wrap XHTML header and footer with given TITLE around current buffer."
3950 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3951 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3952 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3953 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3954 "<head>\n<title>")
3955 (insert title)
3956 (insert "</title>\n")
3957 (when (> (length markdown-content-type) 0)
3958 (insert
3959 (format
3960 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3961 markdown-content-type
3962 (or (and markdown-coding-system
3963 (fboundp 'coding-system-get)
3964 (coding-system-get markdown-coding-system
3965 'mime-charset))
3966 (and (fboundp 'coding-system-get)
3967 (coding-system-get buffer-file-coding-system
3968 'mime-charset))
3969 "iso-8859-1"))))
3970 (if (> (length markdown-css-path) 0)
3971 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3972 markdown-css-path
3973 "\" />\n"))
3974 (when (> (length markdown-xhtml-header-content) 0)
3975 (insert markdown-xhtml-header-content))
3976 (insert "\n</head>\n\n"
3977 "<body>\n\n")
3978 (goto-char (point-max))
3979 (insert "\n"
3980 "</body>\n"
3981 "</html>\n"))
3983 (defun markdown-preview (&optional output-buffer-name)
3984 "Run `markdown-command' on the current buffer and view output in browser.
3985 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3986 that name."
3987 (interactive)
3988 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3990 (defun markdown-export-file-name (&optional extension)
3991 "Attempt to generate a filename for Markdown output.
3992 The file extension will be EXTENSION if given, or .html by default.
3993 If the current buffer is visiting a file, we construct a new
3994 output filename based on that filename. Otherwise, return nil."
3995 (when (buffer-file-name)
3996 (unless extension
3997 (setq extension ".html"))
3998 (concat
3999 (cond
4000 ((buffer-file-name)
4001 (file-name-sans-extension (buffer-file-name)))
4002 (t (buffer-name)))
4003 extension)))
4005 (defun markdown-export (&optional output-file)
4006 "Run Markdown on the current buffer, save to file, and return the filename.
4007 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4008 generated by `markdown-export-file-name', which will be constructed using the
4009 current filename, but with the extension removed and replaced with .html."
4010 (interactive)
4011 (unless output-file
4012 (setq output-file (markdown-export-file-name ".html")))
4013 (when output-file
4014 (let ((output-buffer-name))
4015 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
4016 (run-hook-with-args 'markdown-before-export-hooks output-file)
4017 (markdown-standalone output-buffer-name)
4018 (with-current-buffer output-buffer-name
4019 (save-buffer))
4020 (run-hook-with-args 'markdown-after-export-hooks output-file)
4021 output-file)))
4023 (defun markdown-export-and-preview ()
4024 "Export to XHTML using `markdown-export' and browse the resulting file."
4025 (interactive)
4026 (browse-url (markdown-export)))
4028 (defun markdown-open ()
4029 "Open file for the current buffer with `markdown-open-command'."
4030 (interactive)
4031 (if (not markdown-open-command)
4032 (error "Variable `markdown-open-command' must be set")
4033 (if (not buffer-file-name)
4034 (error "Must be visiting a file")
4035 (call-process markdown-open-command
4036 nil nil nil buffer-file-name))))
4038 (defun markdown-kill-ring-save ()
4039 "Run Markdown on file and store output in the kill ring."
4040 (interactive)
4041 (save-window-excursion
4042 (markdown)
4043 (with-current-buffer markdown-output-buffer-name
4044 (kill-ring-save (point-min) (point-max)))))
4047 ;;; Links =====================================================================
4049 (require 'thingatpt)
4051 (defun markdown-link-p ()
4052 "Return non-nil when `point' is at a non-wiki link.
4053 See `markdown-wiki-link-p' for more information."
4054 (let ((case-fold-search nil))
4055 (and (not (markdown-wiki-link-p))
4056 (or (thing-at-point-looking-at markdown-regex-link-inline)
4057 (thing-at-point-looking-at markdown-regex-link-reference)
4058 (thing-at-point-looking-at markdown-regex-uri)
4059 (thing-at-point-looking-at markdown-regex-angle-uri)))))
4061 (defun markdown-link-link ()
4062 "Return the link part of the regular (non-wiki) link at point.
4063 Works with both inline and reference style links. If point is
4064 not at a link or the link reference is not defined returns nil."
4065 (cond
4066 ((thing-at-point-looking-at markdown-regex-link-inline)
4067 (match-string-no-properties 5))
4068 ((thing-at-point-looking-at markdown-regex-link-reference)
4069 (let* ((text (match-string-no-properties 2))
4070 (reference (match-string-no-properties 4))
4071 (target (downcase (if (string= reference "[]") text reference))))
4072 (car (markdown-reference-definition target))))
4073 ((thing-at-point-looking-at markdown-regex-uri)
4074 (match-string-no-properties 0))
4075 ((thing-at-point-looking-at markdown-regex-angle-uri)
4076 (match-string-no-properties 2))
4077 (t nil)))
4079 (defun markdown-follow-link-at-point ()
4080 "Open the current non-wiki link in a browser."
4081 (interactive)
4082 (if (markdown-link-p) (browse-url (markdown-link-link))
4083 (error "Point is not at a Markdown link or URI")))
4086 ;;; WikiLink Following/Markup =================================================
4088 (defun markdown-wiki-link-p ()
4089 "Return non-nil when `point' is at a true wiki link.
4090 A true wiki link name matches `markdown-regex-wiki-link' but does not
4091 match the current file name after conversion. This modifies the data
4092 returned by `match-data'. Note that the potential wiki link name must
4093 be available via `match-string'."
4094 (let ((case-fold-search nil))
4095 (and (thing-at-point-looking-at markdown-regex-wiki-link)
4096 (or (not buffer-file-name)
4097 (not (string-equal (buffer-file-name)
4098 (markdown-convert-wiki-link-to-filename
4099 (markdown-wiki-link-link)))))
4100 (not (save-match-data
4101 (save-excursion))))))
4103 (defun markdown-wiki-link-link ()
4104 "Return the link part of the wiki link using current match data.
4105 The location of the link component depends on the value of
4106 `markdown-wiki-link-alias-first'."
4107 (if markdown-wiki-link-alias-first
4108 (or (match-string-no-properties 4) (match-string-no-properties 2))
4109 (match-string-no-properties 2)))
4111 (defun markdown-wiki-link-alias ()
4112 "Return the alias or text part of the wiki link using current match data.
4113 The location of the alias component depends on the value of
4114 `markdown-wiki-link-alias-first'."
4115 (if markdown-wiki-link-alias-first
4116 (match-string-no-properties 2)
4117 (or (match-string-no-properties 4) (match-string-no-properties 2))))
4119 (defun markdown-convert-wiki-link-to-filename (name)
4120 "Generate a filename from the wiki link NAME.
4121 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4122 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4123 and [[test test]] both map to Test-test.ext."
4124 (let ((basename (markdown-replace-regexp-in-string
4125 "[[:space:]\n]" markdown-link-space-sub-char name)))
4126 (when (eq major-mode 'gfm-mode)
4127 (setq basename (concat (upcase (substring basename 0 1))
4128 (downcase (substring basename 1 nil)))))
4129 (concat basename
4130 (if (buffer-file-name)
4131 (concat "."
4132 (file-name-extension (buffer-file-name)))))))
4134 (defun markdown-follow-wiki-link (name &optional other)
4135 "Follow the wiki link NAME.
4136 Convert the name to a file name and call `find-file'. Ensure that
4137 the new buffer remains in `markdown-mode'. Open the link in another
4138 window when OTHER is non-nil."
4139 (let ((filename (markdown-convert-wiki-link-to-filename name))
4140 (wp (file-name-directory buffer-file-name)))
4141 (when other (other-window 1))
4142 (find-file (concat wp filename)))
4143 (when (not (eq major-mode 'markdown-mode))
4144 (markdown-mode)))
4146 (defun markdown-follow-wiki-link-at-point (&optional arg)
4147 "Find Wiki Link at point.
4148 With prefix argument ARG, open the file in other window.
4149 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4150 (interactive "P")
4151 (if (markdown-wiki-link-p)
4152 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4153 (error "Point is not at a Wiki Link")))
4155 (defun markdown-highlight-wiki-link (from to face)
4156 "Highlight the wiki link in the region between FROM and TO using FACE."
4157 (put-text-property from to 'font-lock-face face))
4159 (defun markdown-unfontify-region-wiki-links (from to)
4160 "Remove wiki link faces from the region specified by FROM and TO."
4161 (interactive "nfrom: \nnto: ")
4162 (remove-text-properties from to '(font-lock-face markdown-link-face))
4163 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4165 (defun markdown-fontify-region-wiki-links (from to)
4166 "Search region given by FROM and TO for wiki links and fontify them.
4167 If a wiki link is found check to see if the backing file exists
4168 and highlight accordingly."
4169 (goto-char from)
4170 (save-match-data
4171 (while (re-search-forward markdown-regex-wiki-link to t)
4172 (let ((highlight-beginning (match-beginning 1))
4173 (highlight-end (match-end 1))
4174 (file-name
4175 (markdown-convert-wiki-link-to-filename
4176 (markdown-wiki-link-link))))
4177 (if (file-exists-p file-name)
4178 (markdown-highlight-wiki-link
4179 highlight-beginning highlight-end markdown-link-face)
4180 (markdown-highlight-wiki-link
4181 highlight-beginning highlight-end markdown-link-face)
4182 (markdown-highlight-wiki-link
4183 highlight-beginning highlight-end markdown-missing-link-face))))))
4185 (defun markdown-extend-changed-region (from to)
4186 "Extend region given by FROM and TO so that we can fontify all links.
4187 The region is extended to the first newline before and the first
4188 newline after."
4189 ;; start looking for the first new line before 'from
4190 (goto-char from)
4191 (re-search-backward "\n" nil t)
4192 (let ((new-from (point-min))
4193 (new-to (point-max)))
4194 (if (not (= (point) from))
4195 (setq new-from (point)))
4196 ;; do the same thing for the first new line after 'to
4197 (goto-char to)
4198 (re-search-forward "\n" nil t)
4199 (if (not (= (point) to))
4200 (setq new-to (point)))
4201 (values new-from new-to)))
4203 (defun markdown-check-change-for-wiki-link (from to change)
4204 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4205 Designed to be used with the `after-change-functions' hook.
4206 CHANGE is the number of bytes of pre-change text replaced by the
4207 given range."
4208 (interactive "nfrom: \nnto: \nnchange: ")
4209 (let* ((modified (buffer-modified-p))
4210 (buffer-undo-list t)
4211 (inhibit-read-only t)
4212 (inhibit-point-motion-hooks t)
4213 deactivate-mark
4214 buffer-file-truename)
4215 (unwind-protect
4216 (save-excursion
4217 (save-match-data
4218 (save-restriction
4219 ;; Extend the region to fontify so that it starts
4220 ;; and ends at safe places.
4221 (multiple-value-bind (new-from new-to)
4222 (markdown-extend-changed-region from to)
4223 ;; Unfontify existing fontification (start from scratch)
4224 (markdown-unfontify-region-wiki-links new-from new-to)
4225 ;; Now do the fontification.
4226 (markdown-fontify-region-wiki-links new-from new-to)))))
4227 (and (not modified)
4228 (buffer-modified-p)
4229 (set-buffer-modified-p nil)))))
4231 (defun markdown-fontify-buffer-wiki-links ()
4232 "Refontify all wiki links in the buffer."
4233 (interactive)
4234 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4237 ;;; Following and Jumping =====================================================
4239 (defun markdown-follow-thing-at-point (arg)
4240 "Follow thing at point if possible, such as a reference link or wiki link.
4241 Opens inline and reference links in a browser. Opens wiki links
4242 to other files in the current window, or the another window if
4243 ARG is non-nil.
4244 See `markdown-follow-link-at-point' and
4245 `markdown-follow-wiki-link-at-point'."
4246 (interactive "P")
4247 (cond ((markdown-link-p)
4248 (markdown-follow-link-at-point))
4249 ((markdown-wiki-link-p)
4250 (markdown-follow-wiki-link-at-point arg))
4252 (error "Nothing to follow at point"))))
4254 (defun markdown-jump ()
4255 "Jump to another location based on context at point.
4256 Jumps between reference links and definitions; between footnote
4257 markers and footnote text."
4258 (interactive)
4259 (cond ((markdown-footnote-text-positions)
4260 (markdown-footnote-return))
4261 ((markdown-footnote-marker-positions)
4262 (markdown-footnote-goto-text))
4263 ((thing-at-point-looking-at markdown-regex-link-reference)
4264 (markdown-reference-goto-definition))
4265 ((thing-at-point-looking-at markdown-regex-reference-definition)
4266 (markdown-reference-goto-link (match-string-no-properties 1)))
4268 (error "Nothing to jump to from context at point"))))
4271 ;;; Miscellaneous =============================================================
4273 (defun markdown-compress-whitespace-string (str)
4274 "Compress whitespace in STR and return result.
4275 Leading and trailing whitespace is removed. Sequences of multiple
4276 spaces, tabs, and newlines are replaced with single spaces."
4277 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4278 (replace-regexp-in-string "[ \t\n]+" " " str)))
4280 (defun markdown-line-number-at-pos (&optional pos)
4281 "Return (narrowed) buffer line number at position POS.
4282 If POS is nil, use current buffer location.
4283 This is an exact copy of `line-number-at-pos' for use in emacs21."
4284 (let ((opoint (or pos (point))) start)
4285 (save-excursion
4286 (goto-char (point-min))
4287 (setq start (point))
4288 (goto-char opoint)
4289 (forward-line 0)
4290 (1+ (count-lines start (point))))))
4292 (defun markdown-nobreak-p ()
4293 "Return nil if it is acceptable to break the current line at the point."
4294 ;; inside in square brackets (e.g., link anchor text)
4295 (looking-back "\\[[^]]*"))
4297 (defun markdown-adaptive-fill-function ()
4298 "Return prefix for filling paragraph or nil if not determined."
4299 (cond
4300 ;; List item inside blockquote
4301 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4302 (replace-regexp-in-string
4303 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4304 ;; Blockquote
4305 ((looking-at "^[ \t]*>[ \t]*")
4306 (match-string-no-properties 0))
4307 ;; List items
4308 ((looking-at markdown-regex-list)
4309 (match-string-no-properties 0))
4310 ;; No match
4311 (t nil)))
4314 ;;; Extensions ================================================================
4316 (defun markdown-reload-extensions ()
4317 "Check settings, update font-lock keywords, and re-fontify buffer."
4318 (interactive)
4319 (when (eq major-mode 'markdown-mode)
4320 (setq markdown-mode-font-lock-keywords
4321 (append
4322 (when markdown-enable-math
4323 markdown-mode-font-lock-keywords-math)
4324 markdown-mode-font-lock-keywords-basic
4325 markdown-mode-font-lock-keywords-core))
4326 (setq font-lock-defaults '(markdown-mode-font-lock-keywords))
4327 (font-lock-refresh-defaults)))
4329 (defun markdown-enable-math (&optional arg)
4330 "Toggle support for inline and display LaTeX math expressions.
4331 With a prefix argument ARG, enable math mode if ARG is positive,
4332 and disable it otherwise. If called from Lisp, enable the mode
4333 if ARG is omitted or nil."
4334 (interactive (list (or current-prefix-arg 'toggle)))
4335 (setq markdown-enable-math
4336 (if (eq arg 'toggle)
4337 (not markdown-enable-math)
4338 (> (prefix-numeric-value arg) 0)))
4339 (if markdown-enable-math
4340 (message "markdown-mode math support enabled")
4341 (message "markdown-mode math support disabled"))
4342 (markdown-reload-extensions))
4345 ;;; Mode Definition ==========================================================
4347 (defun markdown-show-version ()
4348 "Show the version number in the minibuffer."
4349 (interactive)
4350 (message "markdown-mode, version %s" markdown-mode-version))
4352 ;;;###autoload
4353 (define-derived-mode markdown-mode text-mode "Markdown"
4354 "Major mode for editing Markdown files."
4355 ;; Natural Markdown tab width
4356 (setq tab-width 4)
4357 ;; Comments
4358 (make-local-variable 'comment-start)
4359 (setq comment-start "<!-- ")
4360 (make-local-variable 'comment-end)
4361 (setq comment-end " -->")
4362 (make-local-variable 'comment-start-skip)
4363 (setq comment-start-skip "<!--[ \t]*")
4364 (make-local-variable 'comment-column)
4365 (setq comment-column 0)
4366 ;; Font lock.
4367 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
4368 (set (make-local-variable 'font-lock-defaults) nil)
4369 (set (make-local-variable 'font-lock-multiline) t)
4370 (markdown-reload-extensions)
4371 ;; Extensions
4372 (make-local-variable 'markdown-enable-math)
4373 (add-hook 'hack-local-variables-hook 'markdown-reload-extensions)
4374 ;; For imenu support
4375 (setq imenu-create-index-function 'markdown-imenu-create-index)
4376 ;; For menu support in XEmacs
4377 (easy-menu-add markdown-mode-menu markdown-mode-map)
4378 ;; Defun movement
4379 (set (make-local-variable 'beginning-of-defun-function)
4380 'markdown-beginning-of-defun)
4381 (set (make-local-variable 'end-of-defun-function)
4382 'markdown-end-of-defun)
4383 ;; Paragraph filling
4384 (set (make-local-variable 'paragraph-start)
4385 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4386 (set (make-local-variable 'paragraph-separate)
4387 "\\(?:[ \t\f]\\|.* \\)*$")
4388 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4389 "\\`[ \t]*>[ \t]*?\\'")
4390 (set (make-local-variable 'adaptive-fill-function)
4391 'markdown-adaptive-fill-function)
4392 ;; Outline mode
4393 (make-local-variable 'outline-regexp)
4394 (setq outline-regexp markdown-regex-header)
4395 (make-local-variable 'outline-level)
4396 (setq outline-level 'markdown-outline-level)
4397 ;; Cause use of ellipses for invisible text.
4398 (add-to-invisibility-spec '(outline . t))
4399 ;; Indentation and filling
4400 (make-local-variable 'fill-nobreak-predicate)
4401 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4402 (setq indent-line-function markdown-indent-function)
4404 ;; Prepare hooks for XEmacs compatibility
4405 (when (featurep 'xemacs)
4406 (make-local-hook 'after-change-functions)
4407 (make-local-hook 'font-lock-extend-region-functions)
4408 (make-local-hook 'window-configuration-change-hook))
4410 ;; Multiline font lock
4411 (add-hook 'font-lock-extend-region-functions
4412 'markdown-font-lock-extend-region)
4414 ;; Anytime text changes make sure it gets fontified correctly
4415 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4417 ;; If we left the buffer there is a really good chance we were
4418 ;; creating one of the wiki link documents. Make sure we get
4419 ;; refontified when we come back.
4420 (add-hook 'window-configuration-change-hook
4421 'markdown-fontify-buffer-wiki-links t t)
4423 ;; do the initial link fontification
4424 (markdown-fontify-buffer-wiki-links))
4426 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4429 ;;; GitHub Flavored Markdown Mode ============================================
4431 (defvar gfm-font-lock-keywords
4432 (append
4433 ;; GFM features to match first
4434 (list
4435 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4436 (2 markdown-language-keyword-face)
4437 (3 markdown-pre-face)
4438 (4 markdown-pre-face))))
4439 ;; Basic Markdown features (excluding possibly overridden ones)
4440 markdown-mode-font-lock-keywords-basic
4441 ;; GFM features to match last
4442 (list
4443 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4444 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4446 ;;;###autoload
4447 (define-derived-mode gfm-mode markdown-mode "GFM"
4448 "Major mode for editing GitHub Flavored Markdown files."
4449 (setq markdown-link-space-sub-char "-")
4450 (set (make-local-variable 'font-lock-defaults)
4451 '(gfm-font-lock-keywords))
4452 (auto-fill-mode 0)
4453 ;; Use visual-line-mode if available, fall back to longlines-mode:
4454 (if (fboundp 'visual-line-mode)
4455 (visual-line-mode 1)
4456 (longlines-mode 1))
4457 ;; do the initial link fontification
4458 (markdown-fontify-buffer-wiki-links))
4461 (provide 'markdown-mode)
4463 ;;; markdown-mode.el ends here