Merge pull request #125 from ihodes/fix-markdown-indent
[markdown-mode.git] / markdown-mode.el
blob8a5a48f89cae15f2efc9f5102682aa9482d331c1
1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2007-2016 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>
28 ;; Copyright (C) 2015-2016 Danny McClanahan <danieldmcclanahan@gmail.com>
29 ;; Copyright (C) 2015-2016 Syohei Yoshida <syohex@gmail.com>
30 ;; Copyright (C) 2016 Vitalie Spinu <spinuvit@gmail.com>
32 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
33 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
34 ;; Created: May 24, 2007
35 ;; Version: 2.1
36 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
37 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
38 ;; URL: http://jblevins.org/projects/markdown-mode/
40 ;; This file is not part of GNU Emacs.
42 ;; This program is free software; you can redistribute it and/or modify
43 ;; it under the terms of the GNU General Public License as published by
44 ;; the Free Software Foundation; either version 2, or (at your option)
45 ;; any later version.
47 ;; This program is distributed in the hope that it will be useful,
48 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
49 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
50 ;; GNU General Public License for more details.
52 ;; You should have received a copy of the GNU General Public License
53 ;; along with this program; if not, write to the Free Software
54 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
55 ;; Boston, MA 02110-1301, USA.
57 ;;; Commentary:
59 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
60 ;; text files in GNU Emacs. markdown-mode is free software, licensed
61 ;; under the GNU GPL.
63 ;; [Markdown]: http://daringfireball.net/projects/markdown/
65 ;; The latest stable version is markdown-mode 2.1, released on January 9, 2016:
67 ;; * [markdown-mode.el][]
68 ;; * [Screenshot][][^theme]
69 ;; * [Release notes][]
71 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
72 ;; [Screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20160108-001.png
73 ;; [Release notes]: http://jblevins.org/projects/markdown-mode/rev-2-1
75 ;; [^theme]: The theme used in the screenshot is
76 ;; [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
78 ;; The latest development version can be obtained from the Git
79 ;; repository at <http://jblevins.org/git/markdown-mode.git> or from
80 ;; [GitHub][]:
82 ;; git clone git://jblevins.org/git/markdown-mode.git
83 ;; git clone https://github.com/jrblevin/markdown-mode.git
85 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
86 ;; [GitHub]: https://github.com/jrblevin/markdown-mode/
88 ;; markdown-mode is also available in several package managers, including:
90 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
91 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
92 ;; * RedHat and Fedora Linux: [emacs-goodies][]
93 ;; * NetBSD: [textproc/markdown-mode][]
94 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
95 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
97 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
98 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
99 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
100 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
101 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
102 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
103 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
104 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
105 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
107 ;;; Installation:
109 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
110 ;; the following lines to your `.emacs` file to associate markdown-mode
111 ;; with `.text`, `.markdown`, and `.md` files:
113 ;; (autoload 'markdown-mode "markdown-mode"
114 ;; "Major mode for editing Markdown files" t)
115 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
116 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
117 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
119 ;; There is no official Markdown file extension, nor is there even a
120 ;; _de facto_ standard, so you can easily add, change, or remove any
121 ;; of the file extensions above as needed.
123 ;; `markdown-mode' depends on `cl-lib', which has been bundled with
124 ;; GNU Emacs since 24.3. Users of GNU Emacs 24.1 and 24.2 can install
125 ;; `cl-lib' with `package.el'.
127 ;;; Usage:
129 ;; Keybindings are grouped by prefixes based on their function. For
130 ;; example, the commands for inserting links are grouped under `C-c
131 ;; C-a`, where the `C-a` is a mnemonic for the HTML `<a>` tag. In
132 ;; other cases, the connection to HTML is not direct. For example,
133 ;; commands dealing with headings begin with `C-c C-t` (mnemonic:
134 ;; titling). The primary commands in each group will are described
135 ;; below. You can obtain a list of all keybindings by pressing `C-c
136 ;; C-h`. Movement and shifting commands tend to be associated with
137 ;; paired delimiters such as `M-{` and `M-}` or `C-c <` and `C-c >`.
138 ;; Outline navigation keybindings the same as in `org-mode'. Finally,
139 ;; commands for running Markdown or doing maintenance on an open file
140 ;; are grouped under the `C-c C-c` prefix. The most commonly used
141 ;; commands are described below. You can obtain a list of all
142 ;; keybindings by pressing `C-c C-h`.
144 ;; * Hyperlinks: `C-c C-a`
146 ;; In this group, `C-c C-a l` inserts an inline link of the form
147 ;; `[text](url)`. The link text is determined as follows. First,
148 ;; if there is an active region (i.e., when transient mark mode is
149 ;; on and the mark is active), use it as the link text. Second,
150 ;; if the point is at a word, use that word as the link text. In
151 ;; these two cases, the original text will be replaced with the
152 ;; link and point will be left at the position for inserting a
153 ;; URL. Otherwise, insert empty link markup and place the point
154 ;; for inserting the link text.
156 ;; `C-c C-a L` inserts a reference link of the form `[text][label]`
157 ;; and, optionally, a corresponding reference label definition.
158 ;; The link text is determined in the same way as with an inline
159 ;; link (using the region, when active, or the word at the point),
160 ;; but instead of inserting empty markup as a last resort, the
161 ;; link text will be read from the minibuffer. The reference
162 ;; label will be read from the minibuffer in both cases, with
163 ;; completion from the set of currently defined references. To
164 ;; create an implicit reference link, press `RET` to accept the
165 ;; default, an empty label. If the entered referenced label is
166 ;; not defined, additionally prompt for the URL and (optional)
167 ;; title. If a URL is provided, a reference definition will be
168 ;; inserted in accordance with `markdown-reference-location'.
169 ;; If a title is given, it will be added to the end of the
170 ;; reference definition and will be used to populate the title
171 ;; attribute when converted to XHTML.
173 ;; `C-c C-a u` inserts a bare url, delimited by angle brackets. When
174 ;; there is an active region, the text in the region is used as the
175 ;; URL. If the point is at a URL, that url is used. Otherwise,
176 ;; insert angle brackets and position the point in between them
177 ;; for inserting the URL.
179 ;; `C-c C-a f` inserts a footnote marker at the point, inserts a
180 ;; footnote definition below, and positions the point for
181 ;; inserting the footnote text. Note that footnotes are an
182 ;; extension to Markdown and are not supported by all processors.
184 ;; `C-c C-a w` behaves much like the inline link insertion command
185 ;; and inserts a wiki link of the form `[[WikiLink]]`. If there
186 ;; is an active region, use the region as the link text. If the
187 ;; point is at a word, use the word as the link text. If there is
188 ;; no active region and the point is not at word, simply insert
189 ;; link markup. Note that wiki links are an extension to Markdown
190 ;; and are not supported by all processors.
192 ;; * Images: `C-c C-i`
194 ;; `C-c C-i i` inserts markup for an inline image, using the
195 ;; active region or the word at point, if any, as the alt text.
196 ;; `C-c C-i I` behaves similarly and inserts a reference-style
197 ;; image.
199 ;; * Styles: `C-c C-s`
201 ;; `C-c C-s e` inserts markup to make a region or word italic (`e`
202 ;; for `<em>` or emphasis). If there is an active region, make
203 ;; the region italic. If the point is at a non-italic word, make
204 ;; the word italic. If the point is at an italic word or phrase,
205 ;; remove the italic markup. Otherwise, simply insert italic
206 ;; delimiters and place the cursor in between them. Similarly,
207 ;; use `C-c C-s s` for bold (`<strong>`), `C-c C-s c` for
208 ;; inline code (`<code>`), and `C-c C-s k` for inserting `<kbd>`
209 ;; tags.
211 ;; `C-c C-s b` inserts a blockquote using the active region, if any,
212 ;; or starts a new blockquote. `C-c C-s C-b` is a variation which
213 ;; always operates on the region, regardless of whether it is
214 ;; active or not. The appropriate amount of indentation, if any,
215 ;; is calculated automatically given the surrounding context, but
216 ;; may be adjusted later using the region indentation commands.
218 ;; `C-c C-s p` behaves similarly for inserting preformatted code
219 ;; blocks, with `C-c C-s C-p` being the region-only counterpart.
221 ;; * Headings: `C-c C-t`
223 ;; All heading insertion commands use the text in the active
224 ;; region, if any, as the heading text. Otherwise, if the current
225 ;; line is not blank, they use the text on the current line.
226 ;; Finally, the setext commands will prompt for heading text if
227 ;; there is no active region and the current line is blank.
229 ;; `C-c C-t h` inserts a heading with automatically chosen type and
230 ;; level (both determined by the previous heading). `C-c C-t H`
231 ;; behaves similarly, but uses setext (underlined) headings when
232 ;; possible, still calculating the level automatically.
233 ;; In cases where the automatically-determined level is not what
234 ;; you intended, the level can be quickly promoted or demoted
235 ;; (as described below). Alternatively, a `C-u` prefix can be
236 ;; given to insert a heading promoted by one level or a `C-u C-u`
237 ;; prefix can be given to insert a heading demoted by one level.
239 ;; To insert a heading of a specific level and type, use `C-c C-t 1`
240 ;; through `C-c C-t 6` for atx (hash mark) headings and `C-c C-t !` or
241 ;; `C-c C-t @` for setext headings of level one or two, respectively.
242 ;; Note that `!` is `S-1` and `@` is `S-2`.
244 ;; If the point is at a heading, these commands will replace the
245 ;; existing markup in order to update the level and/or type of the
246 ;; heading. To remove the markup of the heading at the point,
247 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
248 ;; heading text back into the buffer.
250 ;; * Horizontal Rules: `C-c -`
252 ;; `C-c -` inserts a horizontal rule. By default, insert the
253 ;; first string in the list `markdown-hr-strings' (the most
254 ;; prominent rule). With a `C-u` prefix, insert the last string.
255 ;; With a numeric prefix `N`, insert the string in position `N`
256 ;; (counting from 1).
258 ;; * Markdown and Maintenance Commands: `C-c C-c`
260 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
261 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
262 ;; runs Markdown on the current buffer and previews, stores the
263 ;; output in a temporary file, and displays the file in a browser.
264 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
265 ;; and save the result in the file `basename.html`, where
266 ;; `basename` is the name of the Markdown file with the extension
267 ;; removed. *Export and View:* press `C-c C-c v` to export the
268 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
269 ;; the Markdown source file directly using `markdown-open-command'.
270 ;; *Live Export*: Press `C-c C-c l` to turn on
271 ;; `markdown-live-preview-mode' to view the exported output
272 ;; side-by-side with the source Markdown. **For all export commands,
273 ;; the output file will be overwritten without notice.**
274 ;; `markdown-live-preview-window-function' can be customized to open
275 ;; in a browser other than `eww'.
277 ;; To summarize:
279 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
280 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
281 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
282 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
283 ;; - `C-c C-c w`: `markdown-command' > kill ring.
284 ;; - `C-c C-c o`: `markdown-open-command'.
285 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
287 ;; `C-c C-c c` will check for undefined references. If there are
288 ;; any, a small buffer will open with a list of undefined
289 ;; references and the line numbers on which they appear. In Emacs
290 ;; 22 and greater, selecting a reference from this list and
291 ;; pressing `RET` will insert an empty reference definition at the
292 ;; end of the buffer. Similarly, selecting the line number will
293 ;; jump to the corresponding line.
295 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
296 ;; out of sequence.
298 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
299 ;; rules in the buffer.
301 ;; * Following Links: `C-c C-o`
303 ;; Press `C-c C-o` when the point is on an inline or reference
304 ;; link to open the URL in a browser. When the point is at a
305 ;; wiki link, open it in another buffer (in the current window,
306 ;; or in the other window with the `C-u` prefix). Use `M-p` and
307 ;; `M-n` to quickly jump to the previous or next link of any type.
309 ;; * Jumping: `C-c C-l`
311 ;; Use `C-c C-l` to jump from the object at point to its counterpart
312 ;; elsewhere in the text, when possible. Jumps between reference
313 ;; links and definitions; between footnote markers and footnote
314 ;; text. If more than one link uses the same reference name, a
315 ;; new buffer will be created containing clickable buttons for jumping
316 ;; to each link. You may press `TAB` or `S-TAB` to jump between
317 ;; buttons in this window.
319 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
321 ;; Headings, horizontal rules, and list items can be promoted and
322 ;; demoted, as well as bold and italic text. For headings,
323 ;; "promotion" means *decreasing* the level (i.e., moving from
324 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
325 ;; level. For horizontal rules, promotion and demotion means
326 ;; moving backward or forward through the list of rule strings in
327 ;; `markdown-hr-strings'. For bold and italic text, promotion and
328 ;; demotion means changing the markup from underscores to asterisks.
329 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
330 ;; if possible.
332 ;; To remember these commands, note that `-` is for decreasing the
333 ;; level (promoting), and `=` (on the same key as `+`) is for
334 ;; increasing the level (demoting). Similarly, the left and right
335 ;; arrow keys indicate the direction that the atx heading markup
336 ;; is moving in when promoting or demoting.
338 ;; * Completion: `C-c C-]`
340 ;; Complete markup is in normalized form, which means, for
341 ;; example, that the underline portion of a setext header is the
342 ;; same length as the heading text, or that the number of leading
343 ;; and trailing hash marks of an atx header are equal and that
344 ;; there is no extra whitespace in the header text. `C-c C-]`
345 ;; completes the markup at the point, if it is determined to be
346 ;; incomplete.
348 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
350 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
351 ;; command determines the appropriate marker (one of the possible
352 ;; unordered list markers or the next number in sequence for an
353 ;; ordered list) and indentation level by examining nearby list
354 ;; items. If there is no list before or after the point, start a
355 ;; new list. Prefix this command by `C-u` to decrease the
356 ;; indentation by one level. Prefix this command by `C-u C-u` to
357 ;; increase the indentation by one level.
359 ;; Existing list items can be moved up or down with `M-UP` or
360 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
362 ;; * Editing Subtrees: `M-S-UP`, `M-S-DOWN`, `M-S-LEFT`, and `M-S-RIGHT`
364 ;; Entire subtrees of ATX headings can be promoted and demoted
365 ;; with `M-S-LEFT` and `M-S-RIGHT`, which mirror the bindings
366 ;; for promotion and demotion of list items. Similarly, subtrees
367 ;; can be moved up and down with `M-S-UP` and `M-S-DOWN`.
369 ;; Please note the following "boundary" behavior for promotion and
370 ;; demotion. Any level-six headings will not be demoted further
371 ;; (i.e., they remain at level six, since Markdown and HTML define
372 ;; only six levels) and any level-one headings will promoted away
373 ;; entirely (i.e., heading markup will be removed, since a
374 ;; level-zero heading is not defined).
376 ;; * Shifting the Region: `C-c <` and `C-c >`
378 ;; Text in the region can be indented or exdented as a group using
379 ;; `C-c >` to indent to the next indentation point (calculated in
380 ;; the current context), and `C-c <` to exdent to the previous
381 ;; indentation point. These keybindings are the same as those for
382 ;; similar commands in `python-mode'.
384 ;; * Killing Elements: `C-c C-k`
386 ;; Press `C-c C-k` to kill the thing at point and add important
387 ;; text, without markup, to the kill ring. Possible things to
388 ;; kill include (roughly in order of precedece): inline code,
389 ;; headings, horizonal rules, links (add link text to kill ring),
390 ;; images (add alt text to kill ring), angle URIs, email
391 ;; addresses, bold, italics, reference definitions (add URI to
392 ;; kill ring), footnote markers and text (kill both marker and
393 ;; text, add text to kill ring), and list items.
395 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
397 ;; Navigation between headings is possible using `outline-mode'.
398 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
399 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
400 ;; next and previous visible headings at the same level as the one
401 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
402 ;; (higher precedence) visible heading.
404 ;; * Movement by Paragraph or Block: `M-{` and `M-}`
406 ;; The definition of a "paragraph" is slightly different in
407 ;; markdown-mode than, say, text-mode, because markdown-mode
408 ;; supports filling for list items and respects hard line breaks,
409 ;; both of which break paragraphs. So, markdown-mode overrides
410 ;; the usual paragraph navigation commands `M-{` and `M-}` so that
411 ;; with a `C-u` prefix, these commands jump to the beginning or
412 ;; end of an entire block of text, respectively, where "blocks"
413 ;; are separated by one or more lines.
415 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
417 ;; The usual Emacs commands can be used to move by defuns
418 ;; (top-level major definitions). In markdown-mode, a defun is a
419 ;; section. As usual, `C-M-a` will move the point to the
420 ;; beginning of the current or preceding defun, `C-M-e` will move
421 ;; to the end of the current or following defun, and `C-M-h` will
422 ;; put the region around the entire defun.
424 ;; As noted, many of the commands above behave differently depending
425 ;; on whether Transient Mark mode is enabled or not. When it makes
426 ;; sense, if Transient Mark mode is on and the region is active, the
427 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
428 ;; region bold). For users who prefer to work outside of Transient
429 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
430 ;; `C-SPC C-SPC`. When this is not the case, many commands then
431 ;; proceed to look work with the word or line at the point.
433 ;; When applicable, commands that specifically act on the region even
434 ;; outside of Transient Mark mode have the same keybinding as their
435 ;; standard counterpart, but the letter is uppercase. For example,
436 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
437 ;; the region in Transient Mark mode while `markdown-blockquote-region'
438 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
440 ;; Note that these region-specific functions are useful in many
441 ;; cases where it may not be obvious. For example, yanking text from
442 ;; the kill ring sets the mark at the beginning of the yanked text
443 ;; and moves the point to the end. Therefore, the (inactive) region
444 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
445 ;; yank text and turn it into a blockquote.
447 ;; markdown-mode attempts to be flexible in how it handles
448 ;; indentation. When you press `TAB` repeatedly, the point will cycle
449 ;; through several possible indentation levels corresponding to things
450 ;; you might have in mind when you press `RET` at the end of a line or
451 ;; `TAB`. For example, you may want to start a new list item,
452 ;; continue a list item with hanging indentation, indent for a nested
453 ;; pre block, and so on. Exdention is handled similarly when backspace
454 ;; is pressed at the beginning of the non-whitespace portion of a line.
456 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
457 ;; visibility cycling for atx- or hash-style headings. There are two
458 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
459 ;; the table of contents view (headings only), outline view (top-level
460 ;; headings only), and the full document view. Pressing `TAB` while the
461 ;; point is at a heading will cycle through levels of visibility for the
462 ;; subtree: completely folded, visible children, and fully visible.
463 ;; Note that mixing hash and underline style headings will give undesired
464 ;; results.
466 ;;; Customization:
468 ;; Although no configuration is *necessary* there are a few things
469 ;; that can be customized. The `M-x customize-mode` command
470 ;; provides an interface to all of the possible customizations:
472 ;; * `markdown-command' - the command used to run Markdown (default:
473 ;; `markdown`). This variable may be customized to pass
474 ;; command-line options to your Markdown processor of choice.
476 ;; * `markdown-command-needs-filename' - set to `t' if
477 ;; `markdown-command' does not accept standard input (default:
478 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
479 ;; content to `markdown-command' using standard input (`stdin`).
480 ;; When set to `t', `markdown-mode' will pass the name of the file
481 ;; as the final command-line argument to `markdown-command'. Note
482 ;; that in the latter case, you will only be able to run
483 ;; `markdown-command' from buffers which are visiting a file.
485 ;; * `markdown-open-command' - the command used for calling a standalone
486 ;; Markdown previewer which is capable of opening Markdown source files
487 ;; directly (default: `nil'). This command will be called
488 ;; with a single argument, the filename of the current buffer.
489 ;; A representative program is the Mac app [Marked 2][], a
490 ;; live-updating Markdown previewer which can be [called from a
491 ;; simple shell script](http://jblevins.org/log/marked-2-command).
493 ;; * `markdown-hr-strings' - list of strings to use when inserting
494 ;; horizontal rules. Different strings will not be distinguished
495 ;; when converted to HTML--they will all be converted to
496 ;; `<hr/>`--but they may add visual distinction and style to plain
497 ;; text documents. To maintain some notion of promotion and
498 ;; demotion, keep these sorted from largest to smallest.
500 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
501 ;; underscores when inserting bold text instead of two asterisks
502 ;; (default: `nil').
504 ;; * `markdown-italic-underscore' - set to a non-nil value to use
505 ;; underscores when inserting italic text instead of asterisks
506 ;; (default: `nil').
508 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
509 ;; asymmetric header styling, placing header characters only on
510 ;; the left of headers (default: `nil').
512 ;; * `markdown-list-indent-width' - depth of indentation for lists
513 ;; when inserting, promoting, and demoting list items (default: 4).
515 ;; * `markdown-indent-function' - the function to use for automatic
516 ;; indentation (default: `markdown-indent-line').
518 ;; * `markdown-indent-on-enter' - set to a non-nil value to
519 ;; automatically indent new lines when the enter key is pressed
520 ;; (default: `t')
522 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
523 ;; links (default: `nil'). Set this to a non-nil value to turn on
524 ;; wiki link support by default. Wiki link support can be toggled
525 ;; later using the function `markdown-toggle-wiki-links'."
527 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
528 ;; treat aliased wiki links like `[[link text|PageName]]`
529 ;; (default: `t'). When set to nil, they will be treated as
530 ;; `[[PageName|link text]]'.
532 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
533 ;; for URIs that `markdown-mode' should highlight.
535 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
536 ;; fragments (default: `nil'). Set this to `t' to turn on math
537 ;; support by default. Math support can be enabled, disabled, or
538 ;; toggled later using the function `markdown-toggle-math'."
540 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
541 ;; (default: `nil`).
543 ;; * `markdown-content-type' - when set to a nonempty string, an
544 ;; `http-equiv` attribute will be included in the XHTML `<head>`
545 ;; block (default: `""`). If needed, the suggested values are
546 ;; `application/xhtml+xml` or `text/html`. See also:
547 ;; `markdown-coding-system'.
549 ;; * `markdown-coding-system' - used for specifying the character
550 ;; set identifier in the `http-equiv` attribute when included
551 ;; (default: `nil'). See `markdown-content-type', which must
552 ;; be set before this variable has any effect. When set to `nil',
553 ;; `buffer-file-coding-system' will be used to automatically
554 ;; determine the coding system string (falling back to
555 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
556 ;; and `iso-latin-1'.
558 ;; * `markdown-xhtml-header-content' - additional content to include
559 ;; in the XHTML `<head>` block (default: `""`).
561 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
562 ;; `markdown-mode' uses to determine whether the output of
563 ;; `markdown-command' is a standalone XHTML document or an XHTML
564 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
565 ;; this regular expression not matched in the first five lines of
566 ;; output, `markdown-mode' assumes the output is a fragment and
567 ;; adds a header and footer.
569 ;; * `markdown-link-space-sub-char' - a character to replace spaces
570 ;; when mapping wiki links to filenames (default: `"_"`).
571 ;; For example, use an underscore for compatibility with the
572 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
573 ;; set to `"-"` to conform with GitHub wiki links.
575 ;; * `markdown-reference-location' - where to insert reference
576 ;; definitions (default: `header`). The possible locations are
577 ;; the end of the document (`end`), after the current block
578 ;; (`immediately`), before the next header (`header`).
580 ;; * `markdown-footnote-location' - where to insert footnote text
581 ;; (default: `end`). The set of location options is the same as
582 ;; for `markdown-reference-location'.
584 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
585 ;; heading instead of a flat index (default: `nil'). A nested
586 ;; index may provide more natural browsing from the menu, but a
587 ;; flat list may allow for faster keyboard navigation via tab
588 ;; completion.
590 ;; * `comment-auto-fill-only-comments' - variable is made
591 ;; buffer-local and set to `nil' by default. In programming
592 ;; language modes, when this variable is non-nil, only comments
593 ;; will be filled by auto-fill-mode. However, comments in
594 ;; Markdown documents are rare and the most users probably intend
595 ;; for the actual content of the document to be filled. Making
596 ;; this variable buffer-local allows `markdown-mode' to override
597 ;; the default behavior induced when the global variable is non-nil.
599 ;; * `markdown-gfm-additional-languages', - additional languages to
600 ;; make available, aside from those predefined in
601 ;; `markdown-gfm-recognized-languages', when inserting GFM code
602 ;; blocks (default: `nil`). Language strings must have be trimmed
603 ;; of whitespace and not contain any curly braces. They may be of
604 ;; arbitrary capitalization, though.
606 ;; * `markdown-gfm-use-electric-backquote' - use
607 ;; `markdown-electric-backquote' for interactive insertion of GFM
608 ;; code blocks when backquote is pressed three times (default: `t`).
610 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
611 ;; Flavored Markdown style task lists (checkboxes) should be
612 ;; turned into buttons that can be toggled with mouse-1 or RET. If
613 ;; non-nil (default), then buttons are enabled. This works in
614 ;; `markdown-mode' as well as `gfm-mode'.
616 ;; Additionally, the faces used for syntax highlighting can be modified to
617 ;; your liking by issuing `M-x customize-group RET markdown-faces`
618 ;; or by using the "Markdown Faces" link at the bottom of the mode
619 ;; customization screen.
621 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
623 ;;; Extensions:
625 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
626 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
627 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
628 ;; Wiki links may be followed by pressing `C-c C-o` when the point
629 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
630 ;; previous and next links (including links of other types).
631 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
632 ;; are also supported. Since some wikis reverse these components, set
633 ;; `markdown-wiki-link-alias-first' to nil to treat them as
634 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
635 ;; is also non-nil, Markdown Mode will highlight wiki links with
636 ;; missing target file in a different color. By default, Markdown
637 ;; Mode only searches for target files in the current directory.
638 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
639 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
640 ;; to a non-nil value.
642 ;; [Ikiwiki]: https://ikiwiki.info
644 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
645 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
646 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
647 ;; You can do this either by using `M-x customize-group markdown`
648 ;; or by placing the following in your `.emacs` file:
650 ;; (setq markdown-command "markdown | smartypants")
652 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
654 ;; Syntax highlighting for mathematical expressions written
655 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
656 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
657 ;; either via customize or by placing `(setq markdown-enable-math t)`
658 ;; in `.emacs`, and then restarting Emacs or calling
659 ;; `markdown-reload-extensions'.
661 ;;; GitHub Flavored Markdown (GFM):
663 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
664 ;; available. The GitHub implementation differs slightly from
665 ;; standard Markdown in that it supports things like different
666 ;; behavior for underscores inside of words, automatic linking of
667 ;; URLs, strikethrough text, and fenced code blocks with an optional
668 ;; language keyword.
670 ;; The GFM-specific features above apply to `README.md` files, wiki
671 ;; pages, and other Markdown-formatted files in repositories on
672 ;; GitHub. GitHub also enables [additional features][GFM comments] for
673 ;; writing on the site (for issues, pull requests, messages, etc.)
674 ;; that are further extensions of GFM. These features include task
675 ;; lists (checkboxes), newlines corresponding to hard line breaks,
676 ;; auto-linked references to issues and commits, wiki links, and so
677 ;; on. To make matters more confusing, although task lists are not
678 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
679 ;; read-only fashion) in all Markdown documents in repositories on the
680 ;; site. These additional extensions are supported to varying degrees
681 ;; by `markdown-mode' and `gfm-mode' as described below.
683 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
684 ;; highlighting of URLs without angle brackets.
686 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
687 ;; toggle support for underscores inside of words. In this mode
688 ;; variable names such as `a_test_variable` will not trigger
689 ;; emphasis (italics).
691 ;; * **Fenced code blocks:** Code blocks quoted with backticks, with
692 ;; optional programming language keywords, are highlighted in
693 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
694 ;; `C-c C-s P`. If there is an active region, the text in the
695 ;; region will be placed inside the code block. You will be
696 ;; prompted for the name of the language, but may press enter to
697 ;; continue without naming a language.
699 ;; * **Strikethrough:** Strikethrough text is only supported in
700 ;; `gfm-mode' and can be inserted (and toggled) using `C-c C-s d`.
701 ;; Following the mnemonics for the other style keybindings, the
702 ;; letter `d` coincides with the HTML tag `<del>`.
704 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
705 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
706 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
707 ;; (and it is set to t by default). These checkboxes can be
708 ;; toggled by clicking `mouse-1` or pressing `RET` over the button.
710 ;; * **Wiki links:** Generic wiki links are supported in
711 ;; `markdown-mode', but in `gfm-mode' specifically they will be
712 ;; treated as they are on GitHub: spaces will be replaced by hyphens
713 ;; in filenames and the first letter of the filename will be
714 ;; capitalized. For example, `[[wiki link]]' will map to a file
715 ;; named `Wiki-link` with the same extension as the current file.
717 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
718 ;; specifically with respect to newline behavior. If you use
719 ;; `gfm-mode' mostly to write text for comments or issues on the
720 ;; GitHub site--where newlines are significant and correspond to
721 ;; hard line breaks--then you may want to enable `visual-line-mode'
722 ;; for line wrapping in buffers. You can do this with a
723 ;; `gfm-mode-hook' as follows:
725 ;; ;; Use visual-line-mode in gfm-mode
726 ;; (defun my-gfm-mode-hook ()
727 ;; (visual-line-mode 1))
728 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
730 ;; * **Preview:** GFM-specific preview can be powered by setting
731 ;; `markdown-command' to use [Docter][]. This may also be
732 ;; configured to work with [Marked 2][] for `markdown-open-command'.
734 ;; [GFM]: http://github.github.com/github-flavored-markdown/
735 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
736 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
737 ;; [Docter]: https://github.com/alampros/Docter
739 ;;; Acknowledgments:
741 ;; markdown-mode has benefited greatly from the efforts of the
742 ;; following people:
744 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
745 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
746 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
747 ;; GitHub Flavored Markdown mode (`gfm-mode').
748 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
749 ;; `markdown' with an active region.
750 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
751 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
752 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
753 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
754 ;; visibility cycling functionality was derived, and for a bug fix
755 ;; related to `orgtbl-mode'.
756 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
757 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
758 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
759 ;; compatibility and custom CSS.
760 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
761 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
762 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
763 ;; comment matching functions were derived.
764 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
765 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
766 ;; functions, bug reports regarding indentation, and
767 ;; fixes for byte-compilation warnings.
768 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
769 ;; enhancements.
770 ;; * George Ogata <george.ogata@gmail.com> for fixing several
771 ;; byte-compilation warnings.
772 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
773 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
774 ;; customizations and XHTML export.
775 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
776 ;; Markdown processors which do not accept input from stdin.
777 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
778 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
779 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
780 ;; substitution character for mapping wiki links to filenames.
781 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
782 ;; escape shell commands.
783 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
784 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
785 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
786 ;; Emacs Lisp coding conventions.
787 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
788 ;; regexp, refactoring the compilation and preview functions,
789 ;; heading font-lock generalizations, list renumbering,
790 ;; and kill ring save.
791 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
792 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
793 ;; for an autoload token for `gfm-mode'.
794 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
795 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
796 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
797 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
798 ;; declaration in XHTML output.
799 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
800 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
801 ;; and GFM code block insertion.
802 ;; * Peter Jones <pjones@pmade.com> for link following functions.
803 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
804 ;; externally modified files.
805 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
806 ;; related to `orgtbl-mode'.
807 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
808 ;; export hooks, unit test improvements, and updates to support
809 ;; wide characters.
810 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
811 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
812 ;; completion.
813 ;; * Gunnar Franke <Gunnar.Franke@gmx.de> for a completion bug report.
814 ;; * David Glasser <glasser@meteor.com> for a `paragraph-separate' fix.
815 ;; * Daniel Brotsky <dev@brotsky.com> for better auto-fill defaults.
816 ;; * Samuel Freilich <sfreilich@google.com> for improved filling
817 ;; behavior regarding list items, footnotes, and reference
818 ;; definitions, improved killing of footnotes, and numerous other
819 ;; tests and bug fixes.
820 ;; * Antonis Kanouras <antonis@metadosis.gr> for strikethrough support.
821 ;; * Tim Visher <tim.visher@gmail.com> for multiple CSS files and other
822 ;; general improvements.
823 ;; * Matt McClure <matthewlmcclure@gmail.com> for a patch to prevent
824 ;; overwriting source files with .html extensions upon export.
825 ;; * Roger Bolsius <roger.bolsius@gmail.com> for ordered list improvements.
826 ;; * Google's Open Source Programs Office for recognizing the project with
827 ;; a monetary contribution in June 2015.
828 ;; * Howard Melman <hmelman@gmail.com> for supporting GFM checkboxes
829 ;; as buttons.
830 ;; * Danny McClanahan <danieldmcclanahan@gmail.com> for live preview
831 ;; mode, completion of GFM programming language names, improved
832 ;; font lock for fenced code blocks and metadata blocks, `cl-lib'
833 ;; updates, and numerous other improvements.
834 ;; * Syohei Yoshida <syohex@gmail.com> for better heading detection
835 ;; and movement functions, improved italic font lock, fixing adaptive
836 ;; filling for hanging list items, more efficient fontification,
837 ;; and numerous other improvements.
838 ;; * Vitalie Spinu <spinuvit@gmail.com> for improvements to font
839 ;; lock and source code aesthetics.
840 ;; * Kévin Le Gouguec <kevin.legouguec@gmail.com> for improvements
841 ;; related to ATX headings and Pandoc fancy lists.
843 ;;; Bugs:
845 ;; markdown-mode is developed and tested primarily for compatibility
846 ;; with GNU Emacs 24.3 and later. If you find any bugs in
847 ;; markdown-mode, please construct a test case or a patch and open a
848 ;; ticket on the [GitHub issue tracker][issues].
850 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
852 ;;; History:
854 ;; markdown-mode was written and is maintained by Jason Blevins. The
855 ;; first version was released on May 24, 2007.
857 ;; * 2007-05-24: Version 1.1
858 ;; * 2007-05-25: Version 1.2
859 ;; * 2007-06-05: [Version 1.3][]
860 ;; * 2007-06-29: Version 1.4
861 ;; * 2007-10-11: [Version 1.5][]
862 ;; * 2008-06-04: [Version 1.6][]
863 ;; * 2009-10-01: [Version 1.7][]
864 ;; * 2011-08-12: [Version 1.8][]
865 ;; * 2011-08-15: [Version 1.8.1][]
866 ;; * 2013-01-25: [Version 1.9][]
867 ;; * 2013-03-24: [Version 2.0][]
868 ;; * 2016-01-09: [Version 2.1][]
870 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
871 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
872 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
873 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
874 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
875 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
876 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
877 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
878 ;; [Version 2.1]: http://jblevins.org/projects/markdown-mode/rev-2-1
881 ;;; Code:
883 (require 'easymenu)
884 (require 'outline)
885 (require 'thingatpt)
886 (require 'cl-lib)
888 (defvar jit-lock-start)
889 (defvar jit-lock-end)
891 (declare-function eww-open-file "eww")
894 ;;; Constants =================================================================
896 (defconst markdown-mode-version "2.1"
897 "Markdown mode version number.")
899 (defconst markdown-output-buffer-name "*markdown-output*"
900 "Name of temporary buffer for markdown command output.")
903 ;;; Global Variables ==========================================================
905 (defvar markdown-reference-label-history nil
906 "History of used reference labels.")
908 (defvar markdown-live-preview-mode nil
909 "Sentinel variable for command `markdown-live-preview-mode'.")
911 (defvar markdown-gfm-language-history nil
912 "History list of languages used in the current buffer in GFM code blocks.")
915 ;;; Customizable Variables ====================================================
917 (defvar markdown-mode-hook nil
918 "Hook run when entering Markdown mode.")
920 (defvar markdown-before-export-hook nil
921 "Hook run before running Markdown to export XHTML output.
922 The hook may modify the buffer, which will be restored to it's
923 original state after exporting is complete.")
925 (defvar markdown-after-export-hook nil
926 "Hook run after XHTML output has been saved.
927 Any changes to the output buffer made by this hook will be saved.")
929 (defgroup markdown nil
930 "Major mode for editing text files in Markdown format."
931 :prefix "markdown-"
932 :group 'wp
933 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
935 (defcustom markdown-command "markdown"
936 "Command to run markdown."
937 :group 'markdown
938 :type 'string)
940 (defcustom markdown-command-needs-filename nil
941 "Set to non-nil if `markdown-command' does not accept input from stdin.
942 Instead, it will be passed a filename as the final command line
943 option. As a result, you will only be able to run Markdown from
944 buffers which are visiting a file."
945 :group 'markdown
946 :type 'boolean)
948 (defcustom markdown-open-command nil
949 "Command used for opening Markdown files directly.
950 For example, a standalone Markdown previewer. This command will
951 be called with a single argument: the filename of the current
952 buffer."
953 :group 'markdown
954 :type 'string)
956 (defcustom markdown-hr-strings
957 '("-------------------------------------------------------------------------------"
958 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
959 "---------------------------------------"
960 "* * * * * * * * * * * * * * * * * * * *"
961 "---------"
962 "* * * * *")
963 "Strings to use when inserting horizontal rules.
964 The first string in the list will be the default when inserting a
965 horizontal rule. Strings should be listed in decreasing order of
966 prominence (as in headings from level one to six) for use with
967 promotion and demotion functions."
968 :group 'markdown
969 :type 'list)
971 (defcustom markdown-bold-underscore nil
972 "Use two underscores when inserting bold text instead of two asterisks."
973 :group 'markdown
974 :type 'boolean)
976 (defcustom markdown-italic-underscore nil
977 "Use underscores when inserting italic text instead of asterisks."
978 :group 'markdown
979 :type 'boolean)
981 (defcustom markdown-asymmetric-header nil
982 "Determines if header style will be asymmetric.
983 Set to non-nil to only have header characters to the left of the title.
984 The default will ensure header characters are placed to the left and right
985 of the title."
986 :group 'markdown
987 :type 'boolean)
989 (defcustom markdown-indent-function 'markdown-indent-line
990 "Function to use to indent."
991 :group 'markdown
992 :type 'function)
994 (defcustom markdown-indent-on-enter t
995 "Automatically indent new lines when enter key is pressed.
996 When this variable is set to t, pressing RET will call
997 `newline-and-indent'. When set to nil, define RET to call
998 `newline' as usual. In the latter case, you can still use
999 auto-indentation by pressing \\[newline-and-indent]."
1000 :group 'markdown
1001 :type 'boolean)
1003 (defcustom markdown-enable-wiki-links nil
1004 "Syntax highlighting for wiki links.
1005 Set this to a non-nil value to turn on wiki link support by default.
1006 Support can be toggled later using the `markdown-toggle-wiki-links'
1007 function or \\[markdown-toggle-wiki-links]."
1008 :group 'markdown
1009 :type 'boolean
1010 :safe 'booleanp)
1012 (defcustom markdown-wiki-link-alias-first t
1013 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1014 Otherwise, they will be treated as [[PageName|alias text]]."
1015 :group 'markdown
1016 :type 'boolean
1017 :safe 'booleanp)
1019 (defcustom markdown-wiki-link-search-parent-directories nil
1020 "When non-nil, search for wiki link targets in parent directories.
1021 This is the default search behavior of Ikiwiki."
1022 :group 'markdown
1023 :type 'boolean
1024 :safe 'booleanp)
1026 (defcustom markdown-wiki-link-fontify-missing nil
1027 "When non-nil, change wiki link face according to existence of target files.
1028 This is expensive because it requires checking for the file each time the buffer
1029 changes or the user switches windows. It is disabled by default because it may
1030 cause lag when typing on slower machines."
1031 :group 'markdown
1032 :type 'boolean
1033 :safe 'booleanp)
1035 (defcustom markdown-uri-types
1036 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
1037 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
1038 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
1039 "Link types for syntax highlighting of URIs."
1040 :group 'markdown
1041 :type 'list)
1043 (defcustom markdown-enable-math nil
1044 "Syntax highlighting for inline LaTeX and itex expressions.
1045 Set this to a non-nil value to turn on math support by default.
1046 Math support can be enabled, disabled, or toggled later using
1047 `markdown-toggle-math' or \\[markdown-toggle-math]."
1048 :group 'markdown
1049 :type 'boolean
1050 :safe 'booleanp)
1052 (defcustom markdown-css-paths nil
1053 "URL of CSS file to link to in the output XHTML."
1054 :group 'markdown
1055 :type 'list)
1057 (defcustom markdown-content-type ""
1058 "Content type string for the http-equiv header in XHTML output.
1059 When set to a non-empty string, insert the http-equiv attribute.
1060 Otherwise, this attribute is omitted."
1061 :group 'markdown
1062 :type 'string)
1064 (defcustom markdown-coding-system nil
1065 "Character set string for the http-equiv header in XHTML output.
1066 Defaults to `buffer-file-coding-system' (and falling back to
1067 `iso-8859-1' when not available). Common settings are `utf-8'
1068 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1069 :group 'markdown
1070 :type 'coding-system)
1072 (defcustom markdown-xhtml-header-content ""
1073 "Additional content to include in the XHTML <head> block."
1074 :group 'markdown
1075 :type 'string)
1077 (defcustom markdown-xhtml-standalone-regexp
1078 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1079 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1080 :group 'markdown
1081 :type 'regexp)
1083 (defcustom markdown-link-space-sub-char "_"
1084 "Character to use instead of spaces when mapping wiki links to filenames."
1085 :group 'markdown
1086 :type 'string)
1088 (defcustom markdown-reference-location 'header
1089 "Position where new reference definitions are inserted in the document."
1090 :group 'markdown
1091 :type '(choice (const :tag "At the end of the document" end)
1092 (const :tag "Immediately after the current block" immediately)
1093 (const :tag "Before next header" header)))
1095 (defcustom markdown-footnote-location 'end
1096 "Position where new footnotes are inserted in the document."
1097 :group 'markdown
1098 :type '(choice (const :tag "At the end of the document" end)
1099 (const :tag "Immediately after the current block" immediately)
1100 (const :tag "Before next header" header)))
1102 (defcustom markdown-unordered-list-item-prefix " * "
1103 "String inserted before unordered list items."
1104 :group 'markdown
1105 :type 'string)
1107 (defcustom markdown-nested-imenu-heading-index nil
1108 "Use nested or flat imenu heading index.
1109 A nested index may provide more natural browsing from the menu,
1110 but a flat list may allow for faster keyboard navigation via tab
1111 completion."
1112 :group 'markdown
1113 :type 'boolean)
1115 (defcustom markdown-make-gfm-checkboxes-buttons t
1116 "When non-nil, make GFM checkboxes into buttons."
1117 :group 'markdown
1118 :type 'boolean)
1120 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1121 "When non-nil, allow yaml metadata anywhere in the document."
1122 :group 'markdown
1123 :type 'boolean)
1125 (defcustom markdown-live-preview-window-function
1126 'markdown-live-preview-window-eww
1127 "Function to display preview of Markdown output within Emacs.
1128 Function must update the buffer containing the preview and return
1129 the buffer."
1130 :group 'markdown
1131 :type 'function)
1133 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1134 "Delete exported html file when using `markdown-live-preview-export'.
1135 If set to 'delete-on-export, delete on every export. When set to
1136 'delete-on-destroy delete when quitting from command
1137 `markdown-live-preview-mode'. Never delete if set to nil."
1138 :group 'markdown
1139 :type 'symbol)
1141 (defcustom markdown-list-indent-width 4
1142 "Depth of indentation for markdown lists.
1143 Used in `markdown-demote-list-item' and
1144 `markdown-promote-list-item'."
1145 :group 'markdown
1146 :type 'integer)
1148 (defcustom markdown-gfm-additional-languages nil
1149 "Extra languages made available when inserting GFM code blocks.
1150 Language strings must have be trimmed of whitespace and not
1151 contain any curly braces. They may be of arbitrary
1152 capitalization, though."
1153 :group 'markdown
1154 :type '(repeat (string :validate markdown-validate-language-string)))
1156 (defcustom markdown-gfm-use-electric-backquote t
1157 "Use `markdown-electric-backquote' when backquote is hit three times."
1158 :group 'markdown
1159 :type 'boolean)
1161 (defcustom markdown-gfm-downcase-languages t
1162 "If non-nil, downcase suggested languages.
1163 This applies to insertions done with
1164 `markdown-electric-backquote'."
1165 :group 'markdown
1166 :type 'boolean)
1169 ;;; Regular Expressions =======================================================
1171 (defconst markdown-regex-comment-start
1172 "<!--"
1173 "Regular expression matches HTML comment opening.")
1175 (defconst markdown-regex-comment-end
1176 "--[ \t]*>"
1177 "Regular expression matches HTML comment closing.")
1179 (defconst markdown-regex-link-inline
1180 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1181 "Regular expression for a [text](file) or an image link ![text](file).
1182 Group 1 matches the leading exclamation point (optional).
1183 Group 2 matches the opening square bracket.
1184 Group 3 matches the text inside the square brackets.
1185 Group 4 matches the closing square bracket.
1186 Group 5 matches the opening parenthesis.
1187 Group 6 matches the URL.
1188 Group 7 matches the title (optional).
1189 Group 8 matches the closing parenthesis.")
1191 (defconst markdown-regex-link-reference
1192 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1193 "Regular expression for a reference link [text][id].
1194 Group 1 matches the leading exclamation point (optional).
1195 Group 2 matches the opening square bracket for the link text.
1196 Group 3 matches the text inside the square brackets.
1197 Group 4 matches the closing square bracket for the link text.
1198 Group 5 matches the opening square bracket for the reference label.
1199 Group 6 matches the reference label.
1200 Group 7 matches the closing square bracket for the reference label.")
1202 (defconst markdown-regex-reference-definition
1203 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1204 "Regular expression for a reference definition.
1205 Group 1 matches the opening square bracket.
1206 Group 2 matches the reference label.
1207 Group 3 matches the closing square bracket.
1208 Group 4 matches the colon.
1209 Group 5 matches the URL.
1210 Group 6 matches the title attribute (optional).")
1212 (defconst markdown-regex-footnote
1213 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1214 "Regular expression for a footnote marker [^fn].
1215 Group 1 matches the opening square bracket and carat.
1216 Group 2 matches only the label, without the surrounding markup.
1217 Group 3 matches the closing square bracket.")
1219 (defconst markdown-regex-header
1220 "^\\(?:\\(.+?\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)\\)$"
1221 "Regexp identifying Markdown headings.
1222 Group 1 matches the text of a setext heading.
1223 Group 2 matches the underline of a level-1 setext heading.
1224 Group 3 matches the underline of a level-2 setext heading.
1225 Group 4 matches the opening hash marks of an atx heading.
1226 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1227 Group 6 matches the closing hash marks of an atx heading.")
1229 (defconst markdown-regex-header-1-atx
1230 "^\\(#\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1231 "Regular expression for level 1 atx-style (hash mark) headers.")
1233 (defconst markdown-regex-header-2-atx
1234 "^\\(##\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1235 "Regular expression for level 2 atx-style (hash mark) headers.")
1237 (defconst markdown-regex-header-3-atx
1238 "^\\(###\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1239 "Regular expression for level 3 atx-style (hash mark) headers.")
1241 (defconst markdown-regex-header-4-atx
1242 "^\\(####\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1243 "Regular expression for level 4 atx-style (hash mark) headers.")
1245 (defconst markdown-regex-header-5-atx
1246 "^\\(#####\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1247 "Regular expression for level 5 atx-style (hash mark) headers.")
1249 (defconst markdown-regex-header-6-atx
1250 "^\\(######\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1251 "Regular expression for level 6 atx-style (hash mark) headers.")
1253 (defconst markdown-regex-header-1-setext
1254 "^\\(.*\\)\n\\(=+\\)$"
1255 "Regular expression for level 1 setext-style (underline) headers.")
1257 (defconst markdown-regex-header-2-setext
1258 "^\\(.*\\)\n\\(-+\\)$"
1259 "Regular expression for level 2 setext-style (underline) headers.")
1261 (defconst markdown-regex-header-setext
1262 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1263 "Regular expression for generic setext-style (underline) headers.")
1265 (defconst markdown-regex-header-atx
1266 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1267 "Regular expression for generic atx-style (hash mark) headers.")
1269 (defconst markdown-regex-hr
1270 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1271 "Regular expression for matching Markdown horizontal rules.")
1273 (defconst markdown-regex-code
1274 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1275 "Regular expression for matching inline code fragments.
1277 Group 1 matches the entire code fragment including the backticks.
1278 Group 2 matches the opening backticks.
1279 Group 3 matches the code fragment itself, without backticks.
1280 Group 4 matches the closing backticks.
1282 The leading, unnumbered group ensures that the leading backquote
1283 character is not escaped.
1284 The last group, also unnumbered, requires that the character
1285 following the code fragment is not a backquote.
1286 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1287 but not two newlines in a row.")
1289 (defconst markdown-regex-kbd
1290 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1291 "Regular expression for matching <kbd> tags.
1292 Groups 1 and 3 match the opening and closing tags.
1293 Group 2 matches the key sequence.")
1295 (defconst markdown-regex-gfm-code-block-open
1296 "^[[:blank:]]*\\(```\\)[ ]?\\([^[:space:]]+\\|{[^}]*}\\)?\\([[:space:]]*?\\)$"
1297 "Regular expression matching opening of GFM code blocks.
1298 Group 1 matches the opening three backticks.
1299 Group 2 matches the language identifier (optional).")
1301 (defconst markdown-regex-gfm-code-block-close
1302 "^[[:blank:]]*\\(```\\)\\s *?$"
1303 "Regular expression matching closing of GFM code blocks.
1304 Group 1 matches the closing three backticks.")
1306 (defconst markdown-regex-pre
1307 "^\\( \\|\t\\).*$"
1308 "Regular expression for matching preformatted text sections.")
1310 (defconst markdown-regex-list
1311 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1312 "Regular expression for matching list items.")
1314 (defconst markdown-regex-bold
1315 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1316 "Regular expression for matching bold text.
1317 Group 1 matches the character before the opening asterisk or
1318 underscore, if any, ensuring that it is not a backslash escape.
1319 Group 2 matches the entire expression, including delimiters.
1320 Groups 3 and 5 matches the opening and closing delimiters.
1321 Group 4 matches the text inside the delimiters.")
1323 (defconst markdown-regex-italic
1324 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1325 "Regular expression for matching italic text.
1326 The leading unnumbered matches the character before the opening
1327 asterisk or underscore, if any, ensuring that it is not a
1328 backslash escape.
1329 Group 1 matches the entire expression, including delimiters.
1330 Groups 2 and 4 matches the opening and closing delimiters.
1331 Group 3 matches the text inside the delimiters.")
1333 (defconst markdown-regex-strike-through
1334 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1335 "Regular expression for matching strike-through text.
1336 Group 1 matches the character before the opening tilde, if any,
1337 ensuring that it is not a backslash escape.
1338 Group 2 matches the entire expression, including delimiters.
1339 Groups 3 and 5 matches the opening and closing delimiters.
1340 Group 4 matches the text inside the delimiters.")
1342 (defconst markdown-regex-gfm-italic
1343 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1344 "Regular expression for matching italic text in GitHub Flavored Markdown.
1345 Underscores in words are not treated as special.
1346 Group 1 matches the entire expression, including delimiters.
1347 Groups 2 and 4 matches the opening and closing delimiters.
1348 Group 3 matches the text inside the delimiters.")
1350 (defconst markdown-regex-blockquote
1351 "^[ \t]*\\(>\\)\\(.*\\)$"
1352 "Regular expression for matching blockquote lines.
1353 Group 1 matches the leading angle bracket.
1354 Group 2 matches the text.")
1356 (defconst markdown-regex-line-break
1357 "[^ \n\t][ \t]*\\( \\)$"
1358 "Regular expression for matching line breaks.")
1360 (defconst markdown-regex-wiki-link
1361 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1362 "Regular expression for matching wiki links.
1363 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1364 wiki links of the form [[PageName|link text]].
1365 The meanings of the first and second components depend
1366 on the value of `markdown-wiki-link-alias-first'.
1368 Group 1 matches the entire link.
1369 Group 2 matches the opening square brackets.
1370 Group 3 matches the first component of the wiki link.
1371 Group 4 matches the pipe separator, when present.
1372 Group 5 matches the second component of the wiki link, when present.
1373 Group 6 matches the closing square brackets.")
1375 (defconst markdown-regex-uri
1376 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1377 "Regular expression for matching inline URIs.")
1379 (defconst markdown-regex-angle-uri
1380 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1381 "Regular expression for matching inline URIs in angle brackets.")
1383 (defconst markdown-regex-email
1384 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1385 "Regular expression for matching inline email addresses.")
1387 (defsubst markdown-make-regex-link-generic ()
1388 "Make regular expression for matching any recognized link."
1389 (concat "\\(?:" markdown-regex-link-inline
1390 (when markdown-enable-wiki-links
1391 (concat "\\|" markdown-regex-wiki-link))
1392 "\\|" markdown-regex-link-reference
1393 "\\|" markdown-regex-angle-uri "\\)"))
1395 (defconst markdown-regex-gfm-checkbox
1396 " \\(\\[[ xX]\\]\\) "
1397 "Regular expression for matching GFM checkboxes.
1398 Group 1 matches the text to become a button.")
1400 (defconst markdown-regex-block-separator
1401 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1402 "Regular expression for matching block boundaries.")
1404 (defconst markdown-regex-math-inline-single
1405 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1406 "Regular expression for itex $..$ math mode expressions.
1407 Groups 1 and 3 match the opening and closing dollar signs.
1408 Group 3 matches the mathematical expression contained within.")
1410 (defconst markdown-regex-math-inline-double
1411 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1412 "Regular expression for itex $$..$$ math mode expressions.
1413 Groups 1 and 3 match opening and closing dollar signs.
1414 Group 3 matches the mathematical expression contained within.")
1416 (defconst markdown-regex-math-display
1417 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*\\)?\\(\\\\\\]\\)$"
1418 "Regular expression for itex \[..\] display mode expressions.
1419 Groups 1 and 3 match the opening and closing delimiters.
1420 Group 2 matches the mathematical expression contained within.")
1422 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1423 "Return regexp matching a Pandoc code fence at least NUM-TILDES long.
1424 END-OF-LINE is the regexp construct to indicate end of line; $ if
1425 missing."
1426 (format "%s%d%s%s" "^\\([~]\\{" num-tildes ",\\}\\)" (or end-of-line "$")))
1428 (defconst markdown-regex-tilde-fence-begin
1429 (markdown-make-tilde-fence-regex
1430 3 "[ ]?\\([^[:space:]]+\\|{[^}]*}\\)?\\([[:space:]]*?\\)$")
1431 "Regular expression for matching Pandoc tildes.")
1433 (defconst markdown-regex-multimarkdown-metadata
1434 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\(:[ \t]*\\)\\(.*\\)$"
1435 "Regular expression for matching MultiMarkdown metadata.")
1437 (defconst markdown-regex-pandoc-metadata
1438 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1439 "Regular expression for matching Pandoc metadata.")
1441 (defconst markdown-regex-yaml-metadata-border
1442 "\\(\\-\\{3\\}\\)$"
1443 "Regular expression for matching yaml metadata.")
1445 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1446 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1447 "Regular expression for matching yaml metadata end borders.")
1449 (defsubst markdown-get-yaml-metadata-start-border ()
1450 "Return yaml metadata start border depending upon whether Pandoc is used."
1451 (concat
1452 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1453 markdown-regex-yaml-metadata-border))
1455 (defsubst markdown-get-yaml-metadata-end-border (_)
1456 "Return yaml metadata end border depending upon whether Pandoc is used."
1457 (if markdown-use-pandoc-style-yaml-metadata
1458 markdown-regex-yaml-pandoc-metadata-end-border
1459 markdown-regex-yaml-metadata-border))
1462 ;;; Syntax ====================================================================
1464 (defun markdown-syntax-propertize-extend-region (start end)
1465 "Extend START to END region to include an entire block of text.
1466 This helps improve syntax analysis for block constructs.
1467 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1468 Function is called repeatedly until it returns nil. For details, see
1469 `syntax-propertize-extend-region-functions'."
1470 (save-match-data
1471 (save-excursion
1472 (let* ((new-start (progn (goto-char start)
1473 (if (re-search-backward "\n\n" nil t)
1474 (match-end 0) (point-min))))
1475 (new-end (progn (goto-char end)
1476 (if (re-search-forward "\n\n" nil t)
1477 (match-beginning 0) (point-max))))
1478 (code-match (markdown-code-block-at-pos new-start))
1479 (new-start (or (and code-match (cl-first code-match)) new-start))
1480 (code-match (markdown-code-block-at-pos end))
1481 (new-end (or (and code-match (cl-second code-match)) new-end)))
1482 (unless (and (eq new-start start) (eq new-end end))
1483 (cons new-start new-end))))))
1485 (defun markdown-font-lock-extend-region-function (start end _)
1486 "Used in `jit-lock-after-change-extend-region-functions'.
1487 Delegates to `markdown-syntax-propertize-extend-region'. START
1488 and END are the previous region to refontify."
1489 (let ((res (markdown-syntax-propertize-extend-region start end)))
1490 (when res
1491 (setq jit-lock-start (car res)
1492 jit-lock-end (cdr res)))))
1494 (defun markdown-syntax-propertize-pre-blocks (start end)
1495 "Match preformatted text blocks from START to END."
1496 (save-excursion
1497 (goto-char start)
1498 (let ((levels (markdown-calculate-list-levels))
1499 indent pre-regexp close-regexp open close)
1500 (while (and (< (point) end) (not close))
1501 ;; Search for a region with sufficient indentation
1502 (if (null levels)
1503 (setq indent 1)
1504 (setq indent (1+ (length levels))))
1505 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1506 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1508 (cond
1509 ;; If not at the beginning of a line, move forward
1510 ((not (bolp)) (forward-line))
1511 ;; Move past blank lines
1512 ((markdown-cur-line-blank-p) (forward-line))
1513 ;; At headers and horizontal rules, reset levels
1514 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1515 ;; If the current line has sufficient indentation, mark out pre block
1516 ;; The opening should be preceded by a blank line.
1517 ((and (looking-at pre-regexp)
1518 (save-match-data (markdown-prev-line-blank-p)))
1519 (setq open (match-beginning 0))
1520 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1521 (not (eobp)))
1522 (forward-line))
1523 (skip-syntax-backward "-")
1524 (setq close (point)))
1525 ;; If current line has a list marker, update levels, move to end of block
1526 ((looking-at markdown-regex-list)
1527 (setq levels (markdown-update-list-levels
1528 (match-string 2) (current-indentation) levels))
1529 (markdown-end-of-block-element))
1530 ;; If this is the end of the indentation level, adjust levels accordingly.
1531 ;; Only match end of indentation level if levels is not the empty list.
1532 ((and (car levels) (looking-at-p close-regexp))
1533 (setq levels (markdown-update-list-levels
1534 nil (current-indentation) levels))
1535 (markdown-end-of-block-element))
1536 (t (markdown-end-of-block-element))))
1538 (when (and open close)
1539 ;; Set text property data
1540 (put-text-property open close 'markdown-pre (list open close))
1541 ;; Recursively search again
1542 (markdown-syntax-propertize-pre-blocks (point) end)))))
1544 (defconst markdown-fenced-block-pairs
1545 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1546 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1547 markdown-fenced-code)
1548 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1549 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1550 markdown-yaml-metadata-section)
1551 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1552 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1553 markdown-gfm-code))
1554 "Mapping of regular expressions to \"fenced-block\" constructs.
1555 These constructs are distinguished by having a distinctive start
1556 and end pattern, both of which take up an entire line of text,
1557 but no special pattern to identify text within the fenced
1558 blocks (unlike blockquotes and indented-code sections).
1560 Each element within this list takes the form:
1562 ((START-REGEX-OR-FUN START-PROPERTY)
1563 (END-REGEX-OR-FUN END-PROPERTY)
1564 MIDDLE-PROPERTY)
1566 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1567 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1568 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1569 which is the length of the first group of the START-REGEX-OR-FUN match, which
1570 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1571 evaluate these into \"real\" regexps.
1573 The *-PROPERTY elements are the text properties applied to each part of the
1574 block construct when it is matched using
1575 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1576 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1577 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1578 `match-data' when the regexp was matched to the text. In the case of
1579 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1580 begin and end set to the edges of the \"middle\" text. This makes fontification
1581 easier.")
1583 (defun markdown-text-property-at-point (prop)
1584 (get-text-property (point) prop))
1586 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1587 (cond ((functionp object)
1588 (if arg (funcall object arg) (funcall object)))
1589 ((stringp object) object)
1590 (t (error "Object cannot be turned into regex"))))
1592 (defsubst markdown-get-start-fence-regexp ()
1593 "Return regexp to find all \"start\" sections of fenced block constructs.
1594 Which construct is actually contained in the match must be found separately."
1595 (mapconcat
1596 'identity
1597 (cl-mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1598 markdown-fenced-block-pairs)
1599 "\\|"))
1601 (defun markdown-get-fenced-block-begin-properties ()
1602 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1604 (defun markdown-get-fenced-block-end-properties ()
1605 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1607 (defun markdown-get-fenced-block-middle-properties ()
1608 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1610 (defun markdown-find-previous-prop (prop &optional lim)
1611 "Find previous place where property PROP is non-nil, up to LIM.
1612 Return a cons of (pos . property). pos is point if point contains
1613 non-nil PROP."
1614 (let ((res
1615 (if (get-text-property (point) prop) (point)
1616 (previous-single-property-change
1617 (point) prop nil (or lim (point-min))))))
1618 (when (and (not (get-text-property res prop))
1619 (> res (point-min))
1620 (get-text-property (1- res) prop))
1621 (cl-decf res))
1622 (when (and res (get-text-property res prop)) (cons res prop))))
1624 (defun markdown-find-next-prop (prop &optional lim)
1625 "Find next place where property PROP is non-nil, up to LIM.
1626 Return a cons of (POS . PROPERTY) where POS is point if point
1627 contains non-nil PROP."
1628 (let ((res
1629 (if (get-text-property (point) prop) (point)
1630 (next-single-property-change
1631 (point) prop nil (or lim (point-max))))))
1632 (when (and res (get-text-property res prop)) (cons res prop))))
1634 (defun markdown-min-of-seq (map-fn seq)
1635 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1636 (cl-loop for el in seq
1637 with min = 1.0e+INF ; infinity
1638 with min-el = nil
1639 do (let ((res (funcall map-fn el)))
1640 (when (< res min)
1641 (setq min res)
1642 (setq min-el el)))
1643 finally return min-el))
1645 (defun markdown-find-previous-block ()
1646 "Find previous block.
1647 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1648 unable to propertize the entire block, but was able to propertize the beginning
1649 of the block. If so, return a cons of (pos . property) where the beginning of
1650 the block was propertized."
1651 (let ((start-pt (point))
1652 (closest-open
1653 (markdown-min-of-seq
1654 #'car
1655 (cl-remove-if
1656 #'null
1657 (cl-mapcar
1658 #'markdown-find-previous-prop
1659 (markdown-get-fenced-block-begin-properties))))))
1660 (when closest-open
1661 (let* ((length-of-open-match
1662 (let ((match-d
1663 (get-text-property (car closest-open) (cdr closest-open))))
1664 (- (cl-fourth match-d) (cl-third match-d))))
1665 (end-regexp
1666 (markdown-maybe-funcall-regexp
1667 (cl-caadr
1668 (cl-find-if
1669 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1670 markdown-fenced-block-pairs))
1671 length-of-open-match))
1672 (end-prop-loc
1673 (save-excursion
1674 (save-match-data
1675 (goto-char (car closest-open))
1676 (and (re-search-forward end-regexp start-pt t)
1677 (match-beginning 0))))))
1678 (and (not end-prop-loc) closest-open)))))
1680 (defun markdown-get-fenced-block-from-start (prop)
1681 "Return limits of an enclosing fenced block from its start, using PROP.
1682 Return value is a list usable as `match-data'."
1683 (catch 'no-rest-of-block
1684 (let* ((correct-entry
1685 (cl-find-if
1686 (lambda (entry) (eq (cl-cadar entry) prop))
1687 markdown-fenced-block-pairs))
1688 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1689 (middle-prop (cl-third correct-entry))
1690 (end-prop (cl-cadadr correct-entry))
1691 (end-of-end
1692 (save-excursion
1693 (goto-char (match-end 0)) ; end of begin
1694 (unless (eobp) (forward-char))
1695 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1696 (if (not mid-prop-v) ; no middle
1697 (progn
1698 ;; try to find end by advancing one
1699 (let ((end-prop-v
1700 (markdown-text-property-at-point end-prop)))
1701 (if end-prop-v (cl-second end-prop-v)
1702 (throw 'no-rest-of-block nil))))
1703 (set-match-data mid-prop-v)
1704 (goto-char (match-end 0)) ; end of middle
1705 (beginning-of-line) ; into end
1706 (cl-second (markdown-text-property-at-point end-prop)))))))
1707 (list begin-of-begin end-of-end))))
1709 (defun markdown-get-fenced-block-from-middle (prop)
1710 "Return limits of an enclosing fenced block from its middle, using PROP.
1711 Return value is a list usable as `match-data'."
1712 (let* ((correct-entry
1713 (cl-find-if
1714 (lambda (entry) (eq (cl-third entry) prop))
1715 markdown-fenced-block-pairs))
1716 (begin-prop (cl-cadar correct-entry))
1717 (begin-of-begin
1718 (save-excursion
1719 (goto-char (match-beginning 0))
1720 (unless (bobp) (forward-line -1))
1721 (beginning-of-line)
1722 (cl-first (markdown-text-property-at-point begin-prop))))
1723 (end-prop (cl-cadadr correct-entry))
1724 (end-of-end
1725 (save-excursion
1726 (goto-char (match-end 0))
1727 (beginning-of-line)
1728 (cl-second (markdown-text-property-at-point end-prop)))))
1729 (list begin-of-begin end-of-end)))
1731 (defun markdown-get-fenced-block-from-end (prop)
1732 "Return limits of an enclosing fenced block from its end, using PROP.
1733 Return value is a list usable as `match-data'."
1734 (let* ((correct-entry
1735 (cl-find-if
1736 (lambda (entry) (eq (cl-cadadr entry) prop))
1737 markdown-fenced-block-pairs))
1738 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1739 (middle-prop (cl-third correct-entry))
1740 (begin-prop (cl-cadar correct-entry))
1741 (begin-of-begin
1742 (save-excursion
1743 (goto-char (match-beginning 0)) ; beginning of end
1744 (unless (bobp) (backward-char)) ; into middle
1745 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1746 (if (not mid-prop-v)
1747 (progn
1748 (beginning-of-line)
1749 (cl-first (markdown-text-property-at-point begin-prop)))
1750 (set-match-data mid-prop-v)
1751 (goto-char (match-beginning 0)) ; beginning of middle
1752 (unless (bobp) (forward-line -1)) ; into beginning
1753 (beginning-of-line)
1754 (cl-first (markdown-text-property-at-point begin-prop)))))))
1755 (list begin-of-begin end-of-end)))
1757 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1758 "Get \"fake\" match data for block enclosing POS.
1759 Returns fake match data which encloses the start, middle, and end
1760 of the block construct enclosing POS, if it exists. Used in
1761 `markdown-code-block-at-pos'."
1762 (save-excursion
1763 (when pos (goto-char pos))
1764 (beginning-of-line)
1765 (car
1766 (cl-remove-if
1767 #'null
1768 (cl-mapcar
1769 (lambda (fun-and-prop)
1770 (cl-destructuring-bind (fun prop) fun-and-prop
1771 (when prop
1772 (save-match-data
1773 (set-match-data (markdown-text-property-at-point prop))
1774 (funcall fun prop)))))
1775 `((markdown-get-fenced-block-from-start
1776 ,(cl-find-if
1777 #'markdown-text-property-at-point
1778 (markdown-get-fenced-block-begin-properties)))
1779 (markdown-get-fenced-block-from-middle
1780 ,(cl-find-if
1781 #'markdown-text-property-at-point
1782 (markdown-get-fenced-block-middle-properties)))
1783 (markdown-get-fenced-block-from-end
1784 ,(cl-find-if
1785 #'markdown-text-property-at-point
1786 (markdown-get-fenced-block-end-properties)))))))))
1788 (defun markdown-propertize-end-match (reg end correct-entry enclosed-text-start)
1789 "Get match for REG up to END, if exists, and propertize appropriately.
1790 CORRECT-ENTRY is an entry in `markdown-fenced-block-pairs' and
1791 ENCLOSED-TEXT-START is the start of the \"middle\" section of the block."
1792 (when (re-search-forward reg end t)
1793 (put-text-property (match-beginning 0) (match-end 0)
1794 (cl-cadadr correct-entry) (match-data t))
1795 (put-text-property
1796 enclosed-text-start (match-beginning 0) (cl-third correct-entry)
1797 (list enclosed-text-start (match-beginning 0)))))
1799 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1800 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1801 If unable to propertize an entire block (if the start of a block is within START
1802 and END, but the end of the block is not), propertize the start section of a
1803 block, then in a subsequent call propertize both middle and end by finding the
1804 start which was previously propertized."
1805 (let ((start-reg (markdown-get-start-fence-regexp)))
1806 (save-excursion
1807 (goto-char start)
1808 ;; start from previous unclosed block, if exists
1809 (let ((prev-begin-block (markdown-find-previous-block)))
1810 (when prev-begin-block
1811 (let* ((correct-entry
1812 (cl-find-if (lambda (entry)
1813 (eq (cdr prev-begin-block) (cl-cadar entry)))
1814 markdown-fenced-block-pairs))
1815 (enclosed-text-start (1+ (car prev-begin-block)))
1816 (start-length
1817 (save-excursion
1818 (goto-char (car prev-begin-block))
1819 (string-match
1820 (markdown-maybe-funcall-regexp
1821 (caar correct-entry))
1822 (buffer-substring
1823 (point-at-bol) (point-at-eol)))
1824 (- (match-end 1) (match-beginning 1))))
1825 (end-reg (markdown-maybe-funcall-regexp
1826 (cl-caadr correct-entry) start-length)))
1827 (markdown-propertize-end-match
1828 end-reg end correct-entry enclosed-text-start))))
1829 ;; find all new blocks within region
1830 (while (re-search-forward start-reg end t)
1831 ;; we assume the opening constructs take up (only) an entire line,
1832 ;; so we re-check the current line
1833 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1834 ;; find entry in `markdown-fenced-block-pairs' corresponding
1835 ;; to regex which was matched
1836 (correct-entry
1837 (cl-find-if
1838 (lambda (fenced-pair)
1839 (string-match-p
1840 (markdown-maybe-funcall-regexp (caar fenced-pair))
1841 cur-line))
1842 markdown-fenced-block-pairs))
1843 (enclosed-text-start
1844 (save-excursion (1+ (point-at-eol))))
1845 (end-reg
1846 (markdown-maybe-funcall-regexp
1847 (cl-caadr correct-entry)
1848 (if (and (match-beginning 1) (match-end 1))
1849 (- (match-end 1) (match-beginning 1))
1850 0))))
1851 ;; get correct match data
1852 (save-excursion
1853 (beginning-of-line)
1854 (re-search-forward
1855 (markdown-maybe-funcall-regexp (caar correct-entry))
1856 (point-at-eol)))
1857 ;; mark starting, even if ending is outside of region
1858 (put-text-property (match-beginning 0) (match-end 0)
1859 (cl-cadar correct-entry) (match-data t))
1860 (markdown-propertize-end-match
1861 end-reg end correct-entry enclosed-text-start))))))
1863 (defun markdown-syntax-propertize-blockquotes (start end)
1864 "Match blockquotes from START to END."
1865 (save-excursion
1866 (goto-char start)
1867 (while (and (re-search-forward markdown-regex-blockquote end t)
1868 (not (markdown-code-block-at-pos (match-beginning 0))))
1869 (put-text-property (match-beginning 0) (match-end 0)
1870 'markdown-blockquote
1871 (match-data t)))))
1873 (defun markdown-syntax-propertize-yaml-metadata (start end)
1874 (save-excursion
1875 (goto-char start)
1876 (cl-loop
1877 while (re-search-forward markdown-regex-multimarkdown-metadata end t)
1878 do (when (get-text-property (match-beginning 0)
1879 'markdown-yaml-metadata-section)
1880 (put-text-property (match-beginning 1) (match-end 1)
1881 'markdown-metadata-key (match-data t))
1882 (put-text-property (match-beginning 2) (match-end 2)
1883 'markdown-metadata-markup (match-data t))
1884 (put-text-property (match-beginning 3) (match-end 3)
1885 'markdown-metadata-value (match-data t))))))
1887 (defun markdown-syntax-propertize-headings (start end)
1888 "Match headings of type SYMBOL with REGEX from START to END."
1889 (goto-char start)
1890 (while (re-search-forward markdown-regex-header end t)
1891 (unless (markdown-code-block-at-pos (match-beginning 0))
1892 (put-text-property
1893 (match-beginning 0) (match-end 0) 'markdown-heading t)
1894 (put-text-property
1895 (match-beginning 0) (match-end 0)
1896 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1897 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1898 (t (let ((atx-level (length (match-string-no-properties 4))))
1899 (intern (format "markdown-heading-%d-atx" atx-level)))))
1900 (match-data t)))))
1902 (defun markdown-syntax-propertize-comments (start end)
1903 "Match HTML comments from the START to END."
1904 (let* ((state (syntax-ppss)) (in-comment (nth 4 state)))
1905 (goto-char start)
1906 (cond
1907 ;; Comment start
1908 ((and (not in-comment)
1909 (re-search-forward markdown-regex-comment-start end t)
1910 (save-match-data (not (markdown-code-at-point-p)))
1911 (save-match-data (not (markdown-code-block-at-point))))
1912 (let ((open-beg (match-beginning 0)))
1913 (put-text-property open-beg (1+ open-beg)
1914 'syntax-table (string-to-syntax "<"))
1915 (markdown-syntax-propertize-comments
1916 (min (1+ (match-end 0)) end (point-max)) end)))
1917 ;; Comment end
1918 ((and in-comment
1919 (re-search-forward markdown-regex-comment-end end t))
1920 (put-text-property (1- (match-end 0)) (match-end 0)
1921 'syntax-table (string-to-syntax ">"))
1922 (markdown-syntax-propertize-comments
1923 (min (1+ (match-end 0)) end (point-max)) end))
1924 ;; Nothing found
1925 (t nil))))
1927 (defvar markdown--syntax-properties
1928 (list 'markdown-tilde-fence-begin nil
1929 'markdown-tilde-fence-end nil
1930 'markdown-fenced-code nil
1931 'markdown-yaml-metadata-begin nil
1932 'markdown-yaml-metadata-end nil
1933 'markdown-yaml-metadata-section nil
1934 'markdown-gfm-block-begin nil
1935 'markdown-gfm-block-end nil
1936 'markdown-gfm-code nil
1937 'markdown-pre nil
1938 'markdown-blockquote nil
1939 'markdown-heading nil
1940 'markdown-heading-1-setext nil
1941 'markdown-heading-2-setext nil
1942 'markdown-heading-1-atx nil
1943 'markdown-heading-2-atx nil
1944 'markdown-heading-3-atx nil
1945 'markdown-heading-4-atx nil
1946 'markdown-heading-5-atx nil
1947 'markdown-heading-6-atx nil
1948 'markdown-metadata-key nil
1949 'markdown-metadata-value nil
1950 'markdown-metadata-markup nil)
1951 "Property list of all known markdown syntactic properties.")
1953 (defun markdown-syntax-propertize (start end)
1954 "Function used as `syntax-propertize-function'.
1955 START and END delimit region to propertize."
1956 (remove-text-properties start end markdown--syntax-properties)
1957 (markdown-syntax-propertize-fenced-block-constructs start end)
1958 (markdown-syntax-propertize-yaml-metadata start end)
1959 (markdown-syntax-propertize-pre-blocks start end)
1960 (markdown-syntax-propertize-blockquotes start end)
1961 (markdown-syntax-propertize-headings start end)
1962 (markdown-syntax-propertize-comments start end))
1965 ;;; Font Lock =================================================================
1967 (require 'font-lock)
1969 (defvar markdown-italic-face 'markdown-italic-face
1970 "Face name to use for italic text.")
1972 (defvar markdown-bold-face 'markdown-bold-face
1973 "Face name to use for bold text.")
1975 (defvar markdown-strike-through-face 'markdown-strike-through-face
1976 "Face name to use for strike-through text.")
1978 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1979 "Face name to use as a base for header delimiters.")
1981 (defvar markdown-header-rule-face 'markdown-header-rule-face
1982 "Face name to use as a base for header rules.")
1984 (defvar markdown-header-face 'markdown-header-face
1985 "Face name to use as a base for headers.")
1987 (defvar markdown-header-face-1 'markdown-header-face-1
1988 "Face name to use for level-1 headers.")
1990 (defvar markdown-header-face-2 'markdown-header-face-2
1991 "Face name to use for level-2 headers.")
1993 (defvar markdown-header-face-3 'markdown-header-face-3
1994 "Face name to use for level-3 headers.")
1996 (defvar markdown-header-face-4 'markdown-header-face-4
1997 "Face name to use for level-4 headers.")
1999 (defvar markdown-header-face-5 'markdown-header-face-5
2000 "Face name to use for level-5 headers.")
2002 (defvar markdown-header-face-6 'markdown-header-face-6
2003 "Face name to use for level-6 headers.")
2005 (defvar markdown-inline-code-face 'markdown-inline-code-face
2006 "Face name to use for inline code.")
2008 (defvar markdown-list-face 'markdown-list-face
2009 "Face name to use for list markers.")
2011 (defvar markdown-blockquote-face 'markdown-blockquote-face
2012 "Face name to use for blockquote.")
2014 (defvar markdown-pre-face 'markdown-pre-face
2015 "Face name to use for preformatted text.")
2017 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2018 "Face name to use for programming language identifiers.")
2020 (defvar markdown-link-face 'markdown-link-face
2021 "Face name to use for links.")
2023 (defvar markdown-missing-link-face 'markdown-missing-link-face
2024 "Face name to use for links where the linked file does not exist.")
2026 (defvar markdown-reference-face 'markdown-reference-face
2027 "Face name to use for reference.")
2029 (defvar markdown-footnote-face 'markdown-footnote-face
2030 "Face name to use for footnote identifiers.")
2032 (defvar markdown-url-face 'markdown-url-face
2033 "Face name to use for URLs.")
2035 (defvar markdown-link-title-face 'markdown-link-title-face
2036 "Face name to use for reference link titles.")
2038 (defvar markdown-line-break-face 'markdown-line-break-face
2039 "Face name to use for hard line breaks.")
2041 (defvar markdown-comment-face 'markdown-comment-face
2042 "Face name to use for HTML comments.")
2044 (defvar markdown-math-face 'markdown-math-face
2045 "Face name to use for LaTeX expressions.")
2047 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2048 "Face name to use for metadata keys.")
2050 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2051 "Face name to use for metadata values.")
2053 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2054 "Face name to use for GFM checkboxes.")
2056 (defvar markdown-highlight-face 'markdown-highlight-face
2057 "Face name to use for mouse highlighting.")
2059 (defvar markdown-markup-face 'markdown-markup-face
2060 "Face name to use for markup elements.")
2062 (defgroup markdown-faces nil
2063 "Faces used in Markdown Mode"
2064 :group 'markdown
2065 :group 'faces)
2067 (defface markdown-italic-face
2068 '((t (:inherit font-lock-variable-name-face :slant italic :weight normal)))
2069 "Face for italic text."
2070 :group 'markdown-faces)
2072 (defface markdown-bold-face
2073 '((t (:inherit font-lock-variable-name-face :weight bold :slant normal)))
2074 "Face for bold text."
2075 :group 'markdown-faces)
2077 (defface markdown-strike-through-face
2078 '((t (:inherit font-lock-variable-name-face :strike-through t)))
2079 "Face for strike-through text."
2080 :group 'markdown-faces)
2082 (defface markdown-markup-face
2083 '((t (:inherit shadow :slant normal :weight normal)))
2084 "Face for markup elements."
2085 :group 'markdown-faces)
2087 (defface markdown-header-rule-face
2088 '((t (:inherit markdown-markup-face)))
2089 "Base face for headers rules."
2090 :group 'markdown-faces)
2092 (defface markdown-header-delimiter-face
2093 '((t (:inherit markdown-markup-face)))
2094 "Base face for headers hash delimiter."
2095 :group 'markdown-faces)
2097 (defface markdown-header-face
2098 '((t (:inherit font-lock-function-name-face :weight bold)))
2099 "Base face for headers."
2100 :group 'markdown-faces)
2102 (defface markdown-header-face-1
2103 '((t (:inherit markdown-header-face)))
2104 "Face for level-1 headers."
2105 :group 'markdown-faces)
2107 (defface markdown-header-face-2
2108 '((t (:inherit markdown-header-face)))
2109 "Face for level-2 headers."
2110 :group 'markdown-faces)
2112 (defface markdown-header-face-3
2113 '((t (:inherit markdown-header-face)))
2114 "Face for level-3 headers."
2115 :group 'markdown-faces)
2117 (defface markdown-header-face-4
2118 '((t (:inherit markdown-header-face)))
2119 "Face for level-4 headers."
2120 :group 'markdown-faces)
2122 (defface markdown-header-face-5
2123 '((t (:inherit markdown-header-face)))
2124 "Face for level-5 headers."
2125 :group 'markdown-faces)
2127 (defface markdown-header-face-6
2128 '((t (:inherit markdown-header-face)))
2129 "Face for level-6 headers."
2130 :group 'markdown-faces)
2132 (defface markdown-inline-code-face
2133 '((t (:inherit font-lock-constant-face)))
2134 "Face for inline code."
2135 :group 'markdown-faces)
2137 (defface markdown-list-face
2138 '((t (:inherit markdown-markup-face)))
2139 "Face for list item markers."
2140 :group 'markdown-faces)
2142 (defface markdown-blockquote-face
2143 '((t (:inherit font-lock-doc-face)))
2144 "Face for blockquote sections."
2145 :group 'markdown-faces)
2147 (defface markdown-pre-face
2148 '((t (:inherit font-lock-constant-face)))
2149 "Face for preformatted text."
2150 :group 'markdown-faces)
2152 (defface markdown-language-keyword-face
2153 '((t (:inherit font-lock-type-face)))
2154 "Face for programming language identifiers."
2155 :group 'markdown-faces)
2157 (defface markdown-link-face
2158 '((t (:inherit font-lock-keyword-face)))
2159 "Face for links."
2160 :group 'markdown-faces)
2162 (defface markdown-missing-link-face
2163 '((t (:inherit font-lock-warning-face)))
2164 "Face for missing links."
2165 :group 'markdown-faces)
2167 (defface markdown-reference-face
2168 '((t (:inherit markdown-markup-face)))
2169 "Face for link references."
2170 :group 'markdown-faces)
2172 (defface markdown-footnote-face
2173 '((t (:inherit markdown-markup-face)))
2174 "Face for footnote markers."
2175 :group 'markdown-faces)
2177 (defface markdown-url-face
2178 '((t (:inherit font-lock-string-face)))
2179 "Face for URLs."
2180 :group 'markdown-faces)
2182 (defface markdown-link-title-face
2183 '((t (:inherit font-lock-comment-face)))
2184 "Face for reference link titles."
2185 :group 'markdown-faces)
2187 (defface markdown-line-break-face
2188 '((t (:inherit font-lock-constant-face :underline t)))
2189 "Face for hard line breaks."
2190 :group 'markdown-faces)
2192 (defface markdown-comment-face
2193 '((t (:inherit font-lock-comment-face)))
2194 "Face for HTML comments."
2195 :group 'markdown-faces)
2197 (defface markdown-math-face
2198 '((t (:inherit font-lock-string-face)))
2199 "Face for LaTeX expressions."
2200 :group 'markdown-faces)
2202 (defface markdown-metadata-key-face
2203 '((t (:inherit font-lock-variable-name-face)))
2204 "Face for metadata keys."
2205 :group 'markdown-faces)
2207 (defface markdown-metadata-value-face
2208 '((t (:inherit font-lock-string-face)))
2209 "Face for metadata values."
2210 :group 'markdown-faces)
2212 (defface markdown-gfm-checkbox-face
2213 '((t (:inherit font-lock-builtin-face)))
2214 "Face for GFM checkboxes."
2215 :group 'markdown-faces)
2217 (defface markdown-highlight-face
2218 '((t (:inherit highlight)))
2219 "Face for mouse highlighting."
2220 :group 'markdown-faces)
2222 (defun markdown-syntactic-face (state)
2223 "Return font-lock face for characters with given STATE.
2224 See `font-lock-syntactic-face-function' for details."
2225 (let ((in-comment (nth 4 state)))
2226 (cond
2227 (in-comment 'markdown-comment-face)
2228 (t nil))))
2230 (defvar markdown-mode-font-lock-keywords-basic
2231 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2232 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2233 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2234 (2 markdown-markup-face)
2235 (3 markdown-metadata-value-face)))
2236 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-face)
2237 (2 markdown-language-keyword-face nil t)))
2238 (markdown-match-gfm-close-code-blocks . ((1 markdown-markup-face)))
2239 (markdown-match-gfm-code-blocks . ((0 markdown-pre-face)))
2240 (markdown-match-fenced-start-code-block . ((1 markdown-markup-face)
2241 (2 markdown-language-keyword-face nil t)))
2242 (markdown-match-fenced-end-code-block . ((0 markdown-markup-face)))
2243 (markdown-match-fenced-code-blocks . ((0 markdown-pre-face)))
2244 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2245 (markdown-match-blockquotes . ((1 markdown-markup-face)
2246 (2 markdown-blockquote-face)))
2247 (markdown-match-heading-1-setext . ((1 markdown-header-face-1)
2248 (2 markdown-header-rule-face)))
2249 (markdown-match-heading-2-setext . ((1 markdown-header-face-2)
2250 (3 markdown-header-rule-face)))
2251 (markdown-match-heading-6-atx . ((4 markdown-header-delimiter-face)
2252 (5 markdown-header-face-6)
2253 (6 markdown-header-delimiter-face)))
2254 (markdown-match-heading-5-atx . ((4 markdown-header-delimiter-face)
2255 (5 markdown-header-face-5)
2256 (6 markdown-header-delimiter-face)))
2257 (markdown-match-heading-4-atx . ((4 markdown-header-delimiter-face)
2258 (5 markdown-header-face-4)
2259 (6 markdown-header-delimiter-face)))
2260 (markdown-match-heading-3-atx . ((4 markdown-header-delimiter-face)
2261 (5 markdown-header-face-3)
2262 (6 markdown-header-delimiter-face)))
2263 (markdown-match-heading-2-atx . ((4 markdown-header-delimiter-face)
2264 (5 markdown-header-face-2)
2265 (6 markdown-header-delimiter-face)))
2266 (markdown-match-heading-1-atx . ((4 markdown-header-delimiter-face)
2267 (5 markdown-header-face-1)
2268 (6 markdown-header-delimiter-face)))
2269 (markdown-match-multimarkdown-metadata . ((1 markdown-metadata-key-face)
2270 (2 markdown-markup-face)
2271 (3 markdown-metadata-value-face)))
2272 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2273 (2 markdown-markup-face)
2274 (3 markdown-metadata-value-face)))
2275 (markdown-match-hr . markdown-header-delimiter-face)
2276 (markdown-match-code . ((1 markdown-markup-face)
2277 (2 markdown-inline-code-face)
2278 (3 markdown-markup-face)))
2279 (,markdown-regex-kbd . ((1 markdown-markup-face)
2280 (2 markdown-inline-code-face)
2281 (3 markdown-markup-face)))
2282 (,markdown-regex-angle-uri . ((1 markdown-markup-face)
2283 (2 markdown-link-face)
2284 (3 markdown-markup-face)))
2285 (,markdown-regex-list . (2 markdown-list-face))
2286 (,markdown-regex-footnote . ((1 markdown-markup-face) ; [^
2287 (2 markdown-footnote-face) ; label
2288 (3 markdown-markup-face))) ; ]
2289 (,markdown-regex-link-inline . ((1 markdown-markup-face nil t) ; ! (optional)
2290 (2 markdown-markup-face) ; [
2291 (3 markdown-link-face) ; text
2292 (4 markdown-markup-face) ; ]
2293 (5 markdown-markup-face) ; (
2294 (6 markdown-url-face) ; url
2295 (7 markdown-link-title-face nil t) ; "title" (optional)
2296 (8 markdown-markup-face))) ; )
2297 (,markdown-regex-link-reference . ((1 markdown-markup-face nil t) ; ! (optional)
2298 (2 markdown-markup-face) ; [
2299 (3 markdown-link-face) ; text
2300 (4 markdown-markup-face) ; ]
2301 (5 markdown-markup-face) ; [
2302 (6 markdown-reference-face) ; label
2303 (7 markdown-markup-face))) ; ]
2304 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2305 (2 markdown-reference-face) ; label
2306 (3 markdown-markup-face) ; ]
2307 (4 markdown-markup-face) ; :
2308 (5 markdown-url-face) ; url
2309 (6 markdown-link-title-face))) ; "title" (optional)
2310 ;; Math mode $..$
2311 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2312 (2 markdown-math-face append)
2313 (3 markdown-markup-face prepend)))
2314 ;; Math mode $$..$$
2315 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2316 (2 markdown-math-face append)
2317 (3 markdown-markup-face prepend)))
2318 (markdown-match-bold . ((1 markdown-markup-face prepend)
2319 (2 markdown-bold-face append)
2320 (3 markdown-markup-face prepend)))
2321 (markdown-match-italic . ((1 markdown-markup-face prepend)
2322 (2 markdown-italic-face append)
2323 (3 markdown-markup-face prepend)))
2324 (,markdown-regex-uri . markdown-link-face)
2325 (,markdown-regex-email . markdown-link-face)
2326 (,markdown-regex-line-break . (1 markdown-line-break-face prepend)))
2328 "Syntax highlighting for Markdown files.")
2330 (defvar markdown-mode-font-lock-keywords nil
2331 "Default highlighting expressions for Markdown mode.
2332 This variable is defined as a buffer-local variable for dynamic
2333 extension support.")
2335 ;; Footnotes
2336 (defvar markdown-footnote-counter 0
2337 "Counter for footnote numbers.")
2338 (make-variable-buffer-local 'markdown-footnote-counter)
2340 (defconst markdown-footnote-chars
2341 "[[:alnum:]-]"
2342 "Regular expression matching any character that is allowed in a footnote identifier.")
2344 (defconst markdown-regex-footnote-definition
2345 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2346 "Regular expression matching a footnote definition, capturing the label.")
2349 ;;; Compatibility =============================================================
2351 (defun markdown-replace-regexp-in-string (regexp rep string)
2352 "Replace ocurrences of REGEXP with REP in STRING.
2353 This is a compatibility wrapper to provide `replace-regexp-in-string'
2354 in XEmacs 21."
2355 (if (featurep 'xemacs)
2356 (replace-in-string string regexp rep)
2357 (replace-regexp-in-string regexp rep string)))
2359 ;; `markdown-use-region-p' is a compatibility function which checks
2360 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2361 (eval-and-compile
2362 (cond
2363 ;; Emacs 24 and newer
2364 ((fboundp 'use-region-p)
2365 (defalias 'markdown-use-region-p 'use-region-p))
2366 ;; XEmacs
2367 ((fboundp 'region-active-p)
2368 (defalias 'markdown-use-region-p 'region-active-p))))
2370 (defun markdown-use-buttons-p ()
2371 "Determine whether this Emacs supports buttons."
2372 (or (featurep 'button) (locate-library "button")))
2374 ;; Use new names for outline-mode functions in Emacs 25 and later.
2375 (eval-and-compile
2376 (defalias 'markdown-hide-sublevels
2377 (if (fboundp 'outline-hide-sublevels)
2378 'outline-hide-sublevels
2379 'hide-sublevels))
2380 (defalias 'markdown-show-all
2381 (if (fboundp 'outline-show-all)
2382 'outline-show-all
2383 'show-all))
2384 (defalias 'markdown-hide-body
2385 (if (fboundp 'outline-hide-body)
2386 'outline-hide-body
2387 'hide-body))
2388 (defalias 'markdown-show-children
2389 (if (fboundp 'outline-show-children)
2390 'outline-show-children
2391 'show-children))
2392 (defalias 'markdown-show-subtree
2393 (if (fboundp 'outline-show-subtree)
2394 'outline-show-subtree
2395 'show-subtree))
2396 (defalias 'markdown-hide-subtree
2397 (if (fboundp 'outline-hide-subtree)
2398 'outline-hide-subtree
2399 'hide-subtree)))
2402 ;;; Markdown Parsing Functions ================================================
2404 (defun markdown-cur-line-blank-p ()
2405 "Return t if the current line is blank and nil otherwise."
2406 (save-excursion
2407 (beginning-of-line)
2408 (looking-at-p "^\\s *$")))
2410 (defun markdown-prev-line-blank-p ()
2411 "Return t if the previous line is blank and nil otherwise.
2412 If we are at the first line, then consider the previous line to be blank."
2413 (or (= (line-beginning-position) (point-min))
2414 (save-excursion
2415 (forward-line -1)
2416 (markdown-cur-line-blank-p))))
2418 (defun markdown-next-line-blank-p ()
2419 "Return t if the next line is blank and nil otherwise.
2420 If we are at the last line, then consider the next line to be blank."
2421 (or (= (line-end-position) (point-max))
2422 (save-excursion
2423 (forward-line 1)
2424 (markdown-cur-line-blank-p))))
2426 (defun markdown-prev-line-indent ()
2427 "Return the number of leading whitespace characters in the previous line.
2428 Return 0 if the current line is the first line in the buffer."
2429 (save-excursion
2430 (if (= (line-beginning-position) (point-min))
2432 (forward-line -1)
2433 (current-indentation))))
2435 (defun markdown-next-line-indent ()
2436 "Return the number of leading whitespace characters in the next line.
2437 Return 0 if line is the last line in the buffer."
2438 (save-excursion
2439 (if (= (line-end-position) (point-max))
2441 (forward-line 1)
2442 (current-indentation))))
2444 (defun markdown-cur-non-list-indent ()
2445 "Return beginning position of list item text (not including the list marker).
2446 Return nil if the current line is not the beginning of a list item."
2447 (save-match-data
2448 (save-excursion
2449 (beginning-of-line)
2450 (when (re-search-forward markdown-regex-list (line-end-position) t)
2451 (current-column)))))
2453 (defun markdown-prev-non-list-indent ()
2454 "Return position of the first non-list-marker on the previous line."
2455 (save-excursion
2456 (forward-line -1)
2457 (markdown-cur-non-list-indent)))
2459 (defun markdown-new-baseline-p ()
2460 "Determine if the current line begins a new baseline level."
2461 (save-excursion
2462 (beginning-of-line)
2463 (or (looking-at-p markdown-regex-header)
2464 (looking-at-p markdown-regex-hr)
2465 (and (null (markdown-cur-non-list-indent))
2466 (= (current-indentation) 0)
2467 (markdown-prev-line-blank-p)))))
2469 (defun markdown-search-backward-baseline ()
2470 "Search backward baseline point with no indentation and not a list item."
2471 (end-of-line)
2472 (let (stop)
2473 (while (not (or stop (bobp)))
2474 (re-search-backward markdown-regex-block-separator nil t)
2475 (when (match-end 2)
2476 (goto-char (match-end 2))
2477 (cond
2478 ((markdown-new-baseline-p)
2479 (setq stop t))
2480 ((looking-at-p markdown-regex-list)
2481 (setq stop nil))
2482 (t (setq stop t)))))))
2484 (defun markdown-update-list-levels (marker indent levels)
2485 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2486 Here, MARKER is a string representing the type of list, INDENT is an integer
2487 giving the indentation, in spaces, of the current block, and LEVELS is a
2488 list of the indentation levels of parent list items. When LEVELS is nil,
2489 it means we are at baseline (not inside of a nested list)."
2490 (cond
2491 ;; New list item at baseline.
2492 ((and marker (null levels))
2493 (setq levels (list indent)))
2494 ;; List item with greater indentation (four or more spaces).
2495 ;; Increase list level.
2496 ((and marker (>= indent (+ (car levels) 4)))
2497 (setq levels (cons indent levels)))
2498 ;; List item with greater or equal indentation (less than four spaces).
2499 ;; Do not increase list level.
2500 ((and marker (>= indent (car levels)))
2501 levels)
2502 ;; Lesser indentation level.
2503 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2504 ;; indentation could move back more than one list level). Note
2505 ;; that this block need not be the beginning of list item.
2506 ((< indent (car levels))
2507 (while (and (> (length levels) 1)
2508 (< indent (+ (cadr levels) 4)))
2509 (setq levels (cdr levels)))
2510 levels)
2511 ;; Otherwise, do nothing.
2512 (t levels)))
2514 (defun markdown-calculate-list-levels ()
2515 "Calculate list levels at point.
2516 Return a list of the form (n1 n2 n3 ...) where n1 is the
2517 indentation of the deepest nested list item in the branch of
2518 the list at the point, n2 is the indentation of the parent
2519 list item, and so on. The depth of the list item is therefore
2520 the length of the returned list. If the point is not at or
2521 immediately after a list item, return nil."
2522 (save-excursion
2523 (let ((first (point)) levels indent pre-regexp)
2524 ;; Find a baseline point with zero list indentation
2525 (markdown-search-backward-baseline)
2526 ;; Search for all list items between baseline and LOC
2527 (while (and (< (point) first)
2528 (re-search-forward markdown-regex-list first t))
2529 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2530 (beginning-of-line)
2531 (cond
2532 ;; Make sure this is not a header or hr
2533 ((markdown-new-baseline-p) (setq levels nil))
2534 ;; Make sure this is not a line from a pre block
2535 ((looking-at-p pre-regexp))
2536 ;; If not, then update levels
2538 (setq indent (current-indentation))
2539 (setq levels (markdown-update-list-levels (match-string 2)
2540 indent levels))))
2541 (end-of-line))
2542 levels)))
2544 (defun markdown-prev-list-item (level)
2545 "Search backward from point for a list item with indentation LEVEL.
2546 Set point to the beginning of the item, and return point, or nil
2547 upon failure."
2548 (let (bounds indent prev)
2549 (setq prev (point))
2550 (forward-line -1)
2551 (setq indent (current-indentation))
2552 (while
2553 (cond
2554 ;; List item
2555 ((and (looking-at-p markdown-regex-list)
2556 (setq bounds (markdown-cur-list-item-bounds)))
2557 (cond
2558 ;; Stop and return point at item of lesser or equal indentation
2559 ((<= (nth 3 bounds) level)
2560 (setq prev (point))
2561 nil)
2562 ;; Stop at beginning of buffer
2563 ((bobp) (setq prev nil))
2564 ;; Continue at item with greater indentation
2565 ((> (nth 3 bounds) level) t)))
2566 ;; Stop at beginning of buffer
2567 ((bobp) (setq prev nil))
2568 ;; Continue if current line is blank
2569 ((markdown-cur-line-blank-p) t)
2570 ;; Continue while indentation is the same or greater
2571 ((>= indent level) t)
2572 ;; Stop if current indentation is less than list item
2573 ;; and the next is blank
2574 ((and (< indent level)
2575 (markdown-next-line-blank-p))
2576 (setq prev nil))
2577 ;; Stop at a header
2578 ((looking-at-p markdown-regex-header) (setq prev nil))
2579 ;; Stop at a horizontal rule
2580 ((looking-at-p markdown-regex-hr) (setq prev nil))
2581 ;; Otherwise, continue.
2582 (t t))
2583 (forward-line -1)
2584 (setq indent (current-indentation)))
2585 prev))
2587 (defun markdown-next-list-item (level)
2588 "Search forward from point for the next list item with indentation LEVEL.
2589 Set point to the beginning of the item, and return point, or nil
2590 upon failure."
2591 (let (bounds indent next)
2592 (setq next (point))
2593 (forward-line)
2594 (setq indent (current-indentation))
2595 (while
2596 (cond
2597 ;; Stop at end of the buffer.
2598 ((eobp) nil)
2599 ;; Continue if the current line is blank
2600 ((markdown-cur-line-blank-p) t)
2601 ;; List item
2602 ((and (looking-at-p markdown-regex-list)
2603 (setq bounds (markdown-cur-list-item-bounds)))
2604 (cond
2605 ;; Continue at item with greater indentation
2606 ((> (nth 3 bounds) level) t)
2607 ;; Stop and return point at item of equal indentation
2608 ((= (nth 3 bounds) level)
2609 (setq next (point))
2610 nil)
2611 ;; Stop and return nil at item with lesser indentation
2612 ((< (nth 3 bounds) level)
2613 (setq next nil)
2614 nil)))
2615 ;; Continue while indentation is the same or greater
2616 ((>= indent level) t)
2617 ;; Stop if current indentation is less than list item
2618 ;; and the previous line was blank.
2619 ((and (< indent level)
2620 (markdown-prev-line-blank-p))
2621 (setq next nil))
2622 ;; Stop at a header
2623 ((looking-at-p markdown-regex-header) (setq next nil))
2624 ;; Stop at a horizontal rule
2625 ((looking-at-p markdown-regex-hr) (setq next nil))
2626 ;; Otherwise, continue.
2627 (t t))
2628 (forward-line)
2629 (setq indent (current-indentation)))
2630 next))
2632 (defun markdown-cur-list-item-end (level)
2633 "Move to the end of the current list item with nonlist indentation LEVEL.
2634 If the point is not in a list item, do nothing."
2635 (let (indent)
2636 (forward-line)
2637 (setq indent (current-indentation))
2638 (while
2639 (cond
2640 ;; Stop at end of the buffer.
2641 ((eobp) nil)
2642 ;; Continue if the current line is blank
2643 ((markdown-cur-line-blank-p) t)
2644 ;; Continue while indentation is the same or greater
2645 ((>= indent level) t)
2646 ;; Stop if current indentation is less than list item
2647 ;; and the previous line was blank.
2648 ((and (< indent level)
2649 (markdown-prev-line-blank-p))
2650 nil)
2651 ;; Stop at a new list item of the same or lesser indentation
2652 ((looking-at-p markdown-regex-list) nil)
2653 ;; Stop at a header
2654 ((looking-at-p markdown-regex-header) nil)
2655 ;; Stop at a horizontal rule
2656 ((looking-at-p markdown-regex-hr) nil)
2657 ;; Otherwise, continue.
2658 (t t))
2659 (forward-line)
2660 (setq indent (current-indentation)))
2661 ;; Don't skip over whitespace for empty list items (marker and
2662 ;; whitespace only), just move to end of whitespace.
2663 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
2664 (goto-char (match-end 3))
2665 (skip-syntax-backward "-"))))
2667 (defun markdown-cur-list-item-bounds ()
2668 "Return bounds and indentation of the current list item.
2669 Return a list of the form (begin end indent nonlist-indent marker).
2670 If the point is not inside a list item, return nil.
2671 Leave match data intact for `markdown-regex-list'."
2672 (let (cur prev-begin prev-end indent nonlist-indent marker)
2673 ;; Store current location
2674 (setq cur (point))
2675 ;; Verify that cur is between beginning and end of item
2676 (save-excursion
2677 (end-of-line)
2678 (when (re-search-backward markdown-regex-list nil t)
2679 (setq prev-begin (match-beginning 0))
2680 (setq indent (length (match-string 1)))
2681 (setq nonlist-indent (length (match-string 0)))
2682 (setq marker (concat (match-string 2) (match-string 3)))
2683 (save-match-data
2684 (markdown-cur-list-item-end nonlist-indent)
2685 (setq prev-end (point)))
2686 (when (and (>= cur prev-begin)
2687 (<= cur prev-end)
2688 nonlist-indent)
2689 (list prev-begin prev-end indent nonlist-indent marker))))))
2691 (defun markdown-bounds-of-thing-at-point (thing)
2692 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2693 Does not include trailing newlines when THING is 'line. Handles the
2694 end of buffer case by setting both endpoints equal to the value of
2695 `point-max', since an empty region will trigger empty markup insertion.
2696 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2697 (let* ((bounds (bounds-of-thing-at-point thing))
2698 (a (car bounds))
2699 (b (cdr bounds)))
2700 (when bounds
2701 (when (eq thing 'line)
2702 (cond ((and (eobp) (markdown-cur-line-blank-p))
2703 (setq a b))
2704 ((char-equal (char-before b) ?\^J)
2705 (setq b (1- b)))))
2706 (cons a b))))
2708 (defun markdown-reference-definition (reference)
2709 "Find out whether Markdown REFERENCE is defined.
2710 REFERENCE should not include the square brackets.
2711 When REFERENCE is defined, return a list of the form (text start end)
2712 containing the definition text itself followed by the start and end
2713 locations of the text. Otherwise, return nil.
2714 Leave match data for `markdown-regex-reference-definition'
2715 intact additional processing."
2716 (let ((reference (downcase reference)))
2717 (save-excursion
2718 (goto-char (point-min))
2719 (catch 'found
2720 (while (re-search-forward markdown-regex-reference-definition nil t)
2721 (when (string= reference (downcase (match-string-no-properties 2)))
2722 (throw 'found
2723 (list (match-string-no-properties 5)
2724 (match-beginning 5) (match-end 5)))))))))
2726 (defun markdown-get-defined-references ()
2727 "Return a list of all defined reference labels (not including square brackets)."
2728 (save-excursion
2729 (goto-char (point-min))
2730 (let (refs)
2731 (while (re-search-forward markdown-regex-reference-definition nil t)
2732 (let ((target (match-string-no-properties 2)))
2733 (cl-pushnew target refs :test #'equal)))
2734 (reverse refs))))
2736 (defun markdown-code-at-point-p ()
2737 "Return non-nil if the point is at an inline code fragment.
2738 Return nil otherwise. Set match data according to
2739 `markdown-match-code' upon success.
2740 This function searches the block for a code fragment that
2741 contains the point using `markdown-match-code'. We do this
2742 because `thing-at-point-looking-at' does not work reliably with
2743 `markdown-regex-code'.
2745 The match data is set as follows:
2746 Group 1 matches the opening backticks.
2747 Group 2 matches the code fragment itself, without backticks.
2748 Group 3 matches the closing backticks."
2749 (interactive)
2750 (save-excursion
2751 (let ((old-point (point))
2752 (end-of-block (progn (markdown-end-of-block) (point)))
2753 found)
2754 (markdown-beginning-of-block)
2755 (while (and (markdown-match-code end-of-block)
2756 (setq found t)
2757 (< (match-end 0) old-point)))
2758 (and found ; matched something
2759 (<= (match-beginning 0) old-point) ; match contains old-point
2760 (>= (match-end 0) old-point)))))
2762 (defun markdown-code-block-at-pos (pos)
2763 "Return match data list if there is a code block at POS.
2764 This includes pre blocks, tilde-fenced code blocks, and GFM
2765 quoted code blocks. Return nil otherwise."
2766 (or (get-text-property pos 'markdown-pre)
2767 (markdown-get-enclosing-fenced-block-construct pos)
2768 ;; polymode removes text properties set by markdown-mode, so
2769 ;; check if `poly-markdown-mode' is active and whether the
2770 ;; `chunkmode' property is non-nil at POS.
2771 (and (bound-and-true-p poly-markdown-mode)
2772 (get-text-property pos 'chunkmode))))
2774 (defun markdown-code-block-at-point ()
2775 "Return match data if the point is inside a code block.
2776 This includes pre blocks, tilde-fenced code blocks, and
2777 GFM quoted code blocks. Calls `markdown-code-block-at-pos'."
2778 (markdown-code-block-at-pos (point)))
2781 ;;; Markdown Font Lock Matching Functions =====================================
2783 (defun markdown-range-property-any (begin end prop prop-values)
2784 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2785 Also returns t if PROP is a list containing one of the PROP-VALUES.
2786 Return nil otherwise."
2787 (let (props)
2788 (catch 'found
2789 (dolist (loc (number-sequence begin end))
2790 (when (setq props (get-char-property loc prop))
2791 (cond ((listp props)
2792 ;; props is a list, check for membership
2793 (dolist (val prop-values)
2794 (when (memq val props) (throw 'found loc))))
2796 ;; props is a scalar, check for equality
2797 (dolist (val prop-values)
2798 (when (eq val props) (throw 'found loc))))))))))
2800 (defun markdown-range-properties-exist (begin end props)
2801 (cl-loop
2802 for loc in (number-sequence begin end)
2803 with result = nil
2804 while (not
2805 (setq result
2806 (cl-some (lambda (prop) (get-char-property loc prop)) props)))
2807 finally return result))
2809 (defun markdown-match-inline-generic (regex last)
2810 "Match inline REGEX from the point to LAST."
2811 (when (re-search-forward regex last t)
2812 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2813 (if (null bounds)
2814 ;; Not in a code block: keep match data and return t when in bounds
2815 (<= (match-end 0) last)
2816 ;; In code block: move past it and recursively search again
2817 (when (< (goto-char (nth 1 bounds)) last)
2818 (markdown-match-inline-generic regex last))))))
2820 (defun markdown-match-code (last)
2821 "Match inline code fragments from point to LAST."
2822 (unless (bobp)
2823 (backward-char 1))
2824 (when (markdown-match-inline-generic markdown-regex-code last)
2825 (set-match-data (list (match-beginning 1) (match-end 1)
2826 (match-beginning 2) (match-end 2)
2827 (match-beginning 3) (match-end 3)
2828 (match-beginning 4) (match-end 4)))
2829 (goto-char (1+ (match-end 0)))))
2831 (defun markdown-match-bold (last)
2832 "Match inline bold from the point to LAST."
2833 (when (markdown-match-inline-generic markdown-regex-bold last)
2834 (let ((begin (match-beginning 2)) (end (match-end 2)))
2835 (cond
2836 ((markdown-range-property-any
2837 begin end 'face (list markdown-inline-code-face
2838 markdown-math-face))
2839 (goto-char (1+ (match-end 0)))
2840 (markdown-match-bold last))
2842 (set-match-data (list (match-beginning 2) (match-end 2)
2843 (match-beginning 3) (match-end 3)
2844 (match-beginning 4) (match-end 4)
2845 (match-beginning 5) (match-end 5)))
2846 (goto-char (1+ (match-end 0))))))))
2848 (defun markdown-match-italic (last)
2849 "Match inline italics from the point to LAST."
2850 (let ((regex (if (eq major-mode 'gfm-mode)
2851 markdown-regex-gfm-italic markdown-regex-italic)))
2852 (when (markdown-match-inline-generic regex last)
2853 (let ((begin (match-beginning 1)) (end (match-end 1)))
2854 (cond
2855 ((markdown-range-property-any
2856 begin end 'face (list markdown-inline-code-face
2857 markdown-bold-face
2858 markdown-list-face
2859 markdown-math-face))
2860 (goto-char (1+ (match-end 0)))
2861 (markdown-match-italic last))
2863 (set-match-data (list (match-beginning 1) (match-end 1)
2864 (match-beginning 2) (match-end 2)
2865 (match-beginning 3) (match-end 3)
2866 (match-beginning 4) (match-end 4)))
2867 (goto-char (1+ (match-end 0)))))))))
2869 (defun markdown-match-math-generic (regex last)
2870 "Match REGEX from point to LAST.
2871 REGEX is either `markdown-regex-math-inline-single' for matching
2872 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2873 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
2874 (let ((begin (match-beginning 1)) (end (match-end 1)))
2875 (prog1
2876 (if (or (markdown-range-property-any
2877 begin end 'face (list markdown-inline-code-face
2878 markdown-bold-face))
2879 (markdown-range-properties-exist
2880 begin end
2881 (markdown-get-fenced-block-middle-properties)))
2882 (markdown-match-math-generic regex last)
2884 (goto-char (1+ (match-end 0)))))))
2886 (defun markdown-match-math-single (last)
2887 "Match single quoted $..$ math from point to LAST."
2888 (markdown-match-math-generic markdown-regex-math-inline-single last))
2890 (defun markdown-match-math-double (last)
2891 "Match double quoted $$..$$ math from point to LAST."
2892 (markdown-match-math-generic markdown-regex-math-inline-double last))
2894 (defun markdown-match-propertized-text (property last)
2895 "Match text with PROPERTY from point to LAST.
2896 Restore match data previously stored in PROPERTY."
2897 (let ((saved (get-text-property (point) property))
2898 pos)
2899 (unless saved
2900 (setq pos (next-single-char-property-change (point) property nil last))
2901 (setq saved (get-text-property pos property)))
2902 (when saved
2903 (set-match-data saved)
2904 ;; Step at least one character beyond point. Otherwise
2905 ;; `font-lock-fontify-keywords-region' infloops.
2906 (goto-char (min (1+ (max (match-end 0) (point)))
2907 (point-max)))
2908 saved)))
2910 (defun markdown-match-pre-blocks (last)
2911 "Match preformatted blocks from point to LAST.
2912 Use data stored in 'markdown-pre text property during syntax
2913 analysis."
2914 (markdown-match-propertized-text 'markdown-pre last))
2916 (defun markdown-match-gfm-code-blocks (last)
2917 "Match GFM quoted code blocks from point to LAST.
2918 Use data stored in 'markdown-gfm-code text property during syntax
2919 analysis."
2920 (markdown-match-propertized-text 'markdown-gfm-code last))
2922 (defun markdown-match-gfm-open-code-blocks (last)
2923 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
2925 (defun markdown-match-gfm-close-code-blocks (last)
2926 (markdown-match-propertized-text 'markdown-gfm-block-end last))
2928 (defun markdown-match-fenced-code-blocks (last)
2929 "Match fenced code blocks from the point to LAST."
2930 (markdown-match-propertized-text 'markdown-fenced-code last))
2932 (defun markdown-match-fenced-start-code-block (last)
2933 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
2935 (defun markdown-match-fenced-end-code-block (last)
2936 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
2938 (defun markdown-match-blockquotes (last)
2939 "Match blockquotes from point to LAST.
2940 Use data stored in 'markdown-blockquote text property during syntax
2941 analysis."
2942 (markdown-match-propertized-text 'markdown-blockquote last))
2944 (defun markdown-match-heading-1-setext (last)
2945 "Match level 1 setext headings from point to LAST."
2946 (markdown-match-propertized-text 'markdown-heading-1-setext last))
2948 (defun markdown-match-heading-2-setext (last)
2949 "Match level 2 setext headings from point to LAST."
2950 (markdown-match-propertized-text 'markdown-heading-2-setext last))
2952 (defun markdown-match-heading-1-atx (last)
2953 "Match level 1 ATX headings from point to LAST."
2954 (markdown-match-propertized-text 'markdown-heading-1-atx last))
2956 (defun markdown-match-heading-2-atx (last)
2957 "Match level 2 ATX headings from point to LAST."
2958 (markdown-match-propertized-text 'markdown-heading-2-atx last))
2960 (defun markdown-match-heading-3-atx (last)
2961 "Match level 3 ATX headings from point to LAST."
2962 (markdown-match-propertized-text 'markdown-heading-3-atx last))
2964 (defun markdown-match-heading-4-atx (last)
2965 "Match level 4 ATX headings from point to LAST."
2966 (markdown-match-propertized-text 'markdown-heading-4-atx last))
2968 (defun markdown-match-heading-5-atx (last)
2969 "Match level 5 ATX headings from point to LAST."
2970 (markdown-match-propertized-text 'markdown-heading-5-atx last))
2972 (defun markdown-match-heading-6-atx (last)
2973 "Match level 6 ATX headings from point to LAST."
2974 (markdown-match-propertized-text 'markdown-heading-6-atx last))
2976 (defun markdown-match-hr (last)
2977 "Match horizontal rules comments from the point to LAST."
2978 (while (and (re-search-forward markdown-regex-hr last t)
2979 (or (markdown-on-heading-p)
2980 (markdown-code-block-at-point))
2981 (< (match-end 0) last))
2982 (forward-line))
2983 (beginning-of-line)
2984 (cond ((looking-at-p markdown-regex-hr)
2985 (forward-line)
2987 (t nil)))
2989 (defun markdown-match-comments (last)
2990 "Match HTML comments from the point to LAST."
2991 (when (and (skip-syntax-forward "^<" last))
2992 (let ((beg (point)))
2993 (when (and (skip-syntax-forward "^>" last) (< (point) last))
2994 (forward-char)
2995 (set-match-data (list beg (point)))
2996 t))))
2998 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
2999 (save-excursion
3000 (goto-char (or pos (point-min)))
3001 (cl-loop
3002 with cur-result = nil
3003 and st-hdr = (or start-header "\\`")
3004 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3005 while (and (< (point) last)
3006 (re-search-forward st-hdr last t)
3007 (progn
3008 (setq cur-result (match-data))
3009 (re-search-forward end-hdr nil t)))
3010 collect (list cur-result (match-data)))))
3012 (defvar markdown-conditional-search-function #'re-search-forward
3013 "Conditional search function used in `markdown-search-until-condition'.
3014 Made into a variable to allow for dynamic let-binding.")
3016 (defun markdown-search-until-condition (condition &rest args)
3017 (let (ret)
3018 (while (and (not ret) (apply markdown-conditional-search-function args))
3019 (setq ret (funcall condition)))
3020 ret))
3022 (defun markdown-match-generic-metadata
3023 (regexp last &optional start-header end-header)
3024 "Match generic metadata specified by REGEXP from the point to LAST.
3025 If START-HEADER is nil, we assume metadata can only occur at the
3026 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3027 is \"\n\n\""
3028 (let* ((header-bounds
3029 (markdown-get-match-boundaries start-header end-header last))
3030 (enclosing-header
3031 (cl-find-if ; just take first if multiple
3032 (lambda (match-bounds)
3033 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3034 (and (< (point) begin)
3035 (save-excursion (re-search-forward regexp end t)))))
3036 header-bounds))
3037 (header-begin
3038 (when enclosing-header (cl-second (cl-first enclosing-header))))
3039 (header-end
3040 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3041 (cond ((null enclosing-header)
3042 ;; Don't match anything outside of a header.
3043 nil)
3044 ((markdown-search-until-condition
3045 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3046 ;; If a metadata item is found, it may span several lines.
3047 (let ((key-beginning (match-beginning 1))
3048 (key-end (match-end 1))
3049 (markup-begin (match-beginning 2))
3050 (markup-end (match-end 2))
3051 (value-beginning (match-beginning 3)))
3052 (set-match-data (list key-beginning (point) ; complete metadata
3053 key-beginning key-end ; key
3054 markup-begin markup-end ; markup
3055 value-beginning (point))) ; value
3057 (t nil))))
3059 (defun markdown-match-multimarkdown-metadata (last)
3060 "Match MultiMarkdown metadata from the point to LAST."
3061 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
3063 (defun markdown-match-pandoc-metadata (last)
3064 "Match Pandoc metadata from the point to LAST."
3065 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3067 (defun markdown-match-yaml-metadata-begin (last)
3068 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3070 (defun markdown-match-yaml-metadata-end (last)
3071 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3073 (defun markdown-match-yaml-metadata-key (last)
3074 (markdown-match-propertized-text 'markdown-metadata-key last))
3077 ;;; Syntax Table ==============================================================
3079 (defvar markdown-mode-syntax-table
3080 (let ((tab (make-syntax-table text-mode-syntax-table)))
3081 (modify-syntax-entry ?\" "." tab)
3082 tab)
3083 "Syntax table for `markdown-mode'.")
3086 ;;; Element Insertion =========================================================
3088 (defun markdown-ensure-blank-line-before ()
3089 "If previous line is not already blank, insert a blank line before point."
3090 (unless (bolp) (insert "\n"))
3091 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3093 (defun markdown-ensure-blank-line-after ()
3094 "If following line is not already blank, insert a blank line after point.
3095 Return the point where it was originally."
3096 (save-excursion
3097 (unless (eolp) (insert "\n"))
3098 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3100 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3101 "Insert the strings S1 and S2, wrapping around region or THING.
3102 If a region is specified by the optional BEG and END arguments,
3103 wrap the strings S1 and S2 around that region.
3104 If there is an active region, wrap the strings S1 and S2 around
3105 the region. If there is not an active region but the point is at
3106 THING, wrap that thing (which defaults to word). Otherwise, just
3107 insert S1 and S2 and place the cursor in between. Return the
3108 bounds of the entire wrapped string, or nil if nothing was wrapped
3109 and S1 and S2 were only inserted."
3110 (let (a b bounds new-point)
3111 (cond
3112 ;; Given region
3113 ((and beg end)
3114 (setq a beg
3115 b end
3116 new-point (+ (point) (length s1))))
3117 ;; Active region
3118 ((markdown-use-region-p)
3119 (setq a (region-beginning)
3120 b (region-end)
3121 new-point (+ (point) (length s1))))
3122 ;; Thing (word) at point
3123 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3124 (setq a (car bounds)
3125 b (cdr bounds)
3126 new-point (+ (point) (length s1))))
3127 ;; No active region and no word
3129 (setq a (point)
3130 b (point))))
3131 (goto-char b)
3132 (insert s2)
3133 (goto-char a)
3134 (insert s1)
3135 (when new-point (goto-char new-point))
3136 (if (= a b)
3138 (setq b (+ b (length s1) (length s2)))
3139 (cons a b))))
3141 (defun markdown-point-after-unwrap (cur prefix suffix)
3142 "Return desired position of point after an unwrapping operation.
3143 CUR gives the position of the point before the operation.
3144 Additionally, two cons cells must be provided. PREFIX gives the
3145 bounds of the prefix string and SUFFIX gives the bounds of the
3146 suffix string."
3147 (cond ((< cur (cdr prefix)) (car prefix))
3148 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3149 ((<= cur (cdr suffix))
3150 (- cur (+ (- (cdr prefix) (car prefix))
3151 (- cur (car suffix)))))
3152 (t cur)))
3154 (defun markdown-unwrap-thing-at-point (regexp all text)
3155 "Remove prefix and suffix of thing at point and reposition the point.
3156 When the thing at point matches REGEXP, replace the subexpression
3157 ALL with the string in subexpression TEXT. Reposition the point
3158 in an appropriate location accounting for the removal of prefix
3159 and suffix strings. Return new bounds of string from group TEXT.
3160 When REGEXP is nil, assumes match data is already set."
3161 (when (or (null regexp)
3162 (thing-at-point-looking-at regexp))
3163 (let ((cur (point))
3164 (prefix (cons (match-beginning all) (match-beginning text)))
3165 (suffix (cons (match-end text) (match-end all)))
3166 (bounds (cons (match-beginning text) (match-end text))))
3167 ;; Replace the thing at point
3168 (replace-match (match-string text) t t nil all)
3169 ;; Reposition the point
3170 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3171 ;; Adjust bounds
3172 (setq bounds (cons (car prefix)
3173 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3175 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3176 "Remove prefix and suffix of all things in region from BEG to END.
3177 When a thing in the region matches REGEXP, replace the
3178 subexpression ALL with the string in subexpression TEXT.
3179 Return a cons cell containing updated bounds for the region."
3180 (save-excursion
3181 (goto-char beg)
3182 (let ((removed 0) len-all len-text)
3183 (while (re-search-forward regexp (- end removed) t)
3184 (setq len-all (length (match-string-no-properties all)))
3185 (setq len-text (length (match-string-no-properties text)))
3186 (setq removed (+ removed (- len-all len-text)))
3187 (replace-match (match-string text) t t nil all))
3188 (cons beg (- end removed)))))
3190 (defun markdown-insert-hr (arg)
3191 "Insert or replace a horizonal rule.
3192 By default, use the first element of `markdown-hr-strings'. When
3193 ARG is non-nil, as when given a prefix, select a different
3194 element as follows. When prefixed with \\[universal-argument],
3195 use the last element of `markdown-hr-strings' instead. When
3196 prefixed with an integer from 1 to the length of
3197 `markdown-hr-strings', use the element in that position instead."
3198 (interactive "*P")
3199 (when (thing-at-point-looking-at markdown-regex-hr)
3200 (delete-region (match-beginning 0) (match-end 0)))
3201 (markdown-ensure-blank-line-before)
3202 (cond ((equal arg '(4))
3203 (insert (car (reverse markdown-hr-strings))))
3204 ((and (integerp arg) (> arg 0)
3205 (<= arg (length markdown-hr-strings)))
3206 (insert (nth (1- arg) markdown-hr-strings)))
3208 (insert (car markdown-hr-strings))))
3209 (markdown-ensure-blank-line-after))
3211 (defun markdown-insert-bold ()
3212 "Insert markup to make a region or word bold.
3213 If there is an active region, make the region bold. If the point
3214 is at a non-bold word, make the word bold. If the point is at a
3215 bold word or phrase, remove the bold markup. Otherwise, simply
3216 insert bold delimiters and place the cursor in between them."
3217 (interactive)
3218 (let ((delim (if markdown-bold-underscore "__" "**")))
3219 (if (markdown-use-region-p)
3220 ;; Active region
3221 (let ((bounds (markdown-unwrap-things-in-region
3222 (region-beginning) (region-end)
3223 markdown-regex-bold 2 4)))
3224 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3225 ;; Bold markup removal, bold word at point, or empty markup insertion
3226 (if (thing-at-point-looking-at markdown-regex-bold)
3227 (markdown-unwrap-thing-at-point nil 2 4)
3228 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3230 (defun markdown-insert-italic ()
3231 "Insert markup to make a region or word italic.
3232 If there is an active region, make the region italic. If the point
3233 is at a non-italic word, make the word italic. If the point is at an
3234 italic word or phrase, remove the italic markup. Otherwise, simply
3235 insert italic delimiters and place the cursor in between them."
3236 (interactive)
3237 (let ((delim (if markdown-italic-underscore "_" "*")))
3238 (if (markdown-use-region-p)
3239 ;; Active region
3240 (let ((bounds (markdown-unwrap-things-in-region
3241 (region-beginning) (region-end)
3242 markdown-regex-italic 1 3)))
3243 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3244 ;; Italic markup removal, italic word at point, or empty markup insertion
3245 (if (thing-at-point-looking-at markdown-regex-italic)
3246 (markdown-unwrap-thing-at-point nil 1 3)
3247 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3249 (defun markdown-insert-strike-through ()
3250 "Insert markup to make a region or word strikethrough.
3251 If there is an active region, make the region strikethrough. If the point
3252 is at a non-bold word, make the word strikethrough. If the point is at a
3253 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3254 simply insert bold delimiters and place the cursor in between them."
3255 (interactive)
3256 (let ((delim "~~"))
3257 (if (markdown-use-region-p)
3258 ;; Active region
3259 (let ((bounds (markdown-unwrap-things-in-region
3260 (region-beginning) (region-end)
3261 markdown-regex-strike-through 2 4)))
3262 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3263 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3264 (if (thing-at-point-looking-at markdown-regex-strike-through)
3265 (markdown-unwrap-thing-at-point nil 2 4)
3266 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3268 (defun markdown-insert-code ()
3269 "Insert markup to make a region or word an inline code fragment.
3270 If there is an active region, make the region an inline code
3271 fragment. If the point is at a word, make the word an inline
3272 code fragment. Otherwise, simply insert code delimiters and
3273 place the cursor in between them."
3274 (interactive)
3275 (if (markdown-use-region-p)
3276 ;; Active region
3277 (let ((bounds (markdown-unwrap-things-in-region
3278 (region-beginning) (region-end)
3279 markdown-regex-code 1 3)))
3280 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3281 ;; Code markup removal, code markup for word, or empty markup insertion
3282 (if (markdown-code-at-point-p)
3283 (markdown-unwrap-thing-at-point nil 0 2)
3284 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3286 (defun markdown-insert-kbd ()
3287 "Insert markup to wrap region or word in <kbd> tags.
3288 If there is an active region, use the region. If the point is at
3289 a word, use the word. Otherwise, simply insert <kbd> tags and
3290 place the cursor in between them."
3291 (interactive)
3292 (if (markdown-use-region-p)
3293 ;; Active region
3294 (let ((bounds (markdown-unwrap-things-in-region
3295 (region-beginning) (region-end)
3296 markdown-regex-kbd 0 2)))
3297 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3298 ;; Markup removal, markup for word, or empty markup insertion
3299 (if (thing-at-point-looking-at markdown-regex-kbd)
3300 (markdown-unwrap-thing-at-point nil 0 2)
3301 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3303 (defun markdown-insert-link ()
3304 "Insert an inline link, using region or word as link text if possible.
3305 If there is an active region, use the region as the link text. If the
3306 point is at a word, use the word as the link text. In these cases, the
3307 point will be left at the position for inserting a URL. If there is no
3308 active region and the point is not at word, simply insert link markup and
3309 place the point in the position to enter link text."
3310 (interactive)
3311 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3312 (when bounds
3313 (goto-char (- (cdr bounds) 1)))))
3315 (defun markdown-insert-reference-link (text label &optional url title)
3316 "Insert a reference link and, optionally, a reference definition.
3317 The link TEXT will be inserted followed by the optional LABEL.
3318 If a URL is given, also insert a definition for the reference
3319 LABEL according to `markdown-reference-location'. If a TITLE is
3320 given, it will be added to the end of the reference definition
3321 and will be used to populate the title attribute when converted
3322 to XHTML. If URL is nil, insert only the link portion (for
3323 example, when a reference label is already defined)."
3324 (insert (concat "[" text "][" label "]"))
3325 (when url
3326 (markdown-insert-reference-definition
3327 (if (string-equal label "") text label)
3328 url title)))
3330 (defun markdown-insert-reference-definition (label &optional url title)
3331 "Add definition for reference LABEL with URL and TITLE.
3332 LABEL is a Markdown reference label without square brackets.
3333 URL and TITLE are optional. When given, the TITLE will
3334 be used to populate the title attribute when converted to XHTML."
3335 ;; END specifies where to leave the point upon return
3336 (let ((end (point)))
3337 (cl-case markdown-reference-location
3338 (end (goto-char (point-max)))
3339 (immediately (markdown-end-of-block))
3340 (header (markdown-end-of-defun)))
3341 (unless (markdown-cur-line-blank-p) (insert "\n"))
3342 (insert "\n[" label "]: ")
3343 (if url
3344 (insert url)
3345 ;; When no URL is given, leave cursor at END following the colon
3346 (setq end (point)))
3347 (when (> (length title) 0)
3348 (insert " \"" title "\""))
3349 (unless (looking-at-p "\n")
3350 (insert "\n"))
3351 (goto-char end)
3352 (when url
3353 (message
3354 (substitute-command-keys
3355 "Defined reference [%s], press \\[markdown-jump] to jump there")
3356 label))))
3358 (defun markdown-insert-reference-link-dwim ()
3359 "Insert a reference link of the form [text][label] at point.
3360 If there is an active region, the text in the region will be used
3361 as the link text. If the point is at an inline link, it will be
3362 converted to a reference link. If the point is at a word, it will
3363 be used as the link text. Otherwise, the link text will be read from
3364 the minibuffer. The link label will be read from the minibuffer in
3365 both cases, with completion from the set of currently defined
3366 references. To create an implicit reference link, press RET to
3367 accept the default, an empty label. If the entered referenced
3368 label is not defined, additionally prompt for the URL
3369 and (optional) title. The reference definition is placed at the
3370 location determined by `markdown-reference-location'."
3371 (interactive)
3372 (let* ((defined-labels (markdown-get-defined-references))
3373 (switch (thing-at-point-looking-at markdown-regex-link-inline))
3374 (bounds (cond ((markdown-use-region-p)
3375 (cons (region-beginning) (region-end)))
3376 (switch
3377 (cons (match-beginning 0) (match-end 0)))
3379 (markdown-bounds-of-thing-at-point 'word))))
3380 (text (cond (switch (match-string 3))
3381 (bounds (buffer-substring (car bounds) (cdr bounds)))
3382 (t (read-string "Link Text: "))))
3383 (label (completing-read
3384 "Link Label (default: none): " defined-labels
3385 nil nil nil 'markdown-reference-label-history nil))
3386 (ref (save-match-data
3387 (markdown-reference-definition
3388 (if (> (length label) 0) label text))))
3389 (url (cond (ref nil)
3390 (switch (match-string 6))
3391 (t (read-string "Link URL: "))))
3392 (title (cond
3393 ((= (length url) 0) nil)
3394 (switch (if (> (length (match-string 7)) 2)
3395 (substring (match-string 7) 1 -1)
3396 nil))
3397 (t (read-string "Link Title (optional): ")))))
3398 (when bounds (delete-region (car bounds) (cdr bounds)))
3399 (markdown-insert-reference-link text label url title)))
3401 (defun markdown-insert-uri ()
3402 "Insert markup for an inline URI.
3403 If there is an active region, use it as the URI. If the point is
3404 at a URI, wrap it with angle brackets. If the point is at an
3405 inline URI, remove the angle brackets. Otherwise, simply insert
3406 angle brackets place the point between them."
3407 (interactive)
3408 (if (markdown-use-region-p)
3409 ;; Active region
3410 (let ((bounds (markdown-unwrap-things-in-region
3411 (region-beginning) (region-end)
3412 markdown-regex-angle-uri 0 2)))
3413 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
3414 ;; Markup removal, URI at point, or empty markup insertion
3415 (if (thing-at-point-looking-at markdown-regex-angle-uri)
3416 (markdown-unwrap-thing-at-point nil 0 2)
3417 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
3419 (defun markdown-insert-wiki-link ()
3420 "Insert a wiki link of the form [[WikiLink]].
3421 If there is an active region, use the region as the link text.
3422 If the point is at a word, use the word as the link text. If
3423 there is no active region and the point is not at word, simply
3424 insert link markup."
3425 (interactive)
3426 (if (markdown-use-region-p)
3427 ;; Active region
3428 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
3429 ;; Markup removal, wiki link at at point, or empty markup insertion
3430 (if (thing-at-point-looking-at markdown-regex-wiki-link)
3431 (if (or markdown-wiki-link-alias-first
3432 (null (match-string 5)))
3433 (markdown-unwrap-thing-at-point nil 1 3)
3434 (markdown-unwrap-thing-at-point nil 1 5))
3435 (markdown-wrap-or-insert "[[" "]]"))))
3437 (defun markdown-insert-image (&optional arg)
3438 "Insert image markup using region or word as alt text if possible.
3439 If there is an active region, use the region as the alt text. If the
3440 point is at a word, use the word as the alt text. In these cases, the
3441 point will be left at the position for inserting a URL. If there is no
3442 active region and the point is not at word, simply insert image markup and
3443 place the point in the position to enter alt text. If ARG is nil, insert
3444 inline image markup. Otherwise, insert reference image markup."
3445 (interactive "*P")
3446 (let ((bounds (if arg
3447 (markdown-wrap-or-insert "![" "][]")
3448 (markdown-wrap-or-insert "![" "]()"))))
3449 (when bounds
3450 (goto-char (- (cdr bounds) 1)))))
3452 (defun markdown-insert-reference-image ()
3453 "Insert reference-style image markup using region or word as alt text.
3454 Calls `markdown-insert-image' with prefix argument."
3455 (interactive)
3456 (markdown-insert-image t))
3458 (defun markdown-remove-header ()
3459 "Remove header markup if point is at a header.
3460 Return bounds of remaining header text if a header was removed
3461 and nil otherwise."
3462 (interactive "*")
3463 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
3464 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
3466 (defun markdown-insert-header (&optional level text setext)
3467 "Insert or replace header markup.
3468 The level of the header is specified by LEVEL and header text is
3469 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3470 default value is 1.
3471 When TEXT is nil, the header text is obtained as follows.
3472 If there is an active region, it is used as the header text.
3473 Otherwise, the current line will be used as the header text.
3474 If there is not an active region and the point is at a header,
3475 remove the header markup and replace with level N header.
3476 Otherwise, insert empty header markup and place the cursor in
3477 between.
3478 The style of the header will be atx (hash marks) unless
3479 SETEXT is non-nil, in which case a setext-style (underlined)
3480 header will be inserted."
3481 (interactive "p\nsHeader text: ")
3482 (setq level (min (max (or level 1) 1) (if setext 2 6)))
3483 ;; Determine header text if not given
3484 (when (null text)
3485 (if (markdown-use-region-p)
3486 ;; Active region
3487 (setq text (delete-and-extract-region (region-beginning) (region-end)))
3488 ;; No active region
3489 (markdown-remove-header)
3490 (setq text (delete-and-extract-region
3491 (line-beginning-position) (line-end-position)))
3492 (when (and setext (string-match-p "^[ \t]*$" text))
3493 (setq text (read-string "Header text: "))))
3494 (setq text (markdown-compress-whitespace-string text)))
3495 ;; Insertion with given text
3496 (markdown-ensure-blank-line-before)
3497 (let (hdr)
3498 (cond (setext
3499 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
3500 (insert text "\n" hdr))
3502 (setq hdr (make-string level ?#))
3503 (insert hdr " " text)
3504 (when (null markdown-asymmetric-header) (insert " " hdr)))))
3505 (markdown-ensure-blank-line-after)
3506 ;; Leave point at end of text
3507 (cond (setext
3508 (backward-char (1+ (string-width text))))
3509 ((null markdown-asymmetric-header)
3510 (backward-char (1+ level)))))
3512 (defun markdown-insert-header-dwim (&optional arg setext)
3513 "Insert or replace header markup.
3514 The level and type of the header are determined automatically by
3515 the type and level of the previous header, unless a prefix
3516 argument is given via ARG.
3517 With a numeric prefix valued 1 to 6, insert a header of the given
3518 level, with the type being determined automatically (note that
3519 only level 1 or 2 setext headers are possible).
3521 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3522 promote the heading by one level.
3523 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3524 demote the heading by one level.
3525 When SETEXT is non-nil, prefer setext-style headers when
3526 possible (levels one and two).
3528 When there is an active region, use it for the header text. When
3529 the point is at an existing header, change the type and level
3530 according to the rules above.
3531 Otherwise, if the line is not empty, create a header using the
3532 text on the current line as the header text.
3533 Finally, if the point is on a blank line, insert empty header
3534 markup (atx) or prompt for text (setext).
3535 See `markdown-insert-header' for more details about how the
3536 header text is determined."
3537 (interactive "*P")
3538 (let (level)
3539 (save-excursion
3540 (when (or (thing-at-point-looking-at markdown-regex-header)
3541 (re-search-backward markdown-regex-header nil t))
3542 ;; level of current or previous header
3543 (setq level (markdown-outline-level))
3544 ;; match group 1 indicates a setext header
3545 (setq setext (match-end 1))))
3546 ;; check prefix argument
3547 (cond
3548 ((and (equal arg '(4)) level (> level 1)) ;; C-u
3549 (cl-decf level))
3550 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
3551 (cl-incf level))
3552 (arg ;; numeric prefix
3553 (setq level (prefix-numeric-value arg))))
3554 ;; setext headers must be level one or two
3555 (and level (setq setext (and setext (<= level 2))))
3556 ;; insert the heading
3557 (markdown-insert-header level nil setext)))
3559 (defun markdown-insert-header-setext-dwim (&optional arg)
3560 "Insert or replace header markup, with preference for setext.
3561 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3562 (interactive "*P")
3563 (markdown-insert-header-dwim arg t))
3565 (defun markdown-insert-header-atx-1 ()
3566 "Insert a first level atx-style (hash mark) header.
3567 See `markdown-insert-header'."
3568 (interactive "*")
3569 (markdown-insert-header 1 nil nil))
3571 (defun markdown-insert-header-atx-2 ()
3572 "Insert a level two atx-style (hash mark) header.
3573 See `markdown-insert-header'."
3574 (interactive "*")
3575 (markdown-insert-header 2 nil nil))
3577 (defun markdown-insert-header-atx-3 ()
3578 "Insert a level three atx-style (hash mark) header.
3579 See `markdown-insert-header'."
3580 (interactive "*")
3581 (markdown-insert-header 3 nil nil))
3583 (defun markdown-insert-header-atx-4 ()
3584 "Insert a level four atx-style (hash mark) header.
3585 See `markdown-insert-header'."
3586 (interactive "*")
3587 (markdown-insert-header 4 nil nil))
3589 (defun markdown-insert-header-atx-5 ()
3590 "Insert a level five atx-style (hash mark) header.
3591 See `markdown-insert-header'."
3592 (interactive "*")
3593 (markdown-insert-header 5 nil nil))
3595 (defun markdown-insert-header-atx-6 ()
3596 "Insert a sixth level atx-style (hash mark) header.
3597 See `markdown-insert-header'."
3598 (interactive "*")
3599 (markdown-insert-header 6 nil nil))
3601 (defun markdown-insert-header-setext-1 ()
3602 "Insert a setext-style (underlined) first-level header.
3603 See `markdown-insert-header'."
3604 (interactive "*")
3605 (markdown-insert-header 1 nil t))
3607 (defun markdown-insert-header-setext-2 ()
3608 "Insert a setext-style (underlined) second-level header.
3609 See `markdown-insert-header'."
3610 (interactive "*")
3611 (markdown-insert-header 2 nil t))
3613 (defun markdown-blockquote-indentation (loc)
3614 "Return string containing necessary indentation for a blockquote at LOC.
3615 Also see `markdown-pre-indentation'."
3616 (save-excursion
3617 (goto-char loc)
3618 (let* ((list-level (length (markdown-calculate-list-levels)))
3619 (indent ""))
3620 (dotimes (_ list-level indent)
3621 (setq indent (concat indent " "))))))
3623 (defun markdown-insert-blockquote ()
3624 "Start a blockquote section (or blockquote the region).
3625 If Transient Mark mode is on and a region is active, it is used as
3626 the blockquote text."
3627 (interactive)
3628 (if (markdown-use-region-p)
3629 (markdown-blockquote-region (region-beginning) (region-end))
3630 (markdown-ensure-blank-line-before)
3631 (insert (markdown-blockquote-indentation (point)) "> ")
3632 (markdown-ensure-blank-line-after)))
3634 (defun markdown-block-region (beg end prefix)
3635 "Format the region using a block prefix.
3636 Arguments BEG and END specify the beginning and end of the
3637 region. The characters PREFIX will appear at the beginning
3638 of each line."
3639 (save-excursion
3640 (let* ((end-marker (make-marker))
3641 (beg-marker (make-marker)))
3642 ;; Ensure blank line after and remove extra whitespace
3643 (goto-char end)
3644 (skip-syntax-backward "-")
3645 (set-marker end-marker (point))
3646 (delete-horizontal-space)
3647 (markdown-ensure-blank-line-after)
3648 ;; Ensure blank line before and remove extra whitespace
3649 (goto-char beg)
3650 (skip-syntax-forward "-")
3651 (delete-horizontal-space)
3652 (markdown-ensure-blank-line-before)
3653 (set-marker beg-marker (point))
3654 ;; Insert PREFIX before each line
3655 (goto-char beg-marker)
3656 (while (and (< (line-beginning-position) end-marker)
3657 (not (eobp)))
3658 (insert prefix)
3659 (forward-line)))))
3661 (defun markdown-blockquote-region (beg end)
3662 "Blockquote the region.
3663 Arguments BEG and END specify the beginning and end of the region."
3664 (interactive "*r")
3665 (markdown-block-region
3666 beg end (concat (markdown-blockquote-indentation
3667 (max (point-min) (1- beg))) "> ")))
3669 (defun markdown-pre-indentation (loc)
3670 "Return string containing necessary whitespace for a pre block at LOC.
3671 Also see `markdown-blockquote-indentation'."
3672 (save-excursion
3673 (goto-char loc)
3674 (let* ((list-level (length (markdown-calculate-list-levels)))
3675 indent)
3676 (dotimes (_ (1+ list-level) indent)
3677 (setq indent (concat indent " "))))))
3679 (defun markdown-insert-pre ()
3680 "Start a preformatted section (or apply to the region).
3681 If Transient Mark mode is on and a region is active, it is marked
3682 as preformatted text."
3683 (interactive)
3684 (if (markdown-use-region-p)
3685 (markdown-pre-region (region-beginning) (region-end))
3686 (markdown-ensure-blank-line-before)
3687 (insert (markdown-pre-indentation (point)))
3688 (markdown-ensure-blank-line-after)))
3690 (defun markdown-pre-region (beg end)
3691 "Format the region as preformatted text.
3692 Arguments BEG and END specify the beginning and end of the region."
3693 (interactive "*r")
3694 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
3695 (markdown-block-region beg end indent)))
3697 (defun markdown-electric-backquote (arg)
3698 "Insert a backquote.
3699 The numeric prefix argument ARG says how many times to repeat the insertion.
3700 Call `markdown-insert-gfm-code-block' interactively
3701 if three backquotes inserted at the beginning of line."
3702 (interactive "*P")
3703 (self-insert-command (prefix-numeric-value arg))
3704 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
3705 (replace-match "")
3706 (call-interactively #'markdown-insert-gfm-code-block)))
3708 (defconst markdown-gfm-recognized-languages
3709 ;; to reproduce/update, evaluate the let-form in
3710 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3711 ;; but with appropriate use of a keyboard macro, indenting and filling it
3712 ;; properly is pretty fast.
3713 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3714 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3715 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3716 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3717 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3718 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3719 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3720 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3721 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3722 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3723 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3724 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3725 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3726 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3727 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3728 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3729 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3730 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3731 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3732 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3733 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3734 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3735 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3736 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3737 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3738 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3739 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3740 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3741 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3742 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3743 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3744 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3745 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3746 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3747 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3748 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3749 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3750 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3751 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3752 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3753 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3754 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3755 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3756 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3757 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3758 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3759 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3760 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3761 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3762 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3763 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3764 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3765 "Language specifiers recognized by github's syntax highlighting features.")
3767 (defvar markdown-gfm-used-languages nil
3768 "Languages in GFM code blocks which are not explicitly declared.
3769 Known language are declared in
3770 `markdown-gfm-recognized-languages' and
3771 `markdown-gfm-additional-languages'.")
3772 (make-variable-buffer-local 'markdown-gfm-used-languages)
3773 (defvar markdown-gfm-last-used-language nil
3774 "Last language used in the current buffer in GFM code blocks.")
3775 (make-variable-buffer-local 'markdown-gfm-last-used-language)
3777 (defun markdown-trim-whitespace (str)
3778 (markdown-replace-regexp-in-string
3779 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
3781 (defun markdown-clean-language-string (str)
3782 (markdown-replace-regexp-in-string
3783 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
3785 (defun markdown-validate-language-string (widget)
3786 (let ((str (widget-value widget)))
3787 (unless (string= str (markdown-clean-language-string str))
3788 (widget-put widget :error (format "Invalid language spec: '%s'" str))
3789 widget)))
3791 (defun markdown-gfm-get-corpus ()
3792 "Create corpus of recognized GFM code block languages for the given buffer."
3793 (let ((given-corpus (append markdown-gfm-additional-languages
3794 markdown-gfm-recognized-languages)))
3795 (append
3796 markdown-gfm-used-languages
3797 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
3798 given-corpus))))
3800 (defun markdown-add-language-if-new (lang)
3801 (let* ((cleaned-lang (markdown-clean-language-string lang))
3802 (find-result
3803 (cl-find cleaned-lang (markdown-gfm-get-corpus)
3804 :test #'equal)))
3805 (setq markdown-gfm-last-used-language cleaned-lang)
3806 (unless find-result (push cleaned-lang markdown-gfm-used-languages))))
3808 (defun markdown-insert-gfm-code-block (&optional lang)
3809 "Insert GFM code block for language LANG.
3810 If LANG is nil, the language will be queried from user. If a
3811 region is active, wrap this region with the markup instead. If
3812 the region boundaries are not on empty lines, these are added
3813 automatically in order to have the correct markup."
3814 (interactive
3815 (list (let ((completion-ignore-case nil))
3816 (condition-case nil
3817 (markdown-clean-language-string
3818 (completing-read
3819 (format "Programming language [%s]: "
3820 (or markdown-gfm-last-used-language "none"))
3821 (markdown-gfm-get-corpus)
3822 nil 'confirm nil
3823 'markdown-gfm-language-history))
3824 (quit "")))))
3825 (unless (string= lang "") (markdown-add-language-if-new lang))
3826 (when (> (length lang) 0) (setq lang (concat " " lang)))
3827 (if (markdown-use-region-p)
3828 (let ((b (region-beginning)) (e (region-end)))
3829 (goto-char e)
3830 ;; if we're on a blank line, don't newline, otherwise the ```
3831 ;; should go on its own line
3832 (unless (looking-back "\n" nil)
3833 (newline))
3834 (insert "```")
3835 (markdown-ensure-blank-line-after)
3836 (goto-char b)
3837 ;; if we're on a blank line, insert the quotes here, otherwise
3838 ;; add a new line first
3839 (unless (looking-at-p "\n")
3840 (newline)
3841 (forward-line -1))
3842 (markdown-ensure-blank-line-before)
3843 (insert "```" lang))
3844 (markdown-ensure-blank-line-before)
3845 (insert "```" lang "\n\n```")
3846 (markdown-ensure-blank-line-after)
3847 (forward-line -1)))
3849 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
3850 (with-current-buffer (or buffer (current-buffer))
3851 (save-excursion
3852 (goto-char (point-min))
3853 (cl-loop
3854 with prop = 'markdown-gfm-block-begin
3855 for pos-prop = (markdown-find-next-prop prop)
3856 while pos-prop
3857 for lang = (progn
3858 (goto-char (car pos-prop))
3859 (save-match-data
3860 (set-match-data (get-text-property (point) prop))
3861 (when (and (match-beginning 2) (match-end 2))
3862 (buffer-substring-no-properties
3863 (match-beginning 2) (match-end 2)))))
3864 do (progn (when lang (markdown-add-language-if-new lang))
3865 (goto-char (next-single-property-change (point) prop)))))))
3868 ;;; Footnotes ==================================================================
3870 (defun markdown-footnote-counter-inc ()
3871 "Increment `markdown-footnote-counter' and return the new value."
3872 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
3873 (save-excursion
3874 (goto-char (point-min))
3875 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
3876 (point-max) t)
3877 (let ((fn (string-to-number (match-string 1))))
3878 (when (> fn markdown-footnote-counter)
3879 (setq markdown-footnote-counter fn))))))
3880 (cl-incf markdown-footnote-counter))
3882 (defun markdown-insert-footnote ()
3883 "Insert footnote with a new number and move point to footnote definition."
3884 (interactive)
3885 (let ((fn (markdown-footnote-counter-inc)))
3886 (insert (format "[^%d]" fn))
3887 (markdown-footnote-text-find-new-location)
3888 (markdown-ensure-blank-line-before)
3889 (unless (markdown-cur-line-blank-p)
3890 (insert "\n"))
3891 (insert (format "[^%d]: " fn))
3892 (markdown-ensure-blank-line-after)))
3894 (defun markdown-footnote-text-find-new-location ()
3895 "Position the cursor at the proper location for a new footnote text."
3896 (cond
3897 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
3898 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
3899 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
3901 (defun markdown-footnote-kill ()
3902 "Kill the footnote at point.
3903 The footnote text is killed (and added to the kill ring), the
3904 footnote marker is deleted. Point has to be either at the
3905 footnote marker or in the footnote text."
3906 (interactive)
3907 (let ((marker-pos nil)
3908 (skip-deleting-marker nil)
3909 (starting-footnote-text-positions
3910 (markdown-footnote-text-positions)))
3911 (when starting-footnote-text-positions
3912 ;; We're starting in footnote text, so mark our return position and jump
3913 ;; to the marker if possible.
3914 (let ((marker-pos (markdown-footnote-find-marker
3915 (cl-first starting-footnote-text-positions))))
3916 (if marker-pos
3917 (goto-char (1- marker-pos))
3918 ;; If there isn't a marker, we still want to kill the text.
3919 (setq skip-deleting-marker t))))
3920 ;; Either we didn't start in the text, or we started in the text and jumped
3921 ;; to the marker. We want to assume we're at the marker now and error if
3922 ;; we're not.
3923 (unless skip-deleting-marker
3924 (let ((marker (markdown-footnote-delete-marker)))
3925 (unless marker
3926 (error "Not at a footnote"))
3927 ;; Even if we knew the text position before, it changed when we deleted
3928 ;; the label.
3929 (setq marker-pos (cl-second marker))
3930 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
3931 (unless new-text-pos
3932 (error "No text for footnote `%s'" (cl-first marker)))
3933 (goto-char new-text-pos))))
3934 (let ((pos (markdown-footnote-kill-text)))
3935 (goto-char (if starting-footnote-text-positions
3937 marker-pos)))))
3939 (defun markdown-footnote-delete-marker ()
3940 "Delete a footnote marker at point.
3941 Returns a list (ID START) containing the footnote ID and the
3942 start position of the marker before deletion. If no footnote
3943 marker was deleted, this function returns NIL."
3944 (let ((marker (markdown-footnote-marker-positions)))
3945 (when marker
3946 (delete-region (cl-second marker) (cl-third marker))
3947 (butlast marker))))
3949 (defun markdown-footnote-kill-text ()
3950 "Kill footnote text at point.
3951 Returns the start position of the footnote text before deletion,
3952 or NIL if point was not inside a footnote text.
3954 The killed text is placed in the kill ring (without the footnote
3955 number)."
3956 (let ((fn (markdown-footnote-text-positions)))
3957 (when fn
3958 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
3959 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
3960 (kill-new (match-string 1 text))
3961 (when (and (markdown-cur-line-blank-p)
3962 (markdown-prev-line-blank-p)
3963 (not (bobp)))
3964 (delete-region (1- (point)) (point)))
3965 (cl-second fn)))))
3967 (defun markdown-footnote-goto-text ()
3968 "Jump to the text of the footnote at point."
3969 (interactive)
3970 (let ((fn (car (markdown-footnote-marker-positions))))
3971 (unless fn
3972 (error "Not at a footnote marker"))
3973 (let ((new-pos (markdown-footnote-find-text fn)))
3974 (unless new-pos
3975 (error "No definition found for footnote `%s'" fn))
3976 (goto-char new-pos))))
3978 (defun markdown-footnote-return ()
3979 "Return from a footnote to its footnote number in the main text."
3980 (interactive)
3981 (let ((fn (save-excursion
3982 (car (markdown-footnote-text-positions)))))
3983 (unless fn
3984 (error "Not in a footnote"))
3985 (let ((new-pos (markdown-footnote-find-marker fn)))
3986 (unless new-pos
3987 (error "Footnote marker `%s' not found" fn))
3988 (goto-char new-pos))))
3990 (defun markdown-footnote-find-marker (id)
3991 "Find the location of the footnote marker with ID.
3992 The actual buffer position returned is the position directly
3993 following the marker's closing bracket. If no marker is found,
3994 NIL is returned."
3995 (save-excursion
3996 (goto-char (point-min))
3997 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
3998 (skip-chars-backward "^]")
3999 (point))))
4001 (defun markdown-footnote-find-text (id)
4002 "Find the location of the text of footnote ID.
4003 The actual buffer position returned is the position of the first
4004 character of the text, after the footnote's identifier. If no
4005 footnote text is found, NIL is returned."
4006 (save-excursion
4007 (goto-char (point-min))
4008 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
4009 (skip-chars-forward "[ \t]")
4010 (point))))
4012 (defun markdown-footnote-marker-positions ()
4013 "Return the position and ID of the footnote marker point is on.
4014 The return value is a list (ID START END). If point is not on a
4015 footnote, NIL is returned."
4016 ;; first make sure we're at a footnote marker
4017 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4018 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4019 (save-excursion
4020 ;; move point between [ and ^:
4021 (if (looking-at-p "\\[")
4022 (forward-char 1)
4023 (skip-chars-backward "^["))
4024 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4025 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4027 (defun markdown-footnote-text-positions ()
4028 "Return the start and end positions of the footnote text point is in.
4029 The exact return value is a list of three elements: (ID START END).
4030 The start position is the position of the opening bracket
4031 of the footnote id. The end position is directly after the
4032 newline that ends the footnote. If point is not in a footnote,
4033 NIL is returned instead."
4034 (save-excursion
4035 (let (result)
4036 (move-beginning-of-line 1)
4037 ;; Try to find the label. If we haven't found the label and we're at a blank
4038 ;; or indented line, back up if possible.
4039 (while (and
4040 (not (and (looking-at markdown-regex-footnote-definition)
4041 (setq result (list (match-string 1) (point)))))
4042 (and (not (bobp))
4043 (or (markdown-cur-line-blank-p)
4044 (>= (current-indentation) 4))))
4045 (forward-line -1))
4046 (when result
4047 ; Advance if there is a next line that is either blank or indented.
4048 ; (Need to check if we're on the last line, because
4049 ; markdown-next-line-blank-p returns true for last line in buffer.)
4050 (while (and (/= (line-end-position) (point-max))
4051 (or (markdown-next-line-blank-p)
4052 (>= (markdown-next-line-indent) 4)))
4053 (forward-line))
4054 ; Move back while the current line is blank.
4055 (while (markdown-cur-line-blank-p)
4056 (forward-line -1))
4057 ; Advance to capture this line and a single trailing newline (if there
4058 ; is one).
4059 (forward-line)
4060 (append result (list (point)))))))
4063 ;;; Element Removal ===========================================================
4065 (defun markdown-kill-thing-at-point ()
4066 "Kill thing at point and add important text, without markup, to kill ring.
4067 Possible things to kill include (roughly in order of precedence):
4068 inline code, headers, horizonal rules, links (add link text to
4069 kill ring), images (add alt text to kill ring), angle uri, email
4070 addresses, bold, italics, reference definition (add URI to kill
4071 ring), footnote markers and text (kill both marker and text, add
4072 text to kill ring), and list items."
4073 (interactive "*")
4074 (let (val)
4075 (cond
4076 ;; Inline code
4077 ((markdown-code-at-point-p)
4078 (kill-new (match-string 2))
4079 (delete-region (match-beginning 0) (match-end 0)))
4080 ;; ATX header
4081 ((thing-at-point-looking-at markdown-regex-header-atx)
4082 (kill-new (match-string 2))
4083 (delete-region (match-beginning 0) (match-end 0)))
4084 ;; Setext header
4085 ((thing-at-point-looking-at markdown-regex-header-setext)
4086 (kill-new (match-string 1))
4087 (delete-region (match-beginning 0) (match-end 0)))
4088 ;; Horizonal rule
4089 ((thing-at-point-looking-at markdown-regex-hr)
4090 (kill-new (match-string 0))
4091 (delete-region (match-beginning 0) (match-end 0)))
4092 ;; Inline link or image (add link or alt text to kill ring)
4093 ((thing-at-point-looking-at markdown-regex-link-inline)
4094 (kill-new (match-string 3))
4095 (delete-region (match-beginning 0) (match-end 0)))
4096 ;; Reference link or image (add link or alt text to kill ring)
4097 ((thing-at-point-looking-at markdown-regex-link-reference)
4098 (kill-new (match-string 3))
4099 (delete-region (match-beginning 0) (match-end 0)))
4100 ;; Angle URI (add URL to kill ring)
4101 ((thing-at-point-looking-at markdown-regex-angle-uri)
4102 (kill-new (match-string 2))
4103 (delete-region (match-beginning 0) (match-end 0)))
4104 ;; Email address in angle brackets (add email address to kill ring)
4105 ((thing-at-point-looking-at markdown-regex-email)
4106 (kill-new (match-string 1))
4107 (delete-region (match-beginning 0) (match-end 0)))
4108 ;; Wiki link (add alias text to kill ring)
4109 ((and markdown-enable-wiki-links
4110 (thing-at-point-looking-at markdown-regex-wiki-link))
4111 (kill-new (markdown-wiki-link-alias))
4112 (delete-region (match-beginning 1) (match-end 1)))
4113 ;; Bold
4114 ((thing-at-point-looking-at markdown-regex-bold)
4115 (kill-new (match-string 4))
4116 (delete-region (match-beginning 2) (match-end 2)))
4117 ;; Italics
4118 ((thing-at-point-looking-at markdown-regex-italic)
4119 (kill-new (match-string 3))
4120 (delete-region (match-beginning 1) (match-end 1)))
4121 ;; Strikethrough
4122 ((thing-at-point-looking-at markdown-regex-strike-through)
4123 (kill-new (match-string 4))
4124 (delete-region (match-beginning 2) (match-end 2)))
4125 ;; Footnote marker (add footnote text to kill ring)
4126 ((thing-at-point-looking-at markdown-regex-footnote)
4127 (markdown-footnote-kill))
4128 ;; Footnote text (add footnote text to kill ring)
4129 ((setq val (markdown-footnote-text-positions))
4130 (markdown-footnote-kill))
4131 ;; Reference definition (add URL to kill ring)
4132 ((thing-at-point-looking-at markdown-regex-reference-definition)
4133 (kill-new (match-string 5))
4134 (delete-region (match-beginning 0) (match-end 0)))
4135 ;; List item
4136 ((setq val (markdown-cur-list-item-bounds))
4137 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4139 (error "Nothing found at point to kill")))))
4142 ;;; Indentation ====================================================================
4144 (defun markdown-indent-find-next-position (cur-pos positions)
4145 "Return the position after the index of CUR-POS in POSITIONS.
4146 Positions are calculated by `markdown-calc-indents'."
4147 (while (and positions
4148 (not (equal cur-pos (car positions))))
4149 (setq positions (cdr positions)))
4150 (or (cadr positions) 0))
4152 (defun markdown-exdent-find-next-position (cur-pos positions)
4153 "Return the maximal element that precedes CUR-POS from POSITIONS.
4154 Positions are calculated by `markdown-calc-indents'."
4155 (let ((result 0))
4156 (dolist (i positions)
4157 (when (< i cur-pos)
4158 (setq result (max result i))))
4159 result))
4161 (defun markdown-indent-line ()
4162 "Indent the current line using some heuristics.
4163 If the _previous_ command was either `markdown-enter-key' or
4164 `markdown-cycle', then we should cycle to the next
4165 reasonable indentation position. Otherwise, we could have been
4166 called directly by `markdown-enter-key', by an initial call of
4167 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4168 these cases, indent to the default position.
4169 Positions are calculated by `markdown-calc-indents'."
4170 (interactive)
4171 (let ((positions (markdown-calc-indents))
4172 (cursor-pos (current-column))
4173 (_ (back-to-indentation))
4174 (cur-pos (current-column)))
4175 (if (not (equal this-command 'markdown-cycle))
4176 (indent-line-to (car positions))
4177 (setq positions (sort (delete-dups positions) '<))
4178 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4179 (new-cursor-pos
4180 (if (< cur-pos next-pos)
4181 (+ cursor-pos (- next-pos cur-pos))
4182 (- cursor-pos cur-pos))))
4183 (indent-line-to next-pos)
4184 (move-to-column new-cursor-pos)))))
4186 (defun markdown-calc-indents ()
4187 "Return a list of indentation columns to cycle through.
4188 The first element in the returned list should be considered the
4189 default indentation level. This function does not worry about
4190 duplicate positions, which are handled up by calling functions."
4191 (let (pos prev-line-pos positions)
4193 ;; Indentation of previous line
4194 (setq prev-line-pos (markdown-prev-line-indent))
4195 (setq positions (cons prev-line-pos positions))
4197 ;; Indentation of previous non-list-marker text
4198 (when (setq pos (markdown-prev-non-list-indent))
4199 (setq positions (cons pos positions)))
4201 ;; Indentation required for a pre block in current context
4202 (setq pos (length (markdown-pre-indentation (point))))
4203 (setq positions (cons pos positions))
4205 ;; Indentation of the previous line + tab-width
4206 (if prev-line-pos
4207 (setq positions (cons (+ prev-line-pos tab-width) positions))
4208 (setq positions (cons tab-width positions)))
4210 ;; Indentation of the previous line - tab-width
4211 (if (and prev-line-pos (> prev-line-pos tab-width))
4212 (setq positions (cons (- prev-line-pos tab-width) positions)))
4214 ;; Indentation of all preceeding list markers (when in a list)
4215 (when (setq pos (markdown-calculate-list-levels))
4216 (setq positions (append pos positions)))
4218 ;; First column
4219 (setq positions (cons 0 positions))
4221 ;; Return reversed list
4222 (reverse positions)))
4224 (defun markdown-enter-key ()
4225 "Handle RET according to to the value of `markdown-indent-on-enter'."
4226 (interactive)
4227 (newline)
4228 (when markdown-indent-on-enter
4229 (markdown-indent-line)))
4231 (defun markdown-exdent-or-delete (arg)
4232 "Handle BACKSPACE by cycling through indentation points.
4233 When BACKSPACE is pressed, if there is only whitespace
4234 before the current point, then exdent the line one level.
4235 Otherwise, do normal delete by repeating
4236 `backward-delete-char-untabify' ARG times."
4237 (interactive "*p")
4238 (let ((cur-pos (current-column))
4239 (start-of-indention (save-excursion
4240 (back-to-indentation)
4241 (current-column)))
4242 (positions (markdown-calc-indents)))
4243 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4244 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
4245 (backward-delete-char-untabify arg))))
4247 (defun markdown-find-leftmost-column (beg end)
4248 "Find the leftmost column in the region from BEG to END."
4249 (let ((mincol 1000))
4250 (save-excursion
4251 (goto-char beg)
4252 (while (< (point) end)
4253 (back-to-indentation)
4254 (unless (looking-at-p "[ \t]*$")
4255 (setq mincol (min mincol (current-column))))
4256 (forward-line 1)
4258 mincol))
4260 (defun markdown-indent-region (beg end arg)
4261 "Indent the region from BEG to END using some heuristics.
4262 When ARG is non-nil, exdent the region instead.
4263 See `markdown-indent-line' and `markdown-indent-line'."
4264 (interactive "*r\nP")
4265 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4266 (leftmostcol (markdown-find-leftmost-column beg end))
4267 (next-pos (if arg
4268 (markdown-exdent-find-next-position leftmostcol positions)
4269 (markdown-indent-find-next-position leftmostcol positions))))
4270 (indent-rigidly beg end (- next-pos leftmostcol))
4271 (setq deactivate-mark nil)))
4273 (defun markdown-exdent-region (beg end)
4274 "Call `markdown-indent-region' on region from BEG to END with prefix."
4275 (interactive "*r")
4276 (markdown-indent-region beg end t))
4279 ;;; Markup Completion =========================================================
4281 (defconst markdown-complete-alist
4282 '((markdown-regex-header-atx . markdown-complete-atx)
4283 (markdown-regex-header-setext . markdown-complete-setext)
4284 (markdown-regex-hr . markdown-complete-hr))
4285 "Association list of form (regexp . function) for markup completion.")
4287 (defun markdown-incomplete-atx-p ()
4288 "Return t if ATX header markup is incomplete and nil otherwise.
4289 Assumes match data is available for `markdown-regex-header-atx'.
4290 Checks that the number of trailing hash marks equals the number of leading
4291 hash marks, that there is only a single space before and after the text,
4292 and that there is no extraneous whitespace in the text."
4294 ;; Number of starting and ending hash marks differs
4295 (not (= (length (match-string 1)) (length (match-string 3))))
4296 ;; When the header text is not empty...
4297 (and (> (length (match-string 2)) 0)
4298 ;; ...if there are extra leading, trailing, or interior spaces
4299 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4300 (not (= (match-beginning 3) (1+ (match-end 2))))
4301 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4302 ;; When the header text is empty...
4303 (and (= (length (match-string 2)) 0)
4304 ;; ...if there are too many or too few spaces
4305 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4307 (defun markdown-complete-atx ()
4308 "Complete and normalize ATX headers.
4309 Add or remove hash marks to the end of the header to match the
4310 beginning. Ensure that there is only a single space between hash
4311 marks and header text. Removes extraneous whitespace from header text.
4312 Assumes match data is available for `markdown-regex-header-atx'.
4313 Return nil if markup was complete and non-nil if markup was completed."
4314 (when (markdown-incomplete-atx-p)
4315 (let* ((new-marker (make-marker))
4316 (new-marker (set-marker new-marker (match-end 2))))
4317 ;; Hash marks and spacing at end
4318 (goto-char (match-end 2))
4319 (delete-region (match-end 2) (match-end 3))
4320 (insert " " (match-string 1))
4321 ;; Remove extraneous whitespace from title
4322 (replace-match (markdown-compress-whitespace-string (match-string 2))
4323 t t nil 2)
4324 ;; Spacing at beginning
4325 (goto-char (match-end 1))
4326 (delete-region (match-end 1) (match-beginning 2))
4327 (insert " ")
4328 ;; Leave point at end of text
4329 (goto-char new-marker))))
4331 (defun markdown-incomplete-setext-p ()
4332 "Return t if setext header markup is incomplete and nil otherwise.
4333 Assumes match data is available for `markdown-regex-header-setext'.
4334 Checks that length of underline matches text and that there is no
4335 extraneous whitespace in the text."
4336 (or (not (= (length (match-string 1)) (length (match-string 2))))
4337 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4339 (defun markdown-complete-setext ()
4340 "Complete and normalize setext headers.
4341 Add or remove underline characters to match length of header
4342 text. Removes extraneous whitespace from header text. Assumes
4343 match data is available for `markdown-regex-header-setext'.
4344 Return nil if markup was complete and non-nil if markup was completed."
4345 (when (markdown-incomplete-setext-p)
4346 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4347 (char (char-after (match-beginning 2)))
4348 (level (if (char-equal char ?-) 2 1)))
4349 (goto-char (match-beginning 0))
4350 (delete-region (match-beginning 0) (match-end 0))
4351 (markdown-insert-header level text t)
4352 t)))
4354 (defun markdown-incomplete-hr-p ()
4355 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4356 Assumes match data is available for `markdown-regex-hr'."
4357 (not (member (match-string 0) markdown-hr-strings)))
4359 (defun markdown-complete-hr ()
4360 "Complete horizontal rules.
4361 If horizontal rule string is a member of `markdown-hr-strings',
4362 do nothing. Otherwise, replace with the car of
4363 `markdown-hr-strings'.
4364 Assumes match data is available for `markdown-regex-hr'.
4365 Return nil if markup was complete and non-nil if markup was completed."
4366 (when (markdown-incomplete-hr-p)
4367 (replace-match (car markdown-hr-strings))
4370 (defun markdown-complete ()
4371 "Complete markup of object near point or in region when active.
4372 Handle all objects in `markdown-complete-alist', in order.
4373 See `markdown-complete-at-point' and `markdown-complete-region'."
4374 (interactive "*")
4375 (if (markdown-use-region-p)
4376 (markdown-complete-region (region-beginning) (region-end))
4377 (markdown-complete-at-point)))
4379 (defun markdown-complete-at-point ()
4380 "Complete markup of object near point.
4381 Handle all elements of `markdown-complete-alist' in order."
4382 (interactive "*")
4383 (let ((list markdown-complete-alist) found changed)
4384 (while list
4385 (let ((regexp (eval (caar list)))
4386 (function (cdar list)))
4387 (setq list (cdr list))
4388 (when (thing-at-point-looking-at regexp)
4389 (setq found t)
4390 (setq changed (funcall function))
4391 (setq list nil))))
4392 (if found
4393 (or changed (error "Markup at point is complete"))
4394 (error "Nothing to complete at point"))))
4396 (defun markdown-complete-region (beg end)
4397 "Complete markup of objects in region from BEG to END.
4398 Handle all objects in `markdown-complete-alist', in order. Each
4399 match is checked to ensure that a previous regexp does not also
4400 match."
4401 (interactive "*r")
4402 (let ((end-marker (set-marker (make-marker) end))
4403 previous)
4404 (dolist (element markdown-complete-alist)
4405 (let ((regexp (eval (car element)))
4406 (function (cdr element)))
4407 (goto-char beg)
4408 (while (re-search-forward regexp end-marker 'limit)
4409 (when (match-string 0)
4410 ;; Make sure this is not a match for any of the preceding regexps.
4411 ;; This prevents mistaking an HR for a Setext subheading.
4412 (let (match)
4413 (save-match-data
4414 (dolist (prev-regexp previous)
4415 (or match (setq match (looking-back prev-regexp nil)))))
4416 (unless match
4417 (save-excursion (funcall function))))))
4418 (cl-pushnew regexp previous :test #'equal)))
4419 previous))
4421 (defun markdown-complete-buffer ()
4422 "Complete markup for all objects in the current buffer."
4423 (interactive "*")
4424 (markdown-complete-region (point-min) (point-max)))
4427 ;;; Markup Cycling ============================================================
4429 (defun markdown-cycle-atx (arg &optional remove)
4430 "Cycle ATX header markup.
4431 Promote header (decrease level) when ARG is 1 and demote
4432 header (increase level) if arg is -1. When REMOVE is non-nil,
4433 remove the header when the level reaches zero and stop cycling
4434 when it reaches six. Otherwise, perform a proper cycling through
4435 levels one through six. Assumes match data is available for
4436 `markdown-regex-header-atx'."
4437 (let* ((old-level (length (match-string 1)))
4438 (new-level (+ old-level arg))
4439 (text (match-string 2)))
4440 (when (not remove)
4441 (setq new-level (% new-level 6))
4442 (setq new-level (cond ((= new-level 0) 6)
4443 ((< new-level 0) (+ new-level 6))
4444 (t new-level))))
4445 (cond
4446 ((= new-level 0)
4447 (markdown-unwrap-thing-at-point nil 0 2))
4448 ((<= new-level 6)
4449 (goto-char (match-beginning 0))
4450 (delete-region (match-beginning 0) (match-end 0))
4451 (markdown-insert-header new-level text nil)))))
4453 (defun markdown-cycle-setext (arg &optional remove)
4454 "Cycle setext header markup.
4455 Promote header (increase level) when ARG is 1 and demote
4456 header (decrease level or remove) if arg is -1. When demoting a
4457 level-two setext header, replace with a level-three atx header.
4458 When REMOVE is non-nil, remove the header when the level reaches
4459 zero. Otherwise, cycle back to a level six atx header. Assumes
4460 match data is available for `markdown-regex-header-setext'."
4461 (let* ((char (char-after (match-beginning 2)))
4462 (old-level (if (char-equal char ?=) 1 2))
4463 (new-level (+ old-level arg)))
4464 (when (and (not remove) (= new-level 0))
4465 (setq new-level 6))
4466 (cond
4467 ((= new-level 0)
4468 (markdown-unwrap-thing-at-point nil 0 1))
4469 ((<= new-level 2)
4470 (markdown-insert-header new-level nil t))
4471 ((<= new-level 6)
4472 (markdown-insert-header new-level nil nil)))))
4474 (defun markdown-cycle-hr (arg &optional remove)
4475 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4476 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4477 backwards (promote). When REMOVE is non-nil, remove the hr instead
4478 of cycling when the end of the list is reached.
4479 Assumes match data is available for `markdown-regex-hr'."
4480 (let* ((strings (if (= arg -1)
4481 (reverse markdown-hr-strings)
4482 markdown-hr-strings))
4483 (tail (member (match-string 0) strings))
4484 (new (or (cadr tail)
4485 (if remove
4486 (if (= arg 1)
4488 (car tail))
4489 (car strings)))))
4490 (replace-match new)))
4492 (defun markdown-cycle-bold ()
4493 "Cycle bold markup between underscores and asterisks.
4494 Assumes match data is available for `markdown-regex-bold'."
4495 (save-excursion
4496 (let* ((old-delim (match-string 3))
4497 (new-delim (if (string-equal old-delim "**") "__" "**")))
4498 (replace-match new-delim t t nil 3)
4499 (replace-match new-delim t t nil 5))))
4501 (defun markdown-cycle-italic ()
4502 "Cycle italic markup between underscores and asterisks.
4503 Assumes match data is available for `markdown-regex-italic'."
4504 (save-excursion
4505 (let* ((old-delim (match-string 2))
4506 (new-delim (if (string-equal old-delim "*") "_" "*")))
4507 (replace-match new-delim t t nil 2)
4508 (replace-match new-delim t t nil 4))))
4511 ;;; Keymap ====================================================================
4513 (defvar markdown-mode-map
4514 (let ((map (make-keymap)))
4515 ;; Element insertion
4516 (define-key map "\C-c\C-al" 'markdown-insert-link)
4517 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
4518 (define-key map "\C-c\C-au" 'markdown-insert-uri)
4519 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
4520 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
4521 (define-key map "\C-c\C-ii" 'markdown-insert-image)
4522 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
4523 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
4524 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
4525 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
4526 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
4527 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
4528 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
4529 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
4530 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
4531 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
4532 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
4533 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
4534 (define-key map "\C-c\C-se" 'markdown-insert-italic)
4535 (define-key map "\C-c\C-sc" 'markdown-insert-code)
4536 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
4537 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
4538 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
4539 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
4540 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
4541 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
4542 (define-key map "\C-c-" 'markdown-insert-hr)
4543 ;; Element insertion (deprecated)
4544 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
4545 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
4546 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
4547 ;; Element removal
4548 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
4549 ;; Promotion, Demotion, Completion, and Cycling
4550 (define-key map (kbd "C-c C--") 'markdown-promote)
4551 (define-key map (kbd "C-c C-=") 'markdown-demote)
4552 (define-key map (kbd "C-c C-]") 'markdown-complete)
4553 ;; Following and Jumping
4554 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
4555 (define-key map (kbd "C-c C-l") 'markdown-jump)
4556 ;; Indentation
4557 (define-key map (kbd "C-m") 'markdown-enter-key)
4558 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
4559 (define-key map (kbd "C-c >") 'markdown-indent-region)
4560 (define-key map (kbd "C-c <") 'markdown-exdent-region)
4561 ;; Visibility cycling
4562 (define-key map (kbd "TAB") 'markdown-cycle)
4563 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
4564 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
4565 (define-key map (kbd "<backtab>") 'markdown-shifttab)
4566 ;; Header navigation
4567 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
4568 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
4569 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
4570 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
4571 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
4572 ;; Buffer-wide commands
4573 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
4574 (define-key map (kbd "C-c C-c p") 'markdown-preview)
4575 (define-key map (kbd "C-c C-c e") 'markdown-export)
4576 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
4577 (define-key map (kbd "C-c C-c o") 'markdown-open)
4578 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
4579 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
4580 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
4581 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
4582 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
4583 ;; List editing
4584 (define-key map (kbd "M-<up>") 'markdown-move-up)
4585 (define-key map (kbd "M-<down>") 'markdown-move-down)
4586 (define-key map (kbd "M-<left>") 'markdown-promote)
4587 (define-key map (kbd "M-<right>") 'markdown-demote)
4588 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
4589 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
4590 ;; Subtree editing
4591 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
4592 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
4593 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
4594 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
4595 ;; Movement
4596 (define-key map (kbd "M-{") 'markdown-backward-paragraph)
4597 (define-key map (kbd "M-}") 'markdown-forward-paragraph)
4598 (define-key map (kbd "M-n") 'markdown-next-link)
4599 (define-key map (kbd "M-p") 'markdown-previous-link)
4600 ;; Alternative keys (in case of problems with the arrow keys)
4601 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
4602 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
4603 (define-key map (kbd "C-c C-x l") 'markdown-promote)
4604 (define-key map (kbd "C-c C-x r") 'markdown-demote)
4605 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
4606 map)
4607 "Keymap for Markdown major mode.")
4609 (defvar gfm-mode-map
4610 (let ((map (make-sparse-keymap)))
4611 (set-keymap-parent map markdown-mode-map)
4612 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
4613 (define-key map "`" 'markdown-electric-backquote)
4614 map)
4615 "Keymap for `gfm-mode'.
4616 See also `markdown-mode-map'.")
4619 ;;; Menu ==================================================================
4621 (easy-menu-define markdown-mode-menu markdown-mode-map
4622 "Menu for Markdown mode"
4623 '("Markdown"
4624 ("Show/Hide"
4625 ["Cycle visibility" markdown-cycle (markdown-on-heading-p)]
4626 ["Cycle global visibility" markdown-shifttab])
4627 "---"
4628 ["Compile" markdown-other-window]
4629 ["Preview" markdown-preview]
4630 ["Export" markdown-export]
4631 ["Export & View" markdown-export-and-preview]
4632 ["Open" markdown-open]
4633 ["Live Export" markdown-live-preview-mode
4634 :style toggle :selected markdown-live-preview-mode]
4635 ["Kill ring save" markdown-kill-ring-save]
4636 "---"
4637 ("Headings"
4638 ["Automatic" markdown-insert-header-dwim]
4639 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
4640 "---"
4641 ["First level setext" markdown-insert-header-setext-1]
4642 ["Second level setext" markdown-insert-header-setext-2]
4643 "---"
4644 ["First level atx" markdown-insert-header-atx-1]
4645 ["Second level atx" markdown-insert-header-atx-2]
4646 ["Third level atx" markdown-insert-header-atx-3]
4647 ["Fourth level atx" markdown-insert-header-atx-4]
4648 ["Fifth level atx" markdown-insert-header-atx-5]
4649 ["Sixth level atx" markdown-insert-header-atx-6])
4650 "---"
4651 ["Bold" markdown-insert-bold]
4652 ["Italic" markdown-insert-italic]
4653 ["Strikethrough" markdown-insert-strike-through]
4654 ["Blockquote" markdown-insert-blockquote]
4655 ["Preformatted" markdown-insert-pre]
4656 ["Code" markdown-insert-code]
4657 "---"
4658 ["Insert inline link" markdown-insert-link]
4659 ["Insert reference link" markdown-insert-reference-link-dwim]
4660 ["Insert URL" markdown-insert-uri]
4661 ["Insert inline image" markdown-insert-image]
4662 ["Insert reference image" markdown-insert-reference-image]
4663 ["Insert list item" markdown-insert-list-item]
4664 ["Insert horizontal rule" markdown-insert-hr]
4665 ["Insert footnote" markdown-insert-footnote]
4666 ["Kill element" markdown-kill-thing-at-point]
4667 "---"
4668 ["Jump" markdown-jump]
4669 ["Follow link" markdown-follow-thing-at-point]
4670 ("Outline"
4671 ["Next visible heading" markdown-next-visible-heading]
4672 ["Previous visible heading" markdown-previous-visible-heading]
4673 ["Forward same level" markdown-forward-same-level]
4674 ["Backward same level" markdown-backward-same-level]
4675 ["Up to parent heading" markdown-up-heading])
4676 "---"
4677 ("Completion and Cycling"
4678 ["Complete" markdown-complete]
4679 ["Promote" markdown-promote]
4680 ["Demote" markdown-demote])
4681 ("List editing"
4682 ["Indent list item" markdown-demote]
4683 ["Exdent list item" markdown-promote])
4684 ("Region shifting"
4685 ["Indent region" markdown-indent-region]
4686 ["Exdent region" markdown-exdent-region])
4687 "---"
4688 ["Check references" markdown-check-refs]
4689 ["Clean up list numbering" markdown-cleanup-list-numbers]
4690 ["Complete markup" markdown-complete-buffer]
4691 "---"
4692 ["Version" markdown-show-version]
4696 ;;; imenu =====================================================================
4698 (defun markdown-imenu-create-nested-index ()
4699 "Create and return a nested imenu index alist for the current buffer.
4700 See `imenu-create-index-function' and `imenu--index-alist' for details."
4701 (let* ((root '(nil . nil))
4702 cur-alist
4703 (cur-level 0)
4704 (empty-heading "-")
4705 (self-heading ".")
4706 hashes pos level heading)
4707 (save-excursion
4708 (goto-char (point-min))
4709 (while (re-search-forward markdown-regex-header (point-max) t)
4710 (unless (markdown-code-block-at-point)
4711 (cond
4712 ((match-string-no-properties 2) ;; level 1 setext
4713 (setq heading (match-string-no-properties 1))
4714 (setq pos (match-beginning 1)
4715 level 1))
4716 ((match-string-no-properties 3) ;; level 2 setext
4717 (setq heading (match-string-no-properties 1))
4718 (setq pos (match-beginning 1)
4719 level 2))
4720 ((setq hashes (match-string-no-properties 4))
4721 (setq heading (match-string-no-properties 5)
4722 pos (match-beginning 4)
4723 level (length hashes))))
4724 (let ((alist (list (cons heading pos))))
4725 (cond
4726 ((= cur-level level) ; new sibling
4727 (setcdr cur-alist alist)
4728 (setq cur-alist alist))
4729 ((< cur-level level) ; first child
4730 (dotimes (_ (- level cur-level 1))
4731 (setq alist (list (cons empty-heading alist))))
4732 (if cur-alist
4733 (let* ((parent (car cur-alist))
4734 (self-pos (cdr parent)))
4735 (setcdr parent (cons (cons self-heading self-pos) alist)))
4736 (setcdr root alist)) ; primogenitor
4737 (setq cur-alist alist)
4738 (setq cur-level level))
4739 (t ; new sibling of an ancestor
4740 (let ((sibling-alist (last (cdr root))))
4741 (dotimes (_ (1- level))
4742 (setq sibling-alist (last (cdar sibling-alist))))
4743 (setcdr sibling-alist alist)
4744 (setq cur-alist alist))
4745 (setq cur-level level))))))
4746 (cdr root))))
4748 (defun markdown-imenu-create-flat-index ()
4749 "Create and return a flat imenu index alist for the current buffer.
4750 See `imenu-create-index-function' and `imenu--index-alist' for details."
4751 (let* ((empty-heading "-") index heading pos)
4752 (save-excursion
4753 (goto-char (point-min))
4754 (while (re-search-forward markdown-regex-header (point-max) t)
4755 (cond
4756 ((setq heading (match-string-no-properties 1))
4757 (setq pos (match-beginning 1)))
4758 ((setq heading (match-string-no-properties 5))
4759 (setq pos (match-beginning 4))))
4760 (or (> (length heading) 0)
4761 (setq heading empty-heading))
4762 (setq index (append index (list (cons heading pos)))))
4763 index)))
4766 ;;; References ================================================================
4768 (defun markdown-reference-goto-definition ()
4769 "Jump to the definition of the reference at point or create it."
4770 (interactive)
4771 (when (thing-at-point-looking-at markdown-regex-link-reference)
4772 (let* ((text (match-string-no-properties 3))
4773 (reference (match-string-no-properties 6))
4774 (target (downcase (if (string= reference "") text reference)))
4775 (loc (cadr (markdown-reference-definition target))))
4776 (if loc
4777 (goto-char loc)
4778 (goto-char (match-beginning 0))
4779 (markdown-insert-reference-definition target)))))
4781 (defun markdown-reference-find-links (reference)
4782 "Return a list of all links for REFERENCE.
4783 REFERENCE should not include the surrounding square brackets.
4784 Elements of the list have the form (text start line), where
4785 text is the link text, start is the location at the beginning of
4786 the link, and line is the line number on which the link appears."
4787 (let* ((ref-quote (regexp-quote reference))
4788 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4789 ref-quote ref-quote))
4790 links)
4791 (save-excursion
4792 (goto-char (point-min))
4793 (while (re-search-forward regexp nil t)
4794 (let* ((text (or (match-string-no-properties 1)
4795 (match-string-no-properties 2)))
4796 (start (match-beginning 0))
4797 (line (markdown-line-number-at-pos)))
4798 (cl-pushnew (list text start line) links :test #'equal))))
4799 links))
4801 (defun markdown-get-undefined-refs ()
4802 "Return a list of undefined Markdown references.
4803 Result is an alist of pairs (reference . occurrences), where
4804 occurrences is itself another alist of pairs (label . line-number).
4805 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4806 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4807 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4808 (let ((missing))
4809 (save-excursion
4810 (goto-char (point-min))
4811 (while
4812 (re-search-forward markdown-regex-link-reference nil t)
4813 (let* ((text (match-string-no-properties 3))
4814 (reference (match-string-no-properties 6))
4815 (target (downcase (if (string= reference "") text reference))))
4816 (unless (markdown-reference-definition target)
4817 (let ((entry (assoc target missing)))
4818 (if (not entry)
4819 (cl-pushnew
4820 (cons target (list (cons text (markdown-line-number-at-pos))))
4821 missing :test #'equal)
4822 (setcdr entry
4823 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
4824 (reverse missing))))
4826 (defconst markdown-reference-check-buffer
4827 "*Undefined references for %buffer%*"
4828 "Pattern for name of buffer for listing undefined references.
4829 The string %buffer% will be replaced by the corresponding
4830 `markdown-mode' buffer name.")
4832 (defun markdown-reference-check-buffer (&optional buffer-name)
4833 "Name and return buffer for reference checking.
4834 BUFFER-NAME is the name of the main buffer being visited."
4835 (or buffer-name (setq buffer-name (buffer-name)))
4836 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
4837 "%buffer%" buffer-name
4838 markdown-reference-check-buffer))))
4839 (with-current-buffer refbuf
4840 (when view-mode
4841 (View-exit-and-edit))
4842 (use-local-map button-buffer-map)
4843 (erase-buffer))
4844 refbuf))
4846 (defconst markdown-reference-links-buffer
4847 "*Reference links for %buffer%*"
4848 "Pattern for name of buffer for listing references.
4849 The string %buffer% will be replaced by the corresponding buffer name.")
4851 (defun markdown-reference-links-buffer (&optional buffer-name)
4852 "Name, setup, and return a buffer for listing links.
4853 BUFFER-NAME is the name of the main buffer being visited."
4854 (or buffer-name (setq buffer-name (buffer-name)))
4855 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
4856 "%buffer%" buffer-name
4857 markdown-reference-links-buffer))))
4858 (with-current-buffer linkbuf
4859 (when view-mode
4860 (View-exit-and-edit))
4861 (use-local-map button-buffer-map)
4862 (erase-buffer))
4863 linkbuf))
4865 (when (markdown-use-buttons-p)
4866 ;; Add an empty Markdown reference definition to buffer
4867 ;; specified in the 'target-buffer property. The reference name is
4868 ;; the button's label.
4869 (define-button-type 'markdown-undefined-reference-button
4870 'help-echo "mouse-1, RET: create definition for undefined reference"
4871 'follow-link t
4872 'face 'bold
4873 'action (lambda (b)
4874 (let ((buffer (button-get b 'target-buffer))
4875 (line (button-get b 'target-line))
4876 (label (button-label b)))
4877 (switch-to-buffer-other-window buffer)
4878 (goto-char (point-min))
4879 (forward-line line)
4880 (markdown-insert-reference-definition label)
4881 (markdown-check-refs t))))
4883 ;; Jump to line in buffer specified by 'target-buffer property.
4884 ;; Line number is button's 'line property.
4885 (define-button-type 'markdown-goto-line-button
4886 'help-echo "mouse-1, RET: go to line"
4887 'follow-link t
4888 'face 'italic
4889 'action (lambda (b)
4890 (message (button-get b 'buffer))
4891 (switch-to-buffer-other-window (button-get b 'target-buffer))
4892 ;; use call-interactively to silence compiler
4893 (let ((current-prefix-arg (button-get b 'target-line)))
4894 (call-interactively 'goto-line))))
4896 ;; Jumps to a particular link at location given by 'target-char
4897 ;; property in buffer given by 'target-buffer property.
4898 (define-button-type 'markdown-link-button
4899 'help-echo "mouse-1, RET: jump to location of link"
4900 'follow-link t
4901 'face 'bold
4902 'action (lambda (b)
4903 (let ((target (button-get b 'target-buffer))
4904 (loc (button-get b 'target-char)))
4905 (kill-buffer-and-window)
4906 (switch-to-buffer target)
4907 (goto-char loc)))))
4909 (defun markdown-insert-undefined-reference-button (reference oldbuf)
4910 "Insert a button for creating REFERENCE in buffer OLDBUF.
4911 REFERENCE should be a list of the form (reference . occurrences),
4912 as by `markdown-get-undefined-refs'."
4913 (let ((label (car reference)))
4914 (if (markdown-use-buttons-p)
4915 ;; Create a reference button in Emacs 22
4916 (insert-button label
4917 :type 'markdown-undefined-reference-button
4918 'target-buffer oldbuf
4919 'target-line (cdr (car (cdr reference))))
4920 ;; Insert reference as text in Emacs < 22
4921 (insert label))
4922 (insert " (")
4923 (dolist (occurrence (cdr reference))
4924 (let ((line (cdr occurrence)))
4925 (if (markdown-use-buttons-p)
4926 ;; Create a line number button in Emacs 22
4927 (insert-button (number-to-string line)
4928 :type 'markdown-goto-line-button
4929 'target-buffer oldbuf
4930 'target-line line)
4931 ;; Insert line number as text in Emacs < 22
4932 (insert (number-to-string line)))
4933 (insert " ")))
4934 (delete-char -1)
4935 (insert ")")
4936 (newline)))
4938 (defun markdown-insert-link-button (link oldbuf)
4939 "Insert a button for jumping to LINK in buffer OLDBUF.
4940 LINK should be a list of the form (text char line) containing
4941 the link text, location, and line number."
4942 (let ((label (cl-first link))
4943 (char (cl-second link))
4944 (line (cl-third link)))
4945 (if (markdown-use-buttons-p)
4946 ;; Create a reference button in Emacs 22
4947 (insert-button label
4948 :type 'markdown-link-button
4949 'target-buffer oldbuf
4950 'target-char char)
4951 ;; Insert reference as text in Emacs < 22
4952 (insert label))
4953 (insert (format " (line %d)\n" line))))
4955 (defun markdown-reference-goto-link (&optional reference)
4956 "Jump to the location of the first use of REFERENCE."
4957 (interactive)
4958 (unless reference
4959 (if (thing-at-point-looking-at markdown-regex-reference-definition)
4960 (setq reference (match-string-no-properties 2))
4961 (error "No reference definition at point")))
4962 (let ((links (markdown-reference-find-links reference)))
4963 (cond ((= (length links) 1)
4964 (goto-char (cadr (car links))))
4965 ((> (length links) 1)
4966 (let ((oldbuf (current-buffer))
4967 (linkbuf (markdown-reference-links-buffer)))
4968 (with-current-buffer linkbuf
4969 (insert "Links using reference " reference ":\n\n")
4970 (dolist (link (reverse links))
4971 (markdown-insert-link-button link oldbuf)))
4972 (view-buffer-other-window linkbuf)
4973 (goto-char (point-min))
4974 (forward-line 2)))
4976 (error "No links for reference %s" reference)))))
4978 (defun markdown-check-refs (&optional silent)
4979 "Show all undefined Markdown references in current `markdown-mode' buffer.
4980 If SILENT is non-nil, do not message anything when no undefined
4981 references found.
4982 Links which have empty reference definitions are considered to be
4983 defined."
4984 (interactive "P")
4985 (when (not (eq major-mode 'markdown-mode))
4986 (error "Not available in current mode"))
4987 (let ((oldbuf (current-buffer))
4988 (refs (markdown-get-undefined-refs))
4989 (refbuf (markdown-reference-check-buffer)))
4990 (if (null refs)
4991 (progn
4992 (when (not silent)
4993 (message "No undefined references found"))
4994 (kill-buffer refbuf))
4995 (with-current-buffer refbuf
4996 (insert "The following references are undefined:\n\n")
4997 (dolist (ref refs)
4998 (markdown-insert-undefined-reference-button ref oldbuf))
4999 (view-buffer-other-window refbuf)
5000 (goto-char (point-min))
5001 (forward-line 2)))))
5004 ;;; Lists =====================================================================
5006 (defun markdown-insert-list-item (&optional arg)
5007 "Insert a new list item.
5008 If the point is inside unordered list, insert a bullet mark. If
5009 the point is inside ordered list, insert the next number followed
5010 by a period. Use the previous list item to determine the amount
5011 of whitespace to place before and after list markers.
5013 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5014 decrease the indentation by one level.
5016 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5017 increase the indentation by one level."
5018 (interactive "p")
5019 (let (bounds cur-indent marker indent new-indent new-loc)
5020 (save-match-data
5021 ;; Look for a list item on current or previous non-blank line
5022 (save-excursion
5023 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5024 (not (bobp))
5025 (markdown-cur-line-blank-p))
5026 (forward-line -1)))
5027 (when bounds
5028 (cond ((save-excursion
5029 (skip-chars-backward " \t")
5030 (looking-at-p markdown-regex-list))
5031 (beginning-of-line)
5032 (insert "\n")
5033 (forward-line -1))
5034 ((not (markdown-cur-line-blank-p))
5035 (newline)))
5036 (setq new-loc (point)))
5037 ;; Look ahead for a list item on next non-blank line
5038 (unless bounds
5039 (save-excursion
5040 (while (and (null bounds)
5041 (not (eobp))
5042 (markdown-cur-line-blank-p))
5043 (forward-line)
5044 (setq bounds (markdown-cur-list-item-bounds))))
5045 (when bounds
5046 (setq new-loc (point))
5047 (unless (markdown-cur-line-blank-p)
5048 (newline))))
5049 (if (not bounds)
5050 ;; When not in a list, start a new unordered one
5051 (progn
5052 (unless (markdown-cur-line-blank-p)
5053 (insert "\n"))
5054 (insert markdown-unordered-list-item-prefix))
5055 ;; Compute indentation and marker for new list item
5056 (setq cur-indent (nth 2 bounds))
5057 (setq marker (nth 4 bounds))
5058 (cond
5059 ;; Dedent: decrement indentation, find previous marker.
5060 ((= arg 4)
5061 (setq indent (max (- cur-indent 4) 0))
5062 (let ((prev-bounds
5063 (save-excursion
5064 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5065 (markdown-cur-list-item-bounds)))))
5066 (when prev-bounds
5067 (setq marker (nth 4 prev-bounds)))))
5068 ;; Indent: increment indentation by 4, use same marker.
5069 ((= arg 16) (setq indent (+ cur-indent 4)))
5070 ;; Same level: keep current indentation and marker.
5071 (t (setq indent cur-indent)))
5072 (setq new-indent (make-string indent 32))
5073 (goto-char new-loc)
5074 (cond
5075 ;; Ordered list
5076 ((string-match-p "[0-9]" marker)
5077 (if (= arg 16) ;; starting a new column indented one more level
5078 (insert (concat new-indent "1. "))
5079 ;; Don't use previous match-data
5080 (set-match-data nil)
5081 ;; travel up to the last item and pick the correct number. If
5082 ;; the argument was nil, "new-indent = cur-indent" is the same,
5083 ;; so we don't need special treatment. Neat.
5084 (save-excursion
5085 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5086 (>= (forward-line -1) 0))))
5087 (let* ((old-prefix (match-string 1))
5088 (old-spacing (match-string 2))
5089 (new-prefix (if old-prefix
5090 (int-to-string (1+ (string-to-number old-prefix)))
5091 "1"))
5092 (space-adjust (- (length old-prefix) (length new-prefix)))
5093 (new-spacing (if (and (match-string 2)
5094 (not (string-match-p "\t" old-spacing))
5095 (< space-adjust 0)
5096 (> space-adjust (- 1 (length (match-string 2)))))
5097 (substring (match-string 2) 0 space-adjust)
5098 (or old-spacing ". "))))
5099 (insert (concat new-indent new-prefix new-spacing)))))
5100 ;; Unordered list, or ordered list with hash mark
5101 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5102 (insert new-indent marker)))))))
5104 (defun markdown-move-list-item-up ()
5105 "Move the current list item up in the list when possible."
5106 (interactive)
5107 (let (cur prev old)
5108 (when (setq cur (markdown-cur-list-item-bounds))
5109 (setq old (point))
5110 (goto-char (nth 0 cur))
5111 (if (markdown-prev-list-item (nth 3 cur))
5112 (progn
5113 (setq prev (markdown-cur-list-item-bounds))
5114 (condition-case nil
5115 (progn
5116 (transpose-regions (nth 0 prev) (nth 1 prev)
5117 (nth 0 cur) (nth 1 cur) t)
5118 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5119 ;; Catch error in case regions overlap.
5120 (error (goto-char old))))
5121 (goto-char old)))))
5123 (defun markdown-move-list-item-down ()
5124 "Move the current list item down in the list when possible."
5125 (interactive)
5126 (let (cur next old)
5127 (when (setq cur (markdown-cur-list-item-bounds))
5128 (setq old (point))
5129 (if (markdown-next-list-item (nth 3 cur))
5130 (progn
5131 (setq next (markdown-cur-list-item-bounds))
5132 (condition-case nil
5133 (progn
5134 (transpose-regions (nth 0 cur) (nth 1 cur)
5135 (nth 0 next) (nth 1 next) nil)
5136 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5137 ;; Catch error in case regions overlap.
5138 (error (goto-char old))))
5139 (goto-char old)))))
5141 (defun markdown-demote-list-item (&optional bounds)
5142 "Indent (or demote) the current list item.
5143 Optionally, BOUNDS of the current list item may be provided if available."
5144 (interactive)
5145 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5146 (save-excursion
5147 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5148 (goto-char (nth 0 bounds))
5149 (while (< (point) end-marker)
5150 (unless (markdown-cur-line-blank-p)
5151 (insert (make-string markdown-list-indent-width ? )))
5152 (forward-line))))))
5154 (defun markdown-promote-list-item (&optional bounds)
5155 "Unindent (or promote) the current list item.
5156 Optionally, BOUNDS of the current list item may be provided if available."
5157 (interactive)
5158 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5159 (save-excursion
5160 (save-match-data
5161 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5162 num regexp)
5163 (goto-char (nth 0 bounds))
5164 (when (looking-at (format "^[ ]\\{1,%d\\}"
5165 markdown-list-indent-width))
5166 (setq num (- (match-end 0) (match-beginning 0)))
5167 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5168 (while (and (< (point) end-marker)
5169 (re-search-forward regexp end-marker t))
5170 (replace-match "" nil nil)
5171 (forward-line))))))))
5173 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5174 "Update the numbering for level PFX (as a string of spaces).
5176 Assume that the previously found match was for a numbered item in
5177 a list."
5178 (let ((cpfx pfx)
5179 (idx 0)
5180 (continue t)
5181 (step t)
5182 (sep nil))
5183 (while (and continue (not (eobp)))
5184 (setq step t)
5185 (cond
5186 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5187 (setq cpfx (match-string-no-properties 1))
5188 (cond
5189 ((string= cpfx pfx)
5190 (save-excursion
5191 (replace-match
5192 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5193 (setq sep nil))
5194 ;; indented a level
5195 ((string< pfx cpfx)
5196 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5197 (setq step nil))
5198 ;; exit the loop
5200 (setq step nil)
5201 (setq continue nil))))
5203 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5204 (setq cpfx (match-string-no-properties 1))
5205 (cond
5206 ;; reset if separated before
5207 ((string= cpfx pfx) (when sep (setq idx 0)))
5208 ((string< cpfx pfx)
5209 (setq step nil)
5210 (setq continue nil))))
5211 (t (setq sep t)))
5213 (when step
5214 (beginning-of-line)
5215 (setq continue (= (forward-line) 0))))
5216 sep))
5218 (defun markdown-cleanup-list-numbers ()
5219 "Update the numbering of ordered lists."
5220 (interactive)
5221 (save-excursion
5222 (goto-char (point-min))
5223 (markdown-cleanup-list-numbers-level "")))
5226 ;;; Movement ==================================================================
5228 (defun markdown-beginning-of-defun (&optional arg)
5229 "`beginning-of-defun-function' for Markdown.
5230 Move backward to the beginning of the current or previous section.
5231 When ARG is non-nil, repeat that many times. When ARG is negative,
5232 move forward to the ARG-th following section."
5233 (interactive "P")
5234 (or arg (setq arg 1))
5235 (forward-char 1)
5236 (or (re-search-backward markdown-regex-header nil t arg)
5237 (goto-char (point-min))))
5239 (defun markdown-end-of-defun (&optional arg)
5240 "`end-of-defun-function' for Markdown.
5241 Move forward to the end of the current or following section.
5242 When ARG is non-nil, repeat that many times. When ARG is negative,
5243 move back to the ARG-th preceding section."
5244 (interactive "P")
5245 (or arg (setq arg 1))
5246 (when (looking-at markdown-regex-header)
5247 (goto-char (match-beginning 0))
5248 (forward-char 1))
5249 (if (re-search-forward markdown-regex-header nil t arg)
5250 (goto-char (match-beginning 0))
5251 (goto-char (point-max)))
5252 (skip-syntax-backward "-"))
5254 (defun markdown-beginning-of-block ()
5255 "Move the point to the start of the previous text block."
5256 (interactive)
5257 (if (re-search-backward markdown-regex-block-separator nil t)
5258 (goto-char (or (match-end 2) (match-end 0)))
5259 (goto-char (point-min))))
5261 (defun markdown-end-of-block ()
5262 "Move the point to the start of the next text block."
5263 (interactive)
5264 (beginning-of-line)
5265 (skip-syntax-forward "-")
5266 (when (= (point) (point-min))
5267 (forward-char))
5268 (if (re-search-forward markdown-regex-block-separator nil t)
5269 (goto-char (or (match-end 2) (match-end 0)))
5270 (goto-char (point-max)))
5271 (skip-syntax-backward "-")
5272 (forward-line))
5274 (defun markdown-forward-paragraph (arg)
5275 "Move forward one or more paragraphs or by one block.
5276 When ARG is nil or a numeric prefix, call `forward-paragraph'
5277 with ARG. When called with \\[universal-argument], call
5278 `markdown-end-of-block' instead."
5279 (interactive "P")
5280 (or arg (setq arg 1))
5281 (cond ((integerp arg)
5282 (forward-paragraph arg))
5283 ((equal arg '(4))
5284 (markdown-end-of-block))))
5286 (defun markdown-backward-paragraph (arg)
5287 "Move backward one or more paragraphs or by one block.
5288 When ARG is nil or a numeric prefix, call `backward-paragraph'
5289 with ARG. When called with \\[universal-argument], call
5290 `markdown-beginning-of-block' instead."
5291 (interactive "P")
5292 (or arg (setq arg 1))
5293 (cond ((integerp arg)
5294 (backward-paragraph arg))
5295 ((equal arg '(4))
5296 (markdown-beginning-of-block))))
5298 (defun markdown-end-of-block-element ()
5299 "Move the point to the start of the next block unit.
5300 Stops at blank lines, list items, headers, and horizontal rules."
5301 (interactive)
5302 (forward-line)
5303 (while (and (or (not (markdown-prev-line-blank-p))
5304 (markdown-cur-line-blank-p))
5305 (not (or (looking-at-p markdown-regex-list)
5306 (looking-at-p markdown-regex-header)
5307 (looking-at-p markdown-regex-hr)))
5308 (not (eobp)))
5309 (forward-line)))
5311 (defun markdown-next-link ()
5312 "Jump to next inline, reference, or wiki link.
5313 If successful, return point. Otherwise, return nil.
5314 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5315 (interactive)
5316 (let ((opoint (point)))
5317 (when (or (markdown-link-p) (markdown-wiki-link-p))
5318 ;; At a link already, move past it.
5319 (goto-char (+ (match-end 0) 1)))
5320 ;; Search for the next wiki link and move to the beginning.
5321 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5322 (markdown-code-block-at-point)
5323 (< (point) (point-max))))
5324 (if (and (not (eq (point) opoint))
5325 (or (markdown-link-p) (markdown-wiki-link-p)))
5326 ;; Group 1 will move past non-escape character in wiki link regexp.
5327 ;; Go to beginning of group zero for all other link types.
5328 (goto-char (or (match-beginning 1) (match-beginning 0)))
5329 (goto-char opoint)
5330 nil)))
5332 (defun markdown-previous-link ()
5333 "Jump to previous wiki link.
5334 If successful, return point. Otherwise, return nil.
5335 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5336 (interactive)
5337 (let ((opoint (point)))
5338 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5339 (markdown-code-block-at-point)
5340 (> (point) (point-min))))
5341 (if (and (not (eq (point) opoint))
5342 (or (markdown-link-p) (markdown-wiki-link-p)))
5343 (goto-char (or (match-beginning 1) (match-beginning 0)))
5344 (goto-char opoint)
5345 nil)))
5347 (defun markdown-next-heading ()
5348 "Move to the next heading line of any level.
5349 With argument, repeats or can move backward if negative."
5350 (let ((pos (outline-next-heading)))
5351 (while (markdown-code-block-at-point)
5352 (setq pos (outline-next-heading)))
5353 pos))
5355 (defun markdown-previous-heading ()
5356 "Move to the previous heading line of any level.
5357 With argument, repeats or can move backward if negative."
5358 (let ((pos (outline-previous-heading)))
5359 (while (markdown-code-block-at-point)
5360 (setq pos (outline-previous-heading)))
5361 pos))
5364 ;;; Outline ===================================================================
5366 (defun markdown-move-heading-common (move-fn &optional arg)
5367 "Wrapper for `outline-mode' functions to skip false positives.
5368 MOVE-FN is a function and ARG is its argument. For example,
5369 headings inside preformatted code blocks may match
5370 `outline-regexp' but should not be considered as headings."
5371 (funcall move-fn arg)
5372 (let ((prev -1))
5373 (while (and (/= prev (point)) (markdown-code-block-at-point))
5374 (setq prev (point))
5375 (funcall move-fn arg))))
5377 (defun markdown-next-visible-heading (arg)
5378 "Move to the next visible heading line of any level.
5379 With argument, repeats or can move backward if negative. ARG is
5380 passed to `outline-next-visible-heading'."
5381 (interactive "p")
5382 (markdown-move-heading-common 'outline-next-visible-heading arg))
5384 (defun markdown-previous-visible-heading (arg)
5385 "Move to the previous visible heading line of any level.
5386 With argument, repeats or can move backward if negative. ARG is
5387 passed to `outline-previous-visible-heading'."
5388 (interactive "p")
5389 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5391 (defun markdown-forward-same-level (arg)
5392 "Move forward to the ARG'th heading at same level as this one.
5393 Stop at the first and last headings of a superior heading."
5394 (interactive "p")
5395 (markdown-move-heading-common 'outline-forward-same-level arg))
5397 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5398 (beginning-of-line)
5399 (or (and (outline-on-heading-p invisible-ok)
5400 (not (markdown-code-block-at-point)))
5401 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5402 found)
5403 (save-excursion
5404 (while (not found)
5405 (let (finish)
5406 (while (and (not finish) (re-search-backward header-re nil t))
5407 (when (and (or invisible-ok (not (outline-invisible-p)))
5408 (not (markdown-code-block-at-point)))
5409 (setq finish t)))
5410 (if (not finish)
5411 (error "Before first heading")
5412 (setq found (point))))))
5413 (goto-char found)
5414 found)))
5416 (defun markdown-backward-same-level (arg)
5417 "Move backward to the ARG'th heading at same level as this one.
5418 Stop at the first and last headings of a superior heading."
5419 (interactive "p")
5420 (markdown-back-to-heading-over-code-block)
5421 (while (> arg 0)
5422 (let ((point-to-move-to (save-excursion
5423 (outline-get-last-sibling))))
5424 (if point-to-move-to
5425 (progn
5426 (goto-char point-to-move-to)
5427 (setq arg (1- arg)))
5428 (error "No previous same-level heading")))))
5430 (defun markdown-up-heading (arg)
5431 "Move to the visible heading line of which the present line is a subheading.
5432 With argument, move up ARG levels."
5433 (interactive "p")
5434 (markdown-move-heading-common 'outline-up-heading arg))
5436 (defun markdown-back-to-heading (&optional invisible-ok)
5437 "Move to previous heading line, or beg of this line if it's a heading.
5438 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5439 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5441 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5443 (defun markdown-on-heading-p ()
5444 "Return t if point is on a (visible) heading line."
5445 (get-text-property (point) 'markdown-heading))
5447 (defun markdown-end-of-subtree (&optional invisible-OK)
5448 "Move to the end of the current subtree.
5449 Only visible heading lines are considered, unless INVISIBLE-OK is
5450 non-nil.
5451 Derived from `org-end-of-subtree'."
5452 (markdown-back-to-heading invisible-OK)
5453 (let ((first t)
5454 (level (funcall outline-level)))
5455 (while (and (not (eobp))
5456 (or first (> (funcall outline-level) level)))
5457 (setq first nil)
5458 (markdown-next-heading))
5459 (if (memq (preceding-char) '(?\n ?\^M))
5460 (progn
5461 ;; Go to end of line before heading
5462 (forward-char -1)
5463 (if (memq (preceding-char) '(?\n ?\^M))
5464 ;; leave blank line before heading
5465 (forward-char -1)))))
5466 (point))
5468 (defun markdown-outline-fix-visibility ()
5469 "Hide any false positive headings that should not be shown.
5470 For example, headings inside preformatted code blocks may match
5471 `outline-regexp' but should not be shown as headings when cycling."
5472 (save-excursion
5473 (goto-char (point-min))
5474 (unless (outline-on-heading-p)
5475 (outline-next-visible-heading 1))
5476 (while (< (point) (point-max))
5477 (when (markdown-code-block-at-point)
5478 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5479 (outline-next-visible-heading 1))))
5481 (defvar markdown-cycle-global-status 1)
5482 (defvar markdown-cycle-subtree-status nil)
5484 (defun markdown-next-preface ()
5485 (let (finish)
5486 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5487 nil 'move))
5488 (unless (markdown-code-block-at-point)
5489 (goto-char (match-beginning 0))
5490 (setq finish t))))
5491 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5492 (forward-char -1)))
5494 (defun markdown-show-entry ()
5495 (save-excursion
5496 (outline-back-to-heading t)
5497 (outline-flag-region (1- (point))
5498 (progn
5499 (markdown-next-preface)
5500 (if (= 1 (- (point-max) (point)))
5501 (point-max)
5502 (point)))
5503 nil)))
5505 (defun markdown-cycle (&optional arg)
5506 "Visibility cycling for Markdown mode.
5507 If ARG is t, perform global visibility cycling. If the point is
5508 at an atx-style header, cycle visibility of the corresponding
5509 subtree. Otherwise, insert a tab using `indent-relative'.
5510 Derived from `org-cycle'."
5511 (interactive "P")
5512 (cond
5513 ((eq arg t) ;; Global cycling
5514 (cond
5515 ((and (eq last-command this-command)
5516 (eq markdown-cycle-global-status 2))
5517 ;; Move from overview to contents
5518 (markdown-hide-sublevels 1)
5519 (message "CONTENTS")
5520 (setq markdown-cycle-global-status 3)
5521 (markdown-outline-fix-visibility))
5523 ((and (eq last-command this-command)
5524 (eq markdown-cycle-global-status 3))
5525 ;; Move from contents to all
5526 (markdown-show-all)
5527 (message "SHOW ALL")
5528 (setq markdown-cycle-global-status 1))
5531 ;; Defaults to overview
5532 (markdown-hide-body)
5533 (message "OVERVIEW")
5534 (setq markdown-cycle-global-status 2)
5535 (markdown-outline-fix-visibility))))
5537 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5538 ;; At a heading: rotate between three different views
5539 (markdown-back-to-heading)
5540 (let ((goal-column 0) eoh eol eos)
5541 ;; Determine boundaries
5542 (save-excursion
5543 (markdown-back-to-heading)
5544 (save-excursion
5545 (beginning-of-line 2)
5546 (while (and (not (eobp)) ;; this is like `next-line'
5547 (get-char-property (1- (point)) 'invisible))
5548 (beginning-of-line 2)) (setq eol (point)))
5549 (markdown-end-of-heading) (setq eoh (point))
5550 (markdown-end-of-subtree t)
5551 (skip-chars-forward " \t\n")
5552 (beginning-of-line 1) ; in case this is an item
5553 (setq eos (1- (point))))
5554 ;; Find out what to do next and set `this-command'
5555 (cond
5556 ((= eos eoh)
5557 ;; Nothing is hidden behind this heading
5558 (message "EMPTY ENTRY")
5559 (setq markdown-cycle-subtree-status nil))
5560 ((>= eol eos)
5561 ;; Entire subtree is hidden in one line: open it
5562 (markdown-show-entry)
5563 (markdown-show-children)
5564 (message "CHILDREN")
5565 (setq markdown-cycle-subtree-status 'children))
5566 ((and (eq last-command this-command)
5567 (eq markdown-cycle-subtree-status 'children))
5568 ;; We just showed the children, now show everything.
5569 (markdown-show-subtree)
5570 (message "SUBTREE")
5571 (setq markdown-cycle-subtree-status 'subtree))
5573 ;; Default action: hide the subtree.
5574 (markdown-hide-subtree)
5575 (message "FOLDED")
5576 (setq markdown-cycle-subtree-status 'folded)))))
5579 (indent-for-tab-command))))
5581 (defun markdown-shifttab ()
5582 "Global visibility cycling.
5583 Calls `markdown-cycle' with argument t."
5584 (interactive)
5585 (markdown-cycle t))
5587 (defun markdown-outline-level ()
5588 "Return the depth to which a statement is nested in the outline."
5589 (cond
5590 ((markdown-code-block-at-point) 7)
5591 ((match-end 2) 1)
5592 ((match-end 3) 2)
5593 ((- (match-end 4) (match-beginning 4)))))
5595 (defun markdown-promote-subtree (&optional arg)
5596 "Promote the current subtree of ATX headings.
5597 Note that Markdown does not support heading levels higher than
5598 six and therefore level-six headings will not be promoted
5599 further. If ARG is non-nil promote the heading, otherwise
5600 demote."
5601 (interactive "*P")
5602 (save-excursion
5603 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5604 (re-search-backward markdown-regex-header-atx nil t))
5605 (not (markdown-code-block-at-point)))
5606 (let ((level (length (match-string 1)))
5607 (promote-or-demote (if arg 1 -1))
5608 (remove 't))
5609 (markdown-cycle-atx promote-or-demote remove)
5610 (catch 'end-of-subtree
5611 (while (markdown-next-heading)
5612 ;; Exit if this not a higher level heading; promote otherwise.
5613 (if (and (looking-at markdown-regex-header-atx)
5614 (<= (length (match-string-no-properties 1)) level))
5615 (throw 'end-of-subtree nil)
5616 (markdown-cycle-atx promote-or-demote remove))))))))
5618 (defun markdown-demote-subtree ()
5619 "Demote the current subtree of ATX headings."
5620 (interactive)
5621 (markdown-promote-subtree t))
5623 (defun markdown-move-subtree-up ()
5624 "Move the current subtree of ATX headings up."
5625 (interactive)
5626 (outline-move-subtree-up 1))
5628 (defun markdown-move-subtree-down ()
5629 "Move the current subtree of ATX headings down."
5630 (interactive)
5631 (outline-move-subtree-down 1))
5634 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5636 (defun markdown-move-up ()
5637 "Move list item up.
5638 Calls `markdown-move-list-item-up'."
5639 (interactive)
5640 (markdown-move-list-item-up))
5642 (defun markdown-move-down ()
5643 "Move list item down.
5644 Calls `markdown-move-list-item-down'."
5645 (interactive)
5646 (markdown-move-list-item-down))
5648 (defun markdown-promote ()
5649 "Either promote header or list item at point or cycle markup.
5650 See `markdown-cycle-atx', `markdown-cycle-setext', and
5651 `markdown-promote-list-item'."
5652 (interactive)
5653 (let (bounds)
5654 (cond
5655 ;; Promote atx header
5656 ((thing-at-point-looking-at markdown-regex-header-atx)
5657 (markdown-cycle-atx -1))
5658 ;; Promote setext header
5659 ((thing-at-point-looking-at markdown-regex-header-setext)
5660 (markdown-cycle-setext -1))
5661 ;; Promote horizonal rule
5662 ((thing-at-point-looking-at markdown-regex-hr)
5663 (markdown-cycle-hr -1))
5664 ;; Promote list item
5665 ((setq bounds (markdown-cur-list-item-bounds))
5666 (markdown-promote-list-item bounds))
5667 ;; Promote bold
5668 ((thing-at-point-looking-at markdown-regex-bold)
5669 (markdown-cycle-bold))
5670 ;; Promote italic
5671 ((thing-at-point-looking-at markdown-regex-italic)
5672 (markdown-cycle-italic))
5674 (error "Nothing to promote at point")))))
5676 (defun markdown-demote ()
5677 "Either demote header or list item at point or cycle or remove markup.
5678 See `markdown-cycle-atx', `markdown-cycle-setext', and
5679 `markdown-demote-list-item'."
5680 (interactive)
5681 (let (bounds)
5682 (cond
5683 ;; Demote atx header
5684 ((thing-at-point-looking-at markdown-regex-header-atx)
5685 (markdown-cycle-atx 1))
5686 ;; Demote setext header
5687 ((thing-at-point-looking-at markdown-regex-header-setext)
5688 (markdown-cycle-setext 1))
5689 ;; Demote horizonal rule
5690 ((thing-at-point-looking-at markdown-regex-hr)
5691 (markdown-cycle-hr 1))
5692 ;; Demote list item
5693 ((setq bounds (markdown-cur-list-item-bounds))
5694 (markdown-demote-list-item bounds))
5695 ;; Demote bold
5696 ((thing-at-point-looking-at markdown-regex-bold)
5697 (markdown-cycle-bold))
5698 ;; Demote italic
5699 ((thing-at-point-looking-at markdown-regex-italic)
5700 (markdown-cycle-italic))
5702 (error "Nothing to demote at point")))))
5705 ;;; Commands ==================================================================
5707 (defun markdown (&optional output-buffer-name)
5708 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5709 The output buffer name defaults to `markdown-output-buffer-name'.
5710 Return the name of the output buffer used."
5711 (interactive)
5712 (save-window-excursion
5713 (let ((begin-region)
5714 (end-region))
5715 (if (markdown-use-region-p)
5716 (setq begin-region (region-beginning)
5717 end-region (region-end))
5718 (setq begin-region (point-min)
5719 end-region (point-max)))
5721 (unless output-buffer-name
5722 (setq output-buffer-name markdown-output-buffer-name))
5723 (cond
5724 ;; Handle case when `markdown-command' does not read from stdin
5725 (markdown-command-needs-filename
5726 (if (not buffer-file-name)
5727 (error "Must be visiting a file")
5728 (shell-command (concat markdown-command " "
5729 (shell-quote-argument buffer-file-name))
5730 output-buffer-name)))
5731 ;; Pass region to `markdown-command' via stdin
5733 (let ((buf (get-buffer-create output-buffer-name)))
5734 (with-current-buffer buf
5735 (setq buffer-read-only nil)
5736 (erase-buffer))
5737 (call-process-region begin-region end-region
5738 shell-file-name nil buf nil
5739 shell-command-switch markdown-command)))))
5740 output-buffer-name))
5742 (defun markdown-standalone (&optional output-buffer-name)
5743 "Special function to provide standalone HTML output.
5744 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5745 (interactive)
5746 (setq output-buffer-name (markdown output-buffer-name))
5747 (with-current-buffer output-buffer-name
5748 (set-buffer output-buffer-name)
5749 (unless (markdown-output-standalone-p)
5750 (markdown-add-xhtml-header-and-footer output-buffer-name))
5751 (goto-char (point-min))
5752 (html-mode))
5753 output-buffer-name)
5755 (defun markdown-other-window (&optional output-buffer-name)
5756 "Run `markdown-command' on current buffer and display in other window.
5757 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5758 that name."
5759 (interactive)
5760 (markdown-display-buffer-other-window
5761 (markdown-standalone output-buffer-name)))
5763 (defun markdown-output-standalone-p ()
5764 "Determine whether `markdown-command' output is standalone XHTML.
5765 Standalone XHTML output is identified by an occurrence of
5766 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5767 (save-excursion
5768 (goto-char (point-min))
5769 (re-search-forward
5770 markdown-xhtml-standalone-regexp
5771 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5772 t)))
5774 (defun markdown-stylesheet-link-string (stylesheet-path)
5775 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5776 stylesheet-path
5777 "\" />"))
5779 (defun markdown-add-xhtml-header-and-footer (title)
5780 "Wrap XHTML header and footer with given TITLE around current buffer."
5781 (goto-char (point-min))
5782 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5783 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5784 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5785 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5786 "<head>\n<title>")
5787 (insert title)
5788 (insert "</title>\n")
5789 (when (> (length markdown-content-type) 0)
5790 (insert
5791 (format
5792 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5793 markdown-content-type
5794 (or (and markdown-coding-system
5795 (fboundp 'coding-system-get)
5796 (coding-system-get markdown-coding-system
5797 'mime-charset))
5798 (and (fboundp 'coding-system-get)
5799 (coding-system-get buffer-file-coding-system
5800 'mime-charset))
5801 "iso-8859-1"))))
5802 (if (> (length markdown-css-paths) 0)
5803 (insert (mapconcat 'markdown-stylesheet-link-string markdown-css-paths "\n")))
5804 (when (> (length markdown-xhtml-header-content) 0)
5805 (insert markdown-xhtml-header-content))
5806 (insert "\n</head>\n\n"
5807 "<body>\n\n")
5808 (goto-char (point-max))
5809 (insert "\n"
5810 "</body>\n"
5811 "</html>\n"))
5813 (defun markdown-preview (&optional output-buffer-name)
5814 "Run `markdown-command' on the current buffer and view output in browser.
5815 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5816 that name."
5817 (interactive)
5818 (browse-url-of-buffer
5819 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
5821 (defun markdown-export-file-name (&optional extension)
5822 "Attempt to generate a filename for Markdown output.
5823 The file extension will be EXTENSION if given, or .html by default.
5824 If the current buffer is visiting a file, we construct a new
5825 output filename based on that filename. Otherwise, return nil."
5826 (when (buffer-file-name)
5827 (unless extension
5828 (setq extension ".html"))
5829 (let ((candidate
5830 (concat
5831 (cond
5832 ((buffer-file-name)
5833 (file-name-sans-extension (buffer-file-name)))
5834 (t (buffer-name)))
5835 extension)))
5836 (cond
5837 ((equal candidate (buffer-file-name))
5838 (concat candidate extension))
5840 candidate)))))
5842 (defun markdown-export (&optional output-file)
5843 "Run Markdown on the current buffer, save to file, and return the filename.
5844 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
5845 generated by `markdown-export-file-name', which will be constructed using the
5846 current filename, but with the extension removed and replaced with .html."
5847 (interactive)
5848 (unless output-file
5849 (setq output-file (markdown-export-file-name ".html")))
5850 (when output-file
5851 (let* ((init-buf (current-buffer))
5852 (init-point (point))
5853 (init-buf-string (buffer-string))
5854 (output-buffer (find-file-noselect output-file))
5855 (output-buffer-name (buffer-name output-buffer)))
5856 (run-hooks 'markdown-before-export-hook)
5857 (markdown-standalone output-buffer-name)
5858 (with-current-buffer output-buffer
5859 (run-hooks 'markdown-after-export-hook)
5860 (save-buffer))
5861 ;; if modified, restore initial buffer
5862 (when (buffer-modified-p init-buf)
5863 (erase-buffer)
5864 (insert init-buf-string)
5865 (save-buffer)
5866 (goto-char init-point))
5867 output-file)))
5869 (defun markdown-export-and-preview ()
5870 "Export to XHTML using `markdown-export' and browse the resulting file."
5871 (interactive)
5872 (browse-url-of-file (markdown-export)))
5874 (defvar markdown-live-preview-buffer nil
5875 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
5876 (make-variable-buffer-local 'markdown-live-preview-buffer)
5878 (defvar markdown-live-preview-source-buffer nil
5879 "Source buffer from which current buffer was generated.
5880 This is the inverse of `markdown-live-preview-buffer'.")
5881 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
5883 (defvar markdown-live-preview-currently-exporting nil)
5885 (defun markdown-live-preview-get-filename ()
5886 "Standardize the filename exported by `markdown-live-preview-export'."
5887 (markdown-export-file-name ".html"))
5889 (defun markdown-live-preview-window-eww (file)
5890 "Preview FILE with eww.
5891 To be used with `markdown-live-preview-window-function'."
5892 (if (require 'eww nil t)
5893 (progn
5894 (eww-open-file file)
5895 (get-buffer "*eww*"))
5896 (error "EWW is not present or not loaded on this version of Emacs")))
5898 (defun markdown-visual-lines-between-points (beg end)
5899 (save-excursion
5900 (goto-char beg)
5901 (cl-loop with count = 0
5902 while (progn (end-of-visual-line)
5903 (and (< (point) end) (line-move-visual 1 t)))
5904 do (cl-incf count)
5905 finally return count)))
5907 (defun markdown-live-preview-window-serialize (buf)
5908 "Get window point and scroll data for all windows displaying BUF."
5909 (when (buffer-live-p buf)
5910 (with-current-buffer buf
5911 (mapcar
5912 (lambda (win)
5913 (with-selected-window win
5914 (let* ((start (window-start))
5915 (pt (window-point))
5916 (pt-or-sym (cond ((= pt (point-min)) 'min)
5917 ((= pt (point-max)) 'max)
5918 (t pt)))
5919 (diff (markdown-visual-lines-between-points
5920 start pt)))
5921 (list win pt-or-sym diff))))
5922 (get-buffer-window-list buf)))))
5924 (defun markdown-get-point-back-lines (pt num-lines)
5925 (save-excursion
5926 (goto-char pt)
5927 (line-move-visual (- num-lines) t)
5928 ;; in testing, can occasionally overshoot the number of lines to traverse
5929 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
5930 (when (> actual-num-lines num-lines)
5931 (line-move-visual (- actual-num-lines num-lines) t)))
5932 (point)))
5934 (defun markdown-live-preview-window-deserialize (window-posns)
5935 "Apply window point and scroll data from WINDOW-POSNS.
5936 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
5937 (cl-destructuring-bind (win pt-or-sym diff) window-posns
5938 (when (window-live-p win)
5939 (with-current-buffer markdown-live-preview-buffer
5940 (set-window-buffer win (current-buffer))
5941 (cl-destructuring-bind (actual-pt actual-diff)
5942 (cl-case pt-or-sym
5943 (min (list (point-min) 0))
5944 (max (list (point-max) diff))
5945 (t (list pt-or-sym diff)))
5946 (set-window-start
5947 win (markdown-get-point-back-lines actual-pt actual-diff))
5948 (set-window-point win actual-pt))))))
5950 (defun markdown-live-preview-export ()
5951 "Export to XHTML using `markdown-export'.
5952 Browse the resulting file within Emacs using
5953 `markdown-live-preview-window-function' Return the buffer
5954 displaying the rendered output."
5955 (interactive)
5956 (let* ((markdown-live-preview-currently-exporting t)
5957 (cur-buf (current-buffer))
5958 (export-file (markdown-export (markdown-live-preview-get-filename)))
5959 ;; get positions in all windows currently displaying output buffer
5960 (window-data
5961 (markdown-live-preview-window-serialize
5962 markdown-live-preview-buffer)))
5963 (save-window-excursion
5964 (let ((output-buffer
5965 (funcall markdown-live-preview-window-function export-file)))
5966 (with-current-buffer output-buffer
5967 (setq markdown-live-preview-source-buffer cur-buf)
5968 (add-hook 'kill-buffer-hook
5969 #'markdown-live-preview-remove-on-kill t t))
5970 (with-current-buffer cur-buf
5971 (setq markdown-live-preview-buffer output-buffer))))
5972 (with-current-buffer cur-buf
5973 ;; reset all windows displaying output buffer to where they were,
5974 ;; now with the new output
5975 (mapc #'markdown-live-preview-window-deserialize window-data)
5976 ;; delete html editing buffer
5977 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
5978 (when (and export-file (file-exists-p export-file)
5979 (eq markdown-live-preview-delete-export
5980 'delete-on-export))
5981 (delete-file export-file))
5982 markdown-live-preview-buffer)))
5984 (defun markdown-live-preview-remove ()
5985 (when (buffer-live-p markdown-live-preview-buffer)
5986 (kill-buffer markdown-live-preview-buffer))
5987 (setq markdown-live-preview-buffer nil)
5988 ;; if set to 'delete-on-export, the output has already been deleted
5989 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
5990 (let ((outfile-name (markdown-live-preview-get-filename)))
5991 (when (file-exists-p outfile-name)
5992 (delete-file outfile-name)))))
5994 (defun markdown-display-buffer-other-window (buf)
5995 (let ((cur-buf (current-buffer)))
5996 (switch-to-buffer-other-window buf)
5997 (set-buffer cur-buf)))
5999 (defun markdown-live-preview-if-markdown ()
6000 (when (and (derived-mode-p 'markdown-mode)
6001 markdown-live-preview-mode)
6002 (unless markdown-live-preview-currently-exporting
6003 (if (buffer-live-p markdown-live-preview-buffer)
6004 (markdown-live-preview-export)
6005 (markdown-display-buffer-other-window
6006 (markdown-live-preview-export))))))
6008 (defun markdown-live-preview-remove-on-kill ()
6009 (cond ((and (derived-mode-p 'markdown-mode)
6010 markdown-live-preview-mode)
6011 (markdown-live-preview-remove))
6012 (markdown-live-preview-source-buffer
6013 (with-current-buffer markdown-live-preview-source-buffer
6014 (setq markdown-live-preview-buffer nil))
6015 (setq markdown-live-preview-source-buffer nil))))
6017 (defun markdown-live-preview-switch-to-output ()
6018 "Switch to output buffer."
6019 (interactive)
6020 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6021 output buffer in another window."
6022 (if markdown-live-preview-mode
6023 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6024 (markdown-live-preview-mode))
6026 (defun markdown-live-preview-re-export ()
6027 "Re export source buffer."
6028 (interactive)
6029 "If the current buffer is a buffer displaying the exported version of a
6030 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6031 update this buffer's contents."
6032 (when markdown-live-preview-source-buffer
6033 (with-current-buffer markdown-live-preview-source-buffer
6034 (markdown-live-preview-export))))
6036 (defun markdown-open ()
6037 "Open file for the current buffer with `markdown-open-command'."
6038 (interactive)
6039 (if (not markdown-open-command)
6040 (error "Variable `markdown-open-command' must be set")
6041 (if (not buffer-file-name)
6042 (error "Must be visiting a file")
6043 (call-process markdown-open-command
6044 nil nil nil buffer-file-name))))
6046 (defun markdown-kill-ring-save ()
6047 "Run Markdown on file and store output in the kill ring."
6048 (interactive)
6049 (save-window-excursion
6050 (markdown)
6051 (with-current-buffer markdown-output-buffer-name
6052 (kill-ring-save (point-min) (point-max)))))
6055 ;;; Links =====================================================================
6057 (defun markdown-link-p ()
6058 "Return non-nil when `point' is at a non-wiki link.
6059 See `markdown-wiki-link-p' for more information."
6060 (let ((case-fold-search nil))
6061 (and (not (markdown-wiki-link-p))
6062 (not (markdown-code-block-at-point))
6063 (or (thing-at-point-looking-at markdown-regex-link-inline)
6064 (thing-at-point-looking-at markdown-regex-link-reference)
6065 (thing-at-point-looking-at markdown-regex-uri)
6066 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6068 (defun markdown-link-link ()
6069 "Return the link part of the regular (non-wiki) link at point.
6070 Works with both inline and reference style links. If point is
6071 not at a link or the link reference is not defined returns nil."
6072 (cond
6073 ((thing-at-point-looking-at markdown-regex-link-inline)
6074 (match-string-no-properties 6))
6075 ((thing-at-point-looking-at markdown-regex-link-reference)
6076 (let* ((text (match-string-no-properties 3))
6077 (reference (match-string-no-properties 6))
6078 (target (downcase (if (string= reference "") text reference))))
6079 (car (markdown-reference-definition target))))
6080 ((thing-at-point-looking-at markdown-regex-uri)
6081 (match-string-no-properties 0))
6082 ((thing-at-point-looking-at markdown-regex-angle-uri)
6083 (match-string-no-properties 2))
6084 (t nil)))
6086 (defun markdown-follow-link-at-point ()
6087 "Open the current non-wiki link in a browser."
6088 (interactive)
6089 (if (markdown-link-p) (browse-url (markdown-link-link))
6090 (error "Point is not at a Markdown link or URI")))
6093 ;;; WikiLink Following/Markup =================================================
6095 (defun markdown-wiki-link-p ()
6096 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6097 A true wiki link name matches `markdown-regex-wiki-link' but does
6098 not match the current file name after conversion. This modifies
6099 the data returned by `match-data'. Note that the potential wiki
6100 link name must be available via `match-string'."
6101 (when markdown-enable-wiki-links
6102 (let ((case-fold-search nil))
6103 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6104 (not (markdown-code-block-at-point))
6105 (or (not buffer-file-name)
6106 (not (string-equal (buffer-file-name)
6107 (markdown-convert-wiki-link-to-filename
6108 (markdown-wiki-link-link)))))))))
6110 (defun markdown-wiki-link-link ()
6111 "Return the link part of the wiki link using current match data.
6112 The location of the link component depends on the value of
6113 `markdown-wiki-link-alias-first'."
6114 (if markdown-wiki-link-alias-first
6115 (or (match-string-no-properties 5) (match-string-no-properties 3))
6116 (match-string-no-properties 3)))
6118 (defun markdown-wiki-link-alias ()
6119 "Return the alias or text part of the wiki link using current match data.
6120 The location of the alias component depends on the value of
6121 `markdown-wiki-link-alias-first'."
6122 (if markdown-wiki-link-alias-first
6123 (match-string-no-properties 3)
6124 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6126 (defun markdown-convert-wiki-link-to-filename (name)
6127 "Generate a filename from the wiki link NAME.
6128 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6129 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6130 and [[test test]] both map to Test-test.ext."
6131 (let ((basename (markdown-replace-regexp-in-string
6132 "[[:space:]\n]" markdown-link-space-sub-char name)))
6133 (when (eq major-mode 'gfm-mode)
6134 (setq basename (concat (upcase (substring basename 0 1))
6135 (downcase (substring basename 1 nil)))))
6136 (let* ((default
6137 (concat basename
6138 (if (and (buffer-file-name)
6139 (file-name-extension (buffer-file-name)))
6140 (concat "."
6141 (file-name-extension (buffer-file-name))))))
6142 (current default))
6143 (catch 'done
6144 (condition-case nil
6145 (cl-loop
6146 (if (or (not markdown-wiki-link-search-parent-directories)
6147 (file-exists-p current))
6148 (throw 'done current))
6149 (if (string-equal (expand-file-name current)
6150 (concat "/" default))
6151 (throw 'done default))
6152 (setq current (concat "../" current)))
6153 (error default))))))
6155 (defun markdown-follow-wiki-link (name &optional other)
6156 "Follow the wiki link NAME.
6157 Convert the name to a file name and call `find-file'. Ensure that
6158 the new buffer remains in `markdown-mode'. Open the link in another
6159 window when OTHER is non-nil."
6160 (let ((filename (markdown-convert-wiki-link-to-filename name))
6161 (wp (file-name-directory buffer-file-name)))
6162 (when other (other-window 1))
6163 (let ((default-directory wp))
6164 (find-file filename)))
6165 (when (not (eq major-mode 'markdown-mode))
6166 (markdown-mode)))
6168 (defun markdown-follow-wiki-link-at-point (&optional arg)
6169 "Find Wiki Link at point.
6170 With prefix argument ARG, open the file in other window.
6171 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6172 (interactive "P")
6173 (if (markdown-wiki-link-p)
6174 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6175 (error "Point is not at a Wiki Link")))
6177 (defun markdown-highlight-wiki-link (from to face)
6178 "Highlight the wiki link in the region between FROM and TO using FACE."
6179 (put-text-property from to 'font-lock-face face))
6181 (defun markdown-unfontify-region-wiki-links (from to)
6182 "Remove wiki link faces from the region specified by FROM and TO."
6183 (interactive "*r")
6184 (remove-text-properties from to '(font-lock-face markdown-link-face))
6185 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
6187 (defun markdown-fontify-region-wiki-links (from to)
6188 "Search region given by FROM and TO for wiki links and fontify them.
6189 If a wiki link is found check to see if the backing file exists
6190 and highlight accordingly."
6191 (goto-char from)
6192 (save-match-data
6193 (while (re-search-forward markdown-regex-wiki-link to t)
6194 (when (not (markdown-code-block-at-point))
6195 (let ((highlight-beginning (match-beginning 1))
6196 (highlight-end (match-end 1))
6197 (file-name
6198 (markdown-convert-wiki-link-to-filename
6199 (markdown-wiki-link-link))))
6200 (if (condition-case nil (file-exists-p file-name) (error nil))
6201 (markdown-highlight-wiki-link
6202 highlight-beginning highlight-end markdown-link-face)
6203 (markdown-highlight-wiki-link
6204 highlight-beginning highlight-end markdown-missing-link-face)))))))
6206 (defun markdown-extend-changed-region (from to)
6207 "Extend region given by FROM and TO so that we can fontify all links.
6208 The region is extended to the first newline before and the first
6209 newline after."
6210 ;; start looking for the first new line before 'from
6211 (goto-char from)
6212 (re-search-backward "\n" nil t)
6213 (let ((new-from (point-min))
6214 (new-to (point-max)))
6215 (if (not (= (point) from))
6216 (setq new-from (point)))
6217 ;; do the same thing for the first new line after 'to
6218 (goto-char to)
6219 (re-search-forward "\n" nil t)
6220 (if (not (= (point) to))
6221 (setq new-to (point)))
6222 (cl-values new-from new-to)))
6224 (defun markdown-check-change-for-wiki-link (from to)
6225 "Check region between FROM and TO for wiki links and re-fontify as needed."
6226 (interactive "*r")
6227 (let* ((modified (buffer-modified-p))
6228 (buffer-undo-list t)
6229 (inhibit-read-only t)
6230 (inhibit-point-motion-hooks t)
6231 deactivate-mark
6232 buffer-file-truename)
6233 (unwind-protect
6234 (save-excursion
6235 (save-match-data
6236 (save-restriction
6237 ;; Extend the region to fontify so that it starts
6238 ;; and ends at safe places.
6239 (cl-multiple-value-bind (new-from new-to)
6240 (markdown-extend-changed-region from to)
6241 (goto-char new-from)
6242 ;; Only refontify when the range contains text with a
6243 ;; wiki link face or if the wiki link regexp matches.
6244 (when (or (markdown-range-property-any
6245 new-from new-to 'font-lock-face
6246 (list markdown-link-face
6247 markdown-missing-link-face))
6248 (re-search-forward
6249 markdown-regex-wiki-link new-to t))
6250 ;; Unfontify existing fontification (start from scratch)
6251 (markdown-unfontify-region-wiki-links new-from new-to)
6252 ;; Now do the fontification.
6253 (markdown-fontify-region-wiki-links new-from new-to))))))
6254 (and (not modified)
6255 (buffer-modified-p)
6256 (set-buffer-modified-p nil)))))
6258 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6259 "Check region between FROM and TO for wiki links and re-fontify as needed.
6260 Designed to be used with the `after-change-functions' hook."
6261 (markdown-check-change-for-wiki-link from to))
6263 (defun markdown-fontify-buffer-wiki-links ()
6264 "Refontify all wiki links in the buffer."
6265 (interactive)
6266 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6269 ;;; Following and Jumping =====================================================
6271 (defun markdown-follow-thing-at-point (arg)
6272 "Follow thing at point if possible, such as a reference link or wiki link.
6273 Opens inline and reference links in a browser. Opens wiki links
6274 to other files in the current window, or the another window if
6275 ARG is non-nil.
6276 See `markdown-follow-link-at-point' and
6277 `markdown-follow-wiki-link-at-point'."
6278 (interactive "P")
6279 (cond ((markdown-link-p)
6280 (markdown-follow-link-at-point))
6281 ((markdown-wiki-link-p)
6282 (markdown-follow-wiki-link-at-point arg))
6284 (error "Nothing to follow at point"))))
6286 (defun markdown-jump ()
6287 "Jump to another location based on context at point.
6288 Jumps between reference links and definitions; between footnote
6289 markers and footnote text."
6290 (interactive)
6291 (cond ((markdown-footnote-text-positions)
6292 (markdown-footnote-return))
6293 ((markdown-footnote-marker-positions)
6294 (markdown-footnote-goto-text))
6295 ((thing-at-point-looking-at markdown-regex-link-reference)
6296 (markdown-reference-goto-definition))
6297 ((thing-at-point-looking-at markdown-regex-reference-definition)
6298 (markdown-reference-goto-link (match-string-no-properties 2)))
6300 (error "Nothing to jump to from context at point"))))
6303 ;;; Miscellaneous =============================================================
6305 (defun markdown-compress-whitespace-string (str)
6306 "Compress whitespace in STR and return result.
6307 Leading and trailing whitespace is removed. Sequences of multiple
6308 spaces, tabs, and newlines are replaced with single spaces."
6309 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6310 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6312 (defun markdown-line-number-at-pos (&optional pos)
6313 "Return (narrowed) buffer line number at position POS.
6314 If POS is nil, use current buffer location.
6315 This is an exact copy of `line-number-at-pos' for use in emacs21."
6316 (let ((opoint (or pos (point))) start)
6317 (save-excursion
6318 (goto-char (point-min))
6319 (setq start (point))
6320 (goto-char opoint)
6321 (forward-line 0)
6322 (1+ (count-lines start (point))))))
6324 (defun markdown-inside-link-text-p ()
6325 "Return nil if not currently within link anchor text."
6326 (looking-back "\\[[^]]*" nil))
6328 (defun markdown-line-is-reference-definition-p ()
6329 "Return whether the current line is a (non-footnote) reference defition."
6330 (save-excursion
6331 (move-beginning-of-line 1)
6332 (and (looking-at-p markdown-regex-reference-definition)
6333 (not (looking-at-p "[ \t]*\\[^")))))
6335 (defun markdown-adaptive-fill-function ()
6336 "Return prefix for filling paragraph or nil if not determined."
6337 (cond
6338 ;; List item inside blockquote
6339 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+-]\\)[ \t]+")
6340 (markdown-replace-regexp-in-string
6341 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6342 ;; Blockquote
6343 ((looking-at "^[ \t]*>[ \t]*")
6344 (match-string-no-properties 0))
6345 ;; List items
6346 ((looking-at markdown-regex-list)
6347 (match-string-no-properties 0))
6348 ((looking-at-p markdown-regex-footnote-definition)
6349 " ") ; four spaces
6350 ;; No match
6351 (t nil)))
6353 (defun markdown-fill-forward-paragraph-function (&optional arg)
6354 (let* ((arg (or arg 1))
6355 (paragraphs-remaining (forward-paragraph arg))
6356 (start (point)))
6357 (when (< arg 0)
6358 (while (and (not (eobp))
6359 (progn (move-to-left-margin) (not (eobp)))
6360 (looking-at-p paragraph-separate))
6361 (forward-line 1))
6362 (if (looking-at markdown-regex-list)
6363 (forward-char (length (match-string 0)))
6364 (goto-char start)))
6365 paragraphs-remaining))
6368 ;;; Extension Framework =======================================================
6370 (defun markdown-reload-extensions ()
6371 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6372 (interactive)
6373 (when (eq major-mode 'markdown-mode)
6374 ;; Update font lock keywords with extensions
6375 (setq markdown-mode-font-lock-keywords
6376 (append
6377 markdown-mode-font-lock-keywords-basic
6378 (markdown-mode-font-lock-keywords-wiki-links)
6379 (markdown-mode-font-lock-keywords-math)))
6380 ;; Update font lock defaults
6381 (setq font-lock-defaults
6382 '(markdown-mode-font-lock-keywords
6383 nil nil nil nil
6384 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6385 ;; Refontify buffer
6386 (when (fboundp 'font-lock-refresh-defaults) (font-lock-refresh-defaults))
6387 ;; Add or remove hooks related to extensions
6388 (markdown-setup-wiki-link-hooks)))
6390 (defun markdown-handle-local-variables ()
6391 "Run in `hack-local-variables-hook' to update font lock rules.
6392 Checks to see if there is actually a ‘markdown-mode’ file local variable
6393 before regenerating font-lock rules for extensions."
6394 (when (and (boundp 'file-local-variables-alist)
6395 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6396 (assoc 'markdown-enable-math file-local-variables-alist))
6397 (markdown-reload-extensions)))
6399 ;;; Wiki Links ================================================================
6401 (defun markdown-toggle-wiki-links (&optional arg)
6402 "Toggle support for wiki links.
6403 With a prefix argument ARG, enable wiki link support if ARG is positive,
6404 and disable it otherwise."
6405 (interactive (list (or current-prefix-arg 'toggle)))
6406 (setq markdown-enable-wiki-links
6407 (if (eq arg 'toggle)
6408 (not markdown-enable-wiki-links)
6409 (> (prefix-numeric-value arg) 0)))
6410 (if markdown-enable-wiki-links
6411 (message "markdown-mode wiki link support enabled")
6412 (message "markdown-mode wiki link support disabled"))
6413 (markdown-reload-extensions))
6415 (defun markdown-setup-wiki-link-hooks ()
6416 "Add or remove hooks for fontifying wiki links.
6417 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6418 ;; Anytime text changes make sure it gets fontified correctly
6419 (if (and markdown-enable-wiki-links
6420 markdown-wiki-link-fontify-missing)
6421 (add-hook 'after-change-functions
6422 'markdown-check-change-for-wiki-link-after-change t t)
6423 (remove-hook 'after-change-functions
6424 'markdown-check-change-for-wiki-link-after-change t))
6425 ;; If we left the buffer there is a really good chance we were
6426 ;; creating one of the wiki link documents. Make sure we get
6427 ;; refontified when we come back.
6428 (if (and markdown-enable-wiki-links
6429 markdown-wiki-link-fontify-missing)
6430 (progn
6431 (add-hook 'window-configuration-change-hook
6432 'markdown-fontify-buffer-wiki-links t t)
6433 (markdown-fontify-buffer-wiki-links))
6434 (remove-hook 'window-configuration-change-hook
6435 'markdown-fontify-buffer-wiki-links t)
6436 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6438 (defun markdown-mode-font-lock-keywords-wiki-links ()
6439 "Return wiki-link lock keywords if support is enabled.
6440 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6441 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6442 (when (and markdown-enable-wiki-links
6443 (not markdown-wiki-link-fontify-missing))
6444 (list
6445 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6447 ;;; Math Support ==============================================================
6449 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6451 (defun markdown-toggle-math (&optional arg)
6452 "Toggle support for inline and display LaTeX math expressions.
6453 With a prefix argument ARG, enable math mode if ARG is positive,
6454 and disable it otherwise. If called from Lisp, enable the mode
6455 if ARG is omitted or nil."
6456 (interactive (list (or current-prefix-arg 'toggle)))
6457 (setq markdown-enable-math
6458 (if (eq arg 'toggle)
6459 (not markdown-enable-math)
6460 (> (prefix-numeric-value arg) 0)))
6461 (if markdown-enable-math
6462 (message "markdown-mode math support enabled")
6463 (message "markdown-mode math support disabled"))
6464 (markdown-reload-extensions))
6466 (defun markdown-mode-font-lock-keywords-math ()
6467 "Return math font lock keywords if support is enabled."
6468 (when markdown-enable-math
6469 (list
6470 ;; Display mode equations with brackets: \[ \]
6471 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6472 (2 markdown-math-face append)
6473 (3 markdown-markup-face prepend)))
6474 ;; Equation reference (eq:foo)
6475 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6476 (2 markdown-reference-face)
6477 (3 markdown-markup-face)))
6478 ;; Equation reference \eqref{foo}
6479 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6480 (2 markdown-reference-face)
6481 (3 markdown-markup-face))))))
6484 ;;; GFM Checkboxes as Buttons =================================================
6486 (require 'button)
6488 (define-button-type 'markdown-gfm-checkbox-button
6489 'follow-link t
6490 'face 'markdown-gfm-checkbox-face
6491 'mouse-face 'markdown-highlight-face
6492 'action #'markdown-toggle-gfm-checkbox)
6494 (defun markdown-toggle-gfm-checkbox (button)
6495 "Toggle GFM checkbox BUTTON on click."
6496 (save-match-data
6497 (save-excursion
6498 (goto-char (button-start button))
6499 (cond ((looking-at "\\[ \\]")
6500 (replace-match "[x]" nil t))
6501 ((looking-at "\\[[xX]\\]")
6502 (replace-match "[ ]" nil t))))))
6504 (defun markdown-make-gfm-checkboxes-buttons (start end)
6505 "Make GFM checkboxes buttons in region between START and END."
6506 (save-excursion
6507 (goto-char start)
6508 (let ((case-fold-search t))
6509 (save-excursion
6510 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6511 (make-button (match-beginning 1) (match-end 1)
6512 :type 'markdown-gfm-checkbox-button))))))
6514 ;; Called when any modification is made to buffer text.
6515 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6516 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6517 BEG and END are the limits of scanned region."
6518 (save-excursion
6519 (save-match-data
6520 ;; Rescan between start of line from `beg' and start of line after `end'.
6521 (markdown-make-gfm-checkboxes-buttons
6522 (progn (goto-char beg) (beginning-of-line) (point))
6523 (progn (goto-char end) (forward-line 1) (point))))))
6526 ;;; Mode Definition ==========================================================
6528 (defun markdown-show-version ()
6529 "Show the version number in the minibuffer."
6530 (interactive)
6531 (message "markdown-mode, version %s" markdown-mode-version))
6533 ;;;###autoload
6534 (define-derived-mode markdown-mode text-mode "Markdown"
6535 "Major mode for editing Markdown files."
6536 ;; Natural Markdown tab width
6537 (setq tab-width 4)
6538 ;; Comments
6539 (make-local-variable 'comment-start)
6540 (setq comment-start "<!-- ")
6541 (make-local-variable 'comment-end)
6542 (setq comment-end " -->")
6543 (make-local-variable 'comment-start-skip)
6544 (setq comment-start-skip "<!--[ \t]*")
6545 (make-local-variable 'comment-column)
6546 (setq comment-column 0)
6547 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
6548 ;; Syntax
6549 (add-hook 'syntax-propertize-extend-region-functions
6550 'markdown-syntax-propertize-extend-region)
6551 (add-hook 'jit-lock-after-change-extend-region-functions
6552 'markdown-font-lock-extend-region-function t t)
6553 (set (make-local-variable 'syntax-propertize-function)
6554 'markdown-syntax-propertize)
6555 ;; Font lock.
6556 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
6557 (set (make-local-variable 'font-lock-defaults) nil)
6558 (set (make-local-variable 'font-lock-multiline) t)
6559 ;; Extensions
6560 (make-local-variable 'markdown-enable-math)
6561 ;; Reload extensions
6562 (markdown-reload-extensions)
6563 ;; Add a buffer-local hook to reload after file-local variables are read
6564 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
6565 ;; For imenu support
6566 (setq imenu-create-index-function
6567 (if markdown-nested-imenu-heading-index
6568 'markdown-imenu-create-nested-index
6569 'markdown-imenu-create-flat-index))
6570 ;; For menu support in XEmacs
6571 (easy-menu-add markdown-mode-menu markdown-mode-map)
6572 ;; Defun movement
6573 (set (make-local-variable 'beginning-of-defun-function)
6574 'markdown-beginning-of-defun)
6575 (set (make-local-variable 'end-of-defun-function)
6576 'markdown-end-of-defun)
6577 ;; Paragraph filling
6578 (set
6579 ; Should match start of lines that start or separate paragraphs
6580 (make-local-variable 'paragraph-start)
6581 (mapconcat 'identity
6583 "\f" ; starts with a literal line-feed
6584 "[ \t\f]*$" ; space-only line
6585 "[ \t]*[*+-][ \t]+" ; unordered list item
6586 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6587 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6588 "[ \t]*:[ \t]+" ; definition
6590 "\\|"))
6591 (set
6592 ; Should match lines that separate paragraphs without being
6593 ; part of any paragraph:
6594 (make-local-variable 'paragraph-separate)
6595 (mapconcat 'identity
6596 '("[ \t\f]*$" ; space-only line
6597 ; The following is not ideal, but the Fill customization
6598 ; options really only handle paragraph-starting prefixes,
6599 ; not paragraph-ending suffixes:
6600 ".* $" ; line ending in two spaces
6601 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6602 "\\|"))
6603 (set (make-local-variable 'adaptive-fill-first-line-regexp)
6604 "\\`[ \t]*>[ \t]*?\\'")
6605 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
6606 (set (make-local-variable 'adaptive-fill-function)
6607 'markdown-adaptive-fill-function)
6608 (set (make-local-variable 'fill-forward-paragraph-function)
6609 'markdown-fill-forward-paragraph-function)
6610 ;; Outline mode
6611 (make-local-variable 'outline-regexp)
6612 (setq outline-regexp markdown-regex-header)
6613 (make-local-variable 'outline-level)
6614 (setq outline-level 'markdown-outline-level)
6615 ;; Cause use of ellipses for invisible text.
6616 (add-to-invisibility-spec '(outline . t))
6618 ;; Inhibiting line-breaking:
6619 ;; Separating out each condition into a separate function so that users can
6620 ;; override if desired (with remove-hook)
6621 (add-hook 'fill-nobreak-predicate
6622 'markdown-inside-link-text-p nil t)
6623 (add-hook 'fill-nobreak-predicate
6624 'markdown-line-is-reference-definition-p nil t)
6626 ;; Indentation
6627 (setq indent-line-function markdown-indent-function)
6629 ;; Backwards compatibility with markdown-css-path
6630 (when (boundp 'markdown-css-path)
6631 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6632 (add-to-list 'markdown-css-paths markdown-css-path))
6634 ;; Prepare hooks for XEmacs compatibility
6635 (when (featurep 'xemacs)
6636 (make-local-hook 'after-change-functions)
6637 (make-local-hook 'font-lock-extend-region-functions)
6638 (make-local-hook 'window-configuration-change-hook))
6640 ;; Make checkboxes buttons
6641 (when markdown-make-gfm-checkboxes-buttons
6642 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6643 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
6645 ;; add live preview export hook
6646 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
6647 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
6649 ;;;###autoload
6650 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
6651 ;;;###autoload
6652 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
6655 ;;; GitHub Flavored Markdown Mode ============================================
6657 (defvar gfm-mode-hook nil
6658 "Hook run when entering GFM mode.")
6660 (defvar gfm-font-lock-keywords
6661 (append
6662 ;; GFM features to match first
6663 (list
6664 (cons markdown-regex-strike-through '((3 markdown-markup-face)
6665 (4 markdown-strike-through-face)
6666 (5 markdown-markup-face))))
6667 ;; Basic Markdown features (excluding possibly overridden ones)
6668 markdown-mode-font-lock-keywords-basic)
6669 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6671 ;;;###autoload
6672 (define-derived-mode gfm-mode markdown-mode "GFM"
6673 "Major mode for editing GitHub Flavored Markdown files."
6674 (setq markdown-link-space-sub-char "-")
6675 (set (make-local-variable 'font-lock-defaults)
6676 '(gfm-font-lock-keywords))
6677 ;; do the initial link fontification
6678 (markdown-gfm-parse-buffer-for-languages))
6681 ;;; Live Preview Mode ============================================
6682 (define-minor-mode markdown-live-preview-mode
6683 "Toggle native previewing on save for a specific markdown file."
6684 :lighter " MD-Preview"
6685 (if markdown-live-preview-mode
6686 (markdown-display-buffer-other-window (markdown-live-preview-export))
6687 (markdown-live-preview-remove)))
6690 (provide 'markdown-mode)
6691 ;; Local Variables:
6692 ;; indent-tabs-mode: nil
6693 ;; End:
6694 ;;; markdown-mode.el ends here