remove after-revert-hook
[markdown-mode.git] / markdown-mode.el
blobd513a7ff400d9ff7bf560009aa027176bfea1028
1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2015 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>
25 ;; Copyright (C) 2015 Google, Inc. (Contributor: Samuel Freilich <sfreilich@google.com>)
26 ;; Copyright (C) 2015 Antonis Kanouras <antonis@metadosis.gr>
27 ;; Copyright (C) 2015 Howard Melman <hmelman@gmail.com>
29 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
30 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
31 ;; Created: May 24, 2007
32 ;; Version: 2.0
33 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
34 ;; URL: http://jblevins.org/projects/markdown-mode/
36 ;; This file is not part of GNU Emacs.
38 ;; This program is free software; you can redistribute it and/or modify
39 ;; it under the terms of the GNU General Public License as published by
40 ;; the Free Software Foundation; either version 2, or (at your option)
41 ;; any later version.
43 ;; This program is distributed in the hope that it will be useful,
44 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
45 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
46 ;; GNU General Public License for more details.
48 ;; You should have received a copy of the GNU General Public License
49 ;; along with this program; if not, write to the Free Software
50 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
51 ;; Boston, MA 02110-1301, USA.
53 ;;; Commentary:
55 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
56 ;; text files in GNU Emacs. markdown-mode is free software, licensed
57 ;; under the GNU GPL.
59 ;; [Markdown]: http://daringfireball.net/projects/markdown/
61 ;; The latest stable version is markdown-mode 2.0, released on March 24, 2013:
63 ;; * [markdown-mode.el][]
64 ;; * [Screenshot][][^theme]
65 ;; * [Release notes][]
67 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
68 ;; [Screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20130131-002.png
69 ;; [Release notes]: http://jblevins.org/projects/markdown-mode/rev-2-0
71 ;; [^theme]: The theme used in the screenshot is
72 ;; [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
74 ;; markdown-mode is also available in several package managers, including:
76 ;; * Debian Linux: [emacs-goodies-el][]
77 ;; * Ubuntu Linux: [emacs-goodies-el][emacs-goodies-el-ubuntu]
78 ;; * RedHat and Fedora Linux: [emacs-goodies][]
79 ;; * NetBSD: [textproc/markdown-mode][]
80 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
81 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
82 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
84 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
85 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
86 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
87 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
88 ;; [emacs-markdown-mode-git]: https://aur.archlinux.org/packages/emacs-goodies-el/
89 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
90 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
91 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
93 ;; The latest development version can be downloaded directly
94 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
95 ;; (browsable and clonable) Git repository at
96 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
97 ;; including the full project history, can be cloned via the Git protocol
98 ;; by running
100 ;; git clone git://jblevins.org/git/markdown-mode.git
102 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
104 ;;; Installation:
106 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
107 ;; the following lines to your `.emacs` file to associate markdown-mode
108 ;; with `.text`, `.markdown`, and `.md` files:
110 ;; (autoload 'markdown-mode "markdown-mode"
111 ;; "Major mode for editing Markdown files" t)
112 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
113 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
114 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
116 ;; There is no official Markdown file extension, nor is there even a
117 ;; _de facto_ standard, so you can easily add, change, or remove any
118 ;; of the file extensions above as needed.
120 ;;; Usage:
122 ;; Keybindings are grouped by prefixes based on their function. For
123 ;; example, the commands for inserting links are grouped under `C-c
124 ;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag. In
125 ;; other cases, the connection to HTML is not direct. For example,
126 ;; commands dealing with headings begin with `C-c C-t` (mnemonic:
127 ;; titling). The primary commands in each group will are described
128 ;; below. You can obtain a list of all keybindings by pressing `C-c
129 ;; C-h`. Movement and shifting commands tend to be associated with
130 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
131 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
132 ;; commands for running Markdown or doing maintenance on an open file
133 ;; are grouped under the `C-c C-c` prefix. The most commonly used
134 ;; commands are described below. You can obtain a list of all
135 ;; keybindings by pressing `C-c C-h`.
137 ;; * Hyperlinks: `C-c C-a`
139 ;; In this group, `C-c C-a l` inserts an inline link of the form
140 ;; `[text](url)`. The link text is determined as follows. First,
141 ;; if there is an active region (i.e., when transient mark mode is
142 ;; on and the mark is active), use it as the link text. Second,
143 ;; if the point is at a word, use that word as the link text. In
144 ;; these two cases, the original text will be replaced with the
145 ;; link and point will be left at the position for inserting a
146 ;; URL. Otherwise, insert empty link markup and place the point
147 ;; for inserting the link text.
149 ;; `C-c C-a L` inserts a reference link of the form `[text][label]`
150 ;; and, optionally, a corresponding reference label definition.
151 ;; The link text is determined in the same way as with an inline
152 ;; link (using the region, when active, or the word at the point),
153 ;; but instead of inserting empty markup as a last resort, the
154 ;; link text will be read from the minibuffer. The reference
155 ;; label will be read from the minibuffer in both cases, with
156 ;; completion from the set of currently defined references. To
157 ;; create an implicit reference link, press `RET` to accept the
158 ;; default, an empty label. If the entered referenced label is
159 ;; not defined, additionally prompt for the URL and (optional)
160 ;; title. If a URL is provided, a reference definition will be
161 ;; inserted in accordance with `markdown-reference-location'.
162 ;; If a title is given, it will be added to the end of the
163 ;; reference definition and will be used to populate the title
164 ;; attribute when converted to XHTML.
166 ;; `C-c C-a u` inserts a bare url, delimited by angle brackets. When
167 ;; there is an active region, the text in the region is used as the
168 ;; URL. If the point is at a URL, that url is used. Otherwise,
169 ;; insert angle brackets and position the point in between them
170 ;; for inserting the URL.
172 ;; `C-c C-a f` inserts a footnote marker at the point, inserts a
173 ;; footnote definition below, and positions the point for
174 ;; inserting the footnote text. Note that footnotes are an
175 ;; extension to Markdown and are not supported by all processors.
177 ;; `C-c C-a w` behaves much like the inline link insertion command
178 ;; and inserts a wiki link of the form `[[WikiLink]]`. If there
179 ;; is an active region, use the region as the link text. If the
180 ;; point is at a word, use the word as the link text. If there is
181 ;; no active region and the point is not at word, simply insert
182 ;; link markup. Note that wiki links are an extension to Markdown
183 ;; and are not supported by all processors.
185 ;; * Images: `C-c C-i`
187 ;; `C-c C-i i` inserts markup for an inline image, using the
188 ;; active region or the word at point, if any, as the alt text.
189 ;; `C-c C-i I` behaves similarly and inserts a reference-style
190 ;; image.
192 ;; * Styles: `C-c C-s`
194 ;; `C-c C-s e` inserts markup to make a region or word italic (`e`
195 ;; for `<em>` or emphasis). If there is an active region, make
196 ;; the region italic. If the point is at a non-italic word, make
197 ;; the word italic. If the point is at an italic word or phrase,
198 ;; remove the italic markup. Otherwise, simply insert italic
199 ;; delimiters and place the cursor in between them. Similarly,
200 ;; use `C-c C-s s` for bold (`<strong>`) and `C-c C-s c` for
201 ;; inline code (`<code>`).
203 ;; `C-c C-s b` inserts a blockquote using the active region, if any,
204 ;; or starts a new blockquote. `C-c C-s C-b` is a variation which
205 ;; always operates on the region, regardless of whether it is
206 ;; active or not. The appropriate amount of indentation, if any,
207 ;; is calculated automatically given the surrounding context, but
208 ;; may be adjusted later using the region indentation commands.
210 ;; `C-c C-s p` behaves similarly for inserting preformatted code
211 ;; blocks, with `C-c C-s C-p` being the region-only counterpart.
213 ;; * Headings: `C-c C-t`
215 ;; All heading insertion commands use the text in the active
216 ;; region, if any, as the heading text. Otherwise, if the current
217 ;; line is not blank, they use the text on the current line.
218 ;; Finally, the setext commands will prompt for heading text if
219 ;; there is no active region and the current line is blank.
221 ;; `C-c C-t h` inserts a heading with automatically chosen type and
222 ;; level (both determined by the previous heading). `C-c C-t H`
223 ;; behaves similarly, but uses setext (underlined) headings when
224 ;; possible, still calculating the level automatically.
225 ;; In cases where the automatically-determined level is not what
226 ;; you intended, the level can be quickly promoted or demoted
227 ;; (as described below). Alternatively, a `C-u` prefix can be
228 ;; given to insert a heading promoted by one level or a `C-u C-u`
229 ;; prefix can be given to insert a heading demoted by one level.
231 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
232 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
233 ;; `C-c C-t @` for setext headings of level one or two, respectively.
234 ;; Note that `!` is `S-1` and `@` is `S-2`.
236 ;; If the point is at a heading, these commands will replace the
237 ;; existing markup in order to update the level and/or type of the
238 ;; heading. To remove the markup of the heading at the point,
239 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
240 ;; heading text back into the buffer.
242 ;; * Horizontal Rules: `C-c -`
244 ;; `C-c -` inserts a horizontal rule. By default, insert the
245 ;; first string in the list `markdown-hr-strings' (the most
246 ;; prominent rule). With a `C-u` prefix, insert the last string.
247 ;; With a numeric prefix `N`, insert the string in position `N`
248 ;; (counting from 1).
250 ;; * Markdown and Maintenance Commands: `C-c C-c`
252 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
253 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
254 ;; runs Markdown on the current buffer and previews, stores the
255 ;; output in a temporary file, and displays the file in a browser.
256 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
257 ;; and save the result in the file `basename.html`, where
258 ;; `basename` is the name of the Markdown file with the extension
259 ;; removed. *Export and View:* press `C-c C-c v` to export the
260 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
261 ;; the Markdown source file directly using `markdown-open-command'.
262 ;; *Live Export*: Press `C-c C-c l` to turn on
263 ;; `markdown-live-preview-mode' to view the exported output
264 ;; side-by-side with the source Markdown. **For all export commands,
265 ;; the output file will be overwritten without notice.**
266 ;; `markdown-live-preview-window-function' can be customized to open
267 ;; in a browser other than `eww'.
269 ;; To summarize:
271 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
272 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
273 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
274 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
275 ;; - `C-c C-c w`: `markdown-command' > kill ring.
276 ;; - `C-c C-c o`: `markdown-open-command'.
277 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
279 ;; `C-c C-c c` will check for undefined references. If there are
280 ;; any, a small buffer will open with a list of undefined
281 ;; references and the line numbers on which they appear. In Emacs
282 ;; 22 and greater, selecting a reference from this list and
283 ;; pressing `RET` will insert an empty reference definition at the
284 ;; end of the buffer. Similarly, selecting the line number will
285 ;; jump to the corresponding line.
287 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
288 ;; out of sequence.
290 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
291 ;; rules in the buffer.
293 ;; * Following Links: `C-c C-o`
295 ;; Press `C-c C-o` when the point is on an inline or reference
296 ;; link to open the URL in a browser. When the point is at a
297 ;; wiki link, open it in another buffer (in the current window,
298 ;; or in the other window with the `C-u` prefix). Use `M-p` and
299 ;; `M-n` to quickly jump to the previous or next link of any type.
301 ;; * Jumping: `C-c C-j`
303 ;; Use `C-c C-j` to jump from the object at point to its counterpart
304 ;; elsewhere in the text, when possible. Jumps between reference
305 ;; links and definitions; between footnote markers and footnote
306 ;; text. If more than one link uses the same reference name, a
307 ;; new buffer will be created containing clickable buttons for jumping
308 ;; to each link. You may press `TAB` or `S-TAB` to jump between
309 ;; buttons in this window.
311 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
313 ;; Headings, horizontal rules, and list items can be promoted and
314 ;; demoted, as well as bold and italic text. For headings,
315 ;; "promotion" means *decreasing* the level (i.e., moving from
316 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
317 ;; level. For horizontal rules, promotion and demotion means
318 ;; moving backward or forward through the list of rule strings in
319 ;; `markdown-hr-strings'. For bold and italic text, promotion and
320 ;; demotion means changing the markup from underscores to asterisks.
321 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
322 ;; if possible.
324 ;; To remember these commands, note that `-` is for decreasing the
325 ;; level (promoting), and `=` (on the same key as `+`) is for
326 ;; increasing the level (demoting). Similarly, the left and right
327 ;; arrow keys indicate the direction that the atx heading markup
328 ;; is moving in when promoting or demoting.
330 ;; * Completion: `C-c C-]`
332 ;; Complete markup is in normalized form, which means, for
333 ;; example, that the underline portion of a setext header is the
334 ;; same length as the heading text, or that the number of leading
335 ;; and trailing hash marks of an atx header are equal and that
336 ;; there is no extra whitespace in the header text. `C-c C-]`
337 ;; completes the markup at the point, if it is determined to be
338 ;; incomplete.
340 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
342 ;; New list items can be inserted with `M-RET`. This command
343 ;; determines the appropriate marker (one of the possible
344 ;; unordered list markers or the next number in sequence for an
345 ;; ordered list) and indentation level by examining nearby list
346 ;; items. If there is no list before or after the point, start a
347 ;; new list. Prefix this command by `C-u` to decrease the
348 ;; indentation by one level. Prefix this command by `C-u C-u` to
349 ;; increase the indentation by one level.
351 ;; Existing list items can be moved up or down with `M-UP` or
352 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
354 ;; * Editing Subtrees: `M-S-UP`, `M-S-DOWN`, `M-S-LEFT`, and `M-S-RIGHT`
356 ;; Entire subtrees of ATX headings can be promoted and demoted
357 ;; with `M-S-LEFT` and `M-S-RIGHT`, which mirror the bindings
358 ;; for promotion and demotion of list items. Similarly, subtrees
359 ;; can be moved up and down with `M-S-UP` and `M-S-DOWN`.
361 ;; Please note the following "boundary" behavior for promotion and
362 ;; demotion. Any level-six headings will not be demoted further
363 ;; (i.e., they remain at level six, since Markdown and HTML define
364 ;; only six levels) and any level-one headings will promoted away
365 ;; entirely (i.e., heading markup will be removed, since a
366 ;; level-zero heading is not defined).
368 ;; * Shifting the Region: `C-c <` and `C-c >`
370 ;; Text in the region can be indented or exdented as a group using
371 ;; `C-c >` to indent to the next indentation point (calculated in
372 ;; the current context), and `C-c <` to exdent to the previous
373 ;; indentation point. These keybindings are the same as those for
374 ;; similar commands in `python-mode'.
376 ;; * Killing Elements: `C-c C-k`
378 ;; Press `C-c C-k` to kill the thing at point and add important
379 ;; text, without markup, to the kill ring. Possible things to
380 ;; kill include (roughly in order of precedece): inline code,
381 ;; headings, horizonal rules, links (add link text to kill ring),
382 ;; images (add alt text to kill ring), angle URIs, email
383 ;; addresses, bold, italics, reference definitions (add URI to
384 ;; kill ring), footnote markers and text (kill both marker and
385 ;; text, add text to kill ring), and list items.
387 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
389 ;; Navigation between headings is possible using `outline-mode'.
390 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
391 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
392 ;; next and previous visible headings at the same level as the one
393 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
394 ;; (higher precedence) visible heading.
396 ;; * Movement by Paragraph or Block: `M-{` and `M-}`
398 ;; The definition of a "paragraph" is slightly different in
399 ;; markdown-mode than, say, text-mode, because markdown-mode
400 ;; supports filling for list items and respects hard line breaks,
401 ;; both of which break paragraphs. So, markdown-mode overrides
402 ;; the usual paragraph navigation commands `M-{` and `M-}` so that
403 ;; with a `C-u` prefix, these commands jump to the beginning or
404 ;; end of an entire block of text, respectively, where "blocks"
405 ;; are separated by one or more lines.
407 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
409 ;; The usual Emacs commands can be used to move by defuns
410 ;; (top-level major definitions). In markdown-mode, a defun is a
411 ;; section. As usual, `C-M-a` will move the point to the
412 ;; beginning of the current or preceding defun, `C-M-e` will move
413 ;; to the end of the current or following defun, and `C-M-h` will
414 ;; put the region around the entire defun.
416 ;; As noted, many of the commands above behave differently depending
417 ;; on whether Transient Mark mode is enabled or not. When it makes
418 ;; sense, if Transient Mark mode is on and the region is active, the
419 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
420 ;; region bold). For users who prefer to work outside of Transient
421 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
422 ;; `C-SPC C-SPC`. When this is not the case, many commands then
423 ;; proceed to look work with the word or line at the point.
425 ;; When applicable, commands that specifically act on the region even
426 ;; outside of Transient Mark mode have the same keybinding as their
427 ;; standard counterpart, but the letter is uppercase. For example,
428 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
429 ;; the region in Transient Mark mode while `markdown-blockquote-region'
430 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
432 ;; Note that these region-specific functions are useful in many
433 ;; cases where it may not be obvious. For example, yanking text from
434 ;; the kill ring sets the mark at the beginning of the yanked text
435 ;; and moves the point to the end. Therefore, the (inactive) region
436 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
437 ;; yank text and turn it into a blockquote.
439 ;; markdown-mode attempts to be flexible in how it handles
440 ;; indentation. When you press `TAB` repeatedly, the point will cycle
441 ;; through several possible indentation levels corresponding to things
442 ;; you might have in mind when you press `RET` at the end of a line or
443 ;; `TAB`. For example, you may want to start a new list item,
444 ;; continue a list item with hanging indentation, indent for a nested
445 ;; pre block, and so on. Exdention is handled similarly when backspace
446 ;; is pressed at the beginning of the non-whitespace portion of a line.
448 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
449 ;; visibility cycling for atx- or hash-style headings. There are two
450 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
451 ;; the table of contents view (headings only), outline view (top-level
452 ;; headings only), and the full document view. Pressing `TAB` while the
453 ;; point is at a heading will cycle through levels of visibility for the
454 ;; subtree: completely folded, visible children, and fully visible.
455 ;; Note that mixing hash and underline style headings will give undesired
456 ;; results.
458 ;;; Customization:
460 ;; Although no configuration is *necessary* there are a few things
461 ;; that can be customized. The `M-x customize-mode` command
462 ;; provides an interface to all of the possible customizations:
464 ;; * `markdown-command' - the command used to run Markdown (default:
465 ;; `markdown`). This variable may be customized to pass
466 ;; command-line options to your Markdown processor of choice.
468 ;; * `markdown-command-needs-filename' - set to `t' if
469 ;; `markdown-command' does not accept standard input (default:
470 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
471 ;; content to `markdown-command' using standard input (`stdin`).
472 ;; When set to `t', `markdown-mode' will pass the name of the file
473 ;; as the final command-line argument to `markdown-command'. Note
474 ;; that in the latter case, you will only be able to run
475 ;; `markdown-command' from buffers which are visiting a file.
477 ;; * `markdown-open-command' - the command used for calling a standalone
478 ;; Markdown previewer which is capable of opening Markdown source files
479 ;; directly (default: `nil'). This command will be called
480 ;; with a single argument, the filename of the current buffer.
481 ;; A representative program is the Mac app [Marked 2][], a
482 ;; live-updating Markdown previewer which can be [called from a
483 ;; simple shell script](http://jblevins.org/log/marked-2-command).
485 ;; * `markdown-hr-strings' - list of strings to use when inserting
486 ;; horizontal rules. Different strings will not be distinguished
487 ;; when converted to HTML--they will all be converted to
488 ;; `<hr/>`--but they may add visual distinction and style to plain
489 ;; text documents. To maintain some notion of promotion and
490 ;; demotion, keep these sorted from largest to smallest.
492 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
493 ;; underscores for bold instead of two asterisks (default: `nil').
495 ;; * `markdown-italic-underscore' - set to a non-nil value to use
496 ;; underscores for italic instead of asterisks (default: `nil').
498 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
499 ;; asymmetric header styling, placing header characters only on
500 ;; the left of headers (default: `nil').
502 ;; * `markdown-indent-function' - the function to use for automatic
503 ;; indentation (default: `markdown-indent-line').
505 ;; * `markdown-indent-on-enter' - set to a non-nil value to
506 ;; automatically indent new lines when the enter key is pressed
507 ;; (default: `t')
509 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
510 ;; treat aliased wiki links like `[[link text|PageName]]`
511 ;; (default: `t'). When set to nil, they will be treated as
512 ;; `[[PageName|link text]]'.
514 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
515 ;; for URIs that `markdown-mode' should highlight.
517 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
518 ;; fragments (default: `nil'). Set this to `t' to turn on math
519 ;; support by default. Math support can be toggled later using
520 ;; the function `markdown-enable-math'."
522 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
523 ;; (default: `nil`).
525 ;; * `markdown-content-type' - when set to a nonempty string, an
526 ;; `http-equiv` attribute will be included in the XHTML `<head>`
527 ;; block (default: `""`). If needed, the suggested values are
528 ;; `application/xhtml+xml` or `text/html`. See also:
529 ;; `markdown-coding-system'.
531 ;; * `markdown-coding-system' - used for specifying the character
532 ;; set identifier in the `http-equiv` attribute when included
533 ;; (default: `nil'). See `markdown-content-type', which must
534 ;; be set before this variable has any effect. When set to `nil',
535 ;; `buffer-file-coding-system' will be used to automatically
536 ;; determine the coding system string (falling back to
537 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
538 ;; and `iso-latin-1'.
540 ;; * `markdown-xhtml-header-content' - additional content to include
541 ;; in the XHTML `<head>` block (default: `""`).
543 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
544 ;; `markdown-mode' uses to determine whether the output of
545 ;; `markdown-command' is a standalone XHTML document or an XHTML
546 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
547 ;; this regular expression not matched in the first five lines of
548 ;; output, `markdown-mode' assumes the output is a fragment and
549 ;; adds a header and footer.
551 ;; * `markdown-link-space-sub-char' - a character to replace spaces
552 ;; when mapping wiki links to filenames (default: `"_"`).
553 ;; For example, use an underscore for compatibility with the
554 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
555 ;; set to `"-"` to conform with GitHub wiki links.
557 ;; * `markdown-reference-location' - where to insert reference
558 ;; definitions (default: `header`). The possible locations are
559 ;; the end of the document (`end`), after the current block
560 ;; (`immediately`), before the next header (`header`).
562 ;; * `markdown-footnote-location' - where to insert footnote text
563 ;; (default: `end`). The set of location options is the same as
564 ;; for `markdown-reference-location'.
566 ;; * `markdown-font-lock-support-mode' - the variable
567 ;; `font-lock-support-mode' is made buffer-local and set to
568 ;; `markdown-font-lock-support-mode', which is `jit-mode' by
569 ;; default. This is currently the default support mode in Emacs as
570 ;; well. However, if fontification of multi-line constructs such
571 ;; as preformatted code blocks, nested lists, and so on is
572 ;; inaccurate, setting this to `nil' will allow more aggressive
573 ;; fontification at the expense of some performance.
575 ;; * `comment-auto-fill-only-comments' - variable is made
576 ;; buffer-local and set to `nil' by default. In programming
577 ;; language modes, when this variable is non-nil, only comments
578 ;; will be filled by auto-fill-mode. However, comments in
579 ;; Markdown documents are rare and the most users probably intend
580 ;; for the actual content of the document to be filled. Making
581 ;; this variable buffer-local allows `markdown-mode' to override
582 ;; the default behavior induced when the global variable is non-nil.
584 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub Flavored
585 ;; Markdown style checkboxes should be turned into buttons that can
586 ;; be toggled with mouse-1 or RET. If non-nil buttons are enabled, the
587 ;; default is t. This works in `markdown-mode' as well as `gfm-mode'.
589 ;; Additionally, the faces used for syntax highlighting can be modified to
590 ;; your liking by issuing `M-x customize-group RET markdown-faces`
591 ;; or by using the "Markdown Faces" link at the bottom of the mode
592 ;; customization screen.
594 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
596 ;;; Extensions:
598 ;; Besides supporting the basic Markdown syntax, markdown-mode also
599 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
600 ;; links may be followed by pressing `C-c C-o` when the point
601 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
602 ;; previous and next links (including links of other types).
603 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
604 ;; are also supported. Since some wikis reverse these components, set
605 ;; `markdown-wiki-link-alias-first' to nil to treat them as
606 ;; `[[PageName|link text]]`. By default, Markdown Mode only searches
607 ;; for target files in the current directory. Sequential parent
608 ;; directory search (as in [Ikiwiki][]) can be enabled by setting
609 ;; `markdown-wiki-link-search-parent-directories' to a non-nil value.
611 ;; [Ikiwiki]: https://ikiwiki.info
613 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
614 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
615 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
616 ;; You can do this either by using `M-x customize-group markdown`
617 ;; or by placing the following in your `.emacs` file:
619 ;; (defun markdown-custom ()
620 ;; "markdown-mode-hook"
621 ;; (setq markdown-command "markdown | smartypants"))
622 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
624 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
626 ;; Syntax highlighting for mathematical expressions written
627 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
628 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
629 ;; either via customize or by placing `(setq markdown-enable-math t)`
630 ;; in `.emacs`, and then restarting Emacs or calling
631 ;; `markdown-reload-extensions'.
633 ;;; GitHub Flavored Markdown:
635 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
636 ;; available. The GitHub implementation of differs slightly from
637 ;; standard Markdown. The most important differences are that
638 ;; newlines are significant, triggering hard line breaks, and that
639 ;; underscores inside of words (e.g., variable names) need not be
640 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
641 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
642 ;; not available). Underscores inside of words (such as
643 ;; test_variable) will not trigger emphasis.
645 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
646 ;; replacing spaces in filenames and where the first letter of the
647 ;; filename capitalized. For example, `[[wiki link]]' will map to a
648 ;; file named `Wiki-link` with the same extension as the current file.
650 ;; GFM code blocks, with optional programming language keywords, will
651 ;; be highlighted. They can be inserted with `C-c C-s P`. If there
652 ;; is an active region, the text in the region will be placed inside
653 ;; the code block. You will be prompted for the name of the language,
654 ;; but may press enter to continue without naming a language.
656 ;; Similarly, strike through text is supoorted in GFM mode and can be
657 ;; inserted (and toggled) using `C-c C-s d`. Following the mnemonics
658 ;; for the other style keybindings, the letter `d` coincides with the
659 ;; HTML tag `<del>`.
661 ;; For GFM preview can be powered by setting `markdown-command' to
662 ;; use [Docter][]. This may also be configured to work with [Marked 2][]
663 ;; for `markdown-open-command'.
665 ;; [GFM]: http://github.github.com/github-flavored-markdown/
666 ;; [Docter]: https://github.com/alampros/Docter
668 ;;; Acknowledgments:
670 ;; markdown-mode has benefited greatly from the efforts of the
671 ;; following people:
673 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
674 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
675 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
676 ;; GitHub Flavored Markdown mode (`gfm-mode').
677 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
678 ;; `markdown' with an active region.
679 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
680 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
681 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
682 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
683 ;; visibility cycling functionality was derived, and for a bug fix
684 ;; related to `orgtbl-mode'.
685 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
686 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
687 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
688 ;; compatibility and custom CSS.
689 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
690 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
691 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
692 ;; comment matching functions were derived.
693 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
694 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
695 ;; functions, bug reports regarding indentation, and
696 ;; fixes for byte-compilation warnings.
697 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
698 ;; enhancements.
699 ;; * George Ogata <george.ogata@gmail.com> for fixing several
700 ;; byte-compilation warnings.
701 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
702 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
703 ;; customizations and XHTML export.
704 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
705 ;; Markdown processors which do not accept input from stdin.
706 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
707 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
708 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
709 ;; substitution character for mapping wiki links to filenames.
710 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
711 ;; escape shell commands.
712 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
713 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
714 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
715 ;; Emacs Lisp coding conventions.
716 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
717 ;; regexp, refactoring the compilation and preview functions,
718 ;; heading font-lock generalizations, list renumbering,
719 ;; and kill ring save.
720 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
721 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
722 ;; for an autoload token for `gfm-mode'.
723 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
724 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
725 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
726 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
727 ;; declaration in XHTML output.
728 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
729 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
730 ;; and GFM code block insertion.
731 ;; * Peter Jones <pjones@pmade.com> for link following functions.
732 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
733 ;; externally modified files.
734 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
735 ;; related to `orgtbl-mode'.
736 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
737 ;; export hooks, unit test improvements, and updates to support
738 ;; wide characters.
739 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
740 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
741 ;; completion.
742 ;; * Gunnar Franke <Gunnar.Franke@gmx.de> for a completion bug report.
743 ;; * David Glasser <glasser@meteor.com> for a `paragraph-separate' fix.
744 ;; * Daniel Brotsky <dev@brotsky.com> for better auto-fill defaults.
745 ;; * Samuel Freilich <sfreilich@google.com> for improved filling
746 ;; behavior regarding list items, footnotes, and reference
747 ;; definitions, improved killing of footnotes, and numerous other
748 ;; tests and bug fixes.
749 ;; * Antonis Kanouras <antonis@metadosis.gr> for strike through support.
750 ;; * Tim Visher <tim.visher@gmail.com> for multiple CSS files and other
751 ;; general improvements.
752 ;; * Matt McClure <matthewlmcclure@gmail.com> for a patch to prevent
753 ;; overwriting source files with .html extensions upon export.
754 ;; * Roger Bolsius <roger.bolsius@gmail.com> for ordered list improvements.
755 ;; * Google's Open Source Programs Office for recognizing the project with
756 ;; a monetary contribution in June 2015.
757 ;; * Howard Melman <hmelman@gmail.com> for supporting GFM checkboxes
758 ;; as buttons.
760 ;;; Bugs:
762 ;; Although markdown-mode is developed and tested primarily using
763 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
764 ;; priority.
766 ;; If you find any bugs in markdown-mode, please construct a test case
767 ;; or a patch and open a ticket on the [GitHub issue tracker][issues].
769 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
771 ;;; History:
773 ;; markdown-mode was written and is maintained by Jason Blevins. The
774 ;; first version was released on May 24, 2007.
776 ;; * 2007-05-24: Version 1.1
777 ;; * 2007-05-25: Version 1.2
778 ;; * 2007-06-05: [Version 1.3][]
779 ;; * 2007-06-29: Version 1.4
780 ;; * 2007-10-11: [Version 1.5][]
781 ;; * 2008-06-04: [Version 1.6][]
782 ;; * 2009-10-01: [Version 1.7][]
783 ;; * 2011-08-12: [Version 1.8][]
784 ;; * 2011-08-15: [Version 1.8.1][]
785 ;; * 2013-01-25: [Version 1.9][]
786 ;; * 2013-03-24: [Version 2.0][]
788 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
789 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
790 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
791 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
792 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
793 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
794 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
795 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
798 ;;; Code:
800 (require 'easymenu)
801 (require 'outline)
802 (require 'thingatpt)
803 (eval-when-compile (require 'cl))
806 ;;; Constants =================================================================
808 (defconst markdown-mode-version "2.0"
809 "Markdown mode version number.")
811 (defconst markdown-output-buffer-name "*markdown-output*"
812 "Name of temporary buffer for markdown command output.")
815 ;;; Global Variables ==========================================================
817 (defvar markdown-reference-label-history nil
818 "History of used reference labels.")
821 ;;; Customizable Variables ====================================================
823 (defvar markdown-mode-hook nil
824 "Hook run when entering Markdown mode.")
826 (defvar markdown-before-export-hook nil
827 "Hook run before running Markdown to export XHTML output.
828 The hook may modify the buffer, which will be restored to it's
829 original state after exporting is complete.")
831 (defvar markdown-after-export-hook nil
832 "Hook run after XHTML output has been saved.
833 Any changes to the output buffer made by this hook will be saved.")
835 (defgroup markdown nil
836 "Major mode for editing text files in Markdown format."
837 :prefix "markdown-"
838 :group 'wp
839 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
841 (defcustom markdown-command "markdown"
842 "Command to run markdown."
843 :group 'markdown
844 :type 'string)
846 (defcustom markdown-command-needs-filename nil
847 "Set to non-nil if `markdown-command' does not accept input from stdin.
848 Instead, it will be passed a filename as the final command line
849 option. As a result, you will only be able to run Markdown from
850 buffers which are visiting a file."
851 :group 'markdown
852 :type 'boolean)
854 (defcustom markdown-open-command nil
855 "Command used for opening Markdown files directly.
856 For example, a standalone Markdown previewer. This command will
857 be called with a single argument: the filename of the current
858 buffer."
859 :group 'markdown
860 :type 'string)
862 (defcustom markdown-hr-strings
863 '("-------------------------------------------------------------------------------"
864 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
865 "---------------------------------------"
866 "* * * * * * * * * * * * * * * * * * * *"
867 "---------"
868 "* * * * *")
869 "Strings to use when inserting horizontal rules.
870 The first string in the list will be the default when inserting a
871 horizontal rule. Strings should be listed in decreasing order of
872 prominence (as in headings from level one to six) for use with
873 promotion and demotion functions."
874 :group 'markdown
875 :type 'list)
877 (defcustom markdown-bold-underscore nil
878 "Use two underscores for bold instead of two asterisks."
879 :group 'markdown
880 :type 'boolean)
882 (defcustom markdown-italic-underscore nil
883 "Use underscores for italic instead of asterisks."
884 :group 'markdown
885 :type 'boolean)
887 (defcustom markdown-asymmetric-header nil
888 "Determines if header style will be asymmetric.
889 Set to non-nil to only have header characters to the left of the title.
890 The default will ensure header characters are placed to the left and right
891 of the title."
892 :group 'markdown
893 :type 'boolean)
895 (defcustom markdown-indent-function 'markdown-indent-line
896 "Function to use to indent."
897 :group 'markdown
898 :type 'function)
900 (defcustom markdown-indent-on-enter t
901 "Automatically indent new lines when enter key is pressed.
902 When this variable is set to t, pressing RET will call
903 `newline-and-indent'. When set to nil, define RET to call
904 `newline' as usual. In the latter case, you can still use
905 auto-indentation by pressing \\[newline-and-indent]."
906 :group 'markdown
907 :type 'boolean)
909 (defcustom markdown-wiki-link-alias-first t
910 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
911 Otherwise, they will be treated as [[PageName|alias text]]."
912 :group 'markdown
913 :type 'boolean
914 :safe 'booleanp)
916 (defcustom markdown-wiki-link-search-parent-directories nil
917 "When non-nil, search for wiki link targets in parent directories.
918 This is the default search behavior of Ikiwiki."
919 :group 'markdown
920 :type 'boolean
921 :safe 'booleanp)
923 (defcustom markdown-uri-types
924 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
925 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
926 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
927 "Link types for syntax highlighting of URIs."
928 :group 'markdown
929 :type 'list)
931 (defcustom markdown-enable-math nil
932 "Syntax highlighting for inline LaTeX and itex expressions.
933 Set this to a non-nil value to turn on math support by default.
934 Math support can be toggled later using `markdown-enable-math'
935 or \\[markdown-enable-math]."
936 :group 'markdown
937 :type 'boolean
938 :safe 'booleanp)
940 (defcustom markdown-css-paths nil
941 "URL of CSS file to link to in the output XHTML."
942 :group 'markdown
943 :type 'list)
945 (defcustom markdown-content-type ""
946 "Content type string for the http-equiv header in XHTML output.
947 When set to a non-empty string, insert the http-equiv attribute.
948 Otherwise, this attribute is omitted."
949 :group 'markdown
950 :type 'string)
952 (defcustom markdown-coding-system nil
953 "Character set string for the http-equiv header in XHTML output.
954 Defaults to `buffer-file-coding-system' (and falling back to
955 `iso-8859-1' when not available). Common settings are `utf-8'
956 and `iso-latin-1'. Use `list-coding-systems' for more choices."
957 :group 'markdown
958 :type 'coding-system)
960 (defcustom markdown-xhtml-header-content ""
961 "Additional content to include in the XHTML <head> block."
962 :group 'markdown
963 :type 'string)
965 (defcustom markdown-xhtml-standalone-regexp
966 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
967 "Regexp indicating whether `markdown-command' output is standalone XHTML."
968 :group 'markdown
969 :type 'regexp)
971 (defcustom markdown-link-space-sub-char "_"
972 "Character to use instead of spaces when mapping wiki links to filenames."
973 :group 'markdown
974 :type 'string)
976 (defcustom markdown-reference-location 'header
977 "Position where new reference definitions are inserted in the document."
978 :group 'markdown
979 :type '(choice (const :tag "At the end of the document" end)
980 (const :tag "Immediately after the current block" immediately)
981 (const :tag "Before next header" header)))
983 (defcustom markdown-footnote-location 'end
984 "Position where new footnotes are inserted in the document."
985 :group 'markdown
986 :type '(choice (const :tag "At the end of the document" end)
987 (const :tag "Immediately after the current block" immediately)
988 (const :tag "Before next header" header)))
990 (defcustom markdown-unordered-list-item-prefix " * "
991 "String inserted before unordered list items."
992 :group 'markdown
993 :type 'string)
995 (defcustom markdown-font-lock-support-mode 'jit-lock-mode
996 "Support modes speed up Font Lock by being selective about when
997 fontification occurs. Because Markdown has many multline
998 constructions by nature, `markdown-mode' is aggressive about Font
999 Lock by default. If fontification is inaccurate, try setting this
1000 to `nil' instead. See `font-lock-support-mode' for more details."
1001 :type '(choice (const :tag "none" nil)
1002 (const :tag "fast lock" fast-lock-mode)
1003 (const :tag "lazy lock" lazy-lock-mode)
1004 (const :tag "jit lock" jit-lock-mode)))
1006 (defcustom markdown-make-gfm-checkboxes-buttons t
1007 "When non-nil, make GFM checkboxes into buttons."
1008 :group 'markdown
1009 :type 'boolean)
1011 (defcustom markdown-live-preview-window-function 'markdown-live-preview-window-eww
1012 "Function to display preview of Markdown output within Emacs. Function must
1013 update the buffer containing the preview and return the buffer."
1014 :group 'markdown
1015 :type 'function)
1017 (defcustom markdown-live-preview-delete-export t
1018 "When non-nil, deleted exported html file when using
1019 `markdown-live-preview-export'."
1020 :group 'markdown
1021 :type 'boolean)
1024 ;;; Font Lock =================================================================
1026 (require 'font-lock)
1028 (defvar markdown-italic-face 'markdown-italic-face
1029 "Face name to use for italic text.")
1031 (defvar markdown-bold-face 'markdown-bold-face
1032 "Face name to use for bold text.")
1034 (defvar markdown-strike-through-face 'markdown-strike-through-face
1035 "Face name to use for strike-through text.")
1037 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1038 "Face name to use as a base for header delimiters.")
1040 (defvar markdown-header-rule-face 'markdown-header-rule-face
1041 "Face name to use as a base for header rules.")
1043 (defvar markdown-header-face 'markdown-header-face
1044 "Face name to use as a base for headers.")
1046 (defvar markdown-header-face-1 'markdown-header-face-1
1047 "Face name to use for level-1 headers.")
1049 (defvar markdown-header-face-2 'markdown-header-face-2
1050 "Face name to use for level-2 headers.")
1052 (defvar markdown-header-face-3 'markdown-header-face-3
1053 "Face name to use for level-3 headers.")
1055 (defvar markdown-header-face-4 'markdown-header-face-4
1056 "Face name to use for level-4 headers.")
1058 (defvar markdown-header-face-5 'markdown-header-face-5
1059 "Face name to use for level-5 headers.")
1061 (defvar markdown-header-face-6 'markdown-header-face-6
1062 "Face name to use for level-6 headers.")
1064 (defvar markdown-inline-code-face 'markdown-inline-code-face
1065 "Face name to use for inline code.")
1067 (defvar markdown-list-face 'markdown-list-face
1068 "Face name to use for list markers.")
1070 (defvar markdown-blockquote-face 'markdown-blockquote-face
1071 "Face name to use for blockquote.")
1073 (defvar markdown-pre-face 'markdown-pre-face
1074 "Face name to use for preformatted text.")
1076 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1077 "Face name to use for programming language identifiers.")
1079 (defvar markdown-link-face 'markdown-link-face
1080 "Face name to use for links.")
1082 (defvar markdown-missing-link-face 'markdown-missing-link-face
1083 "Face name to use for links where the linked file does not exist.")
1085 (defvar markdown-reference-face 'markdown-reference-face
1086 "Face name to use for reference.")
1088 (defvar markdown-footnote-face 'markdown-footnote-face
1089 "Face name to use for footnote identifiers.")
1091 (defvar markdown-url-face 'markdown-url-face
1092 "Face name to use for URLs.")
1094 (defvar markdown-link-title-face 'markdown-link-title-face
1095 "Face name to use for reference link titles.")
1097 (defvar markdown-line-break-face 'markdown-line-break-face
1098 "Face name to use for hard line breaks.")
1100 (defvar markdown-comment-face 'markdown-comment-face
1101 "Face name to use for HTML comments.")
1103 (defvar markdown-math-face 'markdown-math-face
1104 "Face name to use for LaTeX expressions.")
1106 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
1107 "Face name to use for metadata keys.")
1109 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
1110 "Face name to use for metadata values.")
1112 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
1113 "Face name to use for GFM checkboxes.")
1115 (defvar markdown-highlight-face 'markdown-highlight-face
1116 "Face name to use for mouse highlighting.")
1118 (defvar markdown-markup-face 'markdown-markup-face
1119 "Face name to use for markup elements.")
1121 (defgroup markdown-faces nil
1122 "Faces used in Markdown Mode"
1123 :group 'markdown
1124 :group 'faces)
1126 (defface markdown-italic-face
1127 '((t (:inherit font-lock-variable-name-face :slant italic)))
1128 "Face for italic text."
1129 :group 'markdown-faces)
1131 (defface markdown-bold-face
1132 '((t (:inherit font-lock-variable-name-face :weight bold)))
1133 "Face for bold text."
1134 :group 'markdown-faces)
1136 (defface markdown-strike-through-face
1137 '((t (:inherit font-lock-variable-name-face :strike-through t)))
1138 "Face for strike-through text."
1139 :group 'markdown-faces)
1141 (defface markdown-markup-face
1142 '((t (:inherit shadow :slant normal :weight normal)))
1143 "Face for markup elements."
1144 :group 'markdown-faces)
1146 (defface markdown-header-rule-face
1147 '((t (:inherit markdown-markup-face)))
1148 "Base face for headers rules."
1149 :group 'markdown-faces)
1151 (defface markdown-header-delimiter-face
1152 '((t (:inherit markdown-markup-face)))
1153 "Base face for headers hash delimiter."
1154 :group 'markdown-faces)
1156 (defface markdown-header-face
1157 '((t (:inherit font-lock-function-name-face :weight bold)))
1158 "Base face for headers."
1159 :group 'markdown-faces)
1161 (defface markdown-header-face-1
1162 '((t (:inherit markdown-header-face)))
1163 "Face for level-1 headers."
1164 :group 'markdown-faces)
1166 (defface markdown-header-face-2
1167 '((t (:inherit markdown-header-face)))
1168 "Face for level-2 headers."
1169 :group 'markdown-faces)
1171 (defface markdown-header-face-3
1172 '((t (:inherit markdown-header-face)))
1173 "Face for level-3 headers."
1174 :group 'markdown-faces)
1176 (defface markdown-header-face-4
1177 '((t (:inherit markdown-header-face)))
1178 "Face for level-4 headers."
1179 :group 'markdown-faces)
1181 (defface markdown-header-face-5
1182 '((t (:inherit markdown-header-face)))
1183 "Face for level-5 headers."
1184 :group 'markdown-faces)
1186 (defface markdown-header-face-6
1187 '((t (:inherit markdown-header-face)))
1188 "Face for level-6 headers."
1189 :group 'markdown-faces)
1191 (defface markdown-inline-code-face
1192 '((t (:inherit font-lock-constant-face)))
1193 "Face for inline code."
1194 :group 'markdown-faces)
1196 (defface markdown-list-face
1197 '((t (:inherit markdown-markup-face)))
1198 "Face for list item markers."
1199 :group 'markdown-faces)
1201 (defface markdown-blockquote-face
1202 '((t (:inherit font-lock-doc-face)))
1203 "Face for blockquote sections."
1204 :group 'markdown-faces)
1206 (defface markdown-pre-face
1207 '((t (:inherit font-lock-constant-face)))
1208 "Face for preformatted text."
1209 :group 'markdown-faces)
1211 (defface markdown-language-keyword-face
1212 '((t (:inherit font-lock-type-face)))
1213 "Face for programming language identifiers."
1214 :group 'markdown-faces)
1216 (defface markdown-link-face
1217 '((t (:inherit font-lock-keyword-face)))
1218 "Face for links."
1219 :group 'markdown-faces)
1221 (defface markdown-missing-link-face
1222 '((t (:inherit font-lock-warning-face)))
1223 "Face for missing links."
1224 :group 'markdown-faces)
1226 (defface markdown-reference-face
1227 '((t (:inherit markdown-markup-face)))
1228 "Face for link references."
1229 :group 'markdown-faces)
1231 (defface markdown-footnote-face
1232 '((t (:inherit markdown-markup-face)))
1233 "Face for footnote markers."
1234 :group 'markdown-faces)
1236 (defface markdown-url-face
1237 '((t (:inherit font-lock-string-face)))
1238 "Face for URLs."
1239 :group 'markdown-faces)
1241 (defface markdown-link-title-face
1242 '((t (:inherit font-lock-comment-face)))
1243 "Face for reference link titles."
1244 :group 'markdown-faces)
1246 (defface markdown-line-break-face
1247 '((t (:inherit font-lock-constant-face :underline t)))
1248 "Face for hard line breaks."
1249 :group 'markdown-faces)
1251 (defface markdown-comment-face
1252 '((t (:inherit font-lock-comment-face)))
1253 "Face for HTML comments."
1254 :group 'markdown-faces)
1256 (defface markdown-math-face
1257 '((t (:inherit font-lock-string-face)))
1258 "Face for LaTeX expressions."
1259 :group 'markdown-faces)
1261 (defface markdown-metadata-key-face
1262 '((t (:inherit font-lock-variable-name-face)))
1263 "Face for metadata keys."
1264 :group 'markdown-faces)
1266 (defface markdown-metadata-value-face
1267 '((t (:inherit font-lock-string-face)))
1268 "Face for metadata values."
1269 :group 'markdown-faces)
1271 (defface markdown-gfm-checkbox-face
1272 '((t (:inherit font-lock-builtin-face)))
1273 "Face for GFM checkboxes."
1274 :group 'markdown-faces)
1276 (defface markdown-highlight-face
1277 '((t (:inherit highlight)))
1278 "Face for mouse highlighting."
1279 :group 'markdown-faces)
1281 (defconst markdown-regex-link-inline
1282 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1283 "Regular expression for a [text](file) or an image link ![text](file).
1284 Group 1 matches the leading exclamation point (optional).
1285 Group 2 matches the opening square bracket.
1286 Group 3 matches the text inside the square brackets.
1287 Group 4 matches the closing square bracket.
1288 Group 5 matches the opening parenthesis.
1289 Group 6 matches the URL.
1290 Group 7 matches the title (optional).
1291 Group 8 matches the closing parenthesis.")
1293 (defconst markdown-regex-link-reference
1294 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1295 "Regular expression for a reference link [text][id].
1296 Group 1 matches the leading exclamation point (optional).
1297 Group 2 matches the opening square bracket for the link text.
1298 Group 3 matches the text inside the square brackets.
1299 Group 4 matches the closing square bracket for the link text.
1300 Group 5 matches the opening square bracket for the reference label.
1301 Group 6 matches the reference label.
1302 Group 7 matches the closing square bracket for the reference label.")
1304 (defconst markdown-regex-reference-definition
1305 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1306 "Regular expression for a reference definition.
1307 Group 1 matches the opening square bracket.
1308 Group 2 matches the reference label.
1309 Group 3 matches the closing square bracket.
1310 Group 4 matches the colon.
1311 Group 5 matches the URL.
1312 Group 6 matches the title attribute (optional).")
1314 (defconst markdown-regex-footnote
1315 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1316 "Regular expression for a footnote marker [^fn].
1317 Group 1 matches the opening square bracket and carat.
1318 Group 2 matches only the label, without the surrounding markup.
1319 Group 3 matches the closing square bracket.")
1321 (defconst markdown-regex-header
1322 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1323 "Regexp identifying Markdown headers.")
1325 (defconst markdown-regex-header-1-atx
1326 "^\\(#\\)[ \t]*\\([^\\.].*?\\)[ \t]*\\(#*\\)$"
1327 "Regular expression for level 1 atx-style (hash mark) headers.")
1329 (defconst markdown-regex-header-2-atx
1330 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1331 "Regular expression for level 2 atx-style (hash mark) headers.")
1333 (defconst markdown-regex-header-3-atx
1334 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1335 "Regular expression for level 3 atx-style (hash mark) headers.")
1337 (defconst markdown-regex-header-4-atx
1338 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1339 "Regular expression for level 4 atx-style (hash mark) headers.")
1341 (defconst markdown-regex-header-5-atx
1342 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1343 "Regular expression for level 5 atx-style (hash mark) headers.")
1345 (defconst markdown-regex-header-6-atx
1346 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1347 "Regular expression for level 6 atx-style (hash mark) headers.")
1349 (defconst markdown-regex-header-1-setext
1350 "^\\(.*\\)\n\\(=+\\)$"
1351 "Regular expression for level 1 setext-style (underline) headers.")
1353 (defconst markdown-regex-header-2-setext
1354 "^\\(.*\\)\n\\(-+\\)$"
1355 "Regular expression for level 2 setext-style (underline) headers.")
1357 (defconst markdown-regex-header-setext
1358 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1359 "Regular expression for generic setext-style (underline) headers.")
1361 (defconst markdown-regex-header-atx
1362 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1363 "Regular expression for generic atx-style (hash mark) headers.")
1365 (defconst markdown-regex-hr
1366 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1367 "Regular expression for matching Markdown horizontal rules.")
1369 (defconst markdown-regex-code
1370 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1371 "Regular expression for matching inline code fragments.
1373 Group 1 matches the entire code fragment including the backticks.
1374 Group 2 matches the opening backticks.
1375 Group 3 matches the code fragment itself, without backticks.
1376 Group 4 matches the closing backticks.
1378 The leading, unnumbered group ensures that the leading backquote
1379 character is not escaped.
1380 The last group, also unnumbered, requires that the character
1381 following the code fragment is not a backquote.
1382 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1383 but not two newlines in a row.")
1385 (defconst markdown-regex-kbd
1386 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1387 "Regular expression for matching <kbd> tags.
1388 Groups 1 and 3 match the opening and closing tags.
1389 Group 2 matches the key sequence.")
1391 (defconst markdown-regex-pre
1392 "^\\( \\|\t\\).*$"
1393 "Regular expression for matching preformatted text sections.")
1395 (defconst markdown-regex-list
1396 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1397 "Regular expression for matching list items.")
1399 (defconst markdown-regex-bold
1400 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1401 "Regular expression for matching bold text.
1402 Group 1 matches the character before the opening asterisk or
1403 underscore, if any, ensuring that it is not a backslash escape.
1404 Group 2 matches the entire expression, including delimiters.
1405 Groups 3 and 5 matches the opening and closing delimiters.
1406 Group 4 matches the text inside the delimiters.")
1408 (defconst markdown-regex-italic
1409 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1410 "Regular expression for matching italic text.
1411 The leading unnumbered matches the character before the opening
1412 asterisk or underscore, if any, ensuring that it is not a
1413 backslash escape.
1414 Group 1 matches the entire expression, including delimiters.
1415 Groups 2 and 4 matches the opening and closing delimiters.
1416 Group 3 matches the text inside the delimiters.")
1418 (defconst markdown-regex-strike-through
1419 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1420 "Regular expression for matching strike-through text.
1421 Group 1 matches the character before the opening tilde, if any,
1422 ensuring that it is not a backslash escape.
1423 Group 2 matches the entire expression, including delimiters.
1424 Groups 3 and 5 matches the opening and closing delimiters.
1425 Group 4 matches the text inside the delimiters.")
1427 (defconst markdown-regex-gfm-italic
1428 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1429 "Regular expression for matching italic text in GitHub Flavored Markdown.
1430 Underscores in words are not treated as special.
1431 Group 1 matches the entire expression, including delimiters.
1432 Groups 2 and 4 matches the opening and closing delimiters.
1433 Group 3 matches the text inside the delimiters.")
1435 (defconst markdown-regex-blockquote
1436 "^[ \t]*\\(>\\)\\(.*\\)$"
1437 "Regular expression for matching blockquote lines.
1438 Group 1 matches the leading angle bracket.
1439 Group 2 matches the text.")
1441 (defconst markdown-regex-line-break
1442 "[^ \n\t][ \t]*\\( \\)$"
1443 "Regular expression for matching line breaks.")
1445 (defconst markdown-regex-wiki-link
1446 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1447 "Regular expression for matching wiki links.
1448 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1449 wiki links of the form [[PageName|link text]].
1450 The meanings of the first and second components depend
1451 on the value of `markdown-wiki-link-alias-first'.
1453 Group 1 matches the entire link.
1454 Group 2 matches the opening square brackets.
1455 Group 3 matches the first component of the wiki link.
1456 Group 4 matches the pipe separator, when present.
1457 Group 5 matches the second component of the wiki link, when present.
1458 Group 6 matches the closing square brackets.")
1460 (defconst markdown-regex-uri
1461 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1462 "Regular expression for matching inline URIs.")
1464 (defconst markdown-regex-angle-uri
1465 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1466 "Regular expression for matching inline URIs in angle brackets.")
1468 (defconst markdown-regex-email
1469 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1470 "Regular expression for matching inline email addresses.")
1472 (defconst markdown-regex-link-generic
1473 (concat "\\(?:" markdown-regex-wiki-link
1474 "\\|" markdown-regex-link-inline
1475 "\\|" markdown-regex-link-reference
1476 "\\|" markdown-regex-angle-uri "\\)")
1477 "Regular expression for matching any recognized link.")
1479 (defconst markdown-regex-gfm-checkbox
1480 " \\(\\[[ xX]\\]\\) "
1481 "Regular expression for matching GFM checkboxes.
1482 Group 1 matches the text to become a button.")
1484 (defconst markdown-regex-block-separator
1485 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1486 "Regular expression for matching block boundaries.")
1488 (defconst markdown-regex-math-inline-single
1489 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1490 "Regular expression for itex $..$ math mode expressions.
1491 Groups 1 and 3 match the opening and closing dollar signs.
1492 Group 3 matches the mathematical expression contained within.")
1494 (defconst markdown-regex-math-inline-double
1495 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1496 "Regular expression for itex $$..$$ math mode expressions.
1497 Groups 1 and 3 match opening and closing dollar signs.
1498 Group 3 matches the mathematical expression contained within.")
1500 (defconst markdown-regex-math-display
1501 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*\\)?\\(\\\\\\]\\)$"
1502 "Regular expression for itex \[..\] display mode expressions.
1503 Groups 1 and 3 matche the opening and closing delimiters.
1504 Group 2 matches the mathematical expression contained within.")
1506 (defconst markdown-regex-multimarkdown-metadata
1507 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\(:[ \t]*\\)\\(.*\\)$"
1508 "Regular expression for matching MultiMarkdown metadata.")
1510 (defconst markdown-regex-pandoc-metadata
1511 "^\\(%\\)\\([ \t]*\\)\\(.*\\)$"
1512 "Regular expression for matching Pandoc metadata.")
1514 (defvar markdown-mode-font-lock-keywords-basic
1515 (list
1516 (cons 'markdown-match-gfm-code-blocks '((1 markdown-markup-face)
1517 (2 markdown-language-keyword-face nil t)
1518 (3 markdown-pre-face)
1519 (4 markdown-markup-face)))
1520 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1521 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1522 (cons markdown-regex-blockquote '((1 markdown-markup-face)
1523 (2 markdown-blockquote-face)))
1524 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1525 (2 markdown-header-rule-face)))
1526 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1527 (2 markdown-header-rule-face)))
1528 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1529 (2 markdown-header-face-6)
1530 (3 markdown-header-delimiter-face)))
1531 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1532 (2 markdown-header-face-5)
1533 (3 markdown-header-delimiter-face)))
1534 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1535 (2 markdown-header-face-4)
1536 (3 markdown-header-delimiter-face)))
1537 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1538 (2 markdown-header-face-3)
1539 (3 markdown-header-delimiter-face)))
1540 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1541 (2 markdown-header-face-2)
1542 (3 markdown-header-delimiter-face)))
1543 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1544 (2 markdown-header-face-1)
1545 (3 markdown-header-delimiter-face)))
1546 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1547 (2 markdown-markup-face)
1548 (3 markdown-metadata-value-face)))
1549 (cons 'markdown-match-pandoc-metadata '((1 markdown-markup-face)
1550 (2 markdown-markup-face)
1551 (3 markdown-metadata-value-face)))
1552 (cons markdown-regex-hr 'markdown-header-delimiter-face)
1553 (cons 'markdown-match-comments '((0 markdown-comment-face)))
1554 (cons 'markdown-match-code '((1 markdown-markup-face)
1555 (2 markdown-inline-code-face)
1556 (3 markdown-markup-face)))
1557 (cons markdown-regex-kbd '((1 markdown-markup-face)
1558 (2 markdown-inline-code-face)
1559 (3 markdown-markup-face)))
1560 (cons markdown-regex-angle-uri '((1 markdown-markup-face)
1561 (2 markdown-link-face)
1562 (3 markdown-markup-face)))
1563 (cons markdown-regex-list '(2 markdown-list-face))
1564 (cons markdown-regex-footnote '((1 markdown-markup-face) ; [^
1565 (2 markdown-footnote-face) ; label
1566 (3 markdown-markup-face))) ; ]
1567 (cons markdown-regex-link-inline '((1 markdown-markup-face nil t) ; ! (optional)
1568 (2 markdown-markup-face) ; [
1569 (3 markdown-link-face) ; text
1570 (4 markdown-markup-face) ; ]
1571 (5 markdown-markup-face) ; (
1572 (6 markdown-url-face) ; url
1573 (7 markdown-link-title-face nil t) ; "title" (optional)
1574 (8 markdown-markup-face))) ; )
1575 (cons markdown-regex-link-reference '((1 markdown-markup-face nil t) ; ! (optional)
1576 (2 markdown-markup-face) ; [
1577 (3 markdown-link-face) ; text
1578 (4 markdown-markup-face) ; ]
1579 (5 markdown-markup-face) ; [
1580 (6 markdown-reference-face) ; label
1581 (7 markdown-markup-face))) ; ]
1582 (cons markdown-regex-reference-definition '((1 markdown-markup-face) ; [
1583 (2 markdown-reference-face) ; label
1584 (3 markdown-markup-face) ; ]
1585 (4 markdown-markup-face) ; :
1586 (5 markdown-url-face) ; url
1587 (6 markdown-link-title-face))) ; "title" (optional)
1588 (cons markdown-regex-bold '((3 markdown-markup-face)
1589 (4 markdown-bold-face)
1590 (5 markdown-markup-face)))
1591 (cons markdown-regex-uri 'markdown-link-face)
1592 (cons markdown-regex-email 'markdown-link-face)
1593 (cons markdown-regex-line-break '(1 markdown-line-break-face prepend))
1595 "Syntax highlighting for Markdown files.")
1597 (defvar markdown-mode-font-lock-keywords-core
1598 (list
1599 (cons markdown-regex-italic '((2 markdown-markup-face)
1600 (3 markdown-italic-face)
1601 (4 markdown-markup-face)))
1603 "Additional syntax highlighting for Markdown files.
1604 Includes features which are overridden by some variants.")
1606 (defconst markdown-mode-font-lock-keywords-math
1607 (list
1608 ;; Math mode $..$
1609 (cons markdown-regex-math-inline-single '((1 markdown-markup-face)
1610 (2 markdown-math-face)
1611 (3 markdown-markup-face)))
1612 ;; Math mode $$..$$
1613 (cons markdown-regex-math-inline-double '((1 markdown-markup-face)
1614 (2 markdown-math-face)
1615 (3 markdown-markup-face)))
1616 ;; Display mode equations with brackets: \[ \]
1617 (cons markdown-regex-math-display '((1 markdown-markup-face)
1618 (2 markdown-math-face)
1619 (3 markdown-markup-face)))
1620 ;; Equation reference (eq:foo)
1621 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
1622 (2 markdown-reference-face)
1623 (3 markdown-markup-face)))
1624 ;; Equation reference \eqref{foo}
1625 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
1626 (2 markdown-reference-face)
1627 (3 markdown-markup-face))))
1628 "Syntax highlighting for LaTeX and itex fragments.")
1630 (defvar markdown-mode-font-lock-keywords nil
1631 "Default highlighting expressions for Markdown mode.
1632 This variable is defined as a buffer-local variable for dynamic
1633 extension support.")
1635 ;; Footnotes
1636 (defvar markdown-footnote-counter 0
1637 "Counter for footnote numbers.")
1638 (make-variable-buffer-local 'markdown-footnote-counter)
1640 (defconst markdown-footnote-chars
1641 "[[:alnum:]-]"
1642 "Regular expression maching any character that is allowed in a footnote identifier.")
1644 (defconst markdown-regex-footnote-definition
1645 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
1646 "Regular expression matching a footnote definition, capturing the label.")
1649 ;;; Compatibility =============================================================
1651 (defun markdown-replace-regexp-in-string (regexp rep string)
1652 "Replace ocurrences of REGEXP with REP in STRING.
1653 This is a compatibility wrapper to provide `replace-regexp-in-string'
1654 in XEmacs 21."
1655 (if (featurep 'xemacs)
1656 (replace-in-string string regexp rep)
1657 (replace-regexp-in-string regexp rep string)))
1659 ;; `markdown-use-region-p' is a compatibility function which checks
1660 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1661 (eval-and-compile
1662 (cond
1663 ;; Emacs 23 and newer
1664 ((fboundp 'use-region-p)
1665 (defalias 'markdown-use-region-p 'use-region-p))
1666 ;; Older Emacsen
1667 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1668 (defun markdown-use-region-p ()
1669 "Compatibility wrapper to provide `use-region-p'."
1670 (and transient-mark-mode mark-active)))
1671 ;; XEmacs
1672 ((fboundp 'region-active-p)
1673 (defalias 'markdown-use-region-p 'region-active-p))))
1675 (defun markdown-use-buttons-p ()
1676 "Determine whether this Emacs supports buttons."
1677 (or (featurep 'button) (locate-library "button")))
1680 ;;; Markdown Parsing Functions ================================================
1682 (defun markdown-cur-line-blank-p ()
1683 "Return t if the current line is blank and nil otherwise."
1684 (save-excursion
1685 (beginning-of-line)
1686 (re-search-forward "^\\s *$" (line-end-position) t)))
1688 (defun markdown-prev-line-blank-p ()
1689 "Return t if the previous line is blank and nil otherwise.
1690 If we are at the first line, then consider the previous line to be blank."
1691 (or (= (line-beginning-position) (point-min))
1692 (save-excursion
1693 (forward-line -1)
1694 (markdown-cur-line-blank-p))))
1696 (defun markdown-next-line-blank-p ()
1697 "Return t if the next line is blank and nil otherwise.
1698 If we are at the last line, then consider the next line to be blank."
1699 (or (= (line-end-position) (point-max))
1700 (save-excursion
1701 (forward-line 1)
1702 (markdown-cur-line-blank-p))))
1704 (defun markdown-prev-line-indent-p ()
1705 "Return t if the previous line is indented and nil otherwise."
1706 (save-excursion
1707 (if (= (line-beginning-position) (point-min))
1709 (forward-line -1)
1710 (goto-char (line-beginning-position))
1711 (if (re-search-forward "^\\s " (line-end-position) t) t))))
1713 (defun markdown-cur-line-indent ()
1714 "Return the number of leading whitespace characters in the current line."
1715 (save-match-data
1716 (save-excursion
1717 (goto-char (line-beginning-position))
1718 (re-search-forward "^[ \t]+" (line-end-position) t)
1719 (current-column))))
1721 (defun markdown-prev-line-indent ()
1722 "Return the number of leading whitespace characters in the previous line.
1723 Return 0 if the current line is the first line in the buffer."
1724 (save-excursion
1725 (if (= (line-beginning-position) (point-min))
1727 (forward-line -1)
1728 (markdown-cur-line-indent))))
1730 (defun markdown-next-line-indent ()
1731 "Return the number of leading whitespace characters in the next line.
1732 Return 0 if line is the last line in the buffer."
1733 (save-excursion
1734 (if (= (line-end-position) (point-max))
1736 (forward-line 1)
1737 (markdown-cur-line-indent))))
1739 (defun markdown-cur-non-list-indent ()
1740 "Return beginning position of list item text (not including the list marker).
1741 Return nil if the current line is not the beginning of a list item."
1742 (save-match-data
1743 (save-excursion
1744 (beginning-of-line)
1745 (when (re-search-forward markdown-regex-list (line-end-position) t)
1746 (current-column)))))
1748 (defun markdown-prev-non-list-indent ()
1749 "Return position of the first non-list-marker on the previous line."
1750 (save-excursion
1751 (forward-line -1)
1752 (markdown-cur-non-list-indent)))
1754 (defun markdown-new-baseline-p ()
1755 "Determine if the current line begins a new baseline level."
1756 (save-excursion
1757 (beginning-of-line)
1758 (save-match-data
1759 (or (looking-at markdown-regex-header)
1760 (looking-at markdown-regex-hr)
1761 (and (null (markdown-cur-non-list-indent))
1762 (= (markdown-cur-line-indent) 0)
1763 (markdown-prev-line-blank-p))))))
1765 (defun markdown-search-backward-baseline ()
1766 "Search backward baseline point with no indentation and not a list item."
1767 (end-of-line)
1768 (let (stop)
1769 (while (not (or stop (bobp)))
1770 (re-search-backward markdown-regex-block-separator nil t)
1771 (when (match-end 2)
1772 (goto-char (match-end 2))
1773 (cond
1774 ((markdown-new-baseline-p)
1775 (setq stop t))
1776 ((looking-at markdown-regex-list)
1777 (setq stop nil))
1778 (t (setq stop t)))))))
1780 (defun markdown-update-list-levels (marker indent levels)
1781 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1782 Here, MARKER is a string representing the type of list, INDENT is an integer
1783 giving the indentation, in spaces, of the current block, and LEVELS is a
1784 list of the indentation levels of parent list items. When LEVELS is nil,
1785 it means we are at baseline (not inside of a nested list)."
1786 (cond
1787 ;; New list item at baseline.
1788 ((and marker (null levels))
1789 (setq levels (list indent)))
1790 ;; List item with greater indentation (four or more spaces).
1791 ;; Increase list level.
1792 ((and marker (>= indent (+ (car levels) 4)))
1793 (setq levels (cons indent levels)))
1794 ;; List item with greater or equal indentation (less than four spaces).
1795 ;; Do not increase list level.
1796 ((and marker (>= indent (car levels)))
1797 levels)
1798 ;; Lesser indentation level.
1799 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1800 ;; indentation could move back more than one list level). Note
1801 ;; that this block need not be the beginning of list item.
1802 ((< indent (car levels))
1803 (while (and (> (length levels) 1)
1804 (< indent (+ (cadr levels) 4)))
1805 (setq levels (cdr levels)))
1806 levels)
1807 ;; Otherwise, do nothing.
1808 (t levels)))
1810 (defun markdown-calculate-list-levels ()
1811 "Calculate list levels at point.
1812 Return a list of the form (n1 n2 n3 ...) where n1 is the
1813 indentation of the deepest nested list item in the branch of
1814 the list at the point, n2 is the indentation of the parent
1815 list item, and so on. The depth of the list item is therefore
1816 the length of the returned list. If the point is not at or
1817 immediately after a list item, return nil."
1818 (save-excursion
1819 (let ((first (point)) levels indent pre-regexp)
1820 ;; Find a baseline point with zero list indentation
1821 (markdown-search-backward-baseline)
1822 ;; Search for all list items between baseline and LOC
1823 (while (and (< (point) first)
1824 (re-search-forward markdown-regex-list first t))
1825 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1826 (beginning-of-line)
1827 (cond
1828 ;; Make sure this is not a header or hr
1829 ((markdown-new-baseline-p) (setq levels nil))
1830 ;; Make sure this is not a line from a pre block
1831 ((looking-at pre-regexp))
1832 ;; If not, then update levels
1834 (setq indent (markdown-cur-line-indent))
1835 (setq levels (markdown-update-list-levels (match-string 2)
1836 indent levels))))
1837 (end-of-line))
1838 levels)))
1840 (defun markdown-prev-list-item (level)
1841 "Search backward from point for a list item with indentation LEVEL.
1842 Set point to the beginning of the item, and return point, or nil
1843 upon failure."
1844 (let (bounds indent prev)
1845 (setq prev (point))
1846 (forward-line -1)
1847 (setq indent (markdown-cur-line-indent))
1848 (while
1849 (cond
1850 ;; Stop at beginning of buffer
1851 ((bobp) (setq prev nil))
1852 ;; Continue if current line is blank
1853 ((markdown-cur-line-blank-p) t)
1854 ;; List item
1855 ((and (looking-at markdown-regex-list)
1856 (setq bounds (markdown-cur-list-item-bounds)))
1857 (cond
1858 ;; Continue at item with greater indentation
1859 ((> (nth 3 bounds) level) t)
1860 ;; Stop and return point at item of equal indentation
1861 ((= (nth 3 bounds) level)
1862 (setq prev (point))
1863 nil)
1864 ;; Stop and return nil at item with lesser indentation
1865 ((< (nth 3 bounds) level)
1866 (setq prev nil)
1867 nil)))
1868 ;; Continue while indentation is the same or greater
1869 ((>= indent level) t)
1870 ;; Stop if current indentation is less than list item
1871 ;; and the next is blank
1872 ((and (< indent level)
1873 (markdown-next-line-blank-p))
1874 (setq prev nil))
1875 ;; Stop at a header
1876 ((looking-at markdown-regex-header) (setq prev nil))
1877 ;; Stop at a horizontal rule
1878 ((looking-at markdown-regex-hr) (setq prev nil))
1879 ;; Otherwise, continue.
1880 (t t))
1881 (forward-line -1)
1882 (setq indent (markdown-cur-line-indent)))
1883 prev))
1885 (defun markdown-next-list-item (level)
1886 "Search forward from point for the next list item with indentation LEVEL.
1887 Set point to the beginning of the item, and return point, or nil
1888 upon failure."
1889 (let (bounds indent prev next)
1890 (setq next (point))
1891 (forward-line)
1892 (setq indent (markdown-cur-line-indent))
1893 (while
1894 (cond
1895 ;; Stop at end of the buffer.
1896 ((eobp) (setq prev nil))
1897 ;; Continue if the current line is blank
1898 ((markdown-cur-line-blank-p) t)
1899 ;; List item
1900 ((and (looking-at markdown-regex-list)
1901 (setq bounds (markdown-cur-list-item-bounds)))
1902 (cond
1903 ;; Continue at item with greater indentation
1904 ((> (nth 3 bounds) level) t)
1905 ;; Stop and return point at item of equal indentation
1906 ((= (nth 3 bounds) level)
1907 (setq next (point))
1908 nil)
1909 ;; Stop and return nil at item with lesser indentation
1910 ((< (nth 3 bounds) level)
1911 (setq next nil)
1912 nil)))
1913 ;; Continue while indentation is the same or greater
1914 ((>= indent level) t)
1915 ;; Stop if current indentation is less than list item
1916 ;; and the previous line was blank.
1917 ((and (< indent level)
1918 (markdown-prev-line-blank-p))
1919 (setq next nil))
1920 ;; Stop at a header
1921 ((looking-at markdown-regex-header) (setq next nil))
1922 ;; Stop at a horizontal rule
1923 ((looking-at markdown-regex-hr) (setq next nil))
1924 ;; Otherwise, continue.
1925 (t t))
1926 (forward-line)
1927 (setq indent (markdown-cur-line-indent)))
1928 next))
1930 (defun markdown-cur-list-item-end (level)
1931 "Move to the end of the current list item with nonlist indentation LEVEL.
1932 If the point is not in a list item, do nothing."
1933 (let (indent)
1934 (forward-line)
1935 (setq indent (markdown-cur-line-indent))
1936 (while
1937 (cond
1938 ;; Stop at end of the buffer.
1939 ((eobp) nil)
1940 ;; Continue if the current line is blank
1941 ((markdown-cur-line-blank-p) t)
1942 ;; Continue while indentation is the same or greater
1943 ((>= indent level) t)
1944 ;; Stop if current indentation is less than list item
1945 ;; and the previous line was blank.
1946 ((and (< indent level)
1947 (markdown-prev-line-blank-p))
1948 nil)
1949 ;; Stop at a new list item of the same or lesser indentation
1950 ((looking-at markdown-regex-list) nil)
1951 ;; Stop at a header
1952 ((looking-at markdown-regex-header) nil)
1953 ;; Stop at a horizontal rule
1954 ((looking-at markdown-regex-hr) nil)
1955 ;; Otherwise, continue.
1956 (t t))
1957 (forward-line)
1958 (setq indent (markdown-cur-line-indent)))
1959 ;; Don't skip over whitespace for empty list items (marker and
1960 ;; whitespace only), just move to end of whitespace.
1961 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
1962 (goto-char (match-end 3))
1963 (skip-syntax-backward "-"))))
1965 (defun markdown-cur-list-item-bounds ()
1966 "Return bounds and indentation of the current list item.
1967 Return a list of the form (begin end indent nonlist-indent marker).
1968 If the point is not inside a list item, return nil.
1969 Leave match data intact for `markdown-regex-list'."
1970 (let (cur prev-begin prev-end indent nonlist-indent marker)
1971 ;; Store current location
1972 (setq cur (point))
1973 ;; Verify that cur is between beginning and end of item
1974 (save-excursion
1975 (end-of-line)
1976 (when (re-search-backward markdown-regex-list nil t)
1977 (setq prev-begin (match-beginning 0))
1978 (setq indent (length (match-string 1)))
1979 (setq nonlist-indent (length (match-string 0)))
1980 (setq marker (concat (match-string 2) (match-string 3)))
1981 (save-match-data
1982 (markdown-cur-list-item-end nonlist-indent)
1983 (setq prev-end (point)))
1984 (when (and (>= cur prev-begin)
1985 (<= cur prev-end)
1986 nonlist-indent)
1987 (list prev-begin prev-end indent nonlist-indent marker))))))
1989 (defun markdown-bounds-of-thing-at-point (thing)
1990 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1991 Does not include trailing newlines when THING is 'line. Handles the
1992 end of buffer case by setting both endpoints equal to the value of
1993 `point-max', since an empty region will trigger empty markup insertion.
1994 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1995 (let* ((bounds (bounds-of-thing-at-point thing))
1996 (a (car bounds))
1997 (b (cdr bounds)))
1998 (when bounds
1999 (when (eq thing 'line)
2000 (cond ((and (eobp) (markdown-cur-line-blank-p))
2001 (setq a b))
2002 ((char-equal (char-before b) ?\^J)
2003 (setq b (1- b)))))
2004 (cons a b))))
2006 (defun markdown-reference-definition (reference)
2007 "Find out whether Markdown REFERENCE is defined.
2008 REFERENCE should not include the square brackets.
2009 When REFERENCE is defined, return a list of the form (text start end)
2010 containing the definition text itself followed by the start and end
2011 locations of the text. Otherwise, return nil.
2012 Leave match data for `markdown-regex-reference-definition'
2013 intact additional processing."
2014 (let ((reference (downcase reference)))
2015 (save-excursion
2016 (goto-char (point-min))
2017 (catch 'found
2018 (while (re-search-forward markdown-regex-reference-definition nil t)
2019 (when (string= reference (downcase (match-string-no-properties 2)))
2020 (throw 'found
2021 (list (match-string-no-properties 5)
2022 (match-beginning 5) (match-end 5)))))))))
2024 (defun markdown-get-defined-references ()
2025 "Return a list of all defined reference labels (not including square brackets)."
2026 (save-excursion
2027 (goto-char (point-min))
2028 (let (refs)
2029 (while (re-search-forward markdown-regex-reference-definition nil t)
2030 (let ((target (match-string-no-properties 2)))
2031 (add-to-list 'refs target t)))
2032 refs)))
2034 (defun markdown-code-at-point-p ()
2035 "Return non-nil if the point is at an inline code fragment.
2036 Return nil otherwise. Set match data according to
2037 `markdown-match-code' upon success.
2038 This function searches the block for a code fragment that
2039 contains the point using `markdown-match-code'. We do this
2040 because `thing-at-point-looking-at' does not work reliably with
2041 `markdown-regex-code'.
2043 The match data is set as follows:
2044 Group 1 matches the opening backticks.
2045 Group 2 matches the code fragment itself, without backticks.
2046 Group 3 matches the closing backticks."
2047 (interactive)
2048 (save-excursion
2049 (let ((old-point (point))
2050 (end-of-block (progn (markdown-end-of-block) (point)))
2051 found)
2052 (markdown-beginning-of-block)
2053 (while (and (markdown-match-code end-of-block)
2054 (setq found t)
2055 (< (match-end 0) old-point)))
2056 (and found ; matched something
2057 (<= (match-beginning 0) old-point) ; match contains old-point
2058 (>= (match-end 0) old-point)))))
2061 ;;; Markdown Font Lock Matching Functions =====================================
2063 (defun markdown-match-comments (last)
2064 "Match HTML comments from the point to LAST."
2065 (cond ((search-forward "<!--" last t)
2066 (backward-char 4)
2067 (let ((beg (point)))
2068 (cond ((search-forward-regexp "--[ \t]*>" last t)
2069 (set-match-data (list beg (point)))
2071 (t nil))))
2072 (t nil)))
2074 (defun markdown-match-code (last)
2075 "Match inline code from the point to LAST."
2076 (unless (bobp)
2077 (backward-char 1))
2078 (cond ((re-search-forward markdown-regex-code last t)
2079 (set-match-data (list (match-beginning 1) (match-end 1)
2080 (match-beginning 2) (match-end 2)
2081 (match-beginning 3) (match-end 3)
2082 (match-beginning 4) (match-end 4)))
2083 (goto-char (match-end 0))
2085 (t (forward-char 2) nil)))
2087 (defun markdown-match-pre-blocks (last)
2088 "Match Markdown pre blocks from point to LAST."
2089 (let ((levels (markdown-calculate-list-levels))
2090 indent pre-regexp end-regexp begin end stop)
2091 (while (and (< (point) last) (not end))
2092 ;; Search for a region with sufficient indentation
2093 (if (null levels)
2094 (setq indent 1)
2095 (setq indent (1+ (length levels))))
2096 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
2097 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
2099 (cond
2100 ;; If not at the beginning of a line, move forward
2101 ((not (bolp)) (forward-line))
2102 ;; Move past blank lines
2103 ((markdown-cur-line-blank-p) (forward-line))
2104 ;; At headers and horizontal rules, reset levels
2105 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
2106 ;; If the current line has sufficient indentation, mark out pre block
2107 ;; The opening should be preceded by a blank line.
2108 ((and (looking-at pre-regexp)
2109 (markdown-prev-line-blank-p))
2110 (setq begin (match-beginning 0))
2111 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
2112 (not (eobp)))
2113 (forward-line))
2114 (setq end (point)))
2115 ;; If current line has a list marker, update levels, move to end of block
2116 ((looking-at markdown-regex-list)
2117 (setq levels (markdown-update-list-levels
2118 (match-string 2) (markdown-cur-line-indent) levels))
2119 (markdown-end-of-block-element))
2120 ;; If this is the end of the indentation level, adjust levels accordingly.
2121 ;; Only match end of indentation level if levels is not the empty list.
2122 ((and (car levels) (looking-at end-regexp))
2123 (setq levels (markdown-update-list-levels
2124 nil (markdown-cur-line-indent) levels))
2125 (markdown-end-of-block-element))
2126 (t (markdown-end-of-block-element))))
2128 (if (not (and begin end))
2129 ;; Return nil if no pre block was found
2131 ;; Set match data and return t upon success
2132 (set-match-data (list begin end))
2133 t)))
2135 (defun markdown-match-fenced-code-blocks (last)
2136 "Match fenced code blocks from the point to LAST."
2137 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
2138 (beginning-of-line)
2139 (let ((beg (point)))
2140 (forward-line)
2141 (cond ((search-forward-regexp
2142 (concat "^" (match-string 1) "~*") last t)
2143 (set-match-data (list beg (point)))
2145 (t nil))))
2146 (t nil)))
2148 (defun markdown-match-gfm-code-blocks (last)
2149 "Match GFM quoted code blocks from point to LAST."
2150 (let (open lang body close all)
2151 (if (search-forward-regexp
2152 "\\(?:\\`\\|[\n\r]+\\s *[\n\r]\\)\\(```\\)[ ]?\\([^[:space:]]+[[:space:]]*\\|{[^}]*}\\)?$" last t)
2153 (progn
2154 (beginning-of-line)
2155 (setq open (list (match-beginning 1) (match-end 1))
2156 lang (list (match-beginning 2) (match-end 2)))
2157 (if (markdown-prev-line-blank-p)
2158 (progn
2159 (forward-line)
2160 (setq body (list (point)))
2161 (if (search-forward-regexp "^```$" last t)
2162 (progn
2163 (setq body (reverse (cons (1- (match-beginning 0)) body))
2164 close (list (match-beginning 0) (match-end 0))
2165 all (list (car open) (match-end 0)))
2166 (set-match-data (append all open lang body close))
2167 t)))))
2168 nil)))
2170 (defun markdown-match-generic-metadata (regexp last)
2171 "Match generic metadata specified by REGEXP from the point to LAST."
2172 (let ((header-end (save-excursion
2173 (goto-char (point-min))
2174 (if (re-search-forward "\n\n" (point-max) t)
2175 (match-beginning 0)
2176 (point-max)))))
2177 (cond ((>= (point) header-end)
2178 ;; Don't match anything outside of the header.
2179 nil)
2180 ((re-search-forward regexp (min last header-end) t)
2181 ;; If a metadata item is found, it may span several lines.
2182 (let ((key-beginning (match-beginning 1))
2183 (key-end (match-end 1))
2184 (markup-begin (match-beginning 2))
2185 (markup-end (match-end 2))
2186 (value-beginning (match-beginning 3)))
2187 (while (and (not (looking-at regexp))
2188 (not (> (point) (min last header-end)))
2189 (not (eobp)))
2190 (forward-line))
2191 (unless (eobp)
2192 (forward-line -1)
2193 (end-of-line))
2194 (set-match-data (list key-beginning (point) ; complete metadata
2195 key-beginning key-end ; key
2196 markup-begin markup-end ; markup
2197 value-beginning (point))) ; value
2199 (t nil))))
2201 (defun markdown-match-multimarkdown-metadata (last)
2202 "Match MultiMarkdown metadata from the point to LAST."
2203 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
2205 (defun markdown-match-pandoc-metadata (last)
2206 "Match Pandoc metadata from the point to LAST."
2207 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
2209 (defun markdown-font-lock-extend-region ()
2210 "Extend the search region to include an entire block of text.
2211 This helps improve font locking for block constructs such as pre blocks."
2212 ;; Avoid compiler warnings about these global variables from font-lock.el.
2213 ;; See the documentation for variable `font-lock-extend-region-functions'.
2214 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
2215 (save-excursion
2216 (goto-char font-lock-beg)
2217 (unless (looking-back "\n\n" nil)
2218 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
2219 (goto-char font-lock-end)
2220 (when (re-search-forward "\n\n" nil t)
2221 (setq font-lock-end (match-beginning 0))
2222 (setq font-lock-beg found))))))
2225 ;;; Syntax Table ==============================================================
2227 (defvar markdown-mode-syntax-table
2228 (let ((tab (make-syntax-table text-mode-syntax-table)))
2229 (modify-syntax-entry ?\" "." tab)
2230 tab)
2231 "Syntax table for `markdown-mode'.")
2234 ;;; Element Insertion =========================================================
2236 (defun markdown-ensure-blank-line-before ()
2237 "If previous line is not already blank, insert a blank line before point."
2238 (unless (bolp) (insert "\n"))
2239 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
2241 (defun markdown-ensure-blank-line-after ()
2242 "If following line is not already blank, insert a blank line after point.
2243 Return the point where it was originally."
2244 (save-excursion
2245 (unless (eolp) (insert "\n"))
2246 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
2248 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
2249 "Insert the strings S1 and S2, wrapping around region or THING.
2250 If a region is specified by the optional BEG and END arguments,
2251 wrap the strings S1 and S2 around that region.
2252 If there is an active region, wrap the strings S1 and S2 around
2253 the region. If there is not an active region but the point is at
2254 THING, wrap that thing (which defaults to word). Otherwise, just
2255 insert S1 and S2 and place the cursor in between. Return the
2256 bounds of the entire wrapped string, or nil if nothing was wrapped
2257 and S1 and S2 were only inserted."
2258 (let (a b bounds new-point)
2259 (cond
2260 ;; Given region
2261 ((and beg end)
2262 (setq a beg
2263 b end
2264 new-point (+ (point) (length s1))))
2265 ;; Active region
2266 ((markdown-use-region-p)
2267 (setq a (region-beginning)
2268 b (region-end)
2269 new-point (+ (point) (length s1))))
2270 ;; Thing (word) at point
2271 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
2272 (setq a (car bounds)
2273 b (cdr bounds)
2274 new-point (+ (point) (length s1))))
2275 ;; No active region and no word
2277 (setq a (point)
2278 b (point))))
2279 (goto-char b)
2280 (insert s2)
2281 (goto-char a)
2282 (insert s1)
2283 (when new-point (goto-char new-point))
2284 (if (= a b)
2286 (setq b (+ b (length s1) (length s2)))
2287 (cons a b))))
2289 (defun markdown-point-after-unwrap (cur prefix suffix)
2290 "Return desired position of point after an unwrapping operation.
2291 CUR gives the position of the point before the operation.
2292 Additionally, two cons cells must be provided. PREFIX gives the
2293 bounds of the prefix string and SUFFIX gives the bounds of the
2294 suffix string."
2295 (cond ((< cur (cdr prefix)) (car prefix))
2296 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
2297 ((<= cur (cdr suffix))
2298 (- cur (+ (- (cdr prefix) (car prefix))
2299 (- cur (car suffix)))))
2300 (t cur)))
2302 (defun markdown-unwrap-thing-at-point (regexp all text)
2303 "Remove prefix and suffix of thing at point and reposition the point.
2304 When the thing at point matches REGEXP, replace the subexpression
2305 ALL with the string in subexpression TEXT. Reposition the point
2306 in an appropriate location accounting for the removal of prefix
2307 and suffix strings. Return new bounds of string from group TEXT.
2308 When REGEXP is nil, assumes match data is already set."
2309 (when (or (null regexp)
2310 (thing-at-point-looking-at regexp))
2311 (let ((cur (point))
2312 (prefix (cons (match-beginning all) (match-beginning text)))
2313 (suffix (cons (match-end text) (match-end all)))
2314 (bounds (cons (match-beginning text) (match-end text))))
2315 ;; Replace the thing at point
2316 (replace-match (match-string text) t t nil all)
2317 ;; Reposition the point
2318 (goto-char (markdown-point-after-unwrap cur prefix suffix))
2319 ;; Adjust bounds
2320 (setq bounds (cons (car prefix)
2321 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
2323 (defun markdown-unwrap-things-in-region (beg end regexp all text)
2324 "Remove prefix and suffix of all things in region from BEG to END.
2325 When a thing in the region matches REGEXP, replace the
2326 subexpression ALL with the string in subexpression TEXT.
2327 Return a cons cell containing updated bounds for the region."
2328 (save-excursion
2329 (goto-char beg)
2330 (let ((removed 0) len-all len-text)
2331 (while (re-search-forward regexp (- end removed) t)
2332 (setq len-all (length (match-string-no-properties all)))
2333 (setq len-text (length (match-string-no-properties text)))
2334 (setq removed (+ removed (- len-all len-text)))
2335 (replace-match (match-string text) t t nil all))
2336 (cons beg (- end removed)))))
2338 (defun markdown-insert-hr (arg)
2339 "Insert or replace a horizonal rule.
2340 By default, use the first element of `markdown-hr-strings'. When
2341 ARG is non-nil, as when given a prefix, select a different
2342 element as follows. When prefixed with \\[universal-argument],
2343 use the last element of `markdown-hr-strings' instead. When
2344 prefixed with an integer from 1 to the length of
2345 `markdown-hr-strings', use the element in that position instead."
2346 (interactive "*P")
2347 (when (thing-at-point-looking-at markdown-regex-hr)
2348 (delete-region (match-beginning 0) (match-end 0)))
2349 (markdown-ensure-blank-line-before)
2350 (cond ((equal arg '(4))
2351 (insert (car (reverse markdown-hr-strings))))
2352 ((and (integerp arg) (> arg 0)
2353 (<= arg (length markdown-hr-strings)))
2354 (insert (nth (1- arg) markdown-hr-strings)))
2356 (insert (car markdown-hr-strings))))
2357 (markdown-ensure-blank-line-after))
2359 (defun markdown-insert-bold ()
2360 "Insert markup to make a region or word bold.
2361 If there is an active region, make the region bold. If the point
2362 is at a non-bold word, make the word bold. If the point is at a
2363 bold word or phrase, remove the bold markup. Otherwise, simply
2364 insert bold delimiters and place the cursor in between them."
2365 (interactive)
2366 (let ((delim (if markdown-bold-underscore "__" "**")))
2367 (if (markdown-use-region-p)
2368 ;; Active region
2369 (let ((bounds (markdown-unwrap-things-in-region
2370 (region-beginning) (region-end)
2371 markdown-regex-bold 2 4)))
2372 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2373 ;; Bold markup removal, bold word at point, or empty markup insertion
2374 (if (thing-at-point-looking-at markdown-regex-bold)
2375 (markdown-unwrap-thing-at-point nil 2 4)
2376 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2378 (defun markdown-insert-italic ()
2379 "Insert markup to make a region or word italic.
2380 If there is an active region, make the region italic. If the point
2381 is at a non-italic word, make the word italic. If the point is at an
2382 italic word or phrase, remove the italic markup. Otherwise, simply
2383 insert italic delimiters and place the cursor in between them."
2384 (interactive)
2385 (let ((delim (if markdown-italic-underscore "_" "*")))
2386 (if (markdown-use-region-p)
2387 ;; Active region
2388 (let ((bounds (markdown-unwrap-things-in-region
2389 (region-beginning) (region-end)
2390 markdown-regex-italic 1 3)))
2391 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2392 ;; Italic markup removal, italic word at point, or empty markup insertion
2393 (if (thing-at-point-looking-at markdown-regex-italic)
2394 (markdown-unwrap-thing-at-point nil 1 3)
2395 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2397 (defun markdown-insert-strike-through ()
2398 "Insert markup to make a region or word strike-through.
2399 If there is an active region, make the region strike-through. If the point
2400 is at a non-bold word, make the word strike-through. If the point is at a
2401 strike-through word or phrase, remove the strike-through markup. Otherwise,
2402 simply insert bold delimiters and place the cursor in between them."
2403 (interactive)
2404 (let ((delim "~~"))
2405 (if (markdown-use-region-p)
2406 ;; Active region
2407 (let ((bounds (markdown-unwrap-things-in-region
2408 (region-beginning) (region-end)
2409 markdown-regex-strike-through 2 4)))
2410 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
2411 ;; Strike-through markup removal, strike-through word at point, or empty markup insertion
2412 (if (thing-at-point-looking-at markdown-regex-strike-through)
2413 (markdown-unwrap-thing-at-point nil 2 4)
2414 (markdown-wrap-or-insert delim delim 'word nil nil)))))
2416 (defun markdown-insert-code ()
2417 "Insert markup to make a region or word an inline code fragment.
2418 If there is an active region, make the region an inline code
2419 fragment. If the point is at a word, make the word an inline
2420 code fragment. Otherwise, simply insert code delimiters and
2421 place the cursor in between them."
2422 (interactive)
2423 (if (markdown-use-region-p)
2424 ;; Active region
2425 (let ((bounds (markdown-unwrap-things-in-region
2426 (region-beginning) (region-end)
2427 markdown-regex-code 1 3)))
2428 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
2429 ;; Code markup removal, code markup for word, or empty markup insertion
2430 (if (markdown-code-at-point-p)
2431 (markdown-unwrap-thing-at-point nil 0 2)
2432 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
2434 (defun markdown-insert-link ()
2435 "Insert an inline link, using region or word as link text if possible.
2436 If there is an active region, use the region as the link text. If the
2437 point is at a word, use the word as the link text. In these cases, the
2438 point will be left at the position for inserting a URL. If there is no
2439 active region and the point is not at word, simply insert link markup and
2440 place the point in the position to enter link text."
2441 (interactive)
2442 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
2443 (when bounds
2444 (goto-char (- (cdr bounds) 1)))))
2446 (defun markdown-insert-reference-link (text label &optional url title)
2447 "Insert a reference link and, optionally, a reference definition.
2448 The link TEXT will be inserted followed by the optional LABEL.
2449 If a URL is given, also insert a definition for the reference
2450 LABEL according to `markdown-reference-location'. If a TITLE is
2451 given, it will be added to the end of the reference definition
2452 and will be used to populate the title attribute when converted
2453 to XHTML. If URL is nil, insert only the link portion (for
2454 example, when a reference label is already defined)."
2455 (insert (concat "[" text "][" label "]"))
2456 (when url
2457 (let ((end (point))
2458 (label (if (> (length label) 0) label text)))
2459 (cond
2460 ((eq markdown-reference-location 'end) (goto-char (point-max)))
2461 ((eq markdown-reference-location 'immediately) (markdown-end-of-block))
2462 ((eq markdown-reference-location 'header) (markdown-end-of-defun)))
2463 (unless (markdown-cur-line-blank-p) (insert "\n"))
2464 (insert "\n[" label "]: " url)
2465 (unless (> (length url) 0)
2466 (setq end (point)))
2467 (when (> (length title) 0)
2468 (insert " \"" title "\""))
2469 (insert "\n")
2470 (unless (or (eobp) (looking-at "\n"))
2471 (insert "\n"))
2472 (goto-char end)
2473 (when (> (length url) 0)
2474 (message
2475 (substitute-command-keys
2476 "Defined reference [%s], press \\[markdown-jump] to jump there")
2477 (or label text))))))
2479 (defun markdown-insert-reference-link-dwim ()
2480 "Insert a reference link of the form [text][label] at point.
2481 If there is an active region, the text in the region will be used
2482 as the link text. If the point is at an inline link, it will be
2483 converted to a reference link. If the point is at a word, it will
2484 be used as the link text. Otherwise, the link text will be read from
2485 the minibuffer. The link label will be read from the minibuffer in
2486 both cases, with completion from the set of currently defined
2487 references. To create an implicit reference link, press RET to
2488 accept the default, an empty label. If the entered referenced
2489 label is not defined, additionally prompt for the URL
2490 and (optional) title. The reference definition is placed at the
2491 location determined by `markdown-reference-location'."
2492 (interactive)
2493 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2494 (markdown-get-defined-references)))
2495 (switch (thing-at-point-looking-at markdown-regex-link-inline))
2496 (bounds (cond ((markdown-use-region-p)
2497 (cons (region-beginning) (region-end)))
2498 (switch
2499 (cons (match-beginning 0) (match-end 0)))
2501 (markdown-bounds-of-thing-at-point 'word))))
2502 (text (cond (switch (match-string 3))
2503 (bounds (buffer-substring (car bounds) (cdr bounds)))
2504 (t (read-string "Link Text: "))))
2505 (label (completing-read
2506 "Link Label (default: none): " defined-labels
2507 nil nil nil 'markdown-reference-label-history nil))
2508 (ref (save-match-data
2509 (markdown-reference-definition
2510 (if (> (length label) 0) label text))))
2511 (url (cond (ref nil)
2512 (switch (match-string 6))
2513 (t (read-string "Link URL: "))))
2514 (title (cond
2515 ((= (length url) 0) nil)
2516 (switch (if (> (length (match-string 7)) 2)
2517 (substring (match-string 7) 1 -1)
2518 nil))
2519 (t (read-string "Link Title (optional): ")))))
2520 (when bounds (delete-region (car bounds) (cdr bounds)))
2521 (markdown-insert-reference-link text label url title)))
2523 (defun markdown-insert-uri ()
2524 "Insert markup for an inline URI.
2525 If there is an active region, use it as the URI. If the point is
2526 at a URI, wrap it with angle brackets. If the point is at an
2527 inline URI, remove the angle brackets. Otherwise, simply insert
2528 angle brackets place the point between them."
2529 (interactive)
2530 (if (markdown-use-region-p)
2531 ;; Active region
2532 (let ((bounds (markdown-unwrap-things-in-region
2533 (region-beginning) (region-end)
2534 markdown-regex-angle-uri 0 2)))
2535 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
2536 ;; Markup removal, URI at point, or empty markup insertion
2537 (if (thing-at-point-looking-at markdown-regex-angle-uri)
2538 (markdown-unwrap-thing-at-point nil 0 2)
2539 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
2541 (defun markdown-insert-wiki-link ()
2542 "Insert a wiki link of the form [[WikiLink]].
2543 If there is an active region, use the region as the link text.
2544 If the point is at a word, use the word as the link text. If
2545 there is no active region and the point is not at word, simply
2546 insert link markup."
2547 (interactive)
2548 (if (markdown-use-region-p)
2549 ;; Active region
2550 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
2551 ;; Markup removal, wiki link at at point, or empty markup insertion
2552 (if (thing-at-point-looking-at markdown-regex-wiki-link)
2553 (if (or markdown-wiki-link-alias-first
2554 (null (match-string 5)))
2555 (markdown-unwrap-thing-at-point nil 1 3)
2556 (markdown-unwrap-thing-at-point nil 1 5))
2557 (markdown-wrap-or-insert "[[" "]]"))))
2559 (defun markdown-insert-image (&optional arg)
2560 "Insert image markup using region or word as alt text if possible.
2561 If there is an active region, use the region as the alt text. If the
2562 point is at a word, use the word as the alt text. In these cases, the
2563 point will be left at the position for inserting a URL. If there is no
2564 active region and the point is not at word, simply insert image markup and
2565 place the point in the position to enter alt text. If ARG is nil, insert
2566 inline image markup. Otherwise, insert reference image markup."
2567 (interactive "*P")
2568 (let ((bounds (if arg
2569 (markdown-wrap-or-insert "![" "][]")
2570 (markdown-wrap-or-insert "![" "]()"))))
2571 (when bounds
2572 (goto-char (- (cdr bounds) 1)))))
2574 (defun markdown-insert-reference-image ()
2575 "Insert reference-style image markup using region or word as alt text.
2576 Calls `markdown-insert-image' with prefix argument."
2577 (interactive)
2578 (markdown-insert-image t))
2580 (defun markdown-remove-header ()
2581 "Remove header markup if point is at a header.
2582 Return bounds of remaining header text if a header was removed
2583 and nil otherwise."
2584 (interactive "*")
2585 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2586 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2588 (defun markdown-insert-header (&optional level text setext)
2589 "Insert or replace header markup.
2590 The level of the header is specified by LEVEL and header text is
2591 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2592 default value is 1.
2593 When TEXT is nil, the header text is obtained as follows.
2594 If there is an active region, it is used as the header text.
2595 Otherwise, the current line will be used as the header text.
2596 If there is not an active region and the point is at a header,
2597 remove the header markup and replace with level N header.
2598 Otherwise, insert empty header markup and place the cursor in
2599 between.
2600 The style of the header will be atx (hash marks) unless
2601 SETEXT is non-nil, in which case a setext-style (underlined)
2602 header will be inserted."
2603 (interactive "p\nsHeader text: ")
2604 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2605 ;; Determine header text if not given
2606 (when (null text)
2607 (if (markdown-use-region-p)
2608 ;; Active region
2609 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2610 ;; No active region
2611 (markdown-remove-header)
2612 (setq text (delete-and-extract-region
2613 (line-beginning-position) (line-end-position)))
2614 (when (and setext (string-match "^[ \t]*$" text))
2615 (setq text (read-string "Header text: "))))
2616 (setq text (markdown-compress-whitespace-string text)))
2617 ;; Insertion with given text
2618 (markdown-ensure-blank-line-before)
2619 (let (hdr)
2620 (cond (setext
2621 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
2622 (insert text "\n" hdr))
2624 (setq hdr (make-string level ?#))
2625 (insert hdr " " text)
2626 (when (null markdown-asymmetric-header) (insert " " hdr)))))
2627 (markdown-ensure-blank-line-after)
2628 ;; Leave point at end of text
2629 (if setext
2630 (backward-char (1+ (string-width text)))
2631 (backward-char (1+ level))))
2633 (defun markdown-insert-header-dwim (&optional arg setext)
2634 "Insert or replace header markup.
2635 The level and type of the header are determined automatically by
2636 the type and level of the previous header, unless a prefix
2637 argument is given via ARG.
2638 With a numeric prefix valued 1 to 6, insert a header of the given
2639 level, with the type being determined automatically (note that
2640 only level 1 or 2 setext headers are possible).
2642 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
2643 promote the heading by one level.
2644 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
2645 demote the heading by one level.
2646 When SETEXT is non-nil, prefer setext-style headers when
2647 possible (levels one and two).
2649 When there is an active region, use it for the header text. When
2650 the point is at an existing header, change the type and level
2651 according to the rules above.
2652 Otherwise, if the line is not empty, create a header using the
2653 text on the current line as the header text.
2654 Finally, if the point is on a blank line, insert empty header
2655 markup (atx) or prompt for text (setext).
2656 See `markdown-insert-header' for more details about how the
2657 header text is determined."
2658 (interactive "*P")
2659 (let (level)
2660 (save-excursion
2661 (when (re-search-backward markdown-regex-header nil t)
2662 ;; level of previous header
2663 (setq level (markdown-outline-level))
2664 ;; match groups 1 and 2 indicate setext headers
2665 (setq setext (or setext (match-end 1) (match-end 3)))))
2666 ;; check prefix argument
2667 (cond
2668 ((and (equal arg '(4)) (> level 1)) ;; C-u
2669 (decf level))
2670 ((and (equal arg '(16)) (< level 6)) ;; C-u C-u
2671 (incf level))
2672 (arg ;; numeric prefix
2673 (setq level (prefix-numeric-value arg))))
2674 ;; setext headers must be level one or two
2675 (and level (setq setext (and setext (<= level 2))))
2676 ;; insert the heading
2677 (markdown-insert-header level nil setext)))
2679 (defun markdown-insert-header-setext-dwim (&optional arg)
2680 "Insert or replace header markup, with preference for setext.
2681 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2682 (interactive "*P")
2683 (markdown-insert-header-dwim arg t))
2685 (defun markdown-insert-header-atx-1 ()
2686 "Insert a first level atx-style (hash mark) header.
2687 See `markdown-insert-header'."
2688 (interactive "*")
2689 (markdown-insert-header 1 nil nil))
2691 (defun markdown-insert-header-atx-2 ()
2692 "Insert a level two atx-style (hash mark) header.
2693 See `markdown-insert-header'."
2694 (interactive "*")
2695 (markdown-insert-header 2 nil nil))
2697 (defun markdown-insert-header-atx-3 ()
2698 "Insert a level three atx-style (hash mark) header.
2699 See `markdown-insert-header'."
2700 (interactive "*")
2701 (markdown-insert-header 3 nil nil))
2703 (defun markdown-insert-header-atx-4 ()
2704 "Insert a level four atx-style (hash mark) header.
2705 See `markdown-insert-header'."
2706 (interactive "*")
2707 (markdown-insert-header 4 nil nil))
2709 (defun markdown-insert-header-atx-5 ()
2710 "Insert a level five atx-style (hash mark) header.
2711 See `markdown-insert-header'."
2712 (interactive "*")
2713 (markdown-insert-header 5 nil nil))
2715 (defun markdown-insert-header-atx-6 ()
2716 "Insert a sixth level atx-style (hash mark) header.
2717 See `markdown-insert-header'."
2718 (interactive "*")
2719 (markdown-insert-header 6 nil nil))
2721 (defun markdown-insert-header-setext-1 ()
2722 "Insert a setext-style (underlined) first-level header.
2723 See `markdown-insert-header'."
2724 (interactive "*")
2725 (markdown-insert-header 1 nil t))
2727 (defun markdown-insert-header-setext-2 ()
2728 "Insert a setext-style (underlined) second-level header.
2729 See `markdown-insert-header'."
2730 (interactive "*")
2731 (markdown-insert-header 2 nil t))
2733 (defun markdown-blockquote-indentation (loc)
2734 "Return string containing necessary indentation for a blockquote at LOC.
2735 Also see `markdown-pre-indentation'."
2736 (save-excursion
2737 (goto-char loc)
2738 (let* ((list-level (length (markdown-calculate-list-levels)))
2739 (indent ""))
2740 (dotimes (count list-level indent)
2741 (setq indent (concat indent " "))))))
2743 (defun markdown-insert-blockquote ()
2744 "Start a blockquote section (or blockquote the region).
2745 If Transient Mark mode is on and a region is active, it is used as
2746 the blockquote text."
2747 (interactive)
2748 (if (markdown-use-region-p)
2749 (markdown-blockquote-region (region-beginning) (region-end))
2750 (markdown-ensure-blank-line-before)
2751 (insert (markdown-blockquote-indentation (point)) "> ")
2752 (markdown-ensure-blank-line-after)))
2754 (defun markdown-block-region (beg end prefix)
2755 "Format the region using a block prefix.
2756 Arguments BEG and END specify the beginning and end of the
2757 region. The characters PREFIX will appear at the beginning
2758 of each line."
2759 (save-excursion
2760 (let* ((end-marker (make-marker))
2761 (beg-marker (make-marker)))
2762 ;; Ensure blank line after and remove extra whitespace
2763 (goto-char end)
2764 (skip-syntax-backward "-")
2765 (set-marker end-marker (point))
2766 (delete-horizontal-space)
2767 (markdown-ensure-blank-line-after)
2768 ;; Ensure blank line before and remove extra whitespace
2769 (goto-char beg)
2770 (skip-syntax-forward "-")
2771 (delete-horizontal-space)
2772 (markdown-ensure-blank-line-before)
2773 (set-marker beg-marker (point))
2774 ;; Insert PREFIX before each line
2775 (goto-char beg-marker)
2776 (while (and (< (line-beginning-position) end-marker)
2777 (not (eobp)))
2778 (insert prefix)
2779 (forward-line)))))
2781 (defun markdown-blockquote-region (beg end)
2782 "Blockquote the region.
2783 Arguments BEG and END specify the beginning and end of the region."
2784 (interactive "*r")
2785 (markdown-block-region
2786 beg end (concat (markdown-blockquote-indentation
2787 (max (point-min) (1- beg))) "> ")))
2789 (defun markdown-pre-indentation (loc)
2790 "Return string containing necessary whitespace for a pre block at LOC.
2791 Also see `markdown-blockquote-indentation'."
2792 (save-excursion
2793 (goto-char loc)
2794 (let* ((list-level (length (markdown-calculate-list-levels)))
2795 indent)
2796 (dotimes (count (1+ list-level) indent)
2797 (setq indent (concat indent " "))))))
2799 (defun markdown-insert-pre ()
2800 "Start a preformatted section (or apply to the region).
2801 If Transient Mark mode is on and a region is active, it is marked
2802 as preformatted text."
2803 (interactive)
2804 (if (markdown-use-region-p)
2805 (markdown-pre-region (region-beginning) (region-end))
2806 (markdown-ensure-blank-line-before)
2807 (insert (markdown-pre-indentation (point)))
2808 (markdown-ensure-blank-line-after)))
2810 (defun markdown-pre-region (beg end)
2811 "Format the region as preformatted text.
2812 Arguments BEG and END specify the beginning and end of the region."
2813 (interactive "*r")
2814 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2815 (markdown-block-region beg end indent)))
2817 (defun markdown-electric-backquote (arg)
2818 "Insert a backquote.
2819 The numeric prefix argument ARG says how many times to repeat the insertion.
2820 Call `markdown-insert-gfm-code-block' interactively
2821 if three backquotes inserted at the beginning of line."
2822 (interactive "*P")
2823 (self-insert-command (prefix-numeric-value arg))
2824 (when (looking-back "^```" nil)
2825 (replace-match "")
2826 (call-interactively #'markdown-insert-gfm-code-block)))
2828 (defun markdown-insert-gfm-code-block (&optional lang)
2829 "Insert GFM code block for language LANG.
2830 If LANG is nil, the language will be queried from user. If a
2831 region is active, wrap this region with the markup instead. If
2832 the region boundaries are not on empty lines, these are added
2833 automatically in order to have the correct markup."
2834 (interactive "sProgramming language [none]: ")
2835 (when (> (length lang) 0) (setq lang (concat " " lang)))
2836 (if (markdown-use-region-p)
2837 (let ((b (region-beginning)) (e (region-end)))
2838 (goto-char e)
2839 ;; if we're on a blank line, don't newline, otherwise the ```
2840 ;; should go on its own line
2841 (unless (looking-back "\n" nil)
2842 (newline))
2843 (insert "```")
2844 (markdown-ensure-blank-line-after)
2845 (goto-char b)
2846 ;; if we're on a blank line, insert the quotes here, otherwise
2847 ;; add a new line first
2848 (unless (looking-at "\n")
2849 (newline)
2850 (forward-line -1))
2851 (markdown-ensure-blank-line-before)
2852 (insert "```" lang))
2853 (markdown-ensure-blank-line-before)
2854 (insert "```" lang)
2855 (newline 2)
2856 (insert "```")
2857 (markdown-ensure-blank-line-after)
2858 (forward-line -1)))
2861 ;;; Footnotes ======================================================================
2863 (defun markdown-footnote-counter-inc ()
2864 "Increment `markdown-footnote-counter' and return the new value."
2865 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2866 (save-excursion
2867 (goto-char (point-min))
2868 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2869 (point-max) t)
2870 (let ((fn (string-to-number (match-string 1))))
2871 (when (> fn markdown-footnote-counter)
2872 (setq markdown-footnote-counter fn))))))
2873 (incf markdown-footnote-counter))
2875 (defun markdown-insert-footnote ()
2876 "Insert footnote with a new number and move point to footnote definition."
2877 (interactive)
2878 (let ((fn (markdown-footnote-counter-inc)))
2879 (insert (format "[^%d]" fn))
2880 (markdown-footnote-text-find-new-location)
2881 (markdown-ensure-blank-line-before)
2882 (unless (markdown-cur-line-blank-p)
2883 (insert "\n"))
2884 (insert (format "[^%d]: " fn))
2885 (markdown-ensure-blank-line-after)))
2887 (defun markdown-footnote-text-find-new-location ()
2888 "Position the cursor at the proper location for a new footnote text."
2889 (cond
2890 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2891 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
2892 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2894 (defun markdown-footnote-kill ()
2895 "Kill the footnote at point.
2896 The footnote text is killed (and added to the kill ring), the
2897 footnote marker is deleted. Point has to be either at the
2898 footnote marker or in the footnote text."
2899 (interactive)
2900 (let ((marker-pos nil)
2901 (skip-deleting-marker nil)
2902 (starting-footnote-text-positions
2903 (markdown-footnote-text-positions)))
2904 (when starting-footnote-text-positions
2905 ;; We're starting in footnote text, so mark our return position and jump
2906 ;; to the marker if possible.
2907 (let ((marker-pos (markdown-footnote-find-marker
2908 (first starting-footnote-text-positions))))
2909 (if marker-pos
2910 (goto-char (1- marker-pos))
2911 ;; If there isn't a marker, we still want to kill the text.
2912 (setq skip-deleting-marker t))))
2913 ;; Either we didn't start in the text, or we started in the text and jumped
2914 ;; to the marker. We want to assume we're at the marker now and error if
2915 ;; we're not.
2916 (unless skip-deleting-marker
2917 (let ((marker (markdown-footnote-delete-marker)))
2918 (unless marker
2919 (error "Not at a footnote"))
2920 ;; Even if we knew the text position before, it changed when we deleted
2921 ;; the label.
2922 (setq marker-pos (second marker))
2923 (let ((new-text-pos (markdown-footnote-find-text (first marker))))
2924 (unless new-text-pos
2925 (error "No text for footnote `%s'" (first marker)))
2926 (goto-char new-text-pos))))
2927 (let ((pos (markdown-footnote-kill-text)))
2928 (goto-char (if starting-footnote-text-positions
2930 marker-pos)))))
2932 (defun markdown-footnote-delete-marker ()
2933 "Delete a footnote marker at point.
2934 Returns a list (ID START) containing the footnote ID and the
2935 start position of the marker before deletion. If no footnote
2936 marker was deleted, this function returns NIL."
2937 (let ((marker (markdown-footnote-marker-positions)))
2938 (when marker
2939 (delete-region (second marker) (third marker))
2940 (butlast marker))))
2942 (defun markdown-footnote-kill-text ()
2943 "Kill footnote text at point.
2944 Returns the start position of the footnote text before deletion,
2945 or NIL if point was not inside a footnote text.
2947 The killed text is placed in the kill ring (without the footnote
2948 number)."
2949 (let ((fn (markdown-footnote-text-positions)))
2950 (when fn
2951 (let ((text (delete-and-extract-region (second fn) (third fn))))
2952 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2953 (kill-new (match-string 1 text))
2954 (when (and (markdown-cur-line-blank-p)
2955 (markdown-prev-line-blank-p)
2956 (not (bobp)))
2957 (delete-region (1- (point)) (point)))
2958 (second fn)))))
2960 (defun markdown-footnote-goto-text ()
2961 "Jump to the text of the footnote at point."
2962 (interactive)
2963 (let ((fn (car (markdown-footnote-marker-positions))))
2964 (unless fn
2965 (error "Not at a footnote marker"))
2966 (let ((new-pos (markdown-footnote-find-text fn)))
2967 (unless new-pos
2968 (error "No definition found for footnote `%s'" fn))
2969 (goto-char new-pos))))
2971 (defun markdown-footnote-return ()
2972 "Return from a footnote to its footnote number in the main text."
2973 (interactive)
2974 (let ((fn (save-excursion
2975 (car (markdown-footnote-text-positions)))))
2976 (unless fn
2977 (error "Not in a footnote"))
2978 (let ((new-pos (markdown-footnote-find-marker fn)))
2979 (unless new-pos
2980 (error "Footnote marker `%s' not found" fn))
2981 (goto-char new-pos))))
2983 (defun markdown-footnote-find-marker (id)
2984 "Find the location of the footnote marker with ID.
2985 The actual buffer position returned is the position directly
2986 following the marker's closing bracket. If no marker is found,
2987 NIL is returned."
2988 (save-excursion
2989 (goto-char (point-min))
2990 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2991 (skip-chars-backward "^]")
2992 (point))))
2994 (defun markdown-footnote-find-text (id)
2995 "Find the location of the text of footnote ID.
2996 The actual buffer position returned is the position of the first
2997 character of the text, after the footnote's identifier. If no
2998 footnote text is found, NIL is returned."
2999 (save-excursion
3000 (goto-char (point-min))
3001 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
3002 (skip-chars-forward "[ \t]")
3003 (point))))
3005 (defun markdown-footnote-marker-positions ()
3006 "Return the position and ID of the footnote marker point is on.
3007 The return value is a list (ID START END). If point is not on a
3008 footnote, NIL is returned."
3009 ;; first make sure we're at a footnote marker
3010 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
3011 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
3012 (save-excursion
3013 ;; move point between [ and ^:
3014 (if (looking-at "\\[")
3015 (forward-char 1)
3016 (skip-chars-backward "^["))
3017 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
3018 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
3020 (defun markdown-footnote-text-positions ()
3021 "Return the start and end positions of the footnote text point is in.
3022 The exact return value is a list of three elements: (ID START END).
3023 The start position is the position of the opening bracket
3024 of the footnote id. The end position is directly after the
3025 newline that ends the footnote. If point is not in a footnote,
3026 NIL is returned instead."
3027 (save-excursion
3028 (let (result)
3029 (move-beginning-of-line 1)
3030 ;; Try to find the label. If we haven't found the label and we're at a blank
3031 ;; or indented line, back up if possible.
3032 (while (and
3033 (not (and (looking-at markdown-regex-footnote-definition)
3034 (setq result (list (match-string 1) (point)))))
3035 (and (not (bobp))
3036 (or (markdown-cur-line-blank-p)
3037 (>= (markdown-cur-line-indent) 4))))
3038 (forward-line -1))
3039 (when result
3040 ; Advance if there is a next line that is either blank or indented.
3041 ; (Need to check if we're on the last line, because
3042 ; markdown-next-line-blank-p returns true for last line in buffer.)
3043 (while (and (/= (line-end-position) (point-max))
3044 (or (markdown-next-line-blank-p)
3045 (>= (markdown-next-line-indent) 4)))
3046 (forward-line))
3047 ; Move back while the current line is blank.
3048 (while (markdown-cur-line-blank-p)
3049 (forward-line -1))
3050 ; Advance to capture this line and a single trailing newline (if there
3051 ; is one).
3052 (forward-line)
3053 (append result (list (point)))))))
3056 ;;; Element Removal ===========================================================
3058 (defun markdown-kill-thing-at-point ()
3059 "Kill thing at point and add important text, without markup, to kill ring.
3060 Possible things to kill include (roughly in order of precedence):
3061 inline code, headers, horizonal rules, links (add link text to
3062 kill ring), images (add alt text to kill ring), angle uri, email
3063 addresses, bold, italics, reference definition (add URI to kill
3064 ring), footnote markers and text (kill both marker and text, add
3065 text to kill ring), and list items."
3066 (interactive "*")
3067 (let (val tmp)
3068 (cond
3069 ;; Inline code
3070 ((markdown-code-at-point-p)
3071 (kill-new (match-string 2))
3072 (delete-region (match-beginning 0) (match-end 0)))
3073 ;; ATX header
3074 ((thing-at-point-looking-at markdown-regex-header-atx)
3075 (kill-new (match-string 2))
3076 (delete-region (match-beginning 0) (match-end 0)))
3077 ;; Setext header
3078 ((thing-at-point-looking-at markdown-regex-header-setext)
3079 (kill-new (match-string 1))
3080 (delete-region (match-beginning 0) (match-end 0)))
3081 ;; Horizonal rule
3082 ((thing-at-point-looking-at markdown-regex-hr)
3083 (kill-new (match-string 0))
3084 (delete-region (match-beginning 0) (match-end 0)))
3085 ;; Inline link or image (add link or alt text to kill ring)
3086 ((thing-at-point-looking-at markdown-regex-link-inline)
3087 (kill-new (match-string 3))
3088 (delete-region (match-beginning 0) (match-end 0)))
3089 ;; Reference link or image (add link or alt text to kill ring)
3090 ((thing-at-point-looking-at markdown-regex-link-reference)
3091 (kill-new (match-string 3))
3092 (delete-region (match-beginning 0) (match-end 0)))
3093 ;; Angle URI (add URL to kill ring)
3094 ((thing-at-point-looking-at markdown-regex-angle-uri)
3095 (kill-new (match-string 2))
3096 (delete-region (match-beginning 0) (match-end 0)))
3097 ;; Email address in angle brackets (add email address to kill ring)
3098 ((thing-at-point-looking-at markdown-regex-email)
3099 (kill-new (match-string 1))
3100 (delete-region (match-beginning 0) (match-end 0)))
3101 ;; Wiki link (add alias text to kill ring)
3102 ((thing-at-point-looking-at markdown-regex-wiki-link)
3103 (kill-new (markdown-wiki-link-alias))
3104 (delete-region (match-beginning 1) (match-end 1)))
3105 ;; Bold
3106 ((thing-at-point-looking-at markdown-regex-bold)
3107 (kill-new (match-string 4))
3108 (delete-region (match-beginning 2) (match-end 2)))
3109 ;; Italics
3110 ((thing-at-point-looking-at markdown-regex-italic)
3111 (kill-new (match-string 3))
3112 (delete-region (match-beginning 1) (match-end 1)))
3113 ;; Strike-through
3114 ((thing-at-point-looking-at markdown-regex-strike-through)
3115 (kill-new (match-string 4))
3116 (delete-region (match-beginning 2) (match-end 2)))
3117 ;; Footnote marker (add footnote text to kill ring)
3118 ((thing-at-point-looking-at markdown-regex-footnote)
3119 (markdown-footnote-kill))
3120 ;; Footnote text (add footnote text to kill ring)
3121 ((setq val (markdown-footnote-text-positions))
3122 (markdown-footnote-kill))
3123 ;; Reference definition (add URL to kill ring)
3124 ((thing-at-point-looking-at markdown-regex-reference-definition)
3125 (kill-new (match-string 5))
3126 (delete-region (match-beginning 0) (match-end 0)))
3127 ;; List item
3128 ((setq val (markdown-cur-list-item-bounds))
3129 (kill-new (delete-and-extract-region (first val) (second val))))
3131 (error "Nothing found at point to kill")))))
3134 ;;; Indentation ====================================================================
3136 (defun markdown-indent-find-next-position (cur-pos positions)
3137 "Return the position after the index of CUR-POS in POSITIONS.
3138 Positions are calculated by `markdown-calc-indents'."
3139 (while (and positions
3140 (not (equal cur-pos (car positions))))
3141 (setq positions (cdr positions)))
3142 (or (cadr positions) 0))
3144 (defun markdown-exdent-find-next-position (cur-pos positions)
3145 "Return the maximal element that precedes CUR-POS from POSITIONS.
3146 Positions are calculated by `markdown-calc-indents'."
3147 (let ((result 0))
3148 (dolist (i positions)
3149 (when (< i cur-pos)
3150 (setq result (max result i))))
3151 result))
3153 (defun markdown-indent-line ()
3154 "Indent the current line using some heuristics.
3155 If the _previous_ command was either `markdown-enter-key' or
3156 `markdown-cycle', then we should cycle to the next
3157 reasonable indentation position. Otherwise, we could have been
3158 called directly by `markdown-enter-key', by an initial call of
3159 `markdown-cycle', or indirectly by `auto-fill-mode'. In
3160 these cases, indent to the default position.
3161 Positions are calculated by `markdown-calc-indents'."
3162 (interactive)
3163 (let ((positions (markdown-calc-indents))
3164 (cur-pos (current-column)))
3165 (if (not (equal this-command 'markdown-cycle))
3166 (indent-line-to (car positions))
3167 (setq positions (sort (delete-dups positions) '<))
3168 (indent-line-to
3169 (markdown-indent-find-next-position cur-pos positions)))))
3171 (defun markdown-calc-indents ()
3172 "Return a list of indentation columns to cycle through.
3173 The first element in the returned list should be considered the
3174 default indentation level. This function does not worry about
3175 duplicate positions, which are handled up by calling functions."
3176 (let (pos prev-line-pos positions)
3178 ;; Indentation of previous line
3179 (setq prev-line-pos (markdown-prev-line-indent))
3180 (setq positions (cons prev-line-pos positions))
3182 ;; Indentation of previous non-list-marker text
3183 (when (setq pos (markdown-prev-non-list-indent))
3184 (setq positions (cons pos positions)))
3186 ;; Indentation required for a pre block in current context
3187 (setq pos (length (markdown-pre-indentation (point))))
3188 (setq positions (cons pos positions))
3190 ;; Indentation of the previous line + tab-width
3191 (if prev-line-pos
3192 (setq positions (cons (+ prev-line-pos tab-width) positions))
3193 (setq positions (cons tab-width positions)))
3195 ;; Indentation of the previous line - tab-width
3196 (if (and prev-line-pos (> prev-line-pos tab-width))
3197 (setq positions (cons (- prev-line-pos tab-width) positions)))
3199 ;; Indentation of all preceeding list markers (when in a list)
3200 (when (setq pos (markdown-calculate-list-levels))
3201 (setq positions (append pos positions)))
3203 ;; First column
3204 (setq positions (cons 0 positions))
3206 ;; Return reversed list
3207 (reverse positions)))
3209 (defun markdown-enter-key ()
3210 "Handle RET according to to the value of `markdown-indent-on-enter'."
3211 (interactive)
3212 (if markdown-indent-on-enter
3213 (newline-and-indent)
3214 (newline)))
3216 (defun markdown-exdent-or-delete (arg)
3217 "Handle BACKSPACE by cycling through indentation points.
3218 When BACKSPACE is pressed, if there is only whitespace
3219 before the current point, then exdent the line one level.
3220 Otherwise, do normal delete by repeating
3221 `backward-delete-char-untabify' ARG times."
3222 (interactive "*p")
3223 (let ((cur-pos (current-column))
3224 (start-of-indention (save-excursion
3225 (back-to-indentation)
3226 (current-column)))
3227 (positions (markdown-calc-indents)))
3228 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
3229 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
3230 (backward-delete-char-untabify arg))))
3232 (defun markdown-find-leftmost-column (beg end)
3233 "Find the leftmost column in the region from BEG to END."
3234 (let ((mincol 1000))
3235 (save-excursion
3236 (goto-char beg)
3237 (while (< (point) end)
3238 (back-to-indentation)
3239 (unless (looking-at "[ \t]*$")
3240 (setq mincol (min mincol (current-column))))
3241 (forward-line 1)
3243 mincol))
3245 (defun markdown-indent-region (beg end arg)
3246 "Indent the region from BEG to END using some heuristics.
3247 When ARG is non-nil, exdent the region instead.
3248 See `markdown-indent-line' and `markdown-indent-line'."
3249 (interactive "*r\nP")
3250 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
3251 (leftmostcol (markdown-find-leftmost-column beg end))
3252 (next-pos (if arg
3253 (markdown-exdent-find-next-position leftmostcol positions)
3254 (markdown-indent-find-next-position leftmostcol positions))))
3255 (indent-rigidly beg end (- next-pos leftmostcol))
3256 (setq deactivate-mark nil)))
3258 (defun markdown-exdent-region (beg end)
3259 "Call `markdown-indent-region' on region from BEG to END with prefix."
3260 (interactive "*r")
3261 (markdown-indent-region (region-beginning) (region-end) t))
3264 ;;; Markup Completion =========================================================
3266 (defconst markdown-complete-alist
3267 '((markdown-regex-header-atx . markdown-complete-atx)
3268 (markdown-regex-header-setext . markdown-complete-setext)
3269 (markdown-regex-hr . markdown-complete-hr))
3270 "Association list of form (regexp . function) for markup completion.")
3272 (defun markdown-incomplete-atx-p ()
3273 "Return t if ATX header markup is incomplete and nil otherwise.
3274 Assumes match data is available for `markdown-regex-header-atx'.
3275 Checks that the number of trailing hash marks equals the number of leading
3276 hash marks, that there is only a single space before and after the text,
3277 and that there is no extraneous whitespace in the text."
3278 (save-match-data
3280 ;; Number of starting and ending hash marks differs
3281 (not (= (length (match-string 1)) (length (match-string 3))))
3282 ;; When the header text is not empty...
3283 (and (> (length (match-string 2)) 0)
3284 ;; ...if there are extra leading, trailing, or interior spaces
3285 (or (not (= (match-beginning 2) (1+ (match-end 1))))
3286 (not (= (match-beginning 3) (1+ (match-end 2))))
3287 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
3288 ;; When the header text is empty...
3289 (and (= (length (match-string 2)) 0)
3290 ;; ...if there are too many or too few spaces
3291 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
3293 (defun markdown-complete-atx ()
3294 "Complete and normalize ATX headers.
3295 Add or remove hash marks to the end of the header to match the
3296 beginning. Ensure that there is only a single space between hash
3297 marks and header text. Removes extraneous whitespace from header text.
3298 Assumes match data is available for `markdown-regex-header-atx'.
3299 Return nil if markup was complete and non-nil if markup was completed."
3300 (when (markdown-incomplete-atx-p)
3301 (let* ((new-marker (make-marker))
3302 (new-marker (set-marker new-marker (match-end 2))))
3303 ;; Hash marks and spacing at end
3304 (goto-char (match-end 2))
3305 (delete-region (match-end 2) (match-end 3))
3306 (insert " " (match-string 1))
3307 ;; Remove extraneous whitespace from title
3308 (replace-match (markdown-compress-whitespace-string (match-string 2))
3309 t t nil 2)
3310 ;; Spacing at beginning
3311 (goto-char (match-end 1))
3312 (delete-region (match-end 1) (match-beginning 2))
3313 (insert " ")
3314 ;; Leave point at end of text
3315 (goto-char new-marker))))
3317 (defun markdown-incomplete-setext-p ()
3318 "Return t if setext header markup is incomplete and nil otherwise.
3319 Assumes match data is available for `markdown-regex-header-setext'.
3320 Checks that length of underline matches text and that there is no
3321 extraneous whitespace in the text."
3322 (save-match-data
3323 (or (not (= (length (match-string 1)) (length (match-string 2))))
3324 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
3326 (defun markdown-complete-setext ()
3327 "Complete and normalize setext headers.
3328 Add or remove underline characters to match length of header
3329 text. Removes extraneous whitespace from header text. Assumes
3330 match data is available for `markdown-regex-header-setext'.
3331 Return nil if markup was complete and non-nil if markup was completed."
3332 (when (markdown-incomplete-setext-p)
3333 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
3334 (char (char-after (match-beginning 2)))
3335 (level (if (char-equal char ?-) 2 1)))
3336 (goto-char (match-beginning 0))
3337 (delete-region (match-beginning 0) (match-end 0))
3338 (markdown-insert-header level text t)
3339 t)))
3341 (defun markdown-incomplete-hr-p ()
3342 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
3343 Assumes match data is available for `markdown-regex-hr'."
3344 (not (member (match-string 0) markdown-hr-strings)))
3346 (defun markdown-complete-hr ()
3347 "Complete horizontal rules.
3348 If horizontal rule string is a member of `markdown-hr-strings',
3349 do nothing. Otherwise, replace with the car of
3350 `markdown-hr-strings'.
3351 Assumes match data is available for `markdown-regex-hr'.
3352 Return nil if markup was complete and non-nil if markup was completed."
3353 (when (markdown-incomplete-hr-p)
3354 (replace-match (car markdown-hr-strings))
3357 (defun markdown-complete ()
3358 "Complete markup of object near point or in region when active.
3359 Handle all objects in `markdown-complete-alist', in order.
3360 See `markdown-complete-at-point' and `markdown-complete-region'."
3361 (interactive "*")
3362 (if (markdown-use-region-p)
3363 (markdown-complete-region (region-beginning) (region-end))
3364 (markdown-complete-at-point)))
3366 (defun markdown-complete-at-point ()
3367 "Complete markup of object near point.
3368 Handle all elements of `markdown-complete-alist' in order."
3369 (interactive "*")
3370 (let ((list markdown-complete-alist) found changed)
3371 (while list
3372 (let ((regexp (eval (caar list)))
3373 (function (cdar list)))
3374 (setq list (cdr list))
3375 (when (thing-at-point-looking-at regexp)
3376 (setq found t)
3377 (setq changed (funcall function))
3378 (setq list nil))))
3379 (if found
3380 (or changed (error "Markup at point is complete"))
3381 (error "Nothing to complete at point"))))
3383 (defun markdown-complete-region (beg end)
3384 "Complete markup of objects in region from BEG to END.
3385 Handle all objects in `markdown-complete-alist', in order. Each
3386 match is checked to ensure that a previous regexp does not also
3387 match."
3388 (interactive "*r")
3389 (let ((end-marker (set-marker (make-marker) end))
3390 previous)
3391 (dolist (element markdown-complete-alist)
3392 (let ((regexp (eval (car element)))
3393 (function (cdr element)))
3394 (goto-char beg)
3395 (while (re-search-forward regexp end-marker 'limit)
3396 (when (match-string 0)
3397 ;; Make sure this is not a match for any of the preceding regexps.
3398 ;; This prevents mistaking an HR for a Setext subheading.
3399 (let (match)
3400 (save-match-data
3401 (dolist (prev-regexp previous)
3402 (or match (setq match (looking-back prev-regexp nil)))))
3403 (unless match
3404 (save-excursion (funcall function))))))
3405 (add-to-list 'previous regexp)))))
3407 (defun markdown-complete-buffer ()
3408 "Complete markup for all objects in the current buffer."
3409 (interactive "*")
3410 (markdown-complete-region (point-min) (point-max)))
3413 ;;; Markup Cycling ============================================================
3415 (defun markdown-cycle-atx (arg &optional remove)
3416 "Cycle ATX header markup.
3417 Promote header (decrease level) when ARG is 1 and demote
3418 header (increase level) if arg is -1. When REMOVE is non-nil,
3419 remove the header when the level reaches zero and stop cycling
3420 when it reaches six. Otherwise, perform a proper cycling through
3421 levels one through six. Assumes match data is available for
3422 `markdown-regex-header-atx'."
3423 (let* ((old-level (length (match-string 1)))
3424 (new-level (+ old-level arg))
3425 (text (match-string 2)))
3426 (when (not remove)
3427 (setq new-level (% new-level 6))
3428 (setq new-level (cond ((= new-level 0) 6)
3429 ((< new-level 0) (+ new-level 6))
3430 (t new-level))))
3431 (cond
3432 ((= new-level 0)
3433 (markdown-unwrap-thing-at-point nil 0 2))
3434 ((<= new-level 6)
3435 (goto-char (match-beginning 0))
3436 (delete-region (match-beginning 0) (match-end 0))
3437 (markdown-insert-header new-level text nil)))))
3439 (defun markdown-cycle-setext (arg &optional remove)
3440 "Cycle setext header markup.
3441 Promote header (increase level) when ARG is 1 and demote
3442 header (decrease level or remove) if arg is -1. When demoting a
3443 level-two setext header, replace with a level-three atx header.
3444 When REMOVE is non-nil, remove the header when the level reaches
3445 zero. Otherwise, cycle back to a level six atx header. Assumes
3446 match data is available for `markdown-regex-header-setext'."
3447 (let* ((char (char-after (match-beginning 2)))
3448 (old-level (if (char-equal char ?=) 1 2))
3449 (new-level (+ old-level arg))
3450 (text (match-string 1)))
3451 (when (and (not remove) (= new-level 0))
3452 (setq new-level 6))
3453 (cond
3454 ((= new-level 0)
3455 (markdown-unwrap-thing-at-point nil 0 1))
3456 ((<= new-level 2)
3457 (markdown-insert-header new-level nil t))
3458 ((<= new-level 6)
3459 (markdown-insert-header new-level nil nil)))))
3461 (defun markdown-cycle-hr (arg &optional remove)
3462 "Cycle string used for horizontal rule from `markdown-hr-strings'.
3463 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
3464 backwards (promote). When REMOVE is non-nil, remove the hr instead
3465 of cycling when the end of the list is reached.
3466 Assumes match data is available for `markdown-regex-hr'."
3467 (let* ((strings (if (= arg -1)
3468 (reverse markdown-hr-strings)
3469 markdown-hr-strings))
3470 (tail (member (match-string 0) strings))
3471 (new (or (cadr tail)
3472 (if remove
3473 (if (= arg 1)
3475 (car tail))
3476 (car strings)))))
3477 (replace-match new)))
3479 (defun markdown-cycle-bold ()
3480 "Cycle bold markup between underscores and asterisks.
3481 Assumes match data is available for `markdown-regex-bold'."
3482 (save-excursion
3483 (let* ((old-delim (match-string 3))
3484 (new-delim (if (string-equal old-delim "**") "__" "**")))
3485 (replace-match new-delim t t nil 3)
3486 (replace-match new-delim t t nil 5))))
3488 (defun markdown-cycle-italic ()
3489 "Cycle italic markup between underscores and asterisks.
3490 Assumes match data is available for `markdown-regex-italic'."
3491 (save-excursion
3492 (let* ((old-delim (match-string 2))
3493 (new-delim (if (string-equal old-delim "*") "_" "*")))
3494 (replace-match new-delim t t nil 2)
3495 (replace-match new-delim t t nil 4))))
3498 ;;; Keymap ====================================================================
3500 (defvar markdown-mode-map
3501 (let ((map (make-keymap)))
3502 ;; Element insertion
3503 (define-key map "\C-c\C-al" 'markdown-insert-link)
3504 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
3505 (define-key map "\C-c\C-au" 'markdown-insert-uri)
3506 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
3507 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
3508 (define-key map "\C-c\C-ii" 'markdown-insert-image)
3509 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
3510 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
3511 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
3512 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
3513 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
3514 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
3515 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
3516 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
3517 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
3518 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
3519 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
3520 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
3521 (define-key map "\C-c\C-se" 'markdown-insert-italic)
3522 (define-key map "\C-c\C-sc" 'markdown-insert-code)
3523 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
3524 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
3525 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
3526 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
3527 (define-key map "\C-c-" 'markdown-insert-hr)
3528 ;; Element insertion (deprecated)
3529 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
3530 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
3531 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
3532 ;; Element removal
3533 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
3534 ;; Promotion, Demotion, Completion, and Cycling
3535 (define-key map (kbd "C-c C--") 'markdown-promote)
3536 (define-key map (kbd "C-c C-=") 'markdown-demote)
3537 (define-key map (kbd "C-c C-]") 'markdown-complete)
3538 ;; Following and Jumping
3539 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
3540 (define-key map (kbd "C-c C-j") 'markdown-jump)
3541 ;; Indentation
3542 (define-key map (kbd "C-m") 'markdown-enter-key)
3543 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
3544 (define-key map (kbd "C-c >") 'markdown-indent-region)
3545 (define-key map (kbd "C-c <") 'markdown-exdent-region)
3546 ;; Visibility cycling
3547 (define-key map (kbd "TAB") 'markdown-cycle)
3548 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
3549 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
3550 (define-key map (kbd "<backtab>") 'markdown-shifttab)
3551 ;; Header navigation
3552 (define-key map (kbd "C-c C-n") 'outline-next-visible-heading)
3553 (define-key map (kbd "C-c C-p") 'outline-previous-visible-heading)
3554 (define-key map (kbd "C-c C-f") 'outline-forward-same-level)
3555 (define-key map (kbd "C-c C-b") 'outline-backward-same-level)
3556 (define-key map (kbd "C-c C-u") 'outline-up-heading)
3557 ;; Buffer-wide commands
3558 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
3559 (define-key map (kbd "C-c C-c p") 'markdown-preview)
3560 (define-key map (kbd "C-c C-c e") 'markdown-export)
3561 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
3562 (define-key map (kbd "C-c C-c o") 'markdown-open)
3563 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
3564 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
3565 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
3566 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
3567 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
3568 ;; List editing
3569 (define-key map (kbd "M-<up>") 'markdown-move-up)
3570 (define-key map (kbd "M-<down>") 'markdown-move-down)
3571 (define-key map (kbd "M-<left>") 'markdown-promote)
3572 (define-key map (kbd "M-<right>") 'markdown-demote)
3573 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
3574 ;; Subtree editing
3575 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
3576 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
3577 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
3578 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
3579 ;; Movement
3580 (define-key map (kbd "M-{") 'markdown-backward-paragraph)
3581 (define-key map (kbd "M-}") 'markdown-forward-paragraph)
3582 (define-key map (kbd "M-n") 'markdown-next-link)
3583 (define-key map (kbd "M-p") 'markdown-previous-link)
3584 ;; Alternative keys (in case of problems with the arrow keys)
3585 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
3586 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
3587 (define-key map (kbd "C-c C-x l") 'markdown-promote)
3588 (define-key map (kbd "C-c C-x r") 'markdown-demote)
3589 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
3590 map)
3591 "Keymap for Markdown major mode.")
3593 (defvar gfm-mode-map
3594 (let ((map (make-sparse-keymap)))
3595 (set-keymap-parent map markdown-mode-map)
3596 (define-key map (kbd "C-c C-s P") 'markdown-insert-gfm-code-block)
3597 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
3598 (define-key map "`" 'markdown-electric-backquote)
3599 map)
3600 "Keymap for `gfm-mode'.
3601 See also `markdown-mode-map'.")
3604 ;;; Menu ==================================================================
3606 (easy-menu-define markdown-mode-menu markdown-mode-map
3607 "Menu for Markdown mode"
3608 '("Markdown"
3609 ("Show/Hide"
3610 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
3611 ["Cycle global visibility" markdown-shifttab])
3612 "---"
3613 ["Compile" markdown-other-window]
3614 ["Preview" markdown-preview]
3615 ["Export" markdown-export]
3616 ["Export & View" markdown-export-and-preview]
3617 ["Open" markdown-open]
3618 ["Live Export" markdown-live-preview-mode
3619 :style toggle :selected markdown-live-preview-mode]
3620 ["Kill ring save" markdown-kill-ring-save]
3621 "---"
3622 ("Headings"
3623 ["Automatic" markdown-insert-header-dwim]
3624 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
3625 "---"
3626 ["First level setext" markdown-insert-header-setext-1]
3627 ["Second level setext" markdown-insert-header-setext-2]
3628 "---"
3629 ["First level atx" markdown-insert-header-atx-1]
3630 ["Second level atx" markdown-insert-header-atx-2]
3631 ["Third level atx" markdown-insert-header-atx-3]
3632 ["Fourth level atx" markdown-insert-header-atx-4]
3633 ["Fifth level atx" markdown-insert-header-atx-5]
3634 ["Sixth level atx" markdown-insert-header-atx-6])
3635 "---"
3636 ["Bold" markdown-insert-bold]
3637 ["Italic" markdown-insert-italic]
3638 ["Strike-through" markdown-insert-strike-through]
3639 ["Blockquote" markdown-insert-blockquote]
3640 ["Preformatted" markdown-insert-pre]
3641 ["Code" markdown-insert-code]
3642 "---"
3643 ["Insert inline link" markdown-insert-link]
3644 ["Insert reference link" markdown-insert-reference-link-dwim]
3645 ["Insert URL" markdown-insert-uri]
3646 ["Insert inline image" markdown-insert-image]
3647 ["Insert reference image" markdown-insert-reference-image]
3648 ["Insert list item" markdown-insert-list-item]
3649 ["Insert horizontal rule" markdown-insert-hr]
3650 ["Insert footnote" markdown-insert-footnote]
3651 ["Kill element" markdown-kill-thing-at-point]
3652 "---"
3653 ["Jump" markdown-jump]
3654 ["Follow link" markdown-follow-thing-at-point]
3655 ("Outline"
3656 ["Next visible heading" outline-next-visible-heading]
3657 ["Previous visible heading" outline-previous-visible-heading]
3658 ["Forward same level" outline-forward-same-level]
3659 ["Backward same level" outline-backward-same-level]
3660 ["Up to parent heading" outline-up-heading])
3661 "---"
3662 ("Completion and Cycling"
3663 ["Complete" markdown-complete]
3664 ["Promote" markdown-promote]
3665 ["Demote" markdown-demote])
3666 ("List editing"
3667 ["Indent list item" markdown-demote]
3668 ["Exdent list item" markdown-promote])
3669 ("Region shifting"
3670 ["Indent region" markdown-indent-region]
3671 ["Exdent region" markdown-exdent-region])
3672 "---"
3673 ["Check references" markdown-check-refs]
3674 ["Clean up list numbering" markdown-cleanup-list-numbers]
3675 ["Complete markup" markdown-complete-buffer]
3676 "---"
3677 ["Version" markdown-show-version]
3681 ;;; imenu =====================================================================
3683 (defun markdown-imenu-create-index ()
3684 "Create and return an imenu index alist for the current buffer.
3685 See `imenu-create-index-function' and `imenu--index-alist' for details."
3686 (let* ((root '(nil . nil))
3687 cur-alist
3688 (cur-level 0)
3689 (empty-heading "-")
3690 (self-heading ".")
3691 hashes pos level heading)
3692 (save-excursion
3693 (goto-char (point-min))
3694 (while (re-search-forward markdown-regex-header (point-max) t)
3695 (cond
3696 ((setq heading (match-string-no-properties 1))
3697 (setq pos (match-beginning 1)
3698 level 1))
3699 ((setq heading (match-string-no-properties 3))
3700 (setq pos (match-beginning 3)
3701 level 2))
3702 ((setq hashes (match-string-no-properties 5))
3703 (setq heading (match-string-no-properties 6)
3704 pos (match-beginning 5)
3705 level (length hashes))))
3706 (let ((alist (list (cons heading pos))))
3707 (cond
3708 ((= cur-level level) ; new sibling
3709 (setcdr cur-alist alist)
3710 (setq cur-alist alist))
3711 ((< cur-level level) ; first child
3712 (dotimes (i (- level cur-level 1))
3713 (setq alist (list (cons empty-heading alist))))
3714 (if cur-alist
3715 (let* ((parent (car cur-alist))
3716 (self-pos (cdr parent)))
3717 (setcdr parent (cons (cons self-heading self-pos) alist)))
3718 (setcdr root alist)) ; primogenitor
3719 (setq cur-alist alist)
3720 (setq cur-level level))
3721 (t ; new sibling of an ancestor
3722 (let ((sibling-alist (last (cdr root))))
3723 (dotimes (i (1- level))
3724 (setq sibling-alist (last (cdar sibling-alist))))
3725 (setcdr sibling-alist alist)
3726 (setq cur-alist alist))
3727 (setq cur-level level)))))
3728 (cdr root))))
3731 ;;; References ================================================================
3733 (defun markdown-insert-reference-definition (ref &optional buffer)
3734 "Add blank REF definition to the end of BUFFER.
3735 REF is a Markdown reference without the square brackets."
3736 (or buffer (setq buffer (current-buffer)))
3737 (with-current-buffer buffer
3738 (goto-char (point-max))
3739 (indent-new-comment-line)
3740 (insert (concat "[" ref "]: "))))
3742 (defun markdown-reference-goto-definition ()
3743 "Jump to the definition of the reference at point or create it."
3744 (interactive)
3745 (when (thing-at-point-looking-at markdown-regex-link-reference)
3746 (let* ((text (match-string-no-properties 3))
3747 (reference (match-string-no-properties 6))
3748 (target (downcase (if (string= reference "") text reference)))
3749 (loc (cadr (markdown-reference-definition target))))
3750 (if loc
3751 (goto-char loc)
3752 (markdown-insert-reference-definition target (current-buffer))))))
3754 (defun markdown-reference-find-links (reference)
3755 "Return a list of all links for REFERENCE.
3756 REFERENCE should not include the surrounding square brackets.
3757 Elements of the list have the form (text start line), where
3758 text is the link text, start is the location at the beginning of
3759 the link, and line is the line number on which the link appears."
3760 (let* ((ref-quote (regexp-quote reference))
3761 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3762 ref-quote ref-quote))
3763 links)
3764 (save-excursion
3765 (goto-char (point-min))
3766 (while (re-search-forward regexp nil t)
3767 (let* ((text (or (match-string-no-properties 1)
3768 (match-string-no-properties 2)))
3769 (start (match-beginning 0))
3770 (line (markdown-line-number-at-pos)))
3771 (add-to-list 'links (list text start line)))))
3772 links))
3774 (defun markdown-get-undefined-refs ()
3775 "Return a list of undefined Markdown references.
3776 Result is an alist of pairs (reference . occurrences), where
3777 occurrences is itself another alist of pairs (label . line-number).
3778 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3779 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3780 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
3781 (let ((missing))
3782 (save-excursion
3783 (goto-char (point-min))
3784 (while
3785 (re-search-forward markdown-regex-link-reference nil t)
3786 (let* ((text (match-string-no-properties 3))
3787 (reference (match-string-no-properties 6))
3788 (target (downcase (if (string= reference "") text reference))))
3789 (unless (markdown-reference-definition target)
3790 (let ((entry (assoc target missing)))
3791 (if (not entry)
3792 (add-to-list 'missing (cons target
3793 (list (cons text (markdown-line-number-at-pos)))) t)
3794 (setcdr entry
3795 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3796 missing)))
3798 (defconst markdown-reference-check-buffer
3799 "*Undefined references for %buffer%*"
3800 "Pattern for name of buffer for listing undefined references.
3801 The string %buffer% will be replaced by the corresponding
3802 `markdown-mode' buffer name.")
3804 (defun markdown-reference-check-buffer (&optional buffer-name)
3805 "Name and return buffer for reference checking.
3806 BUFFER-NAME is the name of the main buffer being visited."
3807 (or buffer-name (setq buffer-name (buffer-name)))
3808 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3809 "%buffer%" buffer-name
3810 markdown-reference-check-buffer))))
3811 (with-current-buffer refbuf
3812 (when view-mode
3813 (View-exit-and-edit))
3814 (use-local-map button-buffer-map)
3815 (erase-buffer))
3816 refbuf))
3818 (defconst markdown-reference-links-buffer
3819 "*Reference links for %buffer%*"
3820 "Pattern for name of buffer for listing references.
3821 The string %buffer% will be replaced by the corresponding buffer name.")
3823 (defun markdown-reference-links-buffer (&optional buffer-name)
3824 "Name, setup, and return a buffer for listing links.
3825 BUFFER-NAME is the name of the main buffer being visited."
3826 (or buffer-name (setq buffer-name (buffer-name)))
3827 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3828 "%buffer%" buffer-name
3829 markdown-reference-links-buffer))))
3830 (with-current-buffer linkbuf
3831 (when view-mode
3832 (View-exit-and-edit))
3833 (use-local-map button-buffer-map)
3834 (erase-buffer))
3835 linkbuf))
3837 (when (markdown-use-buttons-p)
3838 ;; Add an empty Markdown reference definition to the end of buffer
3839 ;; specified in the 'target-buffer property. The reference name is
3840 ;; the button's label.
3841 (define-button-type 'markdown-undefined-reference-button
3842 'help-echo "mouse-1, RET: create definition for undefined reference"
3843 'follow-link t
3844 'face 'bold
3845 'action (lambda (b)
3846 (let ((buffer (button-get b 'target-buffer)))
3847 (markdown-insert-reference-definition (button-label b) buffer)
3848 (switch-to-buffer-other-window buffer)
3849 (goto-char (point-max))
3850 (markdown-check-refs t))))
3852 ;; Jump to line in buffer specified by 'target-buffer property.
3853 ;; Line number is button's 'line property.
3854 (define-button-type 'markdown-goto-line-button
3855 'help-echo "mouse-1, RET: go to line"
3856 'follow-link t
3857 'face 'italic
3858 'action (lambda (b)
3859 (message (button-get b 'buffer))
3860 (switch-to-buffer-other-window (button-get b 'target-buffer))
3861 ;; use call-interactively to silence compiler
3862 (let ((current-prefix-arg (button-get b 'target-line)))
3863 (call-interactively 'goto-line))))
3865 ;; Jumps to a particular link at location given by 'target-char
3866 ;; property in buffer given by 'target-buffer property.
3867 (define-button-type 'markdown-link-button
3868 'help-echo "mouse-1, RET: jump to location of link"
3869 'follow-link t
3870 'face 'bold
3871 'action (lambda (b)
3872 (let ((target (button-get b 'target-buffer))
3873 (loc (button-get b 'target-char)))
3874 (kill-buffer-and-window)
3875 (switch-to-buffer target)
3876 (goto-char loc)))))
3878 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3879 "Insert a button for creating REFERENCE in buffer OLDBUF.
3880 REFERENCE should be a list of the form (reference . occurrences),
3881 as by `markdown-get-undefined-refs'."
3882 (let ((label (car reference)))
3883 (if (markdown-use-buttons-p)
3884 ;; Create a reference button in Emacs 22
3885 (insert-button label
3886 :type 'markdown-undefined-reference-button
3887 'target-buffer oldbuf)
3888 ;; Insert reference as text in Emacs < 22
3889 (insert label))
3890 (insert " (")
3891 (dolist (occurrence (cdr reference))
3892 (let ((line (cdr occurrence)))
3893 (if (markdown-use-buttons-p)
3894 ;; Create a line number button in Emacs 22
3895 (insert-button (number-to-string line)
3896 :type 'markdown-goto-line-button
3897 'target-buffer oldbuf
3898 'target-line line)
3899 ;; Insert line number as text in Emacs < 22
3900 (insert (number-to-string line)))
3901 (insert " ")))
3902 (delete-char -1)
3903 (insert ")")
3904 (newline)))
3906 (defun markdown-insert-link-button (link oldbuf)
3907 "Insert a button for jumping to LINK in buffer OLDBUF.
3908 LINK should be a list of the form (text char line) containing
3909 the link text, location, and line number."
3910 (let ((label (first link))
3911 (char (second link))
3912 (line (third link)))
3913 (if (markdown-use-buttons-p)
3914 ;; Create a reference button in Emacs 22
3915 (insert-button label
3916 :type 'markdown-link-button
3917 'target-buffer oldbuf
3918 'target-char char)
3919 ;; Insert reference as text in Emacs < 22
3920 (insert label))
3921 (insert (format " (line %d)\n" line))))
3923 (defun markdown-reference-goto-link (&optional reference)
3924 "Jump to the location of the first use of REFERENCE."
3925 (interactive)
3926 (unless reference
3927 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3928 (setq reference (match-string-no-properties 2))
3929 (error "No reference definition at point")))
3930 (let ((links (markdown-reference-find-links reference)))
3931 (cond ((= (length links) 1)
3932 (goto-char (cadr (car links))))
3933 ((> (length links) 1)
3934 (let ((oldbuf (current-buffer))
3935 (linkbuf (markdown-reference-links-buffer)))
3936 (with-current-buffer linkbuf
3937 (insert "Links using reference " reference ":\n\n")
3938 (dolist (link (reverse links))
3939 (markdown-insert-link-button link oldbuf)))
3940 (view-buffer-other-window linkbuf)
3941 (goto-char (point-min))
3942 (forward-line 2)))
3944 (error "No links for reference %s" reference)))))
3946 (defun markdown-check-refs (&optional silent)
3947 "Show all undefined Markdown references in current `markdown-mode' buffer.
3948 If SILENT is non-nil, do not message anything when no undefined
3949 references found.
3950 Links which have empty reference definitions are considered to be
3951 defined."
3952 (interactive "P")
3953 (when (not (eq major-mode 'markdown-mode))
3954 (error "Not available in current mode"))
3955 (let ((oldbuf (current-buffer))
3956 (refs (markdown-get-undefined-refs))
3957 (refbuf (markdown-reference-check-buffer)))
3958 (if (null refs)
3959 (progn
3960 (when (not silent)
3961 (message "No undefined references found"))
3962 (kill-buffer refbuf))
3963 (with-current-buffer refbuf
3964 (insert "The following references are undefined:\n\n")
3965 (dolist (ref refs)
3966 (markdown-insert-undefined-reference-button ref oldbuf))
3967 (view-buffer-other-window refbuf)
3968 (goto-char (point-min))
3969 (forward-line 2)))))
3972 ;;; Lists =====================================================================
3974 (defun markdown-insert-list-item (&optional arg)
3975 "Insert a new list item.
3976 If the point is inside unordered list, insert a bullet mark. If
3977 the point is inside ordered list, insert the next number followed
3978 by a period. Use the previous list item to determine the amount
3979 of whitespace to place before and after list markers.
3981 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3982 decrease the indentation by one level.
3984 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3985 increase the indentation by one level."
3986 (interactive "p")
3987 (let (bounds item-indent marker indent new-indent new-loc)
3988 (save-match-data
3989 ;; Look for a list item on current or previous non-blank line
3990 (save-excursion
3991 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3992 (not (bobp))
3993 (markdown-cur-line-blank-p))
3994 (forward-line -1)))
3995 (when bounds
3996 (cond ((save-excursion
3997 (skip-chars-backward " \t")
3998 (looking-at markdown-regex-list))
3999 (beginning-of-line)
4000 (insert "\n")
4001 (forward-line -1))
4002 ((not (markdown-cur-line-blank-p))
4003 (newline)))
4004 (setq new-loc (point)))
4005 ;; Look ahead for a list item on next non-blank line
4006 (unless bounds
4007 (save-excursion
4008 (while (and (null bounds)
4009 (not (eobp))
4010 (markdown-cur-line-blank-p))
4011 (forward-line)
4012 (setq bounds (markdown-cur-list-item-bounds))))
4013 (when bounds
4014 (setq new-loc (point))
4015 (unless (markdown-cur-line-blank-p)
4016 (newline))))
4017 (if (not bounds)
4018 ;; When not in a list, start a new unordered one
4019 (progn
4020 (unless (markdown-cur-line-blank-p)
4021 (insert "\n"))
4022 (insert markdown-unordered-list-item-prefix))
4023 ;; Compute indentation for a new list item
4024 (setq item-indent (nth 2 bounds))
4025 (setq marker (nth 4 bounds))
4026 (setq indent (cond
4027 ((= arg 4) (max (- item-indent 4) 0))
4028 ((= arg 16) (+ item-indent 4))
4029 (t item-indent)))
4030 (setq new-indent (make-string indent 32))
4031 (goto-char new-loc)
4032 (cond
4033 ;; Ordered list
4034 ((string-match "[0-9]" marker)
4035 (if (= arg 16) ;; starting a new column indented one more level
4036 (insert (concat new-indent "1. "))
4037 ;; travel up to the last item and pick the correct number. If
4038 ;; the argument was nil, "new-indent = item-indent" is the same,
4039 ;; so we don't need special treatment. Neat.
4040 (save-excursion
4041 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
4042 (>= (forward-line -1) 0))))
4043 (let* ((old-prefix (match-string 1))
4044 (old-spacing (match-string 2))
4045 (new-prefix (if old-prefix
4046 (int-to-string (1+ (string-to-number old-prefix)))
4047 "1"))
4048 (space-adjust (- (length old-prefix) (length new-prefix)))
4049 (new-spacing (if (and (match-string 2)
4050 (not (string-match "\t" old-spacing))
4051 (< space-adjust 0)
4052 (> space-adjust (- 1 (length (match-string 2)))))
4053 (substring (match-string 2) 0 space-adjust)
4054 (or old-spacing ". "))))
4055 (insert (concat new-indent new-prefix new-spacing)))))
4056 ;; Unordered list
4057 ((string-match "[\\*\\+-]" marker)
4058 (insert new-indent marker)))))))
4060 (defun markdown-move-list-item-up ()
4061 "Move the current list item up in the list when possible."
4062 (interactive)
4063 (let (cur prev old)
4064 (when (setq cur (markdown-cur-list-item-bounds))
4065 (setq old (point))
4066 (goto-char (nth 0 cur))
4067 (if (markdown-prev-list-item (nth 3 cur))
4068 (progn
4069 (setq prev (markdown-cur-list-item-bounds))
4070 (condition-case nil
4071 (progn
4072 (transpose-regions (nth 0 prev) (nth 1 prev)
4073 (nth 0 cur) (nth 1 cur) t)
4074 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
4075 ;; Catch error in case regions overlap.
4076 (error (goto-char old))))
4077 (goto-char old)))))
4079 (defun markdown-move-list-item-down ()
4080 "Move the current list item down in the list when possible."
4081 (interactive)
4082 (let (cur next old)
4083 (when (setq cur (markdown-cur-list-item-bounds))
4084 (setq old (point))
4085 (if (markdown-next-list-item (nth 3 cur))
4086 (progn
4087 (setq next (markdown-cur-list-item-bounds))
4088 (condition-case nil
4089 (progn
4090 (transpose-regions (nth 0 cur) (nth 1 cur)
4091 (nth 0 next) (nth 1 next) nil)
4092 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
4093 ;; Catch error in case regions overlap.
4094 (error (goto-char old))))
4095 (goto-char old)))))
4097 (defun markdown-demote-list-item (&optional bounds)
4098 "Indent (or demote) the current list item.
4099 Optionally, BOUNDS of the current list item may be provided if available."
4100 (interactive)
4101 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
4102 (save-excursion
4103 (save-match-data
4104 (let* ((end-marker (make-marker))
4105 (end-marker (set-marker end-marker (nth 1 bounds))))
4106 (goto-char (nth 0 bounds))
4107 (while (< (point) end-marker)
4108 (unless (markdown-cur-line-blank-p)
4109 (insert " "))
4110 (forward-line)))))))
4112 (defun markdown-promote-list-item (&optional bounds)
4113 "Unindent (or promote) the current list item.
4114 Optionally, BOUNDS of the current list item may be provided if available."
4115 (interactive)
4116 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
4117 (save-excursion
4118 (save-match-data
4119 (let* ((end-marker (make-marker))
4120 (end-marker (set-marker end-marker (nth 1 bounds)))
4121 num regexp)
4122 (goto-char (nth 0 bounds))
4123 (when (looking-at "^[ ]\\{1,4\\}")
4124 (setq num (- (match-end 0) (match-beginning 0)))
4125 (setq regexp (format "^[ ]\\{1,%d\\}" num))
4126 (while (and (< (point) end-marker)
4127 (re-search-forward regexp end-marker t))
4128 (replace-match "" nil nil)
4129 (forward-line))))))))
4131 (defun markdown-cleanup-list-numbers-level (&optional pfx)
4132 "Update the numbering for level PFX (as a string of spaces).
4134 Assume that the previously found match was for a numbered item in
4135 a list."
4136 (let ((cpfx pfx)
4137 (idx 0)
4138 (continue t)
4139 (step t)
4140 (sep nil))
4141 (while (and continue (not (eobp)))
4142 (setq step t)
4143 (cond
4144 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
4145 (setq cpfx (match-string-no-properties 1))
4146 (cond
4147 ((string= cpfx pfx)
4148 (replace-match
4149 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
4150 (setq sep nil))
4151 ;; indented a level
4152 ((string< pfx cpfx)
4153 (setq sep (markdown-cleanup-list-numbers-level cpfx))
4154 (setq step nil))
4155 ;; exit the loop
4157 (setq step nil)
4158 (setq continue nil))))
4160 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
4161 (setq cpfx (match-string-no-properties 1))
4162 (cond
4163 ;; reset if separated before
4164 ((string= cpfx pfx) (when sep (setq idx 0)))
4165 ((string< cpfx pfx)
4166 (setq step nil)
4167 (setq continue nil))))
4168 (t (setq sep t)))
4170 (when step
4171 (beginning-of-line)
4172 (setq continue (= (forward-line) 0))))
4173 sep))
4175 (defun markdown-cleanup-list-numbers ()
4176 "Update the numbering of ordered lists."
4177 (interactive)
4178 (save-excursion
4179 (goto-char (point-min))
4180 (markdown-cleanup-list-numbers-level "")))
4183 ;;; Outline ===================================================================
4185 (defvar markdown-cycle-global-status 1)
4186 (defvar markdown-cycle-subtree-status nil)
4188 (defun markdown-end-of-subtree (&optional invisible-OK)
4189 "Move to the end of the current subtree.
4190 Only visible heading lines are considered, unless INVISIBLE-OK is
4191 non-nil.
4192 Derived from `org-end-of-subtree'."
4193 (outline-back-to-heading invisible-OK)
4194 (let ((first t)
4195 (level (funcall outline-level)))
4196 (while (and (not (eobp))
4197 (or first (> (funcall outline-level) level)))
4198 (setq first nil)
4199 (outline-next-heading))
4200 (if (memq (preceding-char) '(?\n ?\^M))
4201 (progn
4202 ;; Go to end of line before heading
4203 (forward-char -1)
4204 (if (memq (preceding-char) '(?\n ?\^M))
4205 ;; leave blank line before heading
4206 (forward-char -1)))))
4207 (point))
4209 (defun markdown-cycle (&optional arg)
4210 "Visibility cycling for Markdown mode.
4211 If ARG is t, perform global visibility cycling. If the point is
4212 at an atx-style header, cycle visibility of the corresponding
4213 subtree. Otherwise, insert a tab using `indent-relative'.
4214 Derived from `org-cycle'."
4215 (interactive "P")
4216 (cond
4217 ((eq arg t) ;; Global cycling
4218 (cond
4219 ((and (eq last-command this-command)
4220 (eq markdown-cycle-global-status 2))
4221 ;; Move from overview to contents
4222 (hide-sublevels 1)
4223 (message "CONTENTS")
4224 (setq markdown-cycle-global-status 3))
4226 ((and (eq last-command this-command)
4227 (eq markdown-cycle-global-status 3))
4228 ;; Move from contents to all
4229 (show-all)
4230 (message "SHOW ALL")
4231 (setq markdown-cycle-global-status 1))
4234 ;; Defaults to overview
4235 (hide-body)
4236 (message "OVERVIEW")
4237 (setq markdown-cycle-global-status 2))))
4239 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4240 ;; At a heading: rotate between three different views
4241 (outline-back-to-heading)
4242 (let ((goal-column 0) eoh eol eos)
4243 ;; Determine boundaries
4244 (save-excursion
4245 (outline-back-to-heading)
4246 (save-excursion
4247 (beginning-of-line 2)
4248 (while (and (not (eobp)) ;; this is like `next-line'
4249 (get-char-property (1- (point)) 'invisible))
4250 (beginning-of-line 2)) (setq eol (point)))
4251 (outline-end-of-heading) (setq eoh (point))
4252 (markdown-end-of-subtree t)
4253 (skip-chars-forward " \t\n")
4254 (beginning-of-line 1) ; in case this is an item
4255 (setq eos (1- (point))))
4256 ;; Find out what to do next and set `this-command'
4257 (cond
4258 ((= eos eoh)
4259 ;; Nothing is hidden behind this heading
4260 (message "EMPTY ENTRY")
4261 (setq markdown-cycle-subtree-status nil))
4262 ((>= eol eos)
4263 ;; Entire subtree is hidden in one line: open it
4264 (show-entry)
4265 (show-children)
4266 (message "CHILDREN")
4267 (setq markdown-cycle-subtree-status 'children))
4268 ((and (eq last-command this-command)
4269 (eq markdown-cycle-subtree-status 'children))
4270 ;; We just showed the children, now show everything.
4271 (show-subtree)
4272 (message "SUBTREE")
4273 (setq markdown-cycle-subtree-status 'subtree))
4275 ;; Default action: hide the subtree.
4276 (hide-subtree)
4277 (message "FOLDED")
4278 (setq markdown-cycle-subtree-status 'folded)))))
4281 (indent-for-tab-command))))
4283 (defun markdown-shifttab ()
4284 "Global visibility cycling.
4285 Calls `markdown-cycle' with argument t."
4286 (interactive)
4287 (markdown-cycle t))
4289 (defun markdown-outline-level ()
4290 "Return the depth to which a statement is nested in the outline."
4291 (cond
4292 ((match-end 1) 1)
4293 ((match-end 3) 2)
4294 ((- (match-end 5) (match-beginning 5)))))
4296 (defun markdown-promote-subtree (&optional arg)
4297 "Promote the current subtree of ATX headings.
4298 Note that Markdown does not support heading levels higher than six
4299 and therefore level-six headings will not be promoted further."
4300 (interactive "*P")
4301 (save-excursion
4302 (when (or (thing-at-point-looking-at markdown-regex-header-atx)
4303 (re-search-backward markdown-regex-header-atx nil t))
4304 (let ((level (length (match-string 1)))
4305 (promote-or-demote (if arg 1 -1))
4306 (remove 't))
4307 (markdown-cycle-atx promote-or-demote remove)
4308 (forward-line)
4309 (catch 'end-of-subtree
4310 (while (re-search-forward markdown-regex-header-atx nil t)
4311 ;; Exit if this not a higher level heading; promote otherwise.
4312 (if (<= (length (match-string-no-properties 1)) level)
4313 (throw 'end-of-subtree nil)
4314 (markdown-cycle-atx promote-or-demote remove))))))))
4316 (defun markdown-demote-subtree ()
4317 "Demote the current subtree of ATX headings."
4318 (interactive)
4319 (markdown-promote-subtree t))
4321 (defun markdown-move-subtree-up ()
4322 "Move the current subtree of ATX headings up."
4323 (interactive)
4324 (outline-move-subtree-up 1))
4326 (defun markdown-move-subtree-down ()
4327 "Move the current subtree of ATX headings down."
4328 (interactive)
4329 (outline-move-subtree-down 1))
4332 ;;; Movement ==================================================================
4334 (defun markdown-beginning-of-defun (&optional arg)
4335 "`beginning-of-defun-function' for Markdown.
4336 Move backward to the beginning of the current or previous section.
4337 When ARG is non-nil, repeat that many times. When ARG is negative,
4338 move forward to the ARG-th following section."
4339 (interactive "P")
4340 (or arg (setq arg 1))
4341 (forward-char 1)
4342 (or (re-search-backward markdown-regex-header nil t arg)
4343 (goto-char (point-min))))
4345 (defun markdown-end-of-defun (&optional arg)
4346 "`end-of-defun-function' for Markdown.
4347 Move forward to the end of the current or following section.
4348 When ARG is non-nil, repeat that many times. When ARG is negative,
4349 move back to the ARG-th preceding section."
4350 (interactive "P")
4351 (or arg (setq arg 1))
4352 (when (looking-at markdown-regex-header)
4353 (goto-char (match-beginning 0))
4354 (forward-char 1))
4355 (if (re-search-forward markdown-regex-header nil t arg)
4356 (goto-char (match-beginning 0))
4357 (goto-char (point-max)))
4358 (skip-syntax-backward "-"))
4360 (defun markdown-beginning-of-block ()
4361 "Move the point to the start of the previous text block."
4362 (interactive)
4363 (if (re-search-backward markdown-regex-block-separator nil t)
4364 (goto-char (or (match-end 2) (match-end 0)))
4365 (goto-char (point-min))))
4367 (defun markdown-end-of-block ()
4368 "Move the point to the start of the next text block."
4369 (interactive)
4370 (beginning-of-line)
4371 (skip-syntax-forward "-")
4372 (when (= (point) (point-min))
4373 (forward-char))
4374 (if (re-search-forward markdown-regex-block-separator nil t)
4375 (goto-char (or (match-end 2) (match-end 0)))
4376 (goto-char (point-max)))
4377 (skip-syntax-backward "-")
4378 (forward-line))
4380 (defun markdown-forward-paragraph (arg)
4381 "Move forward one or more paragraphs or by one block.
4382 When ARG is nil or a numeric prefix, call `forward-paragraph'
4383 with ARG. When called with \\[universal-argument], call
4384 `markdown-end-of-block' instead."
4385 (interactive "P")
4386 (or arg (setq arg 1))
4387 (cond ((integerp arg)
4388 (forward-paragraph arg))
4389 ((equal arg '(4))
4390 (markdown-end-of-block))))
4392 (defun markdown-backward-paragraph (arg)
4393 "Move backward one or more paragraphs or by one block.
4394 When ARG is nil or a numeric prefix, call `backward-paragraph'
4395 with ARG. When called with \\[universal-argument], call
4396 `markdown-beginning-of-block' instead."
4397 (interactive "P")
4398 (or arg (setq arg 1))
4399 (cond ((integerp arg)
4400 (backward-paragraph arg))
4401 ((equal arg '(4))
4402 (markdown-beginning-of-block))))
4404 (defun markdown-end-of-block-element ()
4405 "Move the point to the start of the next block unit.
4406 Stops at blank lines, list items, headers, and horizontal rules."
4407 (interactive)
4408 (forward-line)
4409 (while (and (or (not (markdown-prev-line-blank-p))
4410 (markdown-cur-line-blank-p))
4411 (not (or (looking-at markdown-regex-list)
4412 (looking-at markdown-regex-header)
4413 (looking-at markdown-regex-hr)))
4414 (not (eobp)))
4415 (forward-line)))
4417 (defun markdown-next-link ()
4418 "Jump to next inline, reference, or wiki link.
4419 If successful, return point. Otherwise, return nil.
4420 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
4421 (interactive)
4422 (let ((opoint (point)))
4423 (when (or (markdown-link-p) (markdown-wiki-link-p))
4424 ;; At a link already, move past it.
4425 (goto-char (+ (match-end 0) 1)))
4426 ;; Search for the next wiki link and move to the beginning.
4427 (if (re-search-forward markdown-regex-link-generic nil t)
4428 ;; Group 1 will move past non-escape character in wiki link regexp.
4429 ;; Go to beginning of group zero for all other link types.
4430 (goto-char (or (match-beginning 1) (match-beginning 0)))
4431 (goto-char opoint)
4432 nil)))
4434 (defun markdown-previous-link ()
4435 "Jump to previous wiki link.
4436 If successful, return point. Otherwise, return nil.
4437 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
4438 (interactive)
4439 (if (re-search-backward markdown-regex-link-generic nil t)
4440 (goto-char (or (match-beginning 1) (match-beginning 0)))
4441 nil))
4444 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
4446 (defun markdown-move-up ()
4447 "Move list item up.
4448 Calls `markdown-move-list-item-up'."
4449 (interactive)
4450 (markdown-move-list-item-up))
4452 (defun markdown-move-down ()
4453 "Move list item down.
4454 Calls `markdown-move-list-item-down'."
4455 (interactive)
4456 (markdown-move-list-item-down))
4458 (defun markdown-promote ()
4459 "Either promote header or list item at point or cycle markup.
4460 See `markdown-cycle-atx', `markdown-cycle-setext', and
4461 `markdown-promote-list-item'."
4462 (interactive)
4463 (let (bounds)
4464 (cond
4465 ;; Promote atx header
4466 ((thing-at-point-looking-at markdown-regex-header-atx)
4467 (markdown-cycle-atx -1))
4468 ;; Promote setext header
4469 ((thing-at-point-looking-at markdown-regex-header-setext)
4470 (markdown-cycle-setext -1))
4471 ;; Promote horizonal rule
4472 ((thing-at-point-looking-at markdown-regex-hr)
4473 (markdown-cycle-hr -1))
4474 ;; Promote list item
4475 ((setq bounds (markdown-cur-list-item-bounds))
4476 (markdown-promote-list-item))
4477 ;; Promote bold
4478 ((thing-at-point-looking-at markdown-regex-bold)
4479 (markdown-cycle-bold))
4480 ;; Promote italic
4481 ((thing-at-point-looking-at markdown-regex-italic)
4482 (markdown-cycle-italic))
4484 (error "Nothing to promote at point")))))
4486 (defun markdown-demote ()
4487 "Either demote header or list item at point or cycle or remove markup.
4488 See `markdown-cycle-atx', `markdown-cycle-setext', and
4489 `markdown-demote-list-item'."
4490 (interactive)
4491 (let (bounds)
4492 (cond
4493 ;; Demote atx header
4494 ((thing-at-point-looking-at markdown-regex-header-atx)
4495 (markdown-cycle-atx 1))
4496 ;; Demote setext header
4497 ((thing-at-point-looking-at markdown-regex-header-setext)
4498 (markdown-cycle-setext 1))
4499 ;; Demote horizonal rule
4500 ((thing-at-point-looking-at markdown-regex-hr)
4501 (markdown-cycle-hr 1))
4502 ;; Demote list item
4503 ((setq bounds (markdown-cur-list-item-bounds))
4504 (markdown-demote-list-item))
4505 ;; Demote bold
4506 ((thing-at-point-looking-at markdown-regex-bold)
4507 (markdown-cycle-bold))
4508 ;; Demote italic
4509 ((thing-at-point-looking-at markdown-regex-italic)
4510 (markdown-cycle-italic))
4512 (error "Nothing to demote at point")))))
4515 ;;; Commands ==================================================================
4517 (defun markdown (&optional output-buffer-name)
4518 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
4519 The output buffer name defaults to `markdown-output-buffer-name'.
4520 Return the name of the output buffer used."
4521 (interactive)
4522 (save-window-excursion
4523 (let ((begin-region)
4524 (end-region))
4525 (if (markdown-use-region-p)
4526 (setq begin-region (region-beginning)
4527 end-region (region-end))
4528 (setq begin-region (point-min)
4529 end-region (point-max)))
4531 (unless output-buffer-name
4532 (setq output-buffer-name markdown-output-buffer-name))
4534 (cond
4535 ;; Handle case when `markdown-command' does not read from stdin
4536 (markdown-command-needs-filename
4537 (if (not buffer-file-name)
4538 (error "Must be visiting a file")
4539 (shell-command (concat markdown-command " "
4540 (shell-quote-argument buffer-file-name))
4541 output-buffer-name)))
4542 ;; Pass region to `markdown-command' via stdin
4544 (shell-command-on-region begin-region end-region markdown-command
4545 output-buffer-name))))
4546 output-buffer-name))
4548 (defun markdown-standalone (&optional output-buffer-name)
4549 "Special function to provide standalone HTML output.
4550 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
4551 (interactive)
4552 (setq output-buffer-name (markdown output-buffer-name))
4553 (with-current-buffer output-buffer-name
4554 (set-buffer output-buffer-name)
4555 (unless (markdown-output-standalone-p)
4556 (markdown-add-xhtml-header-and-footer output-buffer-name))
4557 (goto-char (point-min))
4558 (html-mode))
4559 output-buffer-name)
4561 (defun markdown-other-window (&optional output-buffer-name)
4562 "Run `markdown-command' on current buffer and display in other window.
4563 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4564 that name."
4565 (interactive)
4566 (display-buffer (markdown-standalone output-buffer-name)))
4568 (defun markdown-output-standalone-p ()
4569 "Determine whether `markdown-command' output is standalone XHTML.
4570 Standalone XHTML output is identified by an occurrence of
4571 `markdown-xhtml-standalone-regexp' in the first five lines of output."
4572 (save-excursion
4573 (goto-char (point-min))
4574 (re-search-forward
4575 markdown-xhtml-standalone-regexp
4576 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
4577 t)))
4579 (defun markdown-stylesheet-link-string (stylesheet-path)
4580 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
4581 stylesheet-path
4582 "\" />"))
4584 (defun markdown-add-xhtml-header-and-footer (title)
4585 "Wrap XHTML header and footer with given TITLE around current buffer."
4586 (goto-char (point-min))
4587 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
4588 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
4589 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
4590 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
4591 "<head>\n<title>")
4592 (insert title)
4593 (insert "</title>\n")
4594 (when (> (length markdown-content-type) 0)
4595 (insert
4596 (format
4597 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
4598 markdown-content-type
4599 (or (and markdown-coding-system
4600 (fboundp 'coding-system-get)
4601 (coding-system-get markdown-coding-system
4602 'mime-charset))
4603 (and (fboundp 'coding-system-get)
4604 (coding-system-get buffer-file-coding-system
4605 'mime-charset))
4606 "iso-8859-1"))))
4607 (if (> (length markdown-css-paths) 0)
4608 (insert (mapconcat 'markdown-stylesheet-link-string markdown-css-paths "\n")))
4609 (when (> (length markdown-xhtml-header-content) 0)
4610 (insert markdown-xhtml-header-content))
4611 (insert "\n</head>\n\n"
4612 "<body>\n\n")
4613 (goto-char (point-max))
4614 (insert "\n"
4615 "</body>\n"
4616 "</html>\n"))
4618 (defun markdown-preview (&optional output-buffer-name)
4619 "Run `markdown-command' on the current buffer and view output in browser.
4620 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4621 that name."
4622 (interactive)
4623 (browse-url-of-buffer (markdown-standalone markdown-output-buffer-name)))
4625 (defun markdown-export-file-name (&optional extension)
4626 "Attempt to generate a filename for Markdown output.
4627 The file extension will be EXTENSION if given, or .html by default.
4628 If the current buffer is visiting a file, we construct a new
4629 output filename based on that filename. Otherwise, return nil."
4630 (when (buffer-file-name)
4631 (unless extension
4632 (setq extension ".html"))
4633 (let ((candidate
4634 (concat
4635 (cond
4636 ((buffer-file-name)
4637 (file-name-sans-extension (buffer-file-name)))
4638 (t (buffer-name)))
4639 extension)))
4640 (cond
4641 ((equal candidate (buffer-file-name))
4642 (concat candidate extension))
4644 candidate)))))
4646 (defun markdown-export (&optional output-file)
4647 "Run Markdown on the current buffer, save to file, and return the filename.
4648 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4649 generated by `markdown-export-file-name', which will be constructed using the
4650 current filename, but with the extension removed and replaced with .html."
4651 (interactive)
4652 (unless output-file
4653 (setq output-file (markdown-export-file-name ".html")))
4654 (when output-file
4655 (let* ((init-buf (current-buffer))
4656 (init-point (point))
4657 (init-buf-string (buffer-string))
4658 (output-buffer (find-file-noselect output-file))
4659 (output-buffer-name (buffer-name output-buffer)))
4660 (run-hooks 'markdown-before-export-hook)
4661 (markdown-standalone output-buffer-name)
4662 (with-current-buffer output-buffer
4663 (run-hooks 'markdown-after-export-hook)
4664 (save-buffer))
4665 ;; if modified, restore initial buffer
4666 (when (buffer-modified-p init-buf)
4667 (erase-buffer)
4668 (insert init-buf-string)
4669 (save-buffer)
4670 (goto-char init-point))
4671 output-file)))
4673 (defun markdown-export-and-preview ()
4674 "Export to XHTML using `markdown-export' and browse the resulting file."
4675 (interactive)
4676 (browse-url-of-file (markdown-export)))
4678 (defvar-local markdown-live-preview-buffer nil
4679 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
4681 (defun markdown-live-preview-window-eww (file)
4682 "A `markdown-live-preview-window-function' for previewing with eww."
4683 (eww-open-file file)
4684 (get-buffer "*eww*"))
4686 (defun markdown-live-preview-window-serialize (buf)
4687 "Get window point and scroll data for all windows displaying BUF if BUF is
4688 non-nil."
4689 (when buf
4690 (mapcar (lambda (win) (list win (window-point win) (window-start win)))
4691 (get-buffer-window-list buf))))
4693 (defun markdown-live-preview-window-deserialize (window-posns)
4694 "Apply window point and scroll data from WINDOW-POSNS, given by
4695 `markdown-live-preview-window-serialize'."
4696 (destructuring-bind (win pt start) window-posns
4697 (set-window-buffer win markdown-live-preview-buffer)
4698 (set-window-point win pt)
4699 (set-window-start win start)))
4701 (defun markdown-live-preview-export ()
4702 "Export to XHTML using `markdown-export' and browse the resulting file within
4703 Emacs using `markdown-live-preview-window-function'."
4704 (interactive)
4705 (let ((export-file (markdown-export))
4706 ;; get positions in all windows currently displaying output buffer
4707 (window-data
4708 (markdown-live-preview-window-serialize markdown-live-preview-buffer))
4709 (cur-buf (current-buffer)))
4710 (save-window-excursion
4711 ;; protect against `markdown-live-preview-window-function' changing
4712 ;; `current-buffer'
4713 (let ((output-buffer
4714 (funcall markdown-live-preview-window-function export-file)))
4715 (with-current-buffer cur-buf
4716 (setq markdown-live-preview-buffer output-buffer))))
4717 ;; reset all windows displaying output buffer to where they were, now with
4718 ;; the new output
4719 (mapc #'markdown-live-preview-window-deserialize window-data)
4720 (when (and markdown-live-preview-delete-export
4721 export-file
4722 (file-exists-p export-file))
4723 (delete-file export-file)
4724 (let ((buf (get-file-buffer export-file)))
4725 (when buf (kill-buffer buf))))
4726 markdown-live-preview-buffer))
4728 (defun markdown-live-preview-remove ()
4729 (when (buffer-live-p markdown-live-preview-buffer)
4730 (kill-buffer markdown-live-preview-buffer))
4731 (setq markdown-live-preview-buffer nil))
4733 (defun markdown-live-preview-if-markdown ()
4734 (when (and (derived-mode-p 'markdown-mode)
4735 markdown-live-preview-mode)
4736 (markdown-live-preview-export)))
4738 (defun markdown-live-preview-remove-on-kill ()
4739 (when (and (derived-mode-p 'markdown-mode)
4740 markdown-live-preview-mode)
4741 (markdown-live-preview-remove)))
4743 (defun markdown-open ()
4744 "Open file for the current buffer with `markdown-open-command'."
4745 (interactive)
4746 (if (not markdown-open-command)
4747 (error "Variable `markdown-open-command' must be set")
4748 (if (not buffer-file-name)
4749 (error "Must be visiting a file")
4750 (call-process markdown-open-command
4751 nil nil nil buffer-file-name))))
4753 (defun markdown-kill-ring-save ()
4754 "Run Markdown on file and store output in the kill ring."
4755 (interactive)
4756 (save-window-excursion
4757 (markdown)
4758 (with-current-buffer markdown-output-buffer-name
4759 (kill-ring-save (point-min) (point-max)))))
4762 ;;; Links =====================================================================
4764 (defun markdown-link-p ()
4765 "Return non-nil when `point' is at a non-wiki link.
4766 See `markdown-wiki-link-p' for more information."
4767 (let ((case-fold-search nil))
4768 (and (not (markdown-wiki-link-p))
4769 (or (thing-at-point-looking-at markdown-regex-link-inline)
4770 (thing-at-point-looking-at markdown-regex-link-reference)
4771 (thing-at-point-looking-at markdown-regex-uri)
4772 (thing-at-point-looking-at markdown-regex-angle-uri)))))
4774 (defun markdown-link-link ()
4775 "Return the link part of the regular (non-wiki) link at point.
4776 Works with both inline and reference style links. If point is
4777 not at a link or the link reference is not defined returns nil."
4778 (cond
4779 ((thing-at-point-looking-at markdown-regex-link-inline)
4780 (match-string-no-properties 6))
4781 ((thing-at-point-looking-at markdown-regex-link-reference)
4782 (let* ((text (match-string-no-properties 3))
4783 (reference (match-string-no-properties 6))
4784 (target (downcase (if (string= reference "") text reference))))
4785 (car (markdown-reference-definition target))))
4786 ((thing-at-point-looking-at markdown-regex-uri)
4787 (match-string-no-properties 0))
4788 ((thing-at-point-looking-at markdown-regex-angle-uri)
4789 (match-string-no-properties 2))
4790 (t nil)))
4792 (defun markdown-follow-link-at-point ()
4793 "Open the current non-wiki link in a browser."
4794 (interactive)
4795 (if (markdown-link-p) (browse-url (markdown-link-link))
4796 (error "Point is not at a Markdown link or URI")))
4799 ;;; WikiLink Following/Markup =================================================
4801 (defun markdown-wiki-link-p ()
4802 "Return non-nil when `point' is at a true wiki link.
4803 A true wiki link name matches `markdown-regex-wiki-link' but does not
4804 match the current file name after conversion. This modifies the data
4805 returned by `match-data'. Note that the potential wiki link name must
4806 be available via `match-string'."
4807 (let ((case-fold-search nil))
4808 (and (thing-at-point-looking-at markdown-regex-wiki-link)
4809 (or (not buffer-file-name)
4810 (not (string-equal (buffer-file-name)
4811 (markdown-convert-wiki-link-to-filename
4812 (markdown-wiki-link-link)))))
4813 (not (save-match-data
4814 (save-excursion))))))
4816 (defun markdown-wiki-link-link ()
4817 "Return the link part of the wiki link using current match data.
4818 The location of the link component depends on the value of
4819 `markdown-wiki-link-alias-first'."
4820 (if markdown-wiki-link-alias-first
4821 (or (match-string-no-properties 5) (match-string-no-properties 3))
4822 (match-string-no-properties 3)))
4824 (defun markdown-wiki-link-alias ()
4825 "Return the alias or text part of the wiki link using current match data.
4826 The location of the alias component depends on the value of
4827 `markdown-wiki-link-alias-first'."
4828 (if markdown-wiki-link-alias-first
4829 (match-string-no-properties 3)
4830 (or (match-string-no-properties 5) (match-string-no-properties 3))))
4832 (defun markdown-convert-wiki-link-to-filename (name)
4833 "Generate a filename from the wiki link NAME.
4834 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4835 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4836 and [[test test]] both map to Test-test.ext."
4837 (let ((basename (markdown-replace-regexp-in-string
4838 "[[:space:]\n]" markdown-link-space-sub-char name)))
4839 (when (eq major-mode 'gfm-mode)
4840 (setq basename (concat (upcase (substring basename 0 1))
4841 (downcase (substring basename 1 nil)))))
4842 (let* ((default
4843 (concat basename
4844 (if (and (buffer-file-name)
4845 (file-name-extension (buffer-file-name)))
4846 (concat "."
4847 (file-name-extension (buffer-file-name))))))
4848 (current default))
4849 (catch 'done
4850 (loop
4851 (if (or (file-exists-p current)
4852 (not markdown-wiki-link-search-parent-directories))
4853 (throw 'done current))
4854 (if (string-equal (expand-file-name current)
4855 (concat "/" default))
4856 (throw 'done default))
4857 (setq current (concat "../" current)))))))
4859 (defun markdown-follow-wiki-link (name &optional other)
4860 "Follow the wiki link NAME.
4861 Convert the name to a file name and call `find-file'. Ensure that
4862 the new buffer remains in `markdown-mode'. Open the link in another
4863 window when OTHER is non-nil."
4864 (let ((filename (markdown-convert-wiki-link-to-filename name))
4865 (wp (file-name-directory buffer-file-name)))
4866 (when other (other-window 1))
4867 (let ((default-directory wp))
4868 (find-file filename)))
4869 (when (not (eq major-mode 'markdown-mode))
4870 (markdown-mode)))
4872 (defun markdown-follow-wiki-link-at-point (&optional arg)
4873 "Find Wiki Link at point.
4874 With prefix argument ARG, open the file in other window.
4875 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4876 (interactive "P")
4877 (if (markdown-wiki-link-p)
4878 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4879 (error "Point is not at a Wiki Link")))
4881 (defun markdown-highlight-wiki-link (from to face)
4882 "Highlight the wiki link in the region between FROM and TO using FACE."
4883 (put-text-property from to 'font-lock-face face))
4885 (defun markdown-unfontify-region-wiki-links (from to)
4886 "Remove wiki link faces from the region specified by FROM and TO."
4887 (interactive "nfrom: \nnto: ")
4888 (remove-text-properties from to '(font-lock-face markdown-link-face))
4889 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4891 (defun markdown-fontify-region-wiki-links (from to)
4892 "Search region given by FROM and TO for wiki links and fontify them.
4893 If a wiki link is found check to see if the backing file exists
4894 and highlight accordingly."
4895 (goto-char from)
4896 (save-match-data
4897 (while (re-search-forward markdown-regex-wiki-link to t)
4898 (let ((highlight-beginning (match-beginning 1))
4899 (highlight-end (match-end 1))
4900 (file-name
4901 (markdown-convert-wiki-link-to-filename
4902 (markdown-wiki-link-link))))
4903 (if (file-exists-p file-name)
4904 (markdown-highlight-wiki-link
4905 highlight-beginning highlight-end markdown-link-face)
4906 (markdown-highlight-wiki-link
4907 highlight-beginning highlight-end markdown-link-face)
4908 (markdown-highlight-wiki-link
4909 highlight-beginning highlight-end markdown-missing-link-face))))))
4911 (defun markdown-extend-changed-region (from to)
4912 "Extend region given by FROM and TO so that we can fontify all links.
4913 The region is extended to the first newline before and the first
4914 newline after."
4915 ;; start looking for the first new line before 'from
4916 (goto-char from)
4917 (re-search-backward "\n" nil t)
4918 (let ((new-from (point-min))
4919 (new-to (point-max)))
4920 (if (not (= (point) from))
4921 (setq new-from (point)))
4922 ;; do the same thing for the first new line after 'to
4923 (goto-char to)
4924 (re-search-forward "\n" nil t)
4925 (if (not (= (point) to))
4926 (setq new-to (point)))
4927 (values new-from new-to)))
4929 (defun markdown-check-change-for-wiki-link (from to change)
4930 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4931 Designed to be used with the `after-change-functions' hook.
4932 CHANGE is the number of bytes of pre-change text replaced by the
4933 given range."
4934 (interactive "nfrom: \nnto: \nnchange: ")
4935 (let* ((modified (buffer-modified-p))
4936 (buffer-undo-list t)
4937 (inhibit-read-only t)
4938 (inhibit-point-motion-hooks t)
4939 deactivate-mark
4940 buffer-file-truename)
4941 (unwind-protect
4942 (save-excursion
4943 (save-match-data
4944 (save-restriction
4945 ;; Extend the region to fontify so that it starts
4946 ;; and ends at safe places.
4947 (multiple-value-bind (new-from new-to)
4948 (markdown-extend-changed-region from to)
4949 ;; Unfontify existing fontification (start from scratch)
4950 (markdown-unfontify-region-wiki-links new-from new-to)
4951 ;; Now do the fontification.
4952 (markdown-fontify-region-wiki-links new-from new-to)))))
4953 (and (not modified)
4954 (buffer-modified-p)
4955 (set-buffer-modified-p nil)))))
4957 (defun markdown-fontify-buffer-wiki-links ()
4958 "Refontify all wiki links in the buffer."
4959 (interactive)
4960 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4963 ;;; Following and Jumping =====================================================
4965 (defun markdown-follow-thing-at-point (arg)
4966 "Follow thing at point if possible, such as a reference link or wiki link.
4967 Opens inline and reference links in a browser. Opens wiki links
4968 to other files in the current window, or the another window if
4969 ARG is non-nil.
4970 See `markdown-follow-link-at-point' and
4971 `markdown-follow-wiki-link-at-point'."
4972 (interactive "P")
4973 (cond ((markdown-link-p)
4974 (markdown-follow-link-at-point))
4975 ((markdown-wiki-link-p)
4976 (markdown-follow-wiki-link-at-point arg))
4978 (error "Nothing to follow at point"))))
4980 (defun markdown-jump ()
4981 "Jump to another location based on context at point.
4982 Jumps between reference links and definitions; between footnote
4983 markers and footnote text."
4984 (interactive)
4985 (cond ((markdown-footnote-text-positions)
4986 (markdown-footnote-return))
4987 ((markdown-footnote-marker-positions)
4988 (markdown-footnote-goto-text))
4989 ((thing-at-point-looking-at markdown-regex-link-reference)
4990 (markdown-reference-goto-definition))
4991 ((thing-at-point-looking-at markdown-regex-reference-definition)
4992 (markdown-reference-goto-link (match-string-no-properties 2)))
4994 (error "Nothing to jump to from context at point"))))
4997 ;;; Miscellaneous =============================================================
4999 (defun markdown-compress-whitespace-string (str)
5000 "Compress whitespace in STR and return result.
5001 Leading and trailing whitespace is removed. Sequences of multiple
5002 spaces, tabs, and newlines are replaced with single spaces."
5003 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
5004 (replace-regexp-in-string "[ \t\n]+" " " str)))
5006 (defun markdown-line-number-at-pos (&optional pos)
5007 "Return (narrowed) buffer line number at position POS.
5008 If POS is nil, use current buffer location.
5009 This is an exact copy of `line-number-at-pos' for use in emacs21."
5010 (let ((opoint (or pos (point))) start)
5011 (save-excursion
5012 (goto-char (point-min))
5013 (setq start (point))
5014 (goto-char opoint)
5015 (forward-line 0)
5016 (1+ (count-lines start (point))))))
5018 (defun markdown-inside-link-text-p ()
5019 "Return nil if not currently within link anchor text."
5020 (looking-back "\\[[^]]*" nil))
5022 (defun markdown-line-is-reference-definition-p ()
5023 "Return whether the current line is a (non-footnote) reference defition."
5024 (save-excursion
5025 (move-beginning-of-line 1)
5026 (and (looking-at-p markdown-regex-reference-definition)
5027 (not (looking-at-p "[ \t]*\\[^")))))
5029 (defun markdown-adaptive-fill-function ()
5030 "Return prefix for filling paragraph or nil if not determined."
5031 (cond
5032 ;; List item inside blockquote
5033 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+-]\\)[ \t]+")
5034 (replace-regexp-in-string
5035 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
5036 ;; Blockquote
5037 ((looking-at "^[ \t]*>[ \t]*")
5038 (match-string-no-properties 0))
5039 ;; List items
5040 ((looking-at markdown-regex-list)
5041 (match-string-no-properties 0))
5042 ((looking-at markdown-regex-footnote-definition)
5043 " ") ; four spaces
5044 ;; No match
5045 (t nil)))
5047 (defun markdown-fill-forward-paragraph-function (&optional arg)
5048 (let* ((arg (or arg 1))
5049 (paragraphs-remaining (forward-paragraph arg))
5050 (start (point)))
5051 (when (< arg 0)
5052 (while (and (not (eobp))
5053 (progn (move-to-left-margin) (not (eobp)))
5054 (looking-at paragraph-separate))
5055 (forward-line 1))
5056 (if (looking-at markdown-regex-list)
5057 (forward-char (length (match-string 0)))
5058 (goto-char start)))
5059 paragraphs-remaining))
5062 ;;; Extensions ================================================================
5064 (defun markdown-reload-extensions ()
5065 "Check settings, update font-lock keywords, and re-fontify buffer."
5066 (interactive)
5067 (when (eq major-mode 'markdown-mode)
5068 (setq markdown-mode-font-lock-keywords
5069 (append
5070 (when markdown-enable-math
5071 markdown-mode-font-lock-keywords-math)
5072 markdown-mode-font-lock-keywords-basic
5073 markdown-mode-font-lock-keywords-core))
5074 (setq font-lock-defaults '(markdown-mode-font-lock-keywords))
5075 (when (fboundp 'font-lock-refresh-defaults) (font-lock-refresh-defaults))))
5077 (defun markdown-enable-math (&optional arg)
5078 "Toggle support for inline and display LaTeX math expressions.
5079 With a prefix argument ARG, enable math mode if ARG is positive,
5080 and disable it otherwise. If called from Lisp, enable the mode
5081 if ARG is omitted or nil."
5082 (interactive (list (or current-prefix-arg 'toggle)))
5083 (setq markdown-enable-math
5084 (if (eq arg 'toggle)
5085 (not markdown-enable-math)
5086 (> (prefix-numeric-value arg) 0)))
5087 (if markdown-enable-math
5088 (message "markdown-mode math support enabled")
5089 (message "markdown-mode math support disabled"))
5090 (markdown-reload-extensions))
5092 (defun markdown-handle-local-variables ()
5093 "Runs as a `hack-local-variables-hook' to update font lock rules.
5094 Checks to see if there is actually a markdown-mode file local variable
5095 before regenerating font-lock rules for extensions."
5096 (when (and (boundp 'file-local-variables-alist)
5097 (assoc 'markdown-enable-math file-local-variables-alist))
5098 (markdown-reload-extensions)))
5101 ;;; GFM Checkboxes as Buttons =================================================
5103 (require 'button)
5105 (define-button-type 'markdown-gfm-checkbox-button
5106 'follow-link t
5107 'face 'markdown-gfm-checkbox-face
5108 'mouse-face 'markdown-highlight-face
5109 'action #'markdown-toggle-gfm-checkbox)
5111 (defun markdown-toggle-gfm-checkbox (button)
5112 "Toggle a GFM checkbox clicked on."
5113 (save-match-data
5114 (save-excursion
5115 (goto-char (button-start button))
5116 (cond ((looking-at "\\[ \\]")
5117 (replace-match "[x]" nil t))
5118 ((looking-at "\\[[xX]\\]")
5119 (replace-match "[ ]" nil t))))))
5121 (defun markdown-make-gfm-checkboxes-buttons (start end)
5122 "Make GFM checkboxes buttons in region between START and END."
5123 (save-excursion
5124 (goto-char start)
5125 (let ((case-fold-search t))
5126 (save-excursion
5127 (while (re-search-forward markdown-regex-gfm-checkbox end t)
5128 (make-button (match-beginning 1) (match-end 1)
5129 :type 'markdown-gfm-checkbox-button))))))
5131 ;; Called when any modification is made to buffer text.
5132 (defun markdown-gfm-checkbox-after-change-function (beg end old-len)
5133 "Add to `after-change-functions' to setup GFM checkboxes as buttons."
5134 (save-excursion
5135 (save-match-data
5136 ;; Rescan between start of line from `beg' and start of line after `end'.
5137 (markdown-make-gfm-checkboxes-buttons
5138 (progn (goto-char beg) (beginning-of-line) (point))
5139 (progn (goto-char end) (forward-line 1) (point))))))
5142 ;;; Mode Definition ==========================================================
5144 (defun markdown-show-version ()
5145 "Show the version number in the minibuffer."
5146 (interactive)
5147 (message "markdown-mode, version %s" markdown-mode-version))
5149 ;;;###autoload
5150 (define-derived-mode markdown-mode text-mode "Markdown"
5151 "Major mode for editing Markdown files."
5152 ;; Natural Markdown tab width
5153 (setq tab-width 4)
5154 ;; Comments
5155 (make-local-variable 'comment-start)
5156 (setq comment-start "<!-- ")
5157 (make-local-variable 'comment-end)
5158 (setq comment-end " -->")
5159 (make-local-variable 'comment-start-skip)
5160 (setq comment-start-skip "<!--[ \t]*")
5161 (make-local-variable 'comment-column)
5162 (setq comment-column 0)
5163 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
5164 ;; Font lock.
5165 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
5166 (set (make-local-variable 'font-lock-defaults) nil)
5167 (set (make-local-variable 'font-lock-multiline) t)
5168 (set (make-local-variable 'font-lock-support-mode)
5169 markdown-font-lock-support-mode)
5170 ;; Extensions
5171 (make-local-variable 'markdown-enable-math)
5172 ;; Reload extensions
5173 (markdown-reload-extensions)
5174 ;; Add a buffer-local hook to reload after file-local variables are read
5175 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
5176 ;; For imenu support
5177 (setq imenu-create-index-function 'markdown-imenu-create-index)
5178 ;; For menu support in XEmacs
5179 (easy-menu-add markdown-mode-menu markdown-mode-map)
5180 ;; Defun movement
5181 (set (make-local-variable 'beginning-of-defun-function)
5182 'markdown-beginning-of-defun)
5183 (set (make-local-variable 'end-of-defun-function)
5184 'markdown-end-of-defun)
5185 ;; Paragraph filling
5186 (set
5187 ; Should match start of lines that start or separate paragraphs
5188 (make-local-variable 'paragraph-start)
5189 (mapconcat 'identity
5191 "\f" ; starts with a literal line-feed
5192 "[ \t\f]*$" ; space-only line
5193 "[ \t]*[*+-][ \t]+" ; unordered list item
5194 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
5195 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
5196 "[ \t]*:[ \t]+" ; definition
5198 "\\|"))
5199 (set
5200 ; Should match lines that separate paragraphs without being
5201 ; part of any paragraph:
5202 (make-local-variable 'paragraph-separate)
5203 (mapconcat 'identity
5204 '("[ \t\f]*$" ; space-only line
5205 ; The following is not ideal, but the Fill customization
5206 ; options really only handle paragraph-starting prefixes,
5207 ; not paragraph-ending suffixes:
5208 ".* $" ; line ending in two spaces
5209 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
5210 "\\|"))
5211 (set (make-local-variable 'adaptive-fill-first-line-regexp)
5212 "\\`[ \t]*>[ \t]*?\\'")
5213 (set (make-local-variable 'adaptive-fill-function)
5214 'markdown-adaptive-fill-function)
5215 (set (make-local-variable 'fill-forward-paragraph-function)
5216 'markdown-fill-forward-paragraph-function)
5217 ;; Outline mode
5218 (make-local-variable 'outline-regexp)
5219 (setq outline-regexp markdown-regex-header)
5220 (make-local-variable 'outline-level)
5221 (setq outline-level 'markdown-outline-level)
5222 ;; Cause use of ellipses for invisible text.
5223 (add-to-invisibility-spec '(outline . t))
5225 ;; Inhibiting line-breaking:
5226 ;; Separating out each condition into a separate function so that users can
5227 ;; override if desired (with remove-hook)
5228 (add-hook 'fill-nobreak-predicate
5229 'markdown-inside-link-text-p nil t)
5230 (add-hook 'fill-nobreak-predicate
5231 'markdown-line-is-reference-definition-p nil t)
5233 ;; Indentation
5234 (setq indent-line-function markdown-indent-function)
5236 ;; Backwards compatibility with markdown-css-path
5237 (when (boundp 'markdown-css-path)
5238 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
5239 (add-to-list 'markdown-css-paths markdown-css-path))
5241 ;; Prepare hooks for XEmacs compatibility
5242 (when (featurep 'xemacs)
5243 (make-local-hook 'after-change-functions)
5244 (make-local-hook 'font-lock-extend-region-functions)
5245 (make-local-hook 'window-configuration-change-hook))
5247 ;; Multiline font lock
5248 (add-hook 'font-lock-extend-region-functions
5249 'markdown-font-lock-extend-region)
5251 ;; Anytime text changes make sure it gets fontified correctly
5252 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
5254 ;; Make checkboxes buttons
5255 (when markdown-make-gfm-checkboxes-buttons
5256 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
5257 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
5259 ;; If we left the buffer there is a really good chance we were
5260 ;; creating one of the wiki link documents. Make sure we get
5261 ;; refontified when we come back.
5262 (add-hook 'window-configuration-change-hook
5263 'markdown-fontify-buffer-wiki-links t t)
5265 ;; do the initial link fontification
5266 (markdown-fontify-buffer-wiki-links))
5268 ;;;###autoload
5269 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
5270 ;;;###autoload
5271 (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
5272 ;;;###autoload
5273 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
5276 ;;; GitHub Flavored Markdown Mode ============================================
5278 (defvar gfm-font-lock-keywords
5279 (append
5280 ;; GFM features to match first
5281 (list
5282 (cons markdown-regex-strike-through '((3 markdown-markup-face)
5283 (4 markdown-strike-through-face)
5284 (5 markdown-markup-face))))
5285 ;; Basic Markdown features (excluding possibly overridden ones)
5286 markdown-mode-font-lock-keywords-basic
5287 ;; GFM features to match last
5288 (list
5289 (cons markdown-regex-gfm-italic '((2 markdown-markup-face)
5290 (3 markdown-italic-face)
5291 (4 markdown-markup-face)))))
5292 "Default highlighting expressions for GitHub Flavored Markdown mode.")
5294 ;;;###autoload
5295 (define-derived-mode gfm-mode markdown-mode "GFM"
5296 "Major mode for editing GitHub Flavored Markdown files."
5297 (setq markdown-link-space-sub-char "-")
5298 (set (make-local-variable 'font-lock-defaults)
5299 '(gfm-font-lock-keywords))
5300 (auto-fill-mode 0)
5301 ;; Use visual-line-mode if available, fall back to longlines-mode:
5302 (cond ((fboundp 'visual-line-mode)
5303 (visual-line-mode 1))
5304 ((fboundp 'longlines-mode)
5305 (longlines-mode 1)))
5306 ;; do the initial link fontification
5307 (markdown-fontify-buffer-wiki-links))
5310 ;;; Live Preview Mode ============================================
5311 (define-minor-mode markdown-live-preview-mode
5312 "Toggle native previewing on save for a specific markdown file."
5313 :lighter " MD-Preview"
5314 (cond (markdown-live-preview-mode
5315 (switch-to-buffer-other-window (markdown-live-preview-export)))
5316 (t (markdown-live-preview-remove))))
5318 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown)
5319 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill)
5322 (provide 'markdown-mode)
5323 ;; Local Variables:
5324 ;; indent-tabs-mode: nil
5325 ;; End:
5326 ;;; markdown-mode.el ends here