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