Better backwards compatibility for url-parse
[markdown-mode.git] / markdown-mode.el
blobf617b153062e42d6bce896032e402caf5bae6606
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")
953 ;;; Constants =================================================================
955 (defconst markdown-mode-version "2.1"
956 "Markdown mode version number.")
958 (defconst markdown-output-buffer-name "*markdown-output*"
959 "Name of temporary buffer for markdown command output.")
962 ;;; Global Variables ==========================================================
964 (defvar markdown-reference-label-history nil
965 "History of used reference labels.")
967 (defvar markdown-live-preview-mode nil
968 "Sentinel variable for command `markdown-live-preview-mode'.")
970 (defvar markdown-gfm-language-history nil
971 "History list of languages used in the current buffer in GFM code blocks.")
974 ;;; Customizable Variables ====================================================
976 (defvar markdown-mode-hook nil
977 "Hook run when entering Markdown mode.")
979 (defvar markdown-before-export-hook nil
980 "Hook run before running Markdown to export XHTML output.
981 The hook may modify the buffer, which will be restored to it's
982 original state after exporting is complete.")
984 (defvar markdown-after-export-hook nil
985 "Hook run after XHTML output has been saved.
986 Any changes to the output buffer made by this hook will be saved.")
988 (defgroup markdown nil
989 "Major mode for editing text files in Markdown format."
990 :prefix "markdown-"
991 :group 'wp
992 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
994 (defcustom markdown-command "markdown"
995 "Command to run markdown."
996 :group 'markdown
997 :type 'string)
999 (defcustom markdown-command-needs-filename nil
1000 "Set to non-nil if `markdown-command' does not accept input from stdin.
1001 Instead, it will be passed a filename as the final command line
1002 option. As a result, you will only be able to run Markdown from
1003 buffers which are visiting a file."
1004 :group 'markdown
1005 :type 'boolean)
1007 (defcustom markdown-open-command nil
1008 "Command used for opening Markdown files directly.
1009 For example, a standalone Markdown previewer. This command will
1010 be called with a single argument: the filename of the current
1011 buffer."
1012 :group 'markdown
1013 :type 'string)
1015 (defcustom markdown-hr-strings
1016 '("-------------------------------------------------------------------------------"
1017 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1018 "---------------------------------------"
1019 "* * * * * * * * * * * * * * * * * * * *"
1020 "---------"
1021 "* * * * *")
1022 "Strings to use when inserting horizontal rules.
1023 The first string in the list will be the default when inserting a
1024 horizontal rule. Strings should be listed in decreasing order of
1025 prominence (as in headings from level one to six) for use with
1026 promotion and demotion functions."
1027 :group 'markdown
1028 :type 'list)
1030 (defcustom markdown-bold-underscore nil
1031 "Use two underscores when inserting bold text instead of two asterisks."
1032 :group 'markdown
1033 :type 'boolean)
1035 (defcustom markdown-italic-underscore nil
1036 "Use underscores when inserting italic text instead of asterisks."
1037 :group 'markdown
1038 :type 'boolean)
1040 (defcustom markdown-asymmetric-header nil
1041 "Determines if header style will be asymmetric.
1042 Set to non-nil to only have header characters to the left of the title.
1043 The default will ensure header characters are placed to the left and right
1044 of the title."
1045 :group 'markdown
1046 :type 'boolean)
1048 (defcustom markdown-indent-function 'markdown-indent-line
1049 "Function to use to indent."
1050 :group 'markdown
1051 :type 'function)
1053 (defcustom markdown-indent-on-enter t
1054 "Automatically indent new lines when enter key is pressed.
1055 When this variable is set to t, pressing RET will call
1056 `newline-and-indent'. When set to nil, define RET to call
1057 `newline' as usual. In the latter case, you can still use
1058 auto-indentation by pressing \\[newline-and-indent]."
1059 :group 'markdown
1060 :type 'boolean)
1062 (defcustom markdown-enable-wiki-links nil
1063 "Syntax highlighting for wiki links.
1064 Set this to a non-nil value to turn on wiki link support by default.
1065 Support can be toggled later using the `markdown-toggle-wiki-links'
1066 function or \\[markdown-toggle-wiki-links]."
1067 :group 'markdown
1068 :type 'boolean
1069 :safe 'booleanp)
1071 (defcustom markdown-wiki-link-alias-first t
1072 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1073 Otherwise, they will be treated as [[PageName|alias text]]."
1074 :group 'markdown
1075 :type 'boolean
1076 :safe 'booleanp)
1078 (defcustom markdown-wiki-link-search-parent-directories nil
1079 "When non-nil, search for wiki link targets in parent directories.
1080 This is the default search behavior of Ikiwiki."
1081 :group 'markdown
1082 :type 'boolean
1083 :safe 'booleanp)
1085 (defcustom markdown-wiki-link-fontify-missing nil
1086 "When non-nil, change wiki link face according to existence of target files.
1087 This is expensive because it requires checking for the file each time the buffer
1088 changes or the user switches windows. It is disabled by default because it may
1089 cause lag when typing on slower machines."
1090 :group 'markdown
1091 :type 'boolean
1092 :safe 'booleanp)
1094 (defcustom markdown-uri-types
1095 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
1096 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
1097 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
1098 "Link types for syntax highlighting of URIs."
1099 :group 'markdown
1100 :type 'list)
1102 (defcustom markdown-enable-math nil
1103 "Syntax highlighting for inline LaTeX and itex expressions.
1104 Set this to a non-nil value to turn on math support by default.
1105 Math support can be enabled, disabled, or toggled later using
1106 `markdown-toggle-math' or \\[markdown-toggle-math]."
1107 :group 'markdown
1108 :type 'boolean
1109 :safe 'booleanp)
1111 (defcustom markdown-css-paths nil
1112 "URL of CSS file to link to in the output XHTML."
1113 :group 'markdown
1114 :type 'list)
1116 (defcustom markdown-content-type ""
1117 "Content type string for the http-equiv header in XHTML output.
1118 When set to a non-empty string, insert the http-equiv attribute.
1119 Otherwise, this attribute is omitted."
1120 :group 'markdown
1121 :type 'string)
1123 (defcustom markdown-coding-system nil
1124 "Character set string for the http-equiv header in XHTML output.
1125 Defaults to `buffer-file-coding-system' (and falling back to
1126 `iso-8859-1' when not available). Common settings are `utf-8'
1127 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1128 :group 'markdown
1129 :type 'coding-system)
1131 (defcustom markdown-xhtml-header-content ""
1132 "Additional content to include in the XHTML <head> block."
1133 :group 'markdown
1134 :type 'string)
1136 (defcustom markdown-xhtml-standalone-regexp
1137 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1138 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1139 :group 'markdown
1140 :type 'regexp)
1142 (defcustom markdown-link-space-sub-char "_"
1143 "Character to use instead of spaces when mapping wiki links to filenames."
1144 :group 'markdown
1145 :type 'string)
1147 (defcustom markdown-reference-location 'header
1148 "Position where new reference definitions are inserted in the document."
1149 :group 'markdown
1150 :type '(choice (const :tag "At the end of the document" end)
1151 (const :tag "Immediately after the current block" immediately)
1152 (const :tag "Before next header" header)))
1154 (defcustom markdown-footnote-location 'end
1155 "Position where new footnotes are inserted in the document."
1156 :group 'markdown
1157 :type '(choice (const :tag "At the end of the document" end)
1158 (const :tag "Immediately after the current block" immediately)
1159 (const :tag "Before next header" header)))
1161 (defcustom markdown-unordered-list-item-prefix " * "
1162 "String inserted before unordered list items."
1163 :group 'markdown
1164 :type 'string)
1166 (defcustom markdown-nested-imenu-heading-index nil
1167 "Use nested or flat imenu heading index.
1168 A nested index may provide more natural browsing from the menu,
1169 but a flat list may allow for faster keyboard navigation via tab
1170 completion."
1171 :group 'markdown
1172 :type 'boolean)
1174 (defcustom markdown-make-gfm-checkboxes-buttons t
1175 "When non-nil, make GFM checkboxes into buttons."
1176 :group 'markdown
1177 :type 'boolean)
1179 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1180 "When non-nil, allow yaml metadata anywhere in the document."
1181 :group 'markdown
1182 :type 'boolean)
1184 (defcustom markdown-live-preview-window-function
1185 'markdown-live-preview-window-eww
1186 "Function to display preview of Markdown output within Emacs.
1187 Function must update the buffer containing the preview and return
1188 the buffer."
1189 :group 'markdown
1190 :type 'function)
1192 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1193 "Delete exported html file when using `markdown-live-preview-export'.
1194 If set to 'delete-on-export, delete on every export. When set to
1195 'delete-on-destroy delete when quitting from command
1196 `markdown-live-preview-mode'. Never delete if set to nil."
1197 :group 'markdown
1198 :type 'symbol)
1200 (defcustom markdown-list-indent-width 4
1201 "Depth of indentation for markdown lists.
1202 Used in `markdown-demote-list-item' and
1203 `markdown-promote-list-item'."
1204 :group 'markdown
1205 :type 'integer)
1207 (defcustom markdown-gfm-additional-languages nil
1208 "Extra languages made available when inserting GFM code blocks.
1209 Language strings must have be trimmed of whitespace and not
1210 contain any curly braces. They may be of arbitrary
1211 capitalization, though."
1212 :group 'markdown
1213 :type '(repeat (string :validate markdown-validate-language-string)))
1215 (defcustom markdown-gfm-use-electric-backquote t
1216 "Use `markdown-electric-backquote' when backquote is hit three times."
1217 :group 'markdown
1218 :type 'boolean)
1220 (defcustom markdown-gfm-downcase-languages t
1221 "If non-nil, downcase suggested languages.
1222 This applies to insertions done with
1223 `markdown-electric-backquote'."
1224 :group 'markdown
1225 :type 'boolean)
1228 ;;; Regular Expressions =======================================================
1230 (defconst markdown-regex-comment-start
1231 "<!--"
1232 "Regular expression matches HTML comment opening.")
1234 (defconst markdown-regex-comment-end
1235 "--[ \t]*>"
1236 "Regular expression matches HTML comment closing.")
1238 (defconst markdown-regex-link-inline
1239 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1240 "Regular expression for a [text](file) or an image link ![text](file).
1241 Group 1 matches the leading exclamation point (optional).
1242 Group 2 matches the opening square bracket.
1243 Group 3 matches the text inside the square brackets.
1244 Group 4 matches the closing square bracket.
1245 Group 5 matches the opening parenthesis.
1246 Group 6 matches the URL.
1247 Group 7 matches the title (optional).
1248 Group 8 matches the closing parenthesis.")
1250 (defconst markdown-regex-link-reference
1251 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1252 "Regular expression for a reference link [text][id].
1253 Group 1 matches the leading exclamation point (optional).
1254 Group 2 matches the opening square bracket for the link text.
1255 Group 3 matches the text inside the square brackets.
1256 Group 4 matches the closing square bracket for the link text.
1257 Group 5 matches the opening square bracket for the reference label.
1258 Group 6 matches the reference label.
1259 Group 7 matches the closing square bracket for the reference label.")
1261 (defconst markdown-regex-reference-definition
1262 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1263 "Regular expression for a reference definition.
1264 Group 1 matches the opening square bracket.
1265 Group 2 matches the reference label.
1266 Group 3 matches the closing square bracket.
1267 Group 4 matches the colon.
1268 Group 5 matches the URL.
1269 Group 6 matches the title attribute (optional).")
1271 (defconst markdown-regex-footnote
1272 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1273 "Regular expression for a footnote marker [^fn].
1274 Group 1 matches the opening square bracket and carat.
1275 Group 2 matches only the label, without the surrounding markup.
1276 Group 3 matches the closing square bracket.")
1278 (defconst markdown-regex-header
1279 "^\\(?:\\(.+?\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)\\)$"
1280 "Regexp identifying Markdown headings.
1281 Group 1 matches the text of a setext heading.
1282 Group 2 matches the underline of a level-1 setext heading.
1283 Group 3 matches the underline of a level-2 setext heading.
1284 Group 4 matches the opening hash marks of an atx heading.
1285 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1286 Group 6 matches the closing hash marks of an atx heading.")
1288 (defconst markdown-regex-header-1-atx
1289 "^\\(#\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1290 "Regular expression for level 1 atx-style (hash mark) headers.")
1292 (defconst markdown-regex-header-2-atx
1293 "^\\(##\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1294 "Regular expression for level 2 atx-style (hash mark) headers.")
1296 (defconst markdown-regex-header-3-atx
1297 "^\\(###\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1298 "Regular expression for level 3 atx-style (hash mark) headers.")
1300 (defconst markdown-regex-header-4-atx
1301 "^\\(####\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1302 "Regular expression for level 4 atx-style (hash mark) headers.")
1304 (defconst markdown-regex-header-5-atx
1305 "^\\(#####\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1306 "Regular expression for level 5 atx-style (hash mark) headers.")
1308 (defconst markdown-regex-header-6-atx
1309 "^\\(######\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1310 "Regular expression for level 6 atx-style (hash mark) headers.")
1312 (defconst markdown-regex-header-1-setext
1313 "^\\(.*\\)\n\\(=+\\)$"
1314 "Regular expression for level 1 setext-style (underline) headers.")
1316 (defconst markdown-regex-header-2-setext
1317 "^\\(.*\\)\n\\(-+\\)$"
1318 "Regular expression for level 2 setext-style (underline) headers.")
1320 (defconst markdown-regex-header-setext
1321 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1322 "Regular expression for generic setext-style (underline) headers.")
1324 (defconst markdown-regex-header-atx
1325 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1326 "Regular expression for generic atx-style (hash mark) headers.")
1328 (defconst markdown-regex-hr
1329 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1330 "Regular expression for matching Markdown horizontal rules.")
1332 (defconst markdown-regex-code
1333 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1334 "Regular expression for matching inline code fragments.
1336 Group 1 matches the entire code fragment including the backticks.
1337 Group 2 matches the opening backticks.
1338 Group 3 matches the code fragment itself, without backticks.
1339 Group 4 matches the closing backticks.
1341 The leading, unnumbered group ensures that the leading backquote
1342 character is not escaped.
1343 The last group, also unnumbered, requires that the character
1344 following the code fragment is not a backquote.
1345 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1346 but not two newlines in a row.")
1348 (defconst markdown-regex-kbd
1349 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1350 "Regular expression for matching <kbd> tags.
1351 Groups 1 and 3 match the opening and closing tags.
1352 Group 2 matches the key sequence.")
1354 (defconst markdown-regex-gfm-code-block-open
1355 "^[[:blank:]]*\\(```\\)[ ]?\\([^[:space:]]+\\|{[^}]*}\\)?\\([[:space:]]*?\\)$"
1356 "Regular expression matching opening of GFM code blocks.
1357 Group 1 matches the opening three backticks.
1358 Group 2 matches the language identifier (optional).")
1360 (defconst markdown-regex-gfm-code-block-close
1361 "^[[:blank:]]*\\(```\\)\\s *?$"
1362 "Regular expression matching closing of GFM code blocks.
1363 Group 1 matches the closing three backticks.")
1365 (defconst markdown-regex-pre
1366 "^\\( \\|\t\\).*$"
1367 "Regular expression for matching preformatted text sections.")
1369 (defconst markdown-regex-list
1370 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1371 "Regular expression for matching list items.")
1373 (defconst markdown-regex-bold
1374 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1375 "Regular expression for matching bold text.
1376 Group 1 matches the character before the opening asterisk or
1377 underscore, if any, ensuring that it is not a backslash escape.
1378 Group 2 matches the entire expression, including delimiters.
1379 Groups 3 and 5 matches the opening and closing delimiters.
1380 Group 4 matches the text inside the delimiters.")
1382 (defconst markdown-regex-italic
1383 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1384 "Regular expression for matching italic text.
1385 The leading unnumbered matches the character before the opening
1386 asterisk or underscore, if any, ensuring that it is not a
1387 backslash escape.
1388 Group 1 matches the entire expression, including delimiters.
1389 Groups 2 and 4 matches the opening and closing delimiters.
1390 Group 3 matches the text inside the delimiters.")
1392 (defconst markdown-regex-strike-through
1393 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1394 "Regular expression for matching strike-through text.
1395 Group 1 matches the character before the opening tilde, if any,
1396 ensuring that it is not a backslash escape.
1397 Group 2 matches the entire expression, including delimiters.
1398 Groups 3 and 5 matches the opening and closing delimiters.
1399 Group 4 matches the text inside the delimiters.")
1401 (defconst markdown-regex-gfm-italic
1402 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1403 "Regular expression for matching italic text in GitHub Flavored Markdown.
1404 Underscores in words are not treated as special.
1405 Group 1 matches the entire expression, including delimiters.
1406 Groups 2 and 4 matches the opening and closing delimiters.
1407 Group 3 matches the text inside the delimiters.")
1409 (defconst markdown-regex-blockquote
1410 "^[ \t]*\\(>\\)\\(.*\\)$"
1411 "Regular expression for matching blockquote lines.
1412 Group 1 matches the leading angle bracket.
1413 Group 2 matches the text.")
1415 (defconst markdown-regex-line-break
1416 "[^ \n\t][ \t]*\\( \\)$"
1417 "Regular expression for matching line breaks.")
1419 (defconst markdown-regex-wiki-link
1420 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1421 "Regular expression for matching wiki links.
1422 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1423 wiki links of the form [[PageName|link text]].
1424 The meanings of the first and second components depend
1425 on the value of `markdown-wiki-link-alias-first'.
1427 Group 1 matches the entire link.
1428 Group 2 matches the opening square brackets.
1429 Group 3 matches the first component of the wiki link.
1430 Group 4 matches the pipe separator, when present.
1431 Group 5 matches the second component of the wiki link, when present.
1432 Group 6 matches the closing square brackets.")
1434 (defconst markdown-regex-uri
1435 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1436 "Regular expression for matching inline URIs.")
1438 (defconst markdown-regex-angle-uri
1439 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1440 "Regular expression for matching inline URIs in angle brackets.")
1442 (defconst markdown-regex-email
1443 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1444 "Regular expression for matching inline email addresses.")
1446 (defsubst markdown-make-regex-link-generic ()
1447 "Make regular expression for matching any recognized link."
1448 (concat "\\(?:" markdown-regex-link-inline
1449 (when markdown-enable-wiki-links
1450 (concat "\\|" markdown-regex-wiki-link))
1451 "\\|" markdown-regex-link-reference
1452 "\\|" markdown-regex-angle-uri "\\)"))
1454 (defconst markdown-regex-gfm-checkbox
1455 " \\(\\[[ xX]\\]\\) "
1456 "Regular expression for matching GFM checkboxes.
1457 Group 1 matches the text to become a button.")
1459 (defconst markdown-regex-block-separator
1460 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1461 "Regular expression for matching block boundaries.")
1463 (defconst markdown-regex-math-inline-single
1464 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1465 "Regular expression for itex $..$ math mode expressions.
1466 Groups 1 and 3 match the opening and closing dollar signs.
1467 Group 3 matches the mathematical expression contained within.")
1469 (defconst markdown-regex-math-inline-double
1470 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1471 "Regular expression for itex $$..$$ math mode expressions.
1472 Groups 1 and 3 match opening and closing dollar signs.
1473 Group 3 matches the mathematical expression contained within.")
1475 (defconst markdown-regex-math-display
1476 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*\\)?\\(\\\\\\]\\)$"
1477 "Regular expression for itex \[..\] display mode expressions.
1478 Groups 1 and 3 match the opening and closing delimiters.
1479 Group 2 matches the mathematical expression contained within.")
1481 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1482 "Return regexp matching a Pandoc code fence at least NUM-TILDES long.
1483 END-OF-LINE is the regexp construct to indicate end of line; $ if
1484 missing."
1485 (format "%s%d%s%s" "^\\([~]\\{" num-tildes ",\\}\\)" (or end-of-line "$")))
1487 (defconst markdown-regex-tilde-fence-begin
1488 (markdown-make-tilde-fence-regex
1489 3 "[ ]?\\([^[:space:]]+\\|{[^}]*}\\)?\\([[:space:]]*?\\)$")
1490 "Regular expression for matching Pandoc tildes.")
1492 (defconst markdown-regex-declarative-metadata
1493 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1494 "Regular expression for matching declarative metadata statements.
1495 This matches MultiMarkdown metadata as well as YAML and TOML
1496 assignments such as the following:
1498 variable: value
1502 variable = value")
1504 (defconst markdown-regex-pandoc-metadata
1505 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1506 "Regular expression for matching Pandoc metadata.")
1508 (defconst markdown-regex-yaml-metadata-border
1509 "\\(\\-\\{3\\}\\)$"
1510 "Regular expression for matching yaml metadata.")
1512 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1513 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1514 "Regular expression for matching yaml metadata end borders.")
1516 (defsubst markdown-get-yaml-metadata-start-border ()
1517 "Return yaml metadata start border depending upon whether Pandoc is used."
1518 (concat
1519 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1520 markdown-regex-yaml-metadata-border))
1522 (defsubst markdown-get-yaml-metadata-end-border (_)
1523 "Return yaml metadata end border depending upon whether Pandoc is used."
1524 (if markdown-use-pandoc-style-yaml-metadata
1525 markdown-regex-yaml-pandoc-metadata-end-border
1526 markdown-regex-yaml-metadata-border))
1529 ;;; Syntax ====================================================================
1531 (defun markdown-syntax-propertize-extend-region (start end)
1532 "Extend START to END region to include an entire block of text.
1533 This helps improve syntax analysis for block constructs.
1534 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1535 Function is called repeatedly until it returns nil. For details, see
1536 `syntax-propertize-extend-region-functions'."
1537 (save-match-data
1538 (save-excursion
1539 (let* ((new-start (progn (goto-char start)
1540 (skip-chars-forward "\n")
1541 (if (re-search-backward "\n\n" nil t)
1542 (min start (match-end 0))
1543 (point-min))))
1544 (new-end (progn (goto-char end)
1545 (skip-chars-backward "\n")
1546 (if (re-search-forward "\n\n" nil t)
1547 (max end (match-beginning 0))
1548 (point-max))))
1549 (code-match (markdown-code-block-at-pos new-start))
1550 (new-start (or (and code-match (cl-first code-match)) new-start))
1551 (code-match (markdown-code-block-at-pos end))
1552 (new-end (or (and code-match (cl-second code-match)) new-end)))
1553 (unless (and (eq new-start start) (eq new-end end))
1554 (cons new-start new-end))))))
1556 (defun markdown-font-lock-extend-region-function (start end _)
1557 "Used in `jit-lock-after-change-extend-region-functions'.
1558 Delegates to `markdown-syntax-propertize-extend-region'. START
1559 and END are the previous region to refontify."
1560 (let ((res (markdown-syntax-propertize-extend-region start end)))
1561 (when res
1562 (setq jit-lock-start (car res)
1563 jit-lock-end (cdr res)))))
1565 (defun markdown-syntax-propertize-pre-blocks (start end)
1566 "Match preformatted text blocks from START to END."
1567 (save-excursion
1568 (goto-char start)
1569 (let ((levels (markdown-calculate-list-levels))
1570 indent pre-regexp close-regexp open close)
1571 (while (and (< (point) end) (not close))
1572 ;; Search for a region with sufficient indentation
1573 (if (null levels)
1574 (setq indent 1)
1575 (setq indent (1+ (length levels))))
1576 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1577 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1579 (cond
1580 ;; If not at the beginning of a line, move forward
1581 ((not (bolp)) (forward-line))
1582 ;; Move past blank lines
1583 ((markdown-cur-line-blank-p) (forward-line))
1584 ;; At headers and horizontal rules, reset levels
1585 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1586 ;; If the current line has sufficient indentation, mark out pre block
1587 ;; The opening should be preceded by a blank line.
1588 ((and (looking-at pre-regexp)
1589 (save-match-data (markdown-prev-line-blank-p)))
1590 (setq open (match-beginning 0))
1591 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1592 (not (eobp)))
1593 (forward-line))
1594 (skip-syntax-backward "-")
1595 (setq close (point)))
1596 ;; If current line has a list marker, update levels, move to end of block
1597 ((looking-at markdown-regex-list)
1598 (setq levels (markdown-update-list-levels
1599 (match-string 2) (current-indentation) levels))
1600 (markdown-end-of-block-element))
1601 ;; If this is the end of the indentation level, adjust levels accordingly.
1602 ;; Only match end of indentation level if levels is not the empty list.
1603 ((and (car levels) (looking-at-p close-regexp))
1604 (setq levels (markdown-update-list-levels
1605 nil (current-indentation) levels))
1606 (markdown-end-of-block-element))
1607 (t (markdown-end-of-block-element))))
1609 (when (and open close)
1610 ;; Set text property data
1611 (put-text-property open close 'markdown-pre (list open close))
1612 ;; Recursively search again
1613 (markdown-syntax-propertize-pre-blocks (point) end)))))
1615 (defconst markdown-fenced-block-pairs
1616 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1617 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1618 markdown-fenced-code)
1619 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1620 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1621 markdown-yaml-metadata-section)
1622 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1623 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1624 markdown-gfm-code))
1625 "Mapping of regular expressions to \"fenced-block\" constructs.
1626 These constructs are distinguished by having a distinctive start
1627 and end pattern, both of which take up an entire line of text,
1628 but no special pattern to identify text within the fenced
1629 blocks (unlike blockquotes and indented-code sections).
1631 Each element within this list takes the form:
1633 ((START-REGEX-OR-FUN START-PROPERTY)
1634 (END-REGEX-OR-FUN END-PROPERTY)
1635 MIDDLE-PROPERTY)
1637 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1638 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1639 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1640 which is the length of the first group of the START-REGEX-OR-FUN match, which
1641 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1642 evaluate these into \"real\" regexps.
1644 The *-PROPERTY elements are the text properties applied to each part of the
1645 block construct when it is matched using
1646 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1647 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1648 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1649 `match-data' when the regexp was matched to the text. In the case of
1650 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1651 begin and end set to the edges of the \"middle\" text. This makes fontification
1652 easier.")
1654 (defun markdown-text-property-at-point (prop)
1655 (get-text-property (point) prop))
1657 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1658 (cond ((functionp object)
1659 (if arg (funcall object arg) (funcall object)))
1660 ((stringp object) object)
1661 (t (error "Object cannot be turned into regex"))))
1663 (defsubst markdown-get-start-fence-regexp ()
1664 "Return regexp to find all \"start\" sections of fenced block constructs.
1665 Which construct is actually contained in the match must be found separately."
1666 (mapconcat
1667 'identity
1668 (cl-mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1669 markdown-fenced-block-pairs)
1670 "\\|"))
1672 (defun markdown-get-fenced-block-begin-properties ()
1673 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1675 (defun markdown-get-fenced-block-end-properties ()
1676 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1678 (defun markdown-get-fenced-block-middle-properties ()
1679 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1681 (defun markdown-find-previous-prop (prop &optional lim)
1682 "Find previous place where property PROP is non-nil, up to LIM.
1683 Return a cons of (pos . property). pos is point if point contains
1684 non-nil PROP."
1685 (let ((res
1686 (if (get-text-property (point) prop) (point)
1687 (previous-single-property-change
1688 (point) prop nil (or lim (point-min))))))
1689 (when (and (not (get-text-property res prop))
1690 (> res (point-min))
1691 (get-text-property (1- res) prop))
1692 (cl-decf res))
1693 (when (and res (get-text-property res prop)) (cons res prop))))
1695 (defun markdown-find-next-prop (prop &optional lim)
1696 "Find next place where property PROP is non-nil, up to LIM.
1697 Return a cons of (POS . PROPERTY) where POS is point if point
1698 contains non-nil PROP."
1699 (let ((res
1700 (if (get-text-property (point) prop) (point)
1701 (next-single-property-change
1702 (point) prop nil (or lim (point-max))))))
1703 (when (and res (get-text-property res prop)) (cons res prop))))
1705 (defun markdown-min-of-seq (map-fn seq)
1706 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1707 (cl-loop for el in seq
1708 with min = 1.0e+INF ; infinity
1709 with min-el = nil
1710 do (let ((res (funcall map-fn el)))
1711 (when (< res min)
1712 (setq min res)
1713 (setq min-el el)))
1714 finally return min-el))
1716 (defun markdown-find-previous-block ()
1717 "Find previous block.
1718 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1719 unable to propertize the entire block, but was able to propertize the beginning
1720 of the block. If so, return a cons of (pos . property) where the beginning of
1721 the block was propertized."
1722 (let ((start-pt (point))
1723 (closest-open
1724 (markdown-min-of-seq
1725 #'car
1726 (cl-remove-if
1727 #'null
1728 (cl-mapcar
1729 #'markdown-find-previous-prop
1730 (markdown-get-fenced-block-begin-properties))))))
1731 (when closest-open
1732 (let* ((length-of-open-match
1733 (let ((match-d
1734 (get-text-property (car closest-open) (cdr closest-open))))
1735 (- (cl-fourth match-d) (cl-third match-d))))
1736 (end-regexp
1737 (markdown-maybe-funcall-regexp
1738 (cl-caadr
1739 (cl-find-if
1740 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1741 markdown-fenced-block-pairs))
1742 length-of-open-match))
1743 (end-prop-loc
1744 (save-excursion
1745 (save-match-data
1746 (goto-char (car closest-open))
1747 (and (re-search-forward end-regexp start-pt t)
1748 (match-beginning 0))))))
1749 (and (not end-prop-loc) closest-open)))))
1751 (defun markdown-get-fenced-block-from-start (prop)
1752 "Return limits of an enclosing fenced block from its start, using PROP.
1753 Return value is a list usable as `match-data'."
1754 (catch 'no-rest-of-block
1755 (let* ((correct-entry
1756 (cl-find-if
1757 (lambda (entry) (eq (cl-cadar entry) prop))
1758 markdown-fenced-block-pairs))
1759 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1760 (middle-prop (cl-third correct-entry))
1761 (end-prop (cl-cadadr correct-entry))
1762 (end-of-end
1763 (save-excursion
1764 (goto-char (match-end 0)) ; end of begin
1765 (unless (eobp) (forward-char))
1766 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1767 (if (not mid-prop-v) ; no middle
1768 (progn
1769 ;; try to find end by advancing one
1770 (let ((end-prop-v
1771 (markdown-text-property-at-point end-prop)))
1772 (if end-prop-v (cl-second end-prop-v)
1773 (throw 'no-rest-of-block nil))))
1774 (set-match-data mid-prop-v)
1775 (goto-char (match-end 0)) ; end of middle
1776 (beginning-of-line) ; into end
1777 (cl-second (markdown-text-property-at-point end-prop)))))))
1778 (list begin-of-begin end-of-end))))
1780 (defun markdown-get-fenced-block-from-middle (prop)
1781 "Return limits of an enclosing fenced block from its middle, using PROP.
1782 Return value is a list usable as `match-data'."
1783 (let* ((correct-entry
1784 (cl-find-if
1785 (lambda (entry) (eq (cl-third entry) prop))
1786 markdown-fenced-block-pairs))
1787 (begin-prop (cl-cadar correct-entry))
1788 (begin-of-begin
1789 (save-excursion
1790 (goto-char (match-beginning 0))
1791 (unless (bobp) (forward-line -1))
1792 (beginning-of-line)
1793 (cl-first (markdown-text-property-at-point begin-prop))))
1794 (end-prop (cl-cadadr correct-entry))
1795 (end-of-end
1796 (save-excursion
1797 (goto-char (match-end 0))
1798 (beginning-of-line)
1799 (cl-second (markdown-text-property-at-point end-prop)))))
1800 (list begin-of-begin end-of-end)))
1802 (defun markdown-get-fenced-block-from-end (prop)
1803 "Return limits of an enclosing fenced block from its end, using PROP.
1804 Return value is a list usable as `match-data'."
1805 (let* ((correct-entry
1806 (cl-find-if
1807 (lambda (entry) (eq (cl-cadadr entry) prop))
1808 markdown-fenced-block-pairs))
1809 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1810 (middle-prop (cl-third correct-entry))
1811 (begin-prop (cl-cadar correct-entry))
1812 (begin-of-begin
1813 (save-excursion
1814 (goto-char (match-beginning 0)) ; beginning of end
1815 (unless (bobp) (backward-char)) ; into middle
1816 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1817 (if (not mid-prop-v)
1818 (progn
1819 (beginning-of-line)
1820 (cl-first (markdown-text-property-at-point begin-prop)))
1821 (set-match-data mid-prop-v)
1822 (goto-char (match-beginning 0)) ; beginning of middle
1823 (unless (bobp) (forward-line -1)) ; into beginning
1824 (beginning-of-line)
1825 (cl-first (markdown-text-property-at-point begin-prop)))))))
1826 (list begin-of-begin end-of-end)))
1828 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1829 "Get \"fake\" match data for block enclosing POS.
1830 Returns fake match data which encloses the start, middle, and end
1831 of the block construct enclosing POS, if it exists. Used in
1832 `markdown-code-block-at-pos'."
1833 (save-excursion
1834 (when pos (goto-char pos))
1835 (beginning-of-line)
1836 (car
1837 (cl-remove-if
1838 #'null
1839 (cl-mapcar
1840 (lambda (fun-and-prop)
1841 (cl-destructuring-bind (fun prop) fun-and-prop
1842 (when prop
1843 (save-match-data
1844 (set-match-data (markdown-text-property-at-point prop))
1845 (funcall fun prop)))))
1846 `((markdown-get-fenced-block-from-start
1847 ,(cl-find-if
1848 #'markdown-text-property-at-point
1849 (markdown-get-fenced-block-begin-properties)))
1850 (markdown-get-fenced-block-from-middle
1851 ,(cl-find-if
1852 #'markdown-text-property-at-point
1853 (markdown-get-fenced-block-middle-properties)))
1854 (markdown-get-fenced-block-from-end
1855 ,(cl-find-if
1856 #'markdown-text-property-at-point
1857 (markdown-get-fenced-block-end-properties)))))))))
1859 (defun markdown-propertize-end-match (reg end correct-entry enclosed-text-start)
1860 "Get match for REG up to END, if exists, and propertize appropriately.
1861 CORRECT-ENTRY is an entry in `markdown-fenced-block-pairs' and
1862 ENCLOSED-TEXT-START is the start of the \"middle\" section of the block."
1863 (when (re-search-forward reg end t)
1864 (put-text-property (match-beginning 0) (match-end 0)
1865 (cl-cadadr correct-entry) (match-data t))
1866 (put-text-property
1867 enclosed-text-start (match-beginning 0) (cl-third correct-entry)
1868 (list enclosed-text-start (match-beginning 0)))))
1870 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1871 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1872 If unable to propertize an entire block (if the start of a block is within START
1873 and END, but the end of the block is not), propertize the start section of a
1874 block, then in a subsequent call propertize both middle and end by finding the
1875 start which was previously propertized."
1876 (let ((start-reg (markdown-get-start-fence-regexp)))
1877 (save-excursion
1878 (goto-char start)
1879 ;; start from previous unclosed block, if exists
1880 (let ((prev-begin-block (markdown-find-previous-block)))
1881 (when prev-begin-block
1882 (let* ((correct-entry
1883 (cl-find-if (lambda (entry)
1884 (eq (cdr prev-begin-block) (cl-cadar entry)))
1885 markdown-fenced-block-pairs))
1886 (enclosed-text-start (1+ (car prev-begin-block)))
1887 (start-length
1888 (save-excursion
1889 (goto-char (car prev-begin-block))
1890 (string-match
1891 (markdown-maybe-funcall-regexp
1892 (caar correct-entry))
1893 (buffer-substring
1894 (point-at-bol) (point-at-eol)))
1895 (- (match-end 1) (match-beginning 1))))
1896 (end-reg (markdown-maybe-funcall-regexp
1897 (cl-caadr correct-entry) start-length)))
1898 (markdown-propertize-end-match
1899 end-reg end correct-entry enclosed-text-start))))
1900 ;; find all new blocks within region
1901 (while (re-search-forward start-reg end t)
1902 ;; we assume the opening constructs take up (only) an entire line,
1903 ;; so we re-check the current line
1904 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1905 ;; find entry in `markdown-fenced-block-pairs' corresponding
1906 ;; to regex which was matched
1907 (correct-entry
1908 (cl-find-if
1909 (lambda (fenced-pair)
1910 (string-match-p
1911 (markdown-maybe-funcall-regexp (caar fenced-pair))
1912 cur-line))
1913 markdown-fenced-block-pairs))
1914 (enclosed-text-start
1915 (save-excursion (1+ (point-at-eol))))
1916 (end-reg
1917 (markdown-maybe-funcall-regexp
1918 (cl-caadr correct-entry)
1919 (if (and (match-beginning 1) (match-end 1))
1920 (- (match-end 1) (match-beginning 1))
1921 0))))
1922 ;; get correct match data
1923 (save-excursion
1924 (beginning-of-line)
1925 (re-search-forward
1926 (markdown-maybe-funcall-regexp (caar correct-entry))
1927 (point-at-eol)))
1928 ;; mark starting, even if ending is outside of region
1929 (put-text-property (match-beginning 0) (match-end 0)
1930 (cl-cadar correct-entry) (match-data t))
1931 (markdown-propertize-end-match
1932 end-reg end correct-entry enclosed-text-start))))))
1934 (defun markdown-syntax-propertize-blockquotes (start end)
1935 "Match blockquotes from START to END."
1936 (save-excursion
1937 (goto-char start)
1938 (while (and (re-search-forward markdown-regex-blockquote end t)
1939 (not (markdown-code-block-at-pos (match-beginning 0))))
1940 (put-text-property (match-beginning 0) (match-end 0)
1941 'markdown-blockquote
1942 (match-data t)))))
1944 (defun markdown-syntax-propertize-yaml-metadata (start end)
1945 (save-excursion
1946 (goto-char start)
1947 (cl-loop
1948 while (re-search-forward markdown-regex-declarative-metadata end t)
1949 do (when (get-text-property (match-beginning 0)
1950 'markdown-yaml-metadata-section)
1951 (put-text-property (match-beginning 1) (match-end 1)
1952 'markdown-metadata-key (match-data t))
1953 (put-text-property (match-beginning 2) (match-end 2)
1954 'markdown-metadata-markup (match-data t))
1955 (put-text-property (match-beginning 3) (match-end 3)
1956 'markdown-metadata-value (match-data t))))))
1958 (defun markdown-syntax-propertize-headings (start end)
1959 "Match headings of type SYMBOL with REGEX from START to END."
1960 (goto-char start)
1961 (while (re-search-forward markdown-regex-header end t)
1962 (unless (markdown-code-block-at-pos (match-beginning 0))
1963 (put-text-property
1964 (match-beginning 0) (match-end 0) 'markdown-heading t)
1965 (put-text-property
1966 (match-beginning 0) (match-end 0)
1967 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1968 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1969 (t (let ((atx-level (length (match-string-no-properties 4))))
1970 (intern (format "markdown-heading-%d-atx" atx-level)))))
1971 (match-data t)))))
1973 (defun markdown-syntax-propertize-comments (start end)
1974 "Match HTML comments from the START to END."
1975 (let* ((state (syntax-ppss)) (in-comment (nth 4 state)))
1976 (goto-char start)
1977 (cond
1978 ;; Comment start
1979 ((and (not in-comment)
1980 (re-search-forward markdown-regex-comment-start end t)
1981 (save-match-data (not (markdown-code-at-point-p)))
1982 (save-match-data (not (markdown-code-block-at-point))))
1983 (let ((open-beg (match-beginning 0)))
1984 (put-text-property open-beg (1+ open-beg)
1985 'syntax-table (string-to-syntax "<"))
1986 (markdown-syntax-propertize-comments
1987 (min (1+ (match-end 0)) end (point-max)) end)))
1988 ;; Comment end
1989 ((and in-comment
1990 (re-search-forward markdown-regex-comment-end end t))
1991 (put-text-property (1- (match-end 0)) (match-end 0)
1992 'syntax-table (string-to-syntax ">"))
1993 (markdown-syntax-propertize-comments
1994 (min (1+ (match-end 0)) end (point-max)) end))
1995 ;; Nothing found
1996 (t nil))))
1998 (defvar markdown--syntax-properties
1999 (list 'markdown-tilde-fence-begin nil
2000 'markdown-tilde-fence-end nil
2001 'markdown-fenced-code nil
2002 'markdown-yaml-metadata-begin nil
2003 'markdown-yaml-metadata-end nil
2004 'markdown-yaml-metadata-section nil
2005 'markdown-gfm-block-begin nil
2006 'markdown-gfm-block-end nil
2007 'markdown-gfm-code nil
2008 'markdown-pre nil
2009 'markdown-blockquote nil
2010 'markdown-heading nil
2011 'markdown-heading-1-setext nil
2012 'markdown-heading-2-setext nil
2013 'markdown-heading-1-atx nil
2014 'markdown-heading-2-atx nil
2015 'markdown-heading-3-atx nil
2016 'markdown-heading-4-atx nil
2017 'markdown-heading-5-atx nil
2018 'markdown-heading-6-atx nil
2019 'markdown-metadata-key nil
2020 'markdown-metadata-value nil
2021 'markdown-metadata-markup nil)
2022 "Property list of all known markdown syntactic properties.")
2024 (defun markdown-syntax-propertize (start end)
2025 "Function used as `syntax-propertize-function'.
2026 START and END delimit region to propertize."
2027 (remove-text-properties start end markdown--syntax-properties)
2028 (markdown-syntax-propertize-fenced-block-constructs start end)
2029 (markdown-syntax-propertize-yaml-metadata start end)
2030 (markdown-syntax-propertize-pre-blocks start end)
2031 (markdown-syntax-propertize-blockquotes start end)
2032 (markdown-syntax-propertize-headings start end)
2033 (markdown-syntax-propertize-comments start end))
2036 ;;; Font Lock =================================================================
2038 (require 'font-lock)
2040 (defvar markdown-italic-face 'markdown-italic-face
2041 "Face name to use for italic text.")
2043 (defvar markdown-bold-face 'markdown-bold-face
2044 "Face name to use for bold text.")
2046 (defvar markdown-strike-through-face 'markdown-strike-through-face
2047 "Face name to use for strike-through text.")
2049 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2050 "Face name to use as a base for header delimiters.")
2052 (defvar markdown-header-rule-face 'markdown-header-rule-face
2053 "Face name to use as a base for header rules.")
2055 (defvar markdown-header-face 'markdown-header-face
2056 "Face name to use as a base for headers.")
2058 (defvar markdown-header-face-1 'markdown-header-face-1
2059 "Face name to use for level-1 headers.")
2061 (defvar markdown-header-face-2 'markdown-header-face-2
2062 "Face name to use for level-2 headers.")
2064 (defvar markdown-header-face-3 'markdown-header-face-3
2065 "Face name to use for level-3 headers.")
2067 (defvar markdown-header-face-4 'markdown-header-face-4
2068 "Face name to use for level-4 headers.")
2070 (defvar markdown-header-face-5 'markdown-header-face-5
2071 "Face name to use for level-5 headers.")
2073 (defvar markdown-header-face-6 'markdown-header-face-6
2074 "Face name to use for level-6 headers.")
2076 (defvar markdown-inline-code-face 'markdown-inline-code-face
2077 "Face name to use for inline code.")
2079 (defvar markdown-list-face 'markdown-list-face
2080 "Face name to use for list markers.")
2082 (defvar markdown-blockquote-face 'markdown-blockquote-face
2083 "Face name to use for blockquote.")
2085 (defvar markdown-pre-face 'markdown-pre-face
2086 "Face name to use for preformatted text.")
2088 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2089 "Face name to use for programming language identifiers.")
2091 (defvar markdown-link-face 'markdown-link-face
2092 "Face name to use for links.")
2094 (defvar markdown-missing-link-face 'markdown-missing-link-face
2095 "Face name to use for links where the linked file does not exist.")
2097 (defvar markdown-reference-face 'markdown-reference-face
2098 "Face name to use for reference.")
2100 (defvar markdown-footnote-face 'markdown-footnote-face
2101 "Face name to use for footnote identifiers.")
2103 (defvar markdown-url-face 'markdown-url-face
2104 "Face name to use for URLs.")
2106 (defvar markdown-link-title-face 'markdown-link-title-face
2107 "Face name to use for reference link titles.")
2109 (defvar markdown-line-break-face 'markdown-line-break-face
2110 "Face name to use for hard line breaks.")
2112 (defvar markdown-comment-face 'markdown-comment-face
2113 "Face name to use for HTML comments.")
2115 (defvar markdown-math-face 'markdown-math-face
2116 "Face name to use for LaTeX expressions.")
2118 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2119 "Face name to use for metadata keys.")
2121 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2122 "Face name to use for metadata values.")
2124 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2125 "Face name to use for GFM checkboxes.")
2127 (defvar markdown-highlight-face 'markdown-highlight-face
2128 "Face name to use for mouse highlighting.")
2130 (defvar markdown-markup-face 'markdown-markup-face
2131 "Face name to use for markup elements.")
2133 (defgroup markdown-faces nil
2134 "Faces used in Markdown Mode"
2135 :group 'markdown
2136 :group 'faces)
2138 (defface markdown-italic-face
2139 '((t (:inherit font-lock-variable-name-face :slant italic :weight normal)))
2140 "Face for italic text."
2141 :group 'markdown-faces)
2143 (defface markdown-bold-face
2144 '((t (:inherit font-lock-variable-name-face :weight bold :slant normal)))
2145 "Face for bold text."
2146 :group 'markdown-faces)
2148 (defface markdown-strike-through-face
2149 '((t (:inherit font-lock-variable-name-face :strike-through t)))
2150 "Face for strike-through text."
2151 :group 'markdown-faces)
2153 (defface markdown-markup-face
2154 '((t (:inherit shadow :slant normal :weight normal)))
2155 "Face for markup elements."
2156 :group 'markdown-faces)
2158 (defface markdown-header-rule-face
2159 '((t (:inherit markdown-markup-face)))
2160 "Base face for headers rules."
2161 :group 'markdown-faces)
2163 (defface markdown-header-delimiter-face
2164 '((t (:inherit markdown-markup-face)))
2165 "Base face for headers hash delimiter."
2166 :group 'markdown-faces)
2168 (defface markdown-inline-code-face
2169 '((t (:inherit font-lock-constant-face)))
2170 "Face for inline code."
2171 :group 'markdown-faces)
2173 (defface markdown-list-face
2174 '((t (:inherit markdown-markup-face)))
2175 "Face for list item markers."
2176 :group 'markdown-faces)
2178 (defface markdown-blockquote-face
2179 '((t (:inherit font-lock-doc-face)))
2180 "Face for blockquote sections."
2181 :group 'markdown-faces)
2183 (defface markdown-pre-face
2184 '((t (:inherit font-lock-constant-face)))
2185 "Face for preformatted text."
2186 :group 'markdown-faces)
2188 (defface markdown-language-keyword-face
2189 '((t (:inherit font-lock-type-face)))
2190 "Face for programming language identifiers."
2191 :group 'markdown-faces)
2193 (defface markdown-link-face
2194 '((t (:inherit font-lock-keyword-face)))
2195 "Face for links."
2196 :group 'markdown-faces)
2198 (defface markdown-missing-link-face
2199 '((t (:inherit font-lock-warning-face)))
2200 "Face for missing links."
2201 :group 'markdown-faces)
2203 (defface markdown-reference-face
2204 '((t (:inherit markdown-markup-face)))
2205 "Face for link references."
2206 :group 'markdown-faces)
2208 (defface markdown-footnote-face
2209 '((t (:inherit markdown-markup-face)))
2210 "Face for footnote markers."
2211 :group 'markdown-faces)
2213 (defface markdown-url-face
2214 '((t (:inherit font-lock-string-face)))
2215 "Face for URLs."
2216 :group 'markdown-faces)
2218 (defface markdown-link-title-face
2219 '((t (:inherit font-lock-comment-face)))
2220 "Face for reference link titles."
2221 :group 'markdown-faces)
2223 (defface markdown-line-break-face
2224 '((t (:inherit font-lock-constant-face :underline t)))
2225 "Face for hard line breaks."
2226 :group 'markdown-faces)
2228 (defface markdown-comment-face
2229 '((t (:inherit font-lock-comment-face)))
2230 "Face for HTML comments."
2231 :group 'markdown-faces)
2233 (defface markdown-math-face
2234 '((t (:inherit font-lock-string-face)))
2235 "Face for LaTeX expressions."
2236 :group 'markdown-faces)
2238 (defface markdown-metadata-key-face
2239 '((t (:inherit font-lock-variable-name-face)))
2240 "Face for metadata keys."
2241 :group 'markdown-faces)
2243 (defface markdown-metadata-value-face
2244 '((t (:inherit font-lock-string-face)))
2245 "Face for metadata values."
2246 :group 'markdown-faces)
2248 (defface markdown-gfm-checkbox-face
2249 '((t (:inherit font-lock-builtin-face)))
2250 "Face for GFM checkboxes."
2251 :group 'markdown-faces)
2253 (defface markdown-highlight-face
2254 '((t (:inherit highlight)))
2255 "Face for mouse highlighting."
2256 :group 'markdown-faces)
2258 (defcustom markdown-header-scaling nil
2259 "Whether to use variable-height faces for headers.
2260 When non-nil, `markdown-header-face' will inherit from
2261 `variable-pitch' and the scaling values in
2262 `markdown-header-scaling-values' will be applied to
2263 headers of levels one through six respectively."
2264 :type 'boolean
2265 :initialize 'custom-initialize-default
2266 :set (lambda (symbol value)
2267 (set-default symbol value)
2268 (markdown-update-header-faces value))
2269 :group 'markdown-faces)
2271 (defcustom markdown-header-scaling-values
2272 '(1.8 1.4 1.2 1.0 1.0 1.0)
2273 "List of scaling values for headers of level one through six.
2274 Used when `markdown-header-scaling' is non-nil."
2275 :type 'list
2276 :initialize 'custom-initialize-default
2277 :set (lambda (symbol value)
2278 (set-default symbol value)
2279 (markdown-update-header-faces markdown-header-scaling value))
2280 :group 'markdown-faces)
2282 (defun markdown-make-header-faces ()
2283 "Build the faces used for Markdown headers."
2284 (defface markdown-header-face
2285 `((t (:inherit (,(when markdown-header-scaling 'variable-pitch)
2286 font-lock-function-name-face)
2287 :weight bold)))
2288 "Base face for headers."
2289 :group 'markdown-faces)
2290 (dotimes (num 6)
2291 (let* ((num1 (1+ num))
2292 (face-name (intern (format "markdown-header-face-%s" num1)))
2293 (scale (if markdown-header-scaling
2294 (float (nth num markdown-header-scaling-values))
2295 1.0)))
2296 (eval
2297 `(defface ,face-name
2298 '((t (:inherit markdown-header-face :height ,scale)))
2299 (format "Face for level %s headers.
2301 You probably don't want to customize this face directly. Instead
2302 you can customize the base face `markdown-header-face' or the
2303 variable-height variable `markdown-header-scaling'." ,num1)
2304 :group 'markdown-faces)))))
2306 (markdown-make-header-faces)
2308 (defun markdown-update-header-faces (&optional scaling scaling-values)
2309 "Update header faces, depending on if header SCALING is desired.
2310 If so, use given list of SCALING-VALUES relative to the baseline
2311 size of `markdown-header-face'."
2312 (dotimes (num 6)
2313 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2314 (scale (cond ((not scaling) 1.0)
2315 (scaling-values (float (nth num scaling-values)))
2316 (t (float (nth num markdown-header-scaling-values))))))
2317 (unless (get face-name 'saved-face) ; Don't update customized faces
2318 (set-face-attribute face-name nil :height scale)))))
2320 (defun markdown-syntactic-face (state)
2321 "Return font-lock face for characters with given STATE.
2322 See `font-lock-syntactic-face-function' for details."
2323 (let ((in-comment (nth 4 state)))
2324 (cond
2325 (in-comment 'markdown-comment-face)
2326 (t nil))))
2328 (defvar markdown-mode-font-lock-keywords-basic
2329 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2330 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2331 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2332 (2 markdown-markup-face)
2333 (3 markdown-metadata-value-face)))
2334 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-face)
2335 (2 markdown-language-keyword-face nil t)))
2336 (markdown-match-gfm-close-code-blocks . ((1 markdown-markup-face)))
2337 (markdown-match-gfm-code-blocks . ((0 markdown-pre-face)))
2338 (markdown-match-fenced-start-code-block . ((1 markdown-markup-face)
2339 (2 markdown-language-keyword-face nil t)))
2340 (markdown-match-fenced-end-code-block . ((0 markdown-markup-face)))
2341 (markdown-match-fenced-code-blocks . ((0 markdown-pre-face)))
2342 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2343 (markdown-match-blockquotes . ((1 markdown-markup-face)
2344 (2 markdown-blockquote-face)))
2345 (markdown-match-heading-1-setext . ((1 markdown-header-face-1)
2346 (2 markdown-header-rule-face)))
2347 (markdown-match-heading-2-setext . ((1 markdown-header-face-2)
2348 (3 markdown-header-rule-face)))
2349 (markdown-match-heading-6-atx . ((4 markdown-header-delimiter-face)
2350 (5 markdown-header-face-6)
2351 (6 markdown-header-delimiter-face)))
2352 (markdown-match-heading-5-atx . ((4 markdown-header-delimiter-face)
2353 (5 markdown-header-face-5)
2354 (6 markdown-header-delimiter-face)))
2355 (markdown-match-heading-4-atx . ((4 markdown-header-delimiter-face)
2356 (5 markdown-header-face-4)
2357 (6 markdown-header-delimiter-face)))
2358 (markdown-match-heading-3-atx . ((4 markdown-header-delimiter-face)
2359 (5 markdown-header-face-3)
2360 (6 markdown-header-delimiter-face)))
2361 (markdown-match-heading-2-atx . ((4 markdown-header-delimiter-face)
2362 (5 markdown-header-face-2)
2363 (6 markdown-header-delimiter-face)))
2364 (markdown-match-heading-1-atx . ((4 markdown-header-delimiter-face)
2365 (5 markdown-header-face-1)
2366 (6 markdown-header-delimiter-face)))
2367 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2368 (2 markdown-markup-face)
2369 (3 markdown-metadata-value-face)))
2370 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2371 (2 markdown-markup-face)
2372 (3 markdown-metadata-value-face)))
2373 (markdown-match-hr . markdown-header-delimiter-face)
2374 (markdown-match-code . ((1 markdown-markup-face)
2375 (2 markdown-inline-code-face)
2376 (3 markdown-markup-face)))
2377 (,markdown-regex-kbd . ((1 markdown-markup-face)
2378 (2 markdown-inline-code-face)
2379 (3 markdown-markup-face)))
2380 (,markdown-regex-angle-uri . ((1 markdown-markup-face)
2381 (2 markdown-link-face)
2382 (3 markdown-markup-face)))
2383 (,markdown-regex-list . (2 markdown-list-face))
2384 (,markdown-regex-footnote . ((1 markdown-markup-face) ; [^
2385 (2 markdown-footnote-face) ; label
2386 (3 markdown-markup-face))) ; ]
2387 (,markdown-regex-link-inline . ((1 markdown-markup-face nil t) ; ! (optional)
2388 (2 markdown-markup-face) ; [
2389 (3 markdown-link-face) ; text
2390 (4 markdown-markup-face) ; ]
2391 (5 markdown-markup-face) ; (
2392 (6 markdown-url-face) ; url
2393 (7 markdown-link-title-face nil t) ; "title" (optional)
2394 (8 markdown-markup-face))) ; )
2395 (,markdown-regex-link-reference . ((1 markdown-markup-face nil t) ; ! (optional)
2396 (2 markdown-markup-face) ; [
2397 (3 markdown-link-face) ; text
2398 (4 markdown-markup-face) ; ]
2399 (5 markdown-markup-face) ; [
2400 (6 markdown-reference-face) ; label
2401 (7 markdown-markup-face))) ; ]
2402 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2403 (2 markdown-reference-face) ; label
2404 (3 markdown-markup-face) ; ]
2405 (4 markdown-markup-face) ; :
2406 (5 markdown-url-face) ; url
2407 (6 markdown-link-title-face))) ; "title" (optional)
2408 ;; Math mode $..$
2409 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2410 (2 markdown-math-face append)
2411 (3 markdown-markup-face prepend)))
2412 ;; Math mode $$..$$
2413 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2414 (2 markdown-math-face append)
2415 (3 markdown-markup-face prepend)))
2416 (markdown-match-bold . ((1 markdown-markup-face prepend)
2417 (2 markdown-bold-face append)
2418 (3 markdown-markup-face prepend)))
2419 (markdown-match-italic . ((1 markdown-markup-face prepend)
2420 (2 markdown-italic-face append)
2421 (3 markdown-markup-face prepend)))
2422 (,markdown-regex-uri . markdown-link-face)
2423 (,markdown-regex-email . markdown-link-face)
2424 (,markdown-regex-line-break . (1 markdown-line-break-face prepend)))
2426 "Syntax highlighting for Markdown files.")
2428 (defvar markdown-mode-font-lock-keywords nil
2429 "Default highlighting expressions for Markdown mode.
2430 This variable is defined as a buffer-local variable for dynamic
2431 extension support.")
2433 ;; Footnotes
2434 (defvar markdown-footnote-counter 0
2435 "Counter for footnote numbers.")
2436 (make-variable-buffer-local 'markdown-footnote-counter)
2438 (defconst markdown-footnote-chars
2439 "[[:alnum:]-]"
2440 "Regular expression matching any character that is allowed in a footnote identifier.")
2442 (defconst markdown-regex-footnote-definition
2443 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2444 "Regular expression matching a footnote definition, capturing the label.")
2447 ;;; Compatibility =============================================================
2449 (defun markdown-replace-regexp-in-string (regexp rep string)
2450 "Replace ocurrences of REGEXP with REP in STRING.
2451 This is a compatibility wrapper to provide `replace-regexp-in-string'
2452 in XEmacs 21."
2453 (if (featurep 'xemacs)
2454 (replace-in-string string regexp rep)
2455 (replace-regexp-in-string regexp rep string)))
2457 ;; `markdown-use-region-p' is a compatibility function which checks
2458 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2459 (eval-and-compile
2460 (cond
2461 ;; Emacs 24 and newer
2462 ((fboundp 'use-region-p)
2463 (defalias 'markdown-use-region-p 'use-region-p))
2464 ;; XEmacs
2465 ((fboundp 'region-active-p)
2466 (defalias 'markdown-use-region-p 'region-active-p))))
2468 (defun markdown-use-buttons-p ()
2469 "Determine whether this Emacs supports buttons."
2470 (or (featurep 'button) (locate-library "button")))
2472 ;; Use new names for outline-mode functions in Emacs 25 and later.
2473 (eval-and-compile
2474 (defalias 'markdown-hide-sublevels
2475 (if (fboundp 'outline-hide-sublevels)
2476 'outline-hide-sublevels
2477 'hide-sublevels))
2478 (defalias 'markdown-show-all
2479 (if (fboundp 'outline-show-all)
2480 'outline-show-all
2481 'show-all))
2482 (defalias 'markdown-hide-body
2483 (if (fboundp 'outline-hide-body)
2484 'outline-hide-body
2485 'hide-body))
2486 (defalias 'markdown-show-children
2487 (if (fboundp 'outline-show-children)
2488 'outline-show-children
2489 'show-children))
2490 (defalias 'markdown-show-subtree
2491 (if (fboundp 'outline-show-subtree)
2492 'outline-show-subtree
2493 'show-subtree))
2494 (defalias 'markdown-hide-subtree
2495 (if (fboundp 'outline-hide-subtree)
2496 'outline-hide-subtree
2497 'hide-subtree)))
2500 ;;; Markdown Parsing Functions ================================================
2502 (defun markdown-cur-line-blank-p ()
2503 "Return t if the current line is blank and nil otherwise."
2504 (save-excursion
2505 (beginning-of-line)
2506 (looking-at-p "^\\s *$")))
2508 (defun markdown-prev-line-blank-p ()
2509 "Return t if the previous line is blank and nil otherwise.
2510 If we are at the first line, then consider the previous line to be blank."
2511 (or (= (line-beginning-position) (point-min))
2512 (save-excursion
2513 (forward-line -1)
2514 (markdown-cur-line-blank-p))))
2516 (defun markdown-next-line-blank-p ()
2517 "Return t if the next line is blank and nil otherwise.
2518 If we are at the last line, then consider the next line to be blank."
2519 (or (= (line-end-position) (point-max))
2520 (save-excursion
2521 (forward-line 1)
2522 (markdown-cur-line-blank-p))))
2524 (defun markdown-prev-line-indent ()
2525 "Return the number of leading whitespace characters in the previous line.
2526 Return 0 if the current line is the first line in the buffer."
2527 (save-excursion
2528 (if (= (line-beginning-position) (point-min))
2530 (forward-line -1)
2531 (current-indentation))))
2533 (defun markdown-next-line-indent ()
2534 "Return the number of leading whitespace characters in the next line.
2535 Return 0 if line is the last line in the buffer."
2536 (save-excursion
2537 (if (= (line-end-position) (point-max))
2539 (forward-line 1)
2540 (current-indentation))))
2542 (defun markdown-cur-non-list-indent ()
2543 "Return beginning position of list item text (not including the list marker).
2544 Return nil if the current line is not the beginning of a list item."
2545 (save-match-data
2546 (save-excursion
2547 (beginning-of-line)
2548 (when (re-search-forward markdown-regex-list (line-end-position) t)
2549 (current-column)))))
2551 (defun markdown-prev-non-list-indent ()
2552 "Return position of the first non-list-marker on the previous line."
2553 (save-excursion
2554 (forward-line -1)
2555 (markdown-cur-non-list-indent)))
2557 (defun markdown-new-baseline-p ()
2558 "Determine if the current line begins a new baseline level."
2559 (save-excursion
2560 (beginning-of-line)
2561 (or (looking-at-p markdown-regex-header)
2562 (looking-at-p markdown-regex-hr)
2563 (and (null (markdown-cur-non-list-indent))
2564 (= (current-indentation) 0)
2565 (markdown-prev-line-blank-p)))))
2567 (defun markdown-search-backward-baseline ()
2568 "Search backward baseline point with no indentation and not a list item."
2569 (end-of-line)
2570 (let (stop)
2571 (while (not (or stop (bobp)))
2572 (re-search-backward markdown-regex-block-separator nil t)
2573 (when (match-end 2)
2574 (goto-char (match-end 2))
2575 (cond
2576 ((markdown-new-baseline-p)
2577 (setq stop t))
2578 ((looking-at-p markdown-regex-list)
2579 (setq stop nil))
2580 (t (setq stop t)))))))
2582 (defun markdown-update-list-levels (marker indent levels)
2583 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2584 Here, MARKER is a string representing the type of list, INDENT is an integer
2585 giving the indentation, in spaces, of the current block, and LEVELS is a
2586 list of the indentation levels of parent list items. When LEVELS is nil,
2587 it means we are at baseline (not inside of a nested list)."
2588 (cond
2589 ;; New list item at baseline.
2590 ((and marker (null levels))
2591 (setq levels (list indent)))
2592 ;; List item with greater indentation (four or more spaces).
2593 ;; Increase list level.
2594 ((and marker (>= indent (+ (car levels) 4)))
2595 (setq levels (cons indent levels)))
2596 ;; List item with greater or equal indentation (less than four spaces).
2597 ;; Do not increase list level.
2598 ((and marker (>= indent (car levels)))
2599 levels)
2600 ;; Lesser indentation level.
2601 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2602 ;; indentation could move back more than one list level). Note
2603 ;; that this block need not be the beginning of list item.
2604 ((< indent (car levels))
2605 (while (and (> (length levels) 1)
2606 (< indent (+ (cadr levels) 4)))
2607 (setq levels (cdr levels)))
2608 levels)
2609 ;; Otherwise, do nothing.
2610 (t levels)))
2612 (defun markdown-calculate-list-levels ()
2613 "Calculate list levels at point.
2614 Return a list of the form (n1 n2 n3 ...) where n1 is the
2615 indentation of the deepest nested list item in the branch of
2616 the list at the point, n2 is the indentation of the parent
2617 list item, and so on. The depth of the list item is therefore
2618 the length of the returned list. If the point is not at or
2619 immediately after a list item, return nil."
2620 (save-excursion
2621 (let ((first (point)) levels indent pre-regexp)
2622 ;; Find a baseline point with zero list indentation
2623 (markdown-search-backward-baseline)
2624 ;; Search for all list items between baseline and LOC
2625 (while (and (< (point) first)
2626 (re-search-forward markdown-regex-list first t))
2627 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2628 (beginning-of-line)
2629 (cond
2630 ;; Make sure this is not a header or hr
2631 ((markdown-new-baseline-p) (setq levels nil))
2632 ;; Make sure this is not a line from a pre block
2633 ((looking-at-p pre-regexp))
2634 ;; If not, then update levels
2636 (setq indent (current-indentation))
2637 (setq levels (markdown-update-list-levels (match-string 2)
2638 indent levels))))
2639 (end-of-line))
2640 levels)))
2642 (defun markdown-prev-list-item (level)
2643 "Search backward from point for a list item with indentation LEVEL.
2644 Set point to the beginning of the item, and return point, or nil
2645 upon failure."
2646 (let (bounds indent prev)
2647 (setq prev (point))
2648 (forward-line -1)
2649 (setq indent (current-indentation))
2650 (while
2651 (cond
2652 ;; List item
2653 ((and (looking-at-p markdown-regex-list)
2654 (setq bounds (markdown-cur-list-item-bounds)))
2655 (cond
2656 ;; Stop and return point at item of lesser or equal indentation
2657 ((<= (nth 3 bounds) level)
2658 (setq prev (point))
2659 nil)
2660 ;; Stop at beginning of buffer
2661 ((bobp) (setq prev nil))
2662 ;; Continue at item with greater indentation
2663 ((> (nth 3 bounds) level) t)))
2664 ;; Stop at beginning of buffer
2665 ((bobp) (setq prev nil))
2666 ;; Continue if current line is blank
2667 ((markdown-cur-line-blank-p) t)
2668 ;; Continue while indentation is the same or greater
2669 ((>= indent level) t)
2670 ;; Stop if current indentation is less than list item
2671 ;; and the next is blank
2672 ((and (< indent level)
2673 (markdown-next-line-blank-p))
2674 (setq prev nil))
2675 ;; Stop at a header
2676 ((looking-at-p markdown-regex-header) (setq prev nil))
2677 ;; Stop at a horizontal rule
2678 ((looking-at-p markdown-regex-hr) (setq prev nil))
2679 ;; Otherwise, continue.
2680 (t t))
2681 (forward-line -1)
2682 (setq indent (current-indentation)))
2683 prev))
2685 (defun markdown-next-list-item (level)
2686 "Search forward from point for the next list item with indentation LEVEL.
2687 Set point to the beginning of the item, and return point, or nil
2688 upon failure."
2689 (let (bounds indent next)
2690 (setq next (point))
2691 (forward-line)
2692 (setq indent (current-indentation))
2693 (while
2694 (cond
2695 ;; Stop at end of the buffer.
2696 ((eobp) nil)
2697 ;; Continue if the current line is blank
2698 ((markdown-cur-line-blank-p) t)
2699 ;; List item
2700 ((and (looking-at-p markdown-regex-list)
2701 (setq bounds (markdown-cur-list-item-bounds)))
2702 (cond
2703 ;; Continue at item with greater indentation
2704 ((> (nth 3 bounds) level) t)
2705 ;; Stop and return point at item of equal indentation
2706 ((= (nth 3 bounds) level)
2707 (setq next (point))
2708 nil)
2709 ;; Stop and return nil at item with lesser indentation
2710 ((< (nth 3 bounds) level)
2711 (setq next nil)
2712 nil)))
2713 ;; Continue while indentation is the same or greater
2714 ((>= indent level) t)
2715 ;; Stop if current indentation is less than list item
2716 ;; and the previous line was blank.
2717 ((and (< indent level)
2718 (markdown-prev-line-blank-p))
2719 (setq next nil))
2720 ;; Stop at a header
2721 ((looking-at-p markdown-regex-header) (setq next nil))
2722 ;; Stop at a horizontal rule
2723 ((looking-at-p markdown-regex-hr) (setq next nil))
2724 ;; Otherwise, continue.
2725 (t t))
2726 (forward-line)
2727 (setq indent (current-indentation)))
2728 next))
2730 (defun markdown-cur-list-item-end (level)
2731 "Move to the end of the current list item with nonlist indentation LEVEL.
2732 If the point is not in a list item, do nothing."
2733 (let (indent)
2734 (forward-line)
2735 (setq indent (current-indentation))
2736 (while
2737 (cond
2738 ;; Stop at end of the buffer.
2739 ((eobp) nil)
2740 ;; Continue if the current line is blank
2741 ((markdown-cur-line-blank-p) t)
2742 ;; Continue while indentation is the same or greater
2743 ((>= indent level) t)
2744 ;; Stop if current indentation is less than list item
2745 ;; and the previous line was blank.
2746 ((and (< indent level)
2747 (markdown-prev-line-blank-p))
2748 nil)
2749 ;; Stop at a new list item of the same or lesser indentation
2750 ((looking-at-p markdown-regex-list) nil)
2751 ;; Stop at a header
2752 ((looking-at-p markdown-regex-header) nil)
2753 ;; Stop at a horizontal rule
2754 ((looking-at-p markdown-regex-hr) nil)
2755 ;; Otherwise, continue.
2756 (t t))
2757 (forward-line)
2758 (setq indent (current-indentation)))
2759 ;; Don't skip over whitespace for empty list items (marker and
2760 ;; whitespace only), just move to end of whitespace.
2761 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
2762 (goto-char (match-end 3))
2763 (skip-syntax-backward "-"))))
2765 (defun markdown-cur-list-item-bounds ()
2766 "Return bounds and indentation of the current list item.
2767 Return a list of the form (begin end indent nonlist-indent marker).
2768 If the point is not inside a list item, return nil.
2769 Leave match data intact for `markdown-regex-list'."
2770 (let (cur prev-begin prev-end indent nonlist-indent marker)
2771 ;; Store current location
2772 (setq cur (point))
2773 ;; Verify that cur is between beginning and end of item
2774 (save-excursion
2775 (end-of-line)
2776 (when (re-search-backward markdown-regex-list nil t)
2777 (setq prev-begin (match-beginning 0))
2778 (setq indent (length (match-string 1)))
2779 (setq nonlist-indent (length (match-string 0)))
2780 (setq marker (concat (match-string 2) (match-string 3)))
2781 (save-match-data
2782 (markdown-cur-list-item-end nonlist-indent)
2783 (setq prev-end (point)))
2784 (when (and (>= cur prev-begin)
2785 (<= cur prev-end)
2786 nonlist-indent)
2787 (list prev-begin prev-end indent nonlist-indent marker))))))
2789 (defun markdown-bounds-of-thing-at-point (thing)
2790 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2791 Does not include trailing newlines when THING is 'line. Handles the
2792 end of buffer case by setting both endpoints equal to the value of
2793 `point-max', since an empty region will trigger empty markup insertion.
2794 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2795 (let* ((bounds (bounds-of-thing-at-point thing))
2796 (a (car bounds))
2797 (b (cdr bounds)))
2798 (when bounds
2799 (when (eq thing 'line)
2800 (cond ((and (eobp) (markdown-cur-line-blank-p))
2801 (setq a b))
2802 ((char-equal (char-before b) ?\^J)
2803 (setq b (1- b)))))
2804 (cons a b))))
2806 (defun markdown-reference-definition (reference)
2807 "Find out whether Markdown REFERENCE is defined.
2808 REFERENCE should not include the square brackets.
2809 When REFERENCE is defined, return a list of the form (text start end)
2810 containing the definition text itself followed by the start and end
2811 locations of the text. Otherwise, return nil.
2812 Leave match data for `markdown-regex-reference-definition'
2813 intact additional processing."
2814 (let ((reference (downcase reference)))
2815 (save-excursion
2816 (goto-char (point-min))
2817 (catch 'found
2818 (while (re-search-forward markdown-regex-reference-definition nil t)
2819 (when (string= reference (downcase (match-string-no-properties 2)))
2820 (throw 'found
2821 (list (match-string-no-properties 5)
2822 (match-beginning 5) (match-end 5)))))))))
2824 (defun markdown-get-defined-references ()
2825 "Return a list of all defined reference labels (not including square brackets)."
2826 (save-excursion
2827 (goto-char (point-min))
2828 (let (refs)
2829 (while (re-search-forward markdown-regex-reference-definition nil t)
2830 (let ((target (match-string-no-properties 2)))
2831 (cl-pushnew target refs :test #'equal)))
2832 (reverse refs))))
2834 (defun markdown-code-at-point-p ()
2835 "Return non-nil if the point is at an inline code fragment.
2836 Return nil otherwise. Set match data according to
2837 `markdown-match-code' upon success.
2838 This function searches the block for a code fragment that
2839 contains the point using `markdown-match-code'. We do this
2840 because `thing-at-point-looking-at' does not work reliably with
2841 `markdown-regex-code'.
2843 The match data is set as follows:
2844 Group 1 matches the opening backticks.
2845 Group 2 matches the code fragment itself, without backticks.
2846 Group 3 matches the closing backticks."
2847 (interactive)
2848 (save-excursion
2849 (let ((old-point (point))
2850 (end-of-block (progn (markdown-end-of-block) (point)))
2851 found)
2852 (markdown-beginning-of-block)
2853 (while (and (markdown-match-code end-of-block)
2854 (setq found t)
2855 (< (match-end 0) old-point)))
2856 (and found ; matched something
2857 (<= (match-beginning 0) old-point) ; match contains old-point
2858 (>= (match-end 0) old-point)))))
2860 (defun markdown-code-block-at-pos (pos)
2861 "Return match data list if there is a code block at POS.
2862 This includes pre blocks, tilde-fenced code blocks, and GFM
2863 quoted code blocks. Return nil otherwise."
2864 (or (get-text-property pos 'markdown-pre)
2865 (markdown-get-enclosing-fenced-block-construct pos)
2866 ;; polymode removes text properties set by markdown-mode, so
2867 ;; check if `poly-markdown-mode' is active and whether the
2868 ;; `chunkmode' property is non-nil at POS.
2869 (and (bound-and-true-p poly-markdown-mode)
2870 (get-text-property pos 'chunkmode))))
2872 (defun markdown-code-block-at-point ()
2873 "Return match data if the point is inside a code block.
2874 This includes pre blocks, tilde-fenced code blocks, and
2875 GFM quoted code blocks. Calls `markdown-code-block-at-pos'."
2876 (markdown-code-block-at-pos (point)))
2879 ;;; Markdown Font Lock Matching Functions =====================================
2881 (defun markdown-range-property-any (begin end prop prop-values)
2882 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2883 Also returns t if PROP is a list containing one of the PROP-VALUES.
2884 Return nil otherwise."
2885 (let (props)
2886 (catch 'found
2887 (dolist (loc (number-sequence begin end))
2888 (when (setq props (get-char-property loc prop))
2889 (cond ((listp props)
2890 ;; props is a list, check for membership
2891 (dolist (val prop-values)
2892 (when (memq val props) (throw 'found loc))))
2894 ;; props is a scalar, check for equality
2895 (dolist (val prop-values)
2896 (when (eq val props) (throw 'found loc))))))))))
2898 (defun markdown-range-properties-exist (begin end props)
2899 (cl-loop
2900 for loc in (number-sequence begin end)
2901 with result = nil
2902 while (not
2903 (setq result
2904 (cl-some (lambda (prop) (get-char-property loc prop)) props)))
2905 finally return result))
2907 (defun markdown-match-inline-generic (regex last)
2908 "Match inline REGEX from the point to LAST."
2909 (when (re-search-forward regex last t)
2910 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2911 (if (null bounds)
2912 ;; Not in a code block: keep match data and return t when in bounds
2913 (<= (match-end 0) last)
2914 ;; In code block: move past it and recursively search again
2915 (when (< (goto-char (nth 1 bounds)) last)
2916 (markdown-match-inline-generic regex last))))))
2918 (defun markdown-match-code (last)
2919 "Match inline code fragments from point to LAST."
2920 (unless (bobp)
2921 (backward-char 1))
2922 (when (markdown-match-inline-generic markdown-regex-code last)
2923 (set-match-data (list (match-beginning 1) (match-end 1)
2924 (match-beginning 2) (match-end 2)
2925 (match-beginning 3) (match-end 3)
2926 (match-beginning 4) (match-end 4)))
2927 (goto-char (1+ (match-end 0)))))
2929 (defun markdown-match-bold (last)
2930 "Match inline bold from the point to LAST."
2931 (when (markdown-match-inline-generic markdown-regex-bold last)
2932 (let ((begin (match-beginning 2)) (end (match-end 2)))
2933 (cond
2934 ((markdown-range-property-any
2935 begin end 'face (list markdown-inline-code-face
2936 markdown-math-face))
2937 (goto-char (1+ (match-end 0)))
2938 (markdown-match-bold last))
2940 (set-match-data (list (match-beginning 2) (match-end 2)
2941 (match-beginning 3) (match-end 3)
2942 (match-beginning 4) (match-end 4)
2943 (match-beginning 5) (match-end 5)))
2944 (goto-char (1+ (match-end 0))))))))
2946 (defun markdown-match-italic (last)
2947 "Match inline italics from the point to LAST."
2948 (let ((regex (if (eq major-mode 'gfm-mode)
2949 markdown-regex-gfm-italic markdown-regex-italic)))
2950 (when (markdown-match-inline-generic regex last)
2951 (let ((begin (match-beginning 1)) (end (match-end 1)))
2952 (cond
2953 ((markdown-range-property-any
2954 begin begin 'face (list markdown-url-face))
2955 ;; Italics shouldn't begin inside a URL due to an underscore
2956 (goto-char (min (1+ (match-end 0)) last))
2957 (markdown-match-italic last))
2958 ((markdown-range-property-any
2959 begin end 'face (list markdown-inline-code-face
2960 markdown-bold-face
2961 markdown-list-face
2962 markdown-math-face))
2963 (goto-char (1+ (match-end 0)))
2964 (markdown-match-italic last))
2966 (set-match-data (list (match-beginning 1) (match-end 1)
2967 (match-beginning 2) (match-end 2)
2968 (match-beginning 3) (match-end 3)
2969 (match-beginning 4) (match-end 4)))
2970 (goto-char (1+ (match-end 0)))))))))
2972 (defun markdown-match-math-generic (regex last)
2973 "Match REGEX from point to LAST.
2974 REGEX is either `markdown-regex-math-inline-single' for matching
2975 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2976 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
2977 (let ((begin (match-beginning 1)) (end (match-end 1)))
2978 (prog1
2979 (if (or (markdown-range-property-any
2980 begin end 'face (list markdown-inline-code-face
2981 markdown-bold-face))
2982 (markdown-range-properties-exist
2983 begin end
2984 (markdown-get-fenced-block-middle-properties)))
2985 (markdown-match-math-generic regex last)
2987 (goto-char (1+ (match-end 0)))))))
2989 (defun markdown-match-math-single (last)
2990 "Match single quoted $..$ math from point to LAST."
2991 (markdown-match-math-generic markdown-regex-math-inline-single last))
2993 (defun markdown-match-math-double (last)
2994 "Match double quoted $$..$$ math from point to LAST."
2995 (markdown-match-math-generic markdown-regex-math-inline-double last))
2997 (defun markdown-match-propertized-text (property last)
2998 "Match text with PROPERTY from point to LAST.
2999 Restore match data previously stored in PROPERTY."
3000 (let ((saved (get-text-property (point) property))
3001 pos)
3002 (unless saved
3003 (setq pos (next-single-char-property-change (point) property nil last))
3004 (setq saved (get-text-property pos property)))
3005 (when saved
3006 (set-match-data saved)
3007 ;; Step at least one character beyond point. Otherwise
3008 ;; `font-lock-fontify-keywords-region' infloops.
3009 (goto-char (min (1+ (max (match-end 0) (point)))
3010 (point-max)))
3011 saved)))
3013 (defun markdown-match-pre-blocks (last)
3014 "Match preformatted blocks from point to LAST.
3015 Use data stored in 'markdown-pre text property during syntax
3016 analysis."
3017 (markdown-match-propertized-text 'markdown-pre last))
3019 (defun markdown-match-gfm-code-blocks (last)
3020 "Match GFM quoted code blocks from point to LAST.
3021 Use data stored in 'markdown-gfm-code text property during syntax
3022 analysis."
3023 (markdown-match-propertized-text 'markdown-gfm-code last))
3025 (defun markdown-match-gfm-open-code-blocks (last)
3026 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3028 (defun markdown-match-gfm-close-code-blocks (last)
3029 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3031 (defun markdown-match-fenced-code-blocks (last)
3032 "Match fenced code blocks from the point to LAST."
3033 (markdown-match-propertized-text 'markdown-fenced-code last))
3035 (defun markdown-match-fenced-start-code-block (last)
3036 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3038 (defun markdown-match-fenced-end-code-block (last)
3039 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3041 (defun markdown-match-blockquotes (last)
3042 "Match blockquotes from point to LAST.
3043 Use data stored in 'markdown-blockquote text property during syntax
3044 analysis."
3045 (markdown-match-propertized-text 'markdown-blockquote last))
3047 (defun markdown-match-heading-1-setext (last)
3048 "Match level 1 setext headings from point to LAST."
3049 (markdown-match-propertized-text 'markdown-heading-1-setext last))
3051 (defun markdown-match-heading-2-setext (last)
3052 "Match level 2 setext headings from point to LAST."
3053 (markdown-match-propertized-text 'markdown-heading-2-setext last))
3055 (defun markdown-match-heading-1-atx (last)
3056 "Match level 1 ATX headings from point to LAST."
3057 (markdown-match-propertized-text 'markdown-heading-1-atx last))
3059 (defun markdown-match-heading-2-atx (last)
3060 "Match level 2 ATX headings from point to LAST."
3061 (markdown-match-propertized-text 'markdown-heading-2-atx last))
3063 (defun markdown-match-heading-3-atx (last)
3064 "Match level 3 ATX headings from point to LAST."
3065 (markdown-match-propertized-text 'markdown-heading-3-atx last))
3067 (defun markdown-match-heading-4-atx (last)
3068 "Match level 4 ATX headings from point to LAST."
3069 (markdown-match-propertized-text 'markdown-heading-4-atx last))
3071 (defun markdown-match-heading-5-atx (last)
3072 "Match level 5 ATX headings from point to LAST."
3073 (markdown-match-propertized-text 'markdown-heading-5-atx last))
3075 (defun markdown-match-heading-6-atx (last)
3076 "Match level 6 ATX headings from point to LAST."
3077 (markdown-match-propertized-text 'markdown-heading-6-atx last))
3079 (defun markdown-match-hr (last)
3080 "Match horizontal rules comments from the point to LAST."
3081 (while (and (re-search-forward markdown-regex-hr last t)
3082 (or (markdown-on-heading-p)
3083 (markdown-code-block-at-point))
3084 (< (match-end 0) last))
3085 (forward-line))
3086 (beginning-of-line)
3087 (cond ((looking-at-p markdown-regex-hr)
3088 (forward-line)
3090 (t nil)))
3092 (defun markdown-match-comments (last)
3093 "Match HTML comments from the point to LAST."
3094 (when (and (skip-syntax-forward "^<" last))
3095 (let ((beg (point)))
3096 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3097 (forward-char)
3098 (set-match-data (list beg (point)))
3099 t))))
3101 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3102 (save-excursion
3103 (goto-char (or pos (point-min)))
3104 (cl-loop
3105 with cur-result = nil
3106 and st-hdr = (or start-header "\\`")
3107 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3108 while (and (< (point) last)
3109 (re-search-forward st-hdr last t)
3110 (progn
3111 (setq cur-result (match-data))
3112 (re-search-forward end-hdr nil t)))
3113 collect (list cur-result (match-data)))))
3115 (defvar markdown-conditional-search-function #'re-search-forward
3116 "Conditional search function used in `markdown-search-until-condition'.
3117 Made into a variable to allow for dynamic let-binding.")
3119 (defun markdown-search-until-condition (condition &rest args)
3120 (let (ret)
3121 (while (and (not ret) (apply markdown-conditional-search-function args))
3122 (setq ret (funcall condition)))
3123 ret))
3125 (defun markdown-match-generic-metadata
3126 (regexp last &optional start-header end-header)
3127 "Match generic metadata specified by REGEXP from the point to LAST.
3128 If START-HEADER is nil, we assume metadata can only occur at the
3129 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3130 is \"\n\n\""
3131 (let* ((header-bounds
3132 (markdown-get-match-boundaries start-header end-header last))
3133 (enclosing-header
3134 (cl-find-if ; just take first if multiple
3135 (lambda (match-bounds)
3136 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3137 (and (< (point) begin)
3138 (save-excursion (re-search-forward regexp end t)))))
3139 header-bounds))
3140 (header-begin
3141 (when enclosing-header (cl-second (cl-first enclosing-header))))
3142 (header-end
3143 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3144 (cond ((null enclosing-header)
3145 ;; Don't match anything outside of a header.
3146 nil)
3147 ((markdown-search-until-condition
3148 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3149 ;; If a metadata item is found, it may span several lines.
3150 (let ((key-beginning (match-beginning 1))
3151 (key-end (match-end 1))
3152 (markup-begin (match-beginning 2))
3153 (markup-end (match-end 2))
3154 (value-beginning (match-beginning 3)))
3155 (set-match-data (list key-beginning (point) ; complete metadata
3156 key-beginning key-end ; key
3157 markup-begin markup-end ; markup
3158 value-beginning (point))) ; value
3160 (t nil))))
3162 (defun markdown-match-declarative-metadata (last)
3163 "Match declarative metadata from the point to LAST."
3164 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3166 (defun markdown-match-pandoc-metadata (last)
3167 "Match Pandoc metadata from the point to LAST."
3168 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3170 (defun markdown-match-yaml-metadata-begin (last)
3171 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3173 (defun markdown-match-yaml-metadata-end (last)
3174 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3176 (defun markdown-match-yaml-metadata-key (last)
3177 (markdown-match-propertized-text 'markdown-metadata-key last))
3180 ;;; Syntax Table ==============================================================
3182 (defvar markdown-mode-syntax-table
3183 (let ((tab (make-syntax-table text-mode-syntax-table)))
3184 (modify-syntax-entry ?\" "." tab)
3185 tab)
3186 "Syntax table for `markdown-mode'.")
3189 ;;; Element Insertion =========================================================
3191 (defun markdown-ensure-blank-line-before ()
3192 "If previous line is not already blank, insert a blank line before point."
3193 (unless (bolp) (insert "\n"))
3194 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3196 (defun markdown-ensure-blank-line-after ()
3197 "If following line is not already blank, insert a blank line after point.
3198 Return the point where it was originally."
3199 (save-excursion
3200 (unless (eolp) (insert "\n"))
3201 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3203 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3204 "Insert the strings S1 and S2, wrapping around region or THING.
3205 If a region is specified by the optional BEG and END arguments,
3206 wrap the strings S1 and S2 around that region.
3207 If there is an active region, wrap the strings S1 and S2 around
3208 the region. If there is not an active region but the point is at
3209 THING, wrap that thing (which defaults to word). Otherwise, just
3210 insert S1 and S2 and place the cursor in between. Return the
3211 bounds of the entire wrapped string, or nil if nothing was wrapped
3212 and S1 and S2 were only inserted."
3213 (let (a b bounds new-point)
3214 (cond
3215 ;; Given region
3216 ((and beg end)
3217 (setq a beg
3218 b end
3219 new-point (+ (point) (length s1))))
3220 ;; Active region
3221 ((markdown-use-region-p)
3222 (setq a (region-beginning)
3223 b (region-end)
3224 new-point (+ (point) (length s1))))
3225 ;; Thing (word) at point
3226 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3227 (setq a (car bounds)
3228 b (cdr bounds)
3229 new-point (+ (point) (length s1))))
3230 ;; No active region and no word
3232 (setq a (point)
3233 b (point))))
3234 (goto-char b)
3235 (insert s2)
3236 (goto-char a)
3237 (insert s1)
3238 (when new-point (goto-char new-point))
3239 (if (= a b)
3241 (setq b (+ b (length s1) (length s2)))
3242 (cons a b))))
3244 (defun markdown-point-after-unwrap (cur prefix suffix)
3245 "Return desired position of point after an unwrapping operation.
3246 CUR gives the position of the point before the operation.
3247 Additionally, two cons cells must be provided. PREFIX gives the
3248 bounds of the prefix string and SUFFIX gives the bounds of the
3249 suffix string."
3250 (cond ((< cur (cdr prefix)) (car prefix))
3251 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3252 ((<= cur (cdr suffix))
3253 (- cur (+ (- (cdr prefix) (car prefix))
3254 (- cur (car suffix)))))
3255 (t cur)))
3257 (defun markdown-unwrap-thing-at-point (regexp all text)
3258 "Remove prefix and suffix of thing at point and reposition the point.
3259 When the thing at point matches REGEXP, replace the subexpression
3260 ALL with the string in subexpression TEXT. Reposition the point
3261 in an appropriate location accounting for the removal of prefix
3262 and suffix strings. Return new bounds of string from group TEXT.
3263 When REGEXP is nil, assumes match data is already set."
3264 (when (or (null regexp)
3265 (thing-at-point-looking-at regexp))
3266 (let ((cur (point))
3267 (prefix (cons (match-beginning all) (match-beginning text)))
3268 (suffix (cons (match-end text) (match-end all)))
3269 (bounds (cons (match-beginning text) (match-end text))))
3270 ;; Replace the thing at point
3271 (replace-match (match-string text) t t nil all)
3272 ;; Reposition the point
3273 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3274 ;; Adjust bounds
3275 (setq bounds (cons (car prefix)
3276 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3278 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3279 "Remove prefix and suffix of all things in region from BEG to END.
3280 When a thing in the region matches REGEXP, replace the
3281 subexpression ALL with the string in subexpression TEXT.
3282 Return a cons cell containing updated bounds for the region."
3283 (save-excursion
3284 (goto-char beg)
3285 (let ((removed 0) len-all len-text)
3286 (while (re-search-forward regexp (- end removed) t)
3287 (setq len-all (length (match-string-no-properties all)))
3288 (setq len-text (length (match-string-no-properties text)))
3289 (setq removed (+ removed (- len-all len-text)))
3290 (replace-match (match-string text) t t nil all))
3291 (cons beg (- end removed)))))
3293 (defun markdown-insert-hr (arg)
3294 "Insert or replace a horizonal rule.
3295 By default, use the first element of `markdown-hr-strings'. When
3296 ARG is non-nil, as when given a prefix, select a different
3297 element as follows. When prefixed with \\[universal-argument],
3298 use the last element of `markdown-hr-strings' instead. When
3299 prefixed with an integer from 1 to the length of
3300 `markdown-hr-strings', use the element in that position instead."
3301 (interactive "*P")
3302 (when (thing-at-point-looking-at markdown-regex-hr)
3303 (delete-region (match-beginning 0) (match-end 0)))
3304 (markdown-ensure-blank-line-before)
3305 (cond ((equal arg '(4))
3306 (insert (car (reverse markdown-hr-strings))))
3307 ((and (integerp arg) (> arg 0)
3308 (<= arg (length markdown-hr-strings)))
3309 (insert (nth (1- arg) markdown-hr-strings)))
3311 (insert (car markdown-hr-strings))))
3312 (markdown-ensure-blank-line-after))
3314 (defun markdown-insert-bold ()
3315 "Insert markup to make a region or word bold.
3316 If there is an active region, make the region bold. If the point
3317 is at a non-bold word, make the word bold. If the point is at a
3318 bold word or phrase, remove the bold markup. Otherwise, simply
3319 insert bold delimiters and place the cursor in between them."
3320 (interactive)
3321 (let ((delim (if markdown-bold-underscore "__" "**")))
3322 (if (markdown-use-region-p)
3323 ;; Active region
3324 (let ((bounds (markdown-unwrap-things-in-region
3325 (region-beginning) (region-end)
3326 markdown-regex-bold 2 4)))
3327 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3328 ;; Bold markup removal, bold word at point, or empty markup insertion
3329 (if (thing-at-point-looking-at markdown-regex-bold)
3330 (markdown-unwrap-thing-at-point nil 2 4)
3331 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3333 (defun markdown-insert-italic ()
3334 "Insert markup to make a region or word italic.
3335 If there is an active region, make the region italic. If the point
3336 is at a non-italic word, make the word italic. If the point is at an
3337 italic word or phrase, remove the italic markup. Otherwise, simply
3338 insert italic delimiters and place the cursor in between them."
3339 (interactive)
3340 (let ((delim (if markdown-italic-underscore "_" "*")))
3341 (if (markdown-use-region-p)
3342 ;; Active region
3343 (let ((bounds (markdown-unwrap-things-in-region
3344 (region-beginning) (region-end)
3345 markdown-regex-italic 1 3)))
3346 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3347 ;; Italic markup removal, italic word at point, or empty markup insertion
3348 (if (thing-at-point-looking-at markdown-regex-italic)
3349 (markdown-unwrap-thing-at-point nil 1 3)
3350 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3352 (defun markdown-insert-strike-through ()
3353 "Insert markup to make a region or word strikethrough.
3354 If there is an active region, make the region strikethrough. If the point
3355 is at a non-bold word, make the word strikethrough. If the point is at a
3356 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3357 simply insert bold delimiters and place the cursor in between them."
3358 (interactive)
3359 (let ((delim "~~"))
3360 (if (markdown-use-region-p)
3361 ;; Active region
3362 (let ((bounds (markdown-unwrap-things-in-region
3363 (region-beginning) (region-end)
3364 markdown-regex-strike-through 2 4)))
3365 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3366 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3367 (if (thing-at-point-looking-at markdown-regex-strike-through)
3368 (markdown-unwrap-thing-at-point nil 2 4)
3369 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3371 (defun markdown-insert-code ()
3372 "Insert markup to make a region or word an inline code fragment.
3373 If there is an active region, make the region an inline code
3374 fragment. If the point is at a word, make the word an inline
3375 code fragment. Otherwise, simply insert code delimiters and
3376 place the cursor in between them."
3377 (interactive)
3378 (if (markdown-use-region-p)
3379 ;; Active region
3380 (let ((bounds (markdown-unwrap-things-in-region
3381 (region-beginning) (region-end)
3382 markdown-regex-code 1 3)))
3383 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3384 ;; Code markup removal, code markup for word, or empty markup insertion
3385 (if (markdown-code-at-point-p)
3386 (markdown-unwrap-thing-at-point nil 0 2)
3387 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3389 (defun markdown-insert-kbd ()
3390 "Insert markup to wrap region or word in <kbd> tags.
3391 If there is an active region, use the region. If the point is at
3392 a word, use the word. Otherwise, simply insert <kbd> tags and
3393 place the cursor in between them."
3394 (interactive)
3395 (if (markdown-use-region-p)
3396 ;; Active region
3397 (let ((bounds (markdown-unwrap-things-in-region
3398 (region-beginning) (region-end)
3399 markdown-regex-kbd 0 2)))
3400 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3401 ;; Markup removal, markup for word, or empty markup insertion
3402 (if (thing-at-point-looking-at markdown-regex-kbd)
3403 (markdown-unwrap-thing-at-point nil 0 2)
3404 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3406 (defun markdown-insert-link ()
3407 "Insert an inline link, using region or word as link text if possible.
3408 If there is an active region, use the region as the link text. If the
3409 point is at a word, use the word as the link text. In these cases, the
3410 point will be left at the position for inserting a URL. If there is no
3411 active region and the point is not at word, simply insert link markup and
3412 place the point in the position to enter link text."
3413 (interactive)
3414 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3415 (when bounds
3416 (goto-char (- (cdr bounds) 1)))))
3418 (defun markdown-insert-reference-link (text label &optional url title)
3419 "Insert a reference link and, optionally, a reference definition.
3420 The link TEXT will be inserted followed by the optional LABEL.
3421 If a URL is given, also insert a definition for the reference
3422 LABEL according to `markdown-reference-location'. If a TITLE is
3423 given, it will be added to the end of the reference definition
3424 and will be used to populate the title attribute when converted
3425 to XHTML. If URL is nil, insert only the link portion (for
3426 example, when a reference label is already defined)."
3427 (insert (concat "[" text "][" label "]"))
3428 (when url
3429 (markdown-insert-reference-definition
3430 (if (string-equal label "") text label)
3431 url title)))
3433 (defun markdown-insert-reference-definition (label &optional url title)
3434 "Add definition for reference LABEL with URL and TITLE.
3435 LABEL is a Markdown reference label without square brackets.
3436 URL and TITLE are optional. When given, the TITLE will
3437 be used to populate the title attribute when converted to XHTML."
3438 ;; END specifies where to leave the point upon return
3439 (let ((end (point)))
3440 (cl-case markdown-reference-location
3441 (end (goto-char (point-max)))
3442 (immediately (markdown-end-of-block))
3443 (header (markdown-end-of-defun)))
3444 (unless (markdown-cur-line-blank-p) (insert "\n"))
3445 (insert "\n[" label "]: ")
3446 (if url
3447 (insert url)
3448 ;; When no URL is given, leave cursor at END following the colon
3449 (setq end (point)))
3450 (when (> (length title) 0)
3451 (insert " \"" title "\""))
3452 (unless (looking-at-p "\n")
3453 (insert "\n"))
3454 (goto-char end)
3455 (when url
3456 (message
3457 (substitute-command-keys
3458 "Defined reference [%s], press \\[markdown-jump] to jump there")
3459 label))))
3461 (defun markdown-insert-reference-link-dwim ()
3462 "Insert a reference link of the form [text][label] at point.
3463 If there is an active region, the text in the region will be used
3464 as the link text. If the point is at an inline link, it will be
3465 converted to a reference link. If the point is at a word, it will
3466 be used as the link text. Otherwise, the link text will be read from
3467 the minibuffer. The link label will be read from the minibuffer in
3468 both cases, with completion from the set of currently defined
3469 references. To create an implicit reference link, press RET to
3470 accept the default, an empty label. If the entered referenced
3471 label is not defined, additionally prompt for the URL
3472 and (optional) title. The reference definition is placed at the
3473 location determined by `markdown-reference-location'."
3474 (interactive)
3475 (let* ((defined-labels (markdown-get-defined-references))
3476 (switch (thing-at-point-looking-at markdown-regex-link-inline))
3477 (bounds (cond ((markdown-use-region-p)
3478 (cons (region-beginning) (region-end)))
3479 (switch
3480 (cons (match-beginning 0) (match-end 0)))
3482 (markdown-bounds-of-thing-at-point 'word))))
3483 (text (cond (switch (match-string 3))
3484 (bounds (buffer-substring (car bounds) (cdr bounds)))
3485 (t (read-string "Link Text: "))))
3486 (label (completing-read
3487 "Link Label (default: none): " defined-labels
3488 nil nil nil 'markdown-reference-label-history nil))
3489 (ref (save-match-data
3490 (markdown-reference-definition
3491 (if (> (length label) 0) label text))))
3492 (url (cond (ref nil)
3493 (switch (match-string 6))
3494 (t (read-string "Link URL: "))))
3495 (title (cond
3496 ((= (length url) 0) nil)
3497 (switch (if (> (length (match-string 7)) 2)
3498 (substring (match-string 7) 1 -1)
3499 nil))
3500 (t (read-string "Link Title (optional): ")))))
3501 (when bounds (delete-region (car bounds) (cdr bounds)))
3502 (markdown-insert-reference-link text label url title)))
3504 (defun markdown-insert-uri ()
3505 "Insert markup for an inline URI.
3506 If there is an active region, use it as the URI. If the point is
3507 at a URI, wrap it with angle brackets. If the point is at an
3508 inline URI, remove the angle brackets. Otherwise, simply insert
3509 angle brackets place the point between them."
3510 (interactive)
3511 (if (markdown-use-region-p)
3512 ;; Active region
3513 (let ((bounds (markdown-unwrap-things-in-region
3514 (region-beginning) (region-end)
3515 markdown-regex-angle-uri 0 2)))
3516 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
3517 ;; Markup removal, URI at point, or empty markup insertion
3518 (if (thing-at-point-looking-at markdown-regex-angle-uri)
3519 (markdown-unwrap-thing-at-point nil 0 2)
3520 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
3522 (defun markdown-insert-wiki-link ()
3523 "Insert a wiki link of the form [[WikiLink]].
3524 If there is an active region, use the region as the link text.
3525 If the point is at a word, use the word as the link text. If
3526 there is no active region and the point is not at word, simply
3527 insert link markup."
3528 (interactive)
3529 (if (markdown-use-region-p)
3530 ;; Active region
3531 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
3532 ;; Markup removal, wiki link at at point, or empty markup insertion
3533 (if (thing-at-point-looking-at markdown-regex-wiki-link)
3534 (if (or markdown-wiki-link-alias-first
3535 (null (match-string 5)))
3536 (markdown-unwrap-thing-at-point nil 1 3)
3537 (markdown-unwrap-thing-at-point nil 1 5))
3538 (markdown-wrap-or-insert "[[" "]]"))))
3540 (defun markdown-insert-image (&optional arg)
3541 "Insert image markup using region or word as alt text if possible.
3542 If there is an active region, use the region as the alt text. If the
3543 point is at a word, use the word as the alt text. In these cases, the
3544 point will be left at the position for inserting a URL. If there is no
3545 active region and the point is not at word, simply insert image markup and
3546 place the point in the position to enter alt text. If ARG is nil, insert
3547 inline image markup. Otherwise, insert reference image markup."
3548 (interactive "*P")
3549 (let ((bounds (if arg
3550 (markdown-wrap-or-insert "![" "][]")
3551 (markdown-wrap-or-insert "![" "]()"))))
3552 (when bounds
3553 (goto-char (- (cdr bounds) 1)))))
3555 (defun markdown-insert-reference-image ()
3556 "Insert reference-style image markup using region or word as alt text.
3557 Calls `markdown-insert-image' with prefix argument."
3558 (interactive)
3559 (markdown-insert-image t))
3561 (defun markdown-remove-header ()
3562 "Remove header markup if point is at a header.
3563 Return bounds of remaining header text if a header was removed
3564 and nil otherwise."
3565 (interactive "*")
3566 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
3567 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
3569 (defun markdown-insert-header (&optional level text setext)
3570 "Insert or replace header markup.
3571 The level of the header is specified by LEVEL and header text is
3572 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3573 default value is 1.
3574 When TEXT is nil, the header text is obtained as follows.
3575 If there is an active region, it is used as the header text.
3576 Otherwise, the current line will be used as the header text.
3577 If there is not an active region and the point is at a header,
3578 remove the header markup and replace with level N header.
3579 Otherwise, insert empty header markup and place the cursor in
3580 between.
3581 The style of the header will be atx (hash marks) unless
3582 SETEXT is non-nil, in which case a setext-style (underlined)
3583 header will be inserted."
3584 (interactive "p\nsHeader text: ")
3585 (setq level (min (max (or level 1) 1) (if setext 2 6)))
3586 ;; Determine header text if not given
3587 (when (null text)
3588 (if (markdown-use-region-p)
3589 ;; Active region
3590 (setq text (delete-and-extract-region (region-beginning) (region-end)))
3591 ;; No active region
3592 (markdown-remove-header)
3593 (setq text (delete-and-extract-region
3594 (line-beginning-position) (line-end-position)))
3595 (when (and setext (string-match-p "^[ \t]*$" text))
3596 (setq text (read-string "Header text: "))))
3597 (setq text (markdown-compress-whitespace-string text)))
3598 ;; Insertion with given text
3599 (markdown-ensure-blank-line-before)
3600 (let (hdr)
3601 (cond (setext
3602 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
3603 (insert text "\n" hdr))
3605 (setq hdr (make-string level ?#))
3606 (insert hdr " " text)
3607 (when (null markdown-asymmetric-header) (insert " " hdr)))))
3608 (markdown-ensure-blank-line-after)
3609 ;; Leave point at end of text
3610 (cond (setext
3611 (backward-char (1+ (string-width text))))
3612 ((null markdown-asymmetric-header)
3613 (backward-char (1+ level)))))
3615 (defun markdown-insert-header-dwim (&optional arg setext)
3616 "Insert or replace header markup.
3617 The level and type of the header are determined automatically by
3618 the type and level of the previous header, unless a prefix
3619 argument is given via ARG.
3620 With a numeric prefix valued 1 to 6, insert a header of the given
3621 level, with the type being determined automatically (note that
3622 only level 1 or 2 setext headers are possible).
3624 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3625 promote the heading by one level.
3626 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3627 demote the heading by one level.
3628 When SETEXT is non-nil, prefer setext-style headers when
3629 possible (levels one and two).
3631 When there is an active region, use it for the header text. When
3632 the point is at an existing header, change the type and level
3633 according to the rules above.
3634 Otherwise, if the line is not empty, create a header using the
3635 text on the current line as the header text.
3636 Finally, if the point is on a blank line, insert empty header
3637 markup (atx) or prompt for text (setext).
3638 See `markdown-insert-header' for more details about how the
3639 header text is determined."
3640 (interactive "*P")
3641 (let (level)
3642 (save-excursion
3643 (when (or (thing-at-point-looking-at markdown-regex-header)
3644 (re-search-backward markdown-regex-header nil t))
3645 ;; level of current or previous header
3646 (setq level (markdown-outline-level))
3647 ;; match group 1 indicates a setext header
3648 (setq setext (match-end 1))))
3649 ;; check prefix argument
3650 (cond
3651 ((and (equal arg '(4)) level (> level 1)) ;; C-u
3652 (cl-decf level))
3653 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
3654 (cl-incf level))
3655 (arg ;; numeric prefix
3656 (setq level (prefix-numeric-value arg))))
3657 ;; setext headers must be level one or two
3658 (and level (setq setext (and setext (<= level 2))))
3659 ;; insert the heading
3660 (markdown-insert-header level nil setext)))
3662 (defun markdown-insert-header-setext-dwim (&optional arg)
3663 "Insert or replace header markup, with preference for setext.
3664 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3665 (interactive "*P")
3666 (markdown-insert-header-dwim arg t))
3668 (defun markdown-insert-header-atx-1 ()
3669 "Insert a first level atx-style (hash mark) header.
3670 See `markdown-insert-header'."
3671 (interactive "*")
3672 (markdown-insert-header 1 nil nil))
3674 (defun markdown-insert-header-atx-2 ()
3675 "Insert a level two atx-style (hash mark) header.
3676 See `markdown-insert-header'."
3677 (interactive "*")
3678 (markdown-insert-header 2 nil nil))
3680 (defun markdown-insert-header-atx-3 ()
3681 "Insert a level three atx-style (hash mark) header.
3682 See `markdown-insert-header'."
3683 (interactive "*")
3684 (markdown-insert-header 3 nil nil))
3686 (defun markdown-insert-header-atx-4 ()
3687 "Insert a level four atx-style (hash mark) header.
3688 See `markdown-insert-header'."
3689 (interactive "*")
3690 (markdown-insert-header 4 nil nil))
3692 (defun markdown-insert-header-atx-5 ()
3693 "Insert a level five atx-style (hash mark) header.
3694 See `markdown-insert-header'."
3695 (interactive "*")
3696 (markdown-insert-header 5 nil nil))
3698 (defun markdown-insert-header-atx-6 ()
3699 "Insert a sixth level atx-style (hash mark) header.
3700 See `markdown-insert-header'."
3701 (interactive "*")
3702 (markdown-insert-header 6 nil nil))
3704 (defun markdown-insert-header-setext-1 ()
3705 "Insert a setext-style (underlined) first-level header.
3706 See `markdown-insert-header'."
3707 (interactive "*")
3708 (markdown-insert-header 1 nil t))
3710 (defun markdown-insert-header-setext-2 ()
3711 "Insert a setext-style (underlined) second-level header.
3712 See `markdown-insert-header'."
3713 (interactive "*")
3714 (markdown-insert-header 2 nil t))
3716 (defun markdown-blockquote-indentation (loc)
3717 "Return string containing necessary indentation for a blockquote at LOC.
3718 Also see `markdown-pre-indentation'."
3719 (save-excursion
3720 (goto-char loc)
3721 (let* ((list-level (length (markdown-calculate-list-levels)))
3722 (indent ""))
3723 (dotimes (_ list-level indent)
3724 (setq indent (concat indent " "))))))
3726 (defun markdown-insert-blockquote ()
3727 "Start a blockquote section (or blockquote the region).
3728 If Transient Mark mode is on and a region is active, it is used as
3729 the blockquote text."
3730 (interactive)
3731 (if (markdown-use-region-p)
3732 (markdown-blockquote-region (region-beginning) (region-end))
3733 (markdown-ensure-blank-line-before)
3734 (insert (markdown-blockquote-indentation (point)) "> ")
3735 (markdown-ensure-blank-line-after)))
3737 (defun markdown-block-region (beg end prefix)
3738 "Format the region using a block prefix.
3739 Arguments BEG and END specify the beginning and end of the
3740 region. The characters PREFIX will appear at the beginning
3741 of each line."
3742 (save-excursion
3743 (let* ((end-marker (make-marker))
3744 (beg-marker (make-marker)))
3745 ;; Ensure blank line after and remove extra whitespace
3746 (goto-char end)
3747 (skip-syntax-backward "-")
3748 (set-marker end-marker (point))
3749 (delete-horizontal-space)
3750 (markdown-ensure-blank-line-after)
3751 ;; Ensure blank line before and remove extra whitespace
3752 (goto-char beg)
3753 (skip-syntax-forward "-")
3754 (delete-horizontal-space)
3755 (markdown-ensure-blank-line-before)
3756 (set-marker beg-marker (point))
3757 ;; Insert PREFIX before each line
3758 (goto-char beg-marker)
3759 (while (and (< (line-beginning-position) end-marker)
3760 (not (eobp)))
3761 (insert prefix)
3762 (forward-line)))))
3764 (defun markdown-blockquote-region (beg end)
3765 "Blockquote the region.
3766 Arguments BEG and END specify the beginning and end of the region."
3767 (interactive "*r")
3768 (markdown-block-region
3769 beg end (concat (markdown-blockquote-indentation
3770 (max (point-min) (1- beg))) "> ")))
3772 (defun markdown-pre-indentation (loc)
3773 "Return string containing necessary whitespace for a pre block at LOC.
3774 Also see `markdown-blockquote-indentation'."
3775 (save-excursion
3776 (goto-char loc)
3777 (let* ((list-level (length (markdown-calculate-list-levels)))
3778 indent)
3779 (dotimes (_ (1+ list-level) indent)
3780 (setq indent (concat indent " "))))))
3782 (defun markdown-insert-pre ()
3783 "Start a preformatted section (or apply to the region).
3784 If Transient Mark mode is on and a region is active, it is marked
3785 as preformatted text."
3786 (interactive)
3787 (if (markdown-use-region-p)
3788 (markdown-pre-region (region-beginning) (region-end))
3789 (markdown-ensure-blank-line-before)
3790 (insert (markdown-pre-indentation (point)))
3791 (markdown-ensure-blank-line-after)))
3793 (defun markdown-pre-region (beg end)
3794 "Format the region as preformatted text.
3795 Arguments BEG and END specify the beginning and end of the region."
3796 (interactive "*r")
3797 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
3798 (markdown-block-region beg end indent)))
3800 (defun markdown-electric-backquote (arg)
3801 "Insert a backquote.
3802 The numeric prefix argument ARG says how many times to repeat the insertion.
3803 Call `markdown-insert-gfm-code-block' interactively
3804 if three backquotes inserted at the beginning of line."
3805 (interactive "*P")
3806 (self-insert-command (prefix-numeric-value arg))
3807 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
3808 (replace-match "")
3809 (call-interactively #'markdown-insert-gfm-code-block)))
3811 (defconst markdown-gfm-recognized-languages
3812 ;; to reproduce/update, evaluate the let-form in
3813 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3814 ;; but with appropriate use of a keyboard macro, indenting and filling it
3815 ;; properly is pretty fast.
3816 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3817 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3818 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3819 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3820 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3821 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3822 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3823 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3824 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3825 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3826 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3827 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3828 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3829 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3830 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3831 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3832 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3833 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3834 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3835 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3836 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3837 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3838 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3839 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3840 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3841 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3842 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3843 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3844 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3845 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3846 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3847 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3848 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3849 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3850 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3851 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3852 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3853 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3854 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3855 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3856 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3857 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3858 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3859 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3860 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3861 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3862 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3863 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3864 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3865 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3866 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3867 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3868 "Language specifiers recognized by GitHub's syntax highlighting features.")
3870 (defvar markdown-gfm-used-languages nil
3871 "Language names used in GFM code blocks.")
3872 (make-variable-buffer-local 'markdown-gfm-used-languages)
3874 (defun markdown-trim-whitespace (str)
3875 (markdown-replace-regexp-in-string
3876 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
3878 (defun markdown-clean-language-string (str)
3879 (markdown-replace-regexp-in-string
3880 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
3882 (defun markdown-validate-language-string (widget)
3883 (let ((str (widget-value widget)))
3884 (unless (string= str (markdown-clean-language-string str))
3885 (widget-put widget :error (format "Invalid language spec: '%s'" str))
3886 widget)))
3888 (defun markdown-gfm-get-corpus ()
3889 "Create corpus of recognized GFM code block languages for the given buffer."
3890 (let ((given-corpus (append markdown-gfm-additional-languages
3891 markdown-gfm-recognized-languages)))
3892 (append
3893 markdown-gfm-used-languages
3894 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
3895 given-corpus))))
3897 (defun markdown-gfm-add-used-language (lang)
3898 "Clean LANG and add to list of used languages."
3899 (add-to-list 'markdown-gfm-used-languages
3900 (markdown-clean-language-string lang)))
3902 (defun markdown-insert-gfm-code-block (&optional lang)
3903 "Insert GFM code block for language LANG.
3904 If LANG is nil, the language will be queried from user. If a
3905 region is active, wrap this region with the markup instead. If
3906 the region boundaries are not on empty lines, these are added
3907 automatically in order to have the correct markup."
3908 (interactive
3909 (list (let ((completion-ignore-case nil))
3910 (condition-case nil
3911 (markdown-clean-language-string
3912 (completing-read
3913 (format "Programming language [%s]: "
3914 (or (car markdown-gfm-used-languages) "none"))
3915 (markdown-gfm-get-corpus)
3916 nil 'confirm nil
3917 'markdown-gfm-language-history))
3918 (quit "")))))
3919 (unless (string= lang "") (markdown-gfm-add-used-language lang))
3920 (when (> (length lang) 0) (setq lang (concat " " lang)))
3921 (if (markdown-use-region-p)
3922 (let ((b (region-beginning)) (e (region-end)))
3923 (goto-char e)
3924 ;; if we're on a blank line, don't newline, otherwise the ```
3925 ;; should go on its own line
3926 (unless (looking-back "\n" nil)
3927 (newline))
3928 (insert "```")
3929 (markdown-ensure-blank-line-after)
3930 (goto-char b)
3931 ;; if we're on a blank line, insert the quotes here, otherwise
3932 ;; add a new line first
3933 (unless (looking-at-p "\n")
3934 (newline)
3935 (forward-line -1))
3936 (markdown-ensure-blank-line-before)
3937 (insert "```" lang))
3938 (markdown-ensure-blank-line-before)
3939 (insert "```" lang "\n\n```")
3940 (markdown-ensure-blank-line-after)
3941 (forward-line -1)))
3943 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
3944 (with-current-buffer (or buffer (current-buffer))
3945 (save-excursion
3946 (goto-char (point-min))
3947 (cl-loop
3948 with prop = 'markdown-gfm-block-begin
3949 for pos-prop = (markdown-find-next-prop prop)
3950 while pos-prop
3951 for lang = (progn
3952 (goto-char (car pos-prop))
3953 (save-match-data
3954 (set-match-data (get-text-property (point) prop))
3955 (when (and (match-beginning 2) (match-end 2))
3956 (buffer-substring-no-properties
3957 (match-beginning 2) (match-end 2)))))
3958 do (progn (when lang (markdown-gfm-add-used-language lang))
3959 (goto-char (next-single-property-change (point) prop)))))))
3962 ;;; Footnotes ==================================================================
3964 (defun markdown-footnote-counter-inc ()
3965 "Increment `markdown-footnote-counter' and return the new value."
3966 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
3967 (save-excursion
3968 (goto-char (point-min))
3969 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
3970 (point-max) t)
3971 (let ((fn (string-to-number (match-string 1))))
3972 (when (> fn markdown-footnote-counter)
3973 (setq markdown-footnote-counter fn))))))
3974 (cl-incf markdown-footnote-counter))
3976 (defun markdown-insert-footnote ()
3977 "Insert footnote with a new number and move point to footnote definition."
3978 (interactive)
3979 (let ((fn (markdown-footnote-counter-inc)))
3980 (insert (format "[^%d]" fn))
3981 (markdown-footnote-text-find-new-location)
3982 (markdown-ensure-blank-line-before)
3983 (unless (markdown-cur-line-blank-p)
3984 (insert "\n"))
3985 (insert (format "[^%d]: " fn))
3986 (markdown-ensure-blank-line-after)))
3988 (defun markdown-footnote-text-find-new-location ()
3989 "Position the cursor at the proper location for a new footnote text."
3990 (cond
3991 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
3992 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
3993 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
3995 (defun markdown-footnote-kill ()
3996 "Kill the footnote at point.
3997 The footnote text is killed (and added to the kill ring), the
3998 footnote marker is deleted. Point has to be either at the
3999 footnote marker or in the footnote text."
4000 (interactive)
4001 (let ((marker-pos nil)
4002 (skip-deleting-marker nil)
4003 (starting-footnote-text-positions
4004 (markdown-footnote-text-positions)))
4005 (when starting-footnote-text-positions
4006 ;; We're starting in footnote text, so mark our return position and jump
4007 ;; to the marker if possible.
4008 (let ((marker-pos (markdown-footnote-find-marker
4009 (cl-first starting-footnote-text-positions))))
4010 (if marker-pos
4011 (goto-char (1- marker-pos))
4012 ;; If there isn't a marker, we still want to kill the text.
4013 (setq skip-deleting-marker t))))
4014 ;; Either we didn't start in the text, or we started in the text and jumped
4015 ;; to the marker. We want to assume we're at the marker now and error if
4016 ;; we're not.
4017 (unless skip-deleting-marker
4018 (let ((marker (markdown-footnote-delete-marker)))
4019 (unless marker
4020 (error "Not at a footnote"))
4021 ;; Even if we knew the text position before, it changed when we deleted
4022 ;; the label.
4023 (setq marker-pos (cl-second marker))
4024 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4025 (unless new-text-pos
4026 (error "No text for footnote `%s'" (cl-first marker)))
4027 (goto-char new-text-pos))))
4028 (let ((pos (markdown-footnote-kill-text)))
4029 (goto-char (if starting-footnote-text-positions
4031 marker-pos)))))
4033 (defun markdown-footnote-delete-marker ()
4034 "Delete a footnote marker at point.
4035 Returns a list (ID START) containing the footnote ID and the
4036 start position of the marker before deletion. If no footnote
4037 marker was deleted, this function returns NIL."
4038 (let ((marker (markdown-footnote-marker-positions)))
4039 (when marker
4040 (delete-region (cl-second marker) (cl-third marker))
4041 (butlast marker))))
4043 (defun markdown-footnote-kill-text ()
4044 "Kill footnote text at point.
4045 Returns the start position of the footnote text before deletion,
4046 or NIL if point was not inside a footnote text.
4048 The killed text is placed in the kill ring (without the footnote
4049 number)."
4050 (let ((fn (markdown-footnote-text-positions)))
4051 (when fn
4052 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4053 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4054 (kill-new (match-string 1 text))
4055 (when (and (markdown-cur-line-blank-p)
4056 (markdown-prev-line-blank-p)
4057 (not (bobp)))
4058 (delete-region (1- (point)) (point)))
4059 (cl-second fn)))))
4061 (defun markdown-footnote-goto-text ()
4062 "Jump to the text of the footnote at point."
4063 (interactive)
4064 (let ((fn (car (markdown-footnote-marker-positions))))
4065 (unless fn
4066 (error "Not at a footnote marker"))
4067 (let ((new-pos (markdown-footnote-find-text fn)))
4068 (unless new-pos
4069 (error "No definition found for footnote `%s'" fn))
4070 (goto-char new-pos))))
4072 (defun markdown-footnote-return ()
4073 "Return from a footnote to its footnote number in the main text."
4074 (interactive)
4075 (let ((fn (save-excursion
4076 (car (markdown-footnote-text-positions)))))
4077 (unless fn
4078 (error "Not in a footnote"))
4079 (let ((new-pos (markdown-footnote-find-marker fn)))
4080 (unless new-pos
4081 (error "Footnote marker `%s' not found" fn))
4082 (goto-char new-pos))))
4084 (defun markdown-footnote-find-marker (id)
4085 "Find the location of the footnote marker with ID.
4086 The actual buffer position returned is the position directly
4087 following the marker's closing bracket. If no marker is found,
4088 NIL is returned."
4089 (save-excursion
4090 (goto-char (point-min))
4091 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4092 (skip-chars-backward "^]")
4093 (point))))
4095 (defun markdown-footnote-find-text (id)
4096 "Find the location of the text of footnote ID.
4097 The actual buffer position returned is the position of the first
4098 character of the text, after the footnote's identifier. If no
4099 footnote text is found, NIL is returned."
4100 (save-excursion
4101 (goto-char (point-min))
4102 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
4103 (skip-chars-forward "[ \t]")
4104 (point))))
4106 (defun markdown-footnote-marker-positions ()
4107 "Return the position and ID of the footnote marker point is on.
4108 The return value is a list (ID START END). If point is not on a
4109 footnote, NIL is returned."
4110 ;; first make sure we're at a footnote marker
4111 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4112 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4113 (save-excursion
4114 ;; move point between [ and ^:
4115 (if (looking-at-p "\\[")
4116 (forward-char 1)
4117 (skip-chars-backward "^["))
4118 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4119 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4121 (defun markdown-footnote-text-positions ()
4122 "Return the start and end positions of the footnote text point is in.
4123 The exact return value is a list of three elements: (ID START END).
4124 The start position is the position of the opening bracket
4125 of the footnote id. The end position is directly after the
4126 newline that ends the footnote. If point is not in a footnote,
4127 NIL is returned instead."
4128 (save-excursion
4129 (let (result)
4130 (move-beginning-of-line 1)
4131 ;; Try to find the label. If we haven't found the label and we're at a blank
4132 ;; or indented line, back up if possible.
4133 (while (and
4134 (not (and (looking-at markdown-regex-footnote-definition)
4135 (setq result (list (match-string 1) (point)))))
4136 (and (not (bobp))
4137 (or (markdown-cur-line-blank-p)
4138 (>= (current-indentation) 4))))
4139 (forward-line -1))
4140 (when result
4141 ; Advance if there is a next line that is either blank or indented.
4142 ; (Need to check if we're on the last line, because
4143 ; markdown-next-line-blank-p returns true for last line in buffer.)
4144 (while (and (/= (line-end-position) (point-max))
4145 (or (markdown-next-line-blank-p)
4146 (>= (markdown-next-line-indent) 4)))
4147 (forward-line))
4148 ; Move back while the current line is blank.
4149 (while (markdown-cur-line-blank-p)
4150 (forward-line -1))
4151 ; Advance to capture this line and a single trailing newline (if there
4152 ; is one).
4153 (forward-line)
4154 (append result (list (point)))))))
4157 ;;; Element Removal ===========================================================
4159 (defun markdown-kill-thing-at-point ()
4160 "Kill thing at point and add important text, without markup, to kill ring.
4161 Possible things to kill include (roughly in order of precedence):
4162 inline code, headers, horizonal rules, links (add link text to
4163 kill ring), images (add alt text to kill ring), angle uri, email
4164 addresses, bold, italics, reference definition (add URI to kill
4165 ring), footnote markers and text (kill both marker and text, add
4166 text to kill ring), and list items."
4167 (interactive "*")
4168 (let (val)
4169 (cond
4170 ;; Inline code
4171 ((markdown-code-at-point-p)
4172 (kill-new (match-string 2))
4173 (delete-region (match-beginning 0) (match-end 0)))
4174 ;; ATX header
4175 ((thing-at-point-looking-at markdown-regex-header-atx)
4176 (kill-new (match-string 2))
4177 (delete-region (match-beginning 0) (match-end 0)))
4178 ;; Setext header
4179 ((thing-at-point-looking-at markdown-regex-header-setext)
4180 (kill-new (match-string 1))
4181 (delete-region (match-beginning 0) (match-end 0)))
4182 ;; Horizonal rule
4183 ((thing-at-point-looking-at markdown-regex-hr)
4184 (kill-new (match-string 0))
4185 (delete-region (match-beginning 0) (match-end 0)))
4186 ;; Inline link or image (add link or alt text to kill ring)
4187 ((thing-at-point-looking-at markdown-regex-link-inline)
4188 (kill-new (match-string 3))
4189 (delete-region (match-beginning 0) (match-end 0)))
4190 ;; Reference link or image (add link or alt text to kill ring)
4191 ((thing-at-point-looking-at markdown-regex-link-reference)
4192 (kill-new (match-string 3))
4193 (delete-region (match-beginning 0) (match-end 0)))
4194 ;; Angle URI (add URL to kill ring)
4195 ((thing-at-point-looking-at markdown-regex-angle-uri)
4196 (kill-new (match-string 2))
4197 (delete-region (match-beginning 0) (match-end 0)))
4198 ;; Email address in angle brackets (add email address to kill ring)
4199 ((thing-at-point-looking-at markdown-regex-email)
4200 (kill-new (match-string 1))
4201 (delete-region (match-beginning 0) (match-end 0)))
4202 ;; Wiki link (add alias text to kill ring)
4203 ((and markdown-enable-wiki-links
4204 (thing-at-point-looking-at markdown-regex-wiki-link))
4205 (kill-new (markdown-wiki-link-alias))
4206 (delete-region (match-beginning 1) (match-end 1)))
4207 ;; Bold
4208 ((thing-at-point-looking-at markdown-regex-bold)
4209 (kill-new (match-string 4))
4210 (delete-region (match-beginning 2) (match-end 2)))
4211 ;; Italics
4212 ((thing-at-point-looking-at markdown-regex-italic)
4213 (kill-new (match-string 3))
4214 (delete-region (match-beginning 1) (match-end 1)))
4215 ;; Strikethrough
4216 ((thing-at-point-looking-at markdown-regex-strike-through)
4217 (kill-new (match-string 4))
4218 (delete-region (match-beginning 2) (match-end 2)))
4219 ;; Footnote marker (add footnote text to kill ring)
4220 ((thing-at-point-looking-at markdown-regex-footnote)
4221 (markdown-footnote-kill))
4222 ;; Footnote text (add footnote text to kill ring)
4223 ((setq val (markdown-footnote-text-positions))
4224 (markdown-footnote-kill))
4225 ;; Reference definition (add URL to kill ring)
4226 ((thing-at-point-looking-at markdown-regex-reference-definition)
4227 (kill-new (match-string 5))
4228 (delete-region (match-beginning 0) (match-end 0)))
4229 ;; List item
4230 ((setq val (markdown-cur-list-item-bounds))
4231 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4233 (error "Nothing found at point to kill")))))
4236 ;;; Indentation ====================================================================
4238 (defun markdown-indent-find-next-position (cur-pos positions)
4239 "Return the position after the index of CUR-POS in POSITIONS.
4240 Positions are calculated by `markdown-calc-indents'."
4241 (while (and positions
4242 (not (equal cur-pos (car positions))))
4243 (setq positions (cdr positions)))
4244 (or (cadr positions) 0))
4246 (defun markdown-exdent-find-next-position (cur-pos positions)
4247 "Return the maximal element that precedes CUR-POS from POSITIONS.
4248 Positions are calculated by `markdown-calc-indents'."
4249 (let ((result 0))
4250 (dolist (i positions)
4251 (when (< i cur-pos)
4252 (setq result (max result i))))
4253 result))
4255 (defun markdown-indent-line ()
4256 "Indent the current line using some heuristics.
4257 If the _previous_ command was either `markdown-enter-key' or
4258 `markdown-cycle', then we should cycle to the next
4259 reasonable indentation position. Otherwise, we could have been
4260 called directly by `markdown-enter-key', by an initial call of
4261 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4262 these cases, indent to the default position.
4263 Positions are calculated by `markdown-calc-indents'."
4264 (interactive)
4265 (let ((positions (markdown-calc-indents))
4266 (cursor-pos (current-column))
4267 (_ (back-to-indentation))
4268 (cur-pos (current-column)))
4269 (if (not (equal this-command 'markdown-cycle))
4270 (indent-line-to (car positions))
4271 (setq positions (sort (delete-dups positions) '<))
4272 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4273 (new-cursor-pos
4274 (if (< cur-pos next-pos)
4275 (+ cursor-pos (- next-pos cur-pos))
4276 (- cursor-pos cur-pos))))
4277 (indent-line-to next-pos)
4278 (move-to-column new-cursor-pos)))))
4280 (defun markdown-calc-indents ()
4281 "Return a list of indentation columns to cycle through.
4282 The first element in the returned list should be considered the
4283 default indentation level. This function does not worry about
4284 duplicate positions, which are handled up by calling functions."
4285 (let (pos prev-line-pos positions)
4287 ;; Indentation of previous line
4288 (setq prev-line-pos (markdown-prev-line-indent))
4289 (setq positions (cons prev-line-pos positions))
4291 ;; Indentation of previous non-list-marker text
4292 (when (setq pos (markdown-prev-non-list-indent))
4293 (setq positions (cons pos positions)))
4295 ;; Indentation required for a pre block in current context
4296 (setq pos (length (markdown-pre-indentation (point))))
4297 (setq positions (cons pos positions))
4299 ;; Indentation of the previous line + tab-width
4300 (if prev-line-pos
4301 (setq positions (cons (+ prev-line-pos tab-width) positions))
4302 (setq positions (cons tab-width positions)))
4304 ;; Indentation of the previous line - tab-width
4305 (if (and prev-line-pos (> prev-line-pos tab-width))
4306 (setq positions (cons (- prev-line-pos tab-width) positions)))
4308 ;; Indentation of all preceeding list markers (when in a list)
4309 (when (setq pos (markdown-calculate-list-levels))
4310 (setq positions (append pos positions)))
4312 ;; First column
4313 (setq positions (cons 0 positions))
4315 ;; Return reversed list
4316 (reverse positions)))
4318 (defun markdown-enter-key ()
4319 "Handle RET according to to the value of `markdown-indent-on-enter'."
4320 (interactive)
4321 (newline)
4322 (when markdown-indent-on-enter
4323 (markdown-indent-line)))
4325 (defun markdown-exdent-or-delete (arg)
4326 "Handle BACKSPACE by cycling through indentation points.
4327 When BACKSPACE is pressed, if there is only whitespace
4328 before the current point, then exdent the line one level.
4329 Otherwise, do normal delete by repeating
4330 `backward-delete-char-untabify' ARG times."
4331 (interactive "*p")
4332 (let ((cur-pos (current-column))
4333 (start-of-indention (save-excursion
4334 (back-to-indentation)
4335 (current-column)))
4336 (positions (markdown-calc-indents)))
4337 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4338 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
4339 (backward-delete-char-untabify arg))))
4341 (defun markdown-find-leftmost-column (beg end)
4342 "Find the leftmost column in the region from BEG to END."
4343 (let ((mincol 1000))
4344 (save-excursion
4345 (goto-char beg)
4346 (while (< (point) end)
4347 (back-to-indentation)
4348 (unless (looking-at-p "[ \t]*$")
4349 (setq mincol (min mincol (current-column))))
4350 (forward-line 1)
4352 mincol))
4354 (defun markdown-indent-region (beg end arg)
4355 "Indent the region from BEG to END using some heuristics.
4356 When ARG is non-nil, exdent the region instead.
4357 See `markdown-indent-line' and `markdown-indent-line'."
4358 (interactive "*r\nP")
4359 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4360 (leftmostcol (markdown-find-leftmost-column beg end))
4361 (next-pos (if arg
4362 (markdown-exdent-find-next-position leftmostcol positions)
4363 (markdown-indent-find-next-position leftmostcol positions))))
4364 (indent-rigidly beg end (- next-pos leftmostcol))
4365 (setq deactivate-mark nil)))
4367 (defun markdown-exdent-region (beg end)
4368 "Call `markdown-indent-region' on region from BEG to END with prefix."
4369 (interactive "*r")
4370 (markdown-indent-region beg end t))
4373 ;;; Markup Completion =========================================================
4375 (defconst markdown-complete-alist
4376 '((markdown-regex-header-atx . markdown-complete-atx)
4377 (markdown-regex-header-setext . markdown-complete-setext)
4378 (markdown-regex-hr . markdown-complete-hr))
4379 "Association list of form (regexp . function) for markup completion.")
4381 (defun markdown-incomplete-atx-p ()
4382 "Return t if ATX header markup is incomplete and nil otherwise.
4383 Assumes match data is available for `markdown-regex-header-atx'.
4384 Checks that the number of trailing hash marks equals the number of leading
4385 hash marks, that there is only a single space before and after the text,
4386 and that there is no extraneous whitespace in the text."
4388 ;; Number of starting and ending hash marks differs
4389 (not (= (length (match-string 1)) (length (match-string 3))))
4390 ;; When the header text is not empty...
4391 (and (> (length (match-string 2)) 0)
4392 ;; ...if there are extra leading, trailing, or interior spaces
4393 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4394 (not (= (match-beginning 3) (1+ (match-end 2))))
4395 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4396 ;; When the header text is empty...
4397 (and (= (length (match-string 2)) 0)
4398 ;; ...if there are too many or too few spaces
4399 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4401 (defun markdown-complete-atx ()
4402 "Complete and normalize ATX headers.
4403 Add or remove hash marks to the end of the header to match the
4404 beginning. Ensure that there is only a single space between hash
4405 marks and header text. Removes extraneous whitespace from header text.
4406 Assumes match data is available for `markdown-regex-header-atx'.
4407 Return nil if markup was complete and non-nil if markup was completed."
4408 (when (markdown-incomplete-atx-p)
4409 (let* ((new-marker (make-marker))
4410 (new-marker (set-marker new-marker (match-end 2))))
4411 ;; Hash marks and spacing at end
4412 (goto-char (match-end 2))
4413 (delete-region (match-end 2) (match-end 3))
4414 (insert " " (match-string 1))
4415 ;; Remove extraneous whitespace from title
4416 (replace-match (markdown-compress-whitespace-string (match-string 2))
4417 t t nil 2)
4418 ;; Spacing at beginning
4419 (goto-char (match-end 1))
4420 (delete-region (match-end 1) (match-beginning 2))
4421 (insert " ")
4422 ;; Leave point at end of text
4423 (goto-char new-marker))))
4425 (defun markdown-incomplete-setext-p ()
4426 "Return t if setext header markup is incomplete and nil otherwise.
4427 Assumes match data is available for `markdown-regex-header-setext'.
4428 Checks that length of underline matches text and that there is no
4429 extraneous whitespace in the text."
4430 (or (not (= (length (match-string 1)) (length (match-string 2))))
4431 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4433 (defun markdown-complete-setext ()
4434 "Complete and normalize setext headers.
4435 Add or remove underline characters to match length of header
4436 text. Removes extraneous whitespace from header text. Assumes
4437 match data is available for `markdown-regex-header-setext'.
4438 Return nil if markup was complete and non-nil if markup was completed."
4439 (when (markdown-incomplete-setext-p)
4440 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4441 (char (char-after (match-beginning 2)))
4442 (level (if (char-equal char ?-) 2 1)))
4443 (goto-char (match-beginning 0))
4444 (delete-region (match-beginning 0) (match-end 0))
4445 (markdown-insert-header level text t)
4446 t)))
4448 (defun markdown-incomplete-hr-p ()
4449 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4450 Assumes match data is available for `markdown-regex-hr'."
4451 (not (member (match-string 0) markdown-hr-strings)))
4453 (defun markdown-complete-hr ()
4454 "Complete horizontal rules.
4455 If horizontal rule string is a member of `markdown-hr-strings',
4456 do nothing. Otherwise, replace with the car of
4457 `markdown-hr-strings'.
4458 Assumes match data is available for `markdown-regex-hr'.
4459 Return nil if markup was complete and non-nil if markup was completed."
4460 (when (markdown-incomplete-hr-p)
4461 (replace-match (car markdown-hr-strings))
4464 (defun markdown-complete ()
4465 "Complete markup of object near point or in region when active.
4466 Handle all objects in `markdown-complete-alist', in order.
4467 See `markdown-complete-at-point' and `markdown-complete-region'."
4468 (interactive "*")
4469 (if (markdown-use-region-p)
4470 (markdown-complete-region (region-beginning) (region-end))
4471 (markdown-complete-at-point)))
4473 (defun markdown-complete-at-point ()
4474 "Complete markup of object near point.
4475 Handle all elements of `markdown-complete-alist' in order."
4476 (interactive "*")
4477 (let ((list markdown-complete-alist) found changed)
4478 (while list
4479 (let ((regexp (eval (caar list)))
4480 (function (cdar list)))
4481 (setq list (cdr list))
4482 (when (thing-at-point-looking-at regexp)
4483 (setq found t)
4484 (setq changed (funcall function))
4485 (setq list nil))))
4486 (if found
4487 (or changed (error "Markup at point is complete"))
4488 (error "Nothing to complete at point"))))
4490 (defun markdown-complete-region (beg end)
4491 "Complete markup of objects in region from BEG to END.
4492 Handle all objects in `markdown-complete-alist', in order. Each
4493 match is checked to ensure that a previous regexp does not also
4494 match."
4495 (interactive "*r")
4496 (let ((end-marker (set-marker (make-marker) end))
4497 previous)
4498 (dolist (element markdown-complete-alist)
4499 (let ((regexp (eval (car element)))
4500 (function (cdr element)))
4501 (goto-char beg)
4502 (while (re-search-forward regexp end-marker 'limit)
4503 (when (match-string 0)
4504 ;; Make sure this is not a match for any of the preceding regexps.
4505 ;; This prevents mistaking an HR for a Setext subheading.
4506 (let (match)
4507 (save-match-data
4508 (dolist (prev-regexp previous)
4509 (or match (setq match (looking-back prev-regexp nil)))))
4510 (unless match
4511 (save-excursion (funcall function))))))
4512 (cl-pushnew regexp previous :test #'equal)))
4513 previous))
4515 (defun markdown-complete-buffer ()
4516 "Complete markup for all objects in the current buffer."
4517 (interactive "*")
4518 (markdown-complete-region (point-min) (point-max)))
4521 ;;; Markup Cycling ============================================================
4523 (defun markdown-cycle-atx (arg &optional remove)
4524 "Cycle ATX header markup.
4525 Promote header (decrease level) when ARG is 1 and demote
4526 header (increase level) if arg is -1. When REMOVE is non-nil,
4527 remove the header when the level reaches zero and stop cycling
4528 when it reaches six. Otherwise, perform a proper cycling through
4529 levels one through six. Assumes match data is available for
4530 `markdown-regex-header-atx'."
4531 (let* ((old-level (length (match-string 1)))
4532 (new-level (+ old-level arg))
4533 (text (match-string 2)))
4534 (when (not remove)
4535 (setq new-level (% new-level 6))
4536 (setq new-level (cond ((= new-level 0) 6)
4537 ((< new-level 0) (+ new-level 6))
4538 (t new-level))))
4539 (cond
4540 ((= new-level 0)
4541 (markdown-unwrap-thing-at-point nil 0 2))
4542 ((<= new-level 6)
4543 (goto-char (match-beginning 0))
4544 (delete-region (match-beginning 0) (match-end 0))
4545 (markdown-insert-header new-level text nil)))))
4547 (defun markdown-cycle-setext (arg &optional remove)
4548 "Cycle setext header markup.
4549 Promote header (increase level) when ARG is 1 and demote
4550 header (decrease level or remove) if arg is -1. When demoting a
4551 level-two setext header, replace with a level-three atx header.
4552 When REMOVE is non-nil, remove the header when the level reaches
4553 zero. Otherwise, cycle back to a level six atx header. Assumes
4554 match data is available for `markdown-regex-header-setext'."
4555 (let* ((char (char-after (match-beginning 2)))
4556 (old-level (if (char-equal char ?=) 1 2))
4557 (new-level (+ old-level arg)))
4558 (when (and (not remove) (= new-level 0))
4559 (setq new-level 6))
4560 (cond
4561 ((= new-level 0)
4562 (markdown-unwrap-thing-at-point nil 0 1))
4563 ((<= new-level 2)
4564 (markdown-insert-header new-level nil t))
4565 ((<= new-level 6)
4566 (markdown-insert-header new-level nil nil)))))
4568 (defun markdown-cycle-hr (arg &optional remove)
4569 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4570 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4571 backwards (promote). When REMOVE is non-nil, remove the hr instead
4572 of cycling when the end of the list is reached.
4573 Assumes match data is available for `markdown-regex-hr'."
4574 (let* ((strings (if (= arg -1)
4575 (reverse markdown-hr-strings)
4576 markdown-hr-strings))
4577 (tail (member (match-string 0) strings))
4578 (new (or (cadr tail)
4579 (if remove
4580 (if (= arg 1)
4582 (car tail))
4583 (car strings)))))
4584 (replace-match new)))
4586 (defun markdown-cycle-bold ()
4587 "Cycle bold markup between underscores and asterisks.
4588 Assumes match data is available for `markdown-regex-bold'."
4589 (save-excursion
4590 (let* ((old-delim (match-string 3))
4591 (new-delim (if (string-equal old-delim "**") "__" "**")))
4592 (replace-match new-delim t t nil 3)
4593 (replace-match new-delim t t nil 5))))
4595 (defun markdown-cycle-italic ()
4596 "Cycle italic markup between underscores and asterisks.
4597 Assumes match data is available for `markdown-regex-italic'."
4598 (save-excursion
4599 (let* ((old-delim (match-string 2))
4600 (new-delim (if (string-equal old-delim "*") "_" "*")))
4601 (replace-match new-delim t t nil 2)
4602 (replace-match new-delim t t nil 4))))
4605 ;;; Keymap ====================================================================
4607 (defvar markdown-mode-map
4608 (let ((map (make-keymap)))
4609 ;; Element insertion
4610 (define-key map "\C-c\C-al" 'markdown-insert-link)
4611 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
4612 (define-key map "\C-c\C-au" 'markdown-insert-uri)
4613 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
4614 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
4615 (define-key map "\C-c\C-ii" 'markdown-insert-image)
4616 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
4617 (define-key map "\C-c\C-i\C-t" 'markdown-toggle-inline-images)
4618 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
4619 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
4620 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
4621 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
4622 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
4623 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
4624 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
4625 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
4626 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
4627 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
4628 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
4629 (define-key map "\C-c\C-se" 'markdown-insert-italic)
4630 (define-key map "\C-c\C-sc" 'markdown-insert-code)
4631 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
4632 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
4633 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
4634 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
4635 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
4636 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
4637 (define-key map "\C-c-" 'markdown-insert-hr)
4638 ;; Element insertion (deprecated)
4639 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
4640 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
4641 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
4642 ;; Element removal
4643 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
4644 ;; Promotion, Demotion, Completion, and Cycling
4645 (define-key map (kbd "C-c C--") 'markdown-promote)
4646 (define-key map (kbd "C-c C-=") 'markdown-demote)
4647 (define-key map (kbd "C-c C-]") 'markdown-complete)
4648 ;; Following and Jumping
4649 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
4650 (define-key map (kbd "C-c C-l") 'markdown-jump)
4651 ;; Indentation
4652 (define-key map (kbd "C-m") 'markdown-enter-key)
4653 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
4654 (define-key map (kbd "C-c >") 'markdown-indent-region)
4655 (define-key map (kbd "C-c <") 'markdown-exdent-region)
4656 ;; Visibility cycling
4657 (define-key map (kbd "TAB") 'markdown-cycle)
4658 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
4659 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
4660 (define-key map (kbd "<backtab>") 'markdown-shifttab)
4661 ;; Header navigation
4662 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
4663 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
4664 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
4665 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
4666 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
4667 ;; Buffer-wide commands
4668 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
4669 (define-key map (kbd "C-c C-c p") 'markdown-preview)
4670 (define-key map (kbd "C-c C-c e") 'markdown-export)
4671 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
4672 (define-key map (kbd "C-c C-c o") 'markdown-open)
4673 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
4674 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
4675 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
4676 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
4677 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
4678 ;; List editing
4679 (define-key map (kbd "M-<up>") 'markdown-move-up)
4680 (define-key map (kbd "M-<down>") 'markdown-move-down)
4681 (define-key map (kbd "M-<left>") 'markdown-promote)
4682 (define-key map (kbd "M-<right>") 'markdown-demote)
4683 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
4684 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
4685 ;; Subtree editing
4686 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
4687 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
4688 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
4689 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
4690 ;; Movement
4691 (define-key map (kbd "M-{") 'markdown-backward-paragraph)
4692 (define-key map (kbd "M-}") 'markdown-forward-paragraph)
4693 (define-key map (kbd "M-n") 'markdown-next-link)
4694 (define-key map (kbd "M-p") 'markdown-previous-link)
4695 ;; Alternative keys (in case of problems with the arrow keys)
4696 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
4697 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
4698 (define-key map (kbd "C-c C-x l") 'markdown-promote)
4699 (define-key map (kbd "C-c C-x r") 'markdown-demote)
4700 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
4701 map)
4702 "Keymap for Markdown major mode.")
4704 (defvar gfm-mode-map
4705 (let ((map (make-sparse-keymap)))
4706 (set-keymap-parent map markdown-mode-map)
4707 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
4708 (define-key map "`" 'markdown-electric-backquote)
4709 map)
4710 "Keymap for `gfm-mode'.
4711 See also `markdown-mode-map'.")
4714 ;;; Menu ==================================================================
4716 (easy-menu-define markdown-mode-menu markdown-mode-map
4717 "Menu for Markdown mode"
4718 '("Markdown"
4719 ("Show/Hide"
4720 ["Cycle visibility" markdown-cycle (markdown-on-heading-p)]
4721 ["Cycle global visibility" markdown-shifttab])
4722 "---"
4723 ["Compile" markdown-other-window]
4724 ["Preview" markdown-preview]
4725 ["Export" markdown-export]
4726 ["Export & View" markdown-export-and-preview]
4727 ["Open" markdown-open]
4728 ["Live Export" markdown-live-preview-mode
4729 :style toggle :selected markdown-live-preview-mode]
4730 ["Kill ring save" markdown-kill-ring-save]
4731 "---"
4732 ("Headings"
4733 ["Automatic" markdown-insert-header-dwim]
4734 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
4735 "---"
4736 ["First level setext" markdown-insert-header-setext-1]
4737 ["Second level setext" markdown-insert-header-setext-2]
4738 "---"
4739 ["First level atx" markdown-insert-header-atx-1]
4740 ["Second level atx" markdown-insert-header-atx-2]
4741 ["Third level atx" markdown-insert-header-atx-3]
4742 ["Fourth level atx" markdown-insert-header-atx-4]
4743 ["Fifth level atx" markdown-insert-header-atx-5]
4744 ["Sixth level atx" markdown-insert-header-atx-6])
4745 "---"
4746 ["Bold" markdown-insert-bold]
4747 ["Italic" markdown-insert-italic]
4748 ["Strikethrough" markdown-insert-strike-through]
4749 ["Blockquote" markdown-insert-blockquote]
4750 ["Preformatted" markdown-insert-pre]
4751 ["Code" markdown-insert-code]
4752 "---"
4753 ["Insert inline link" markdown-insert-link]
4754 ["Insert reference link" markdown-insert-reference-link-dwim]
4755 ["Insert URL" markdown-insert-uri]
4756 ["Insert inline image" markdown-insert-image]
4757 ["Insert reference image" markdown-insert-reference-image]
4758 ["Insert list item" markdown-insert-list-item]
4759 ["Insert horizontal rule" markdown-insert-hr]
4760 ["Insert footnote" markdown-insert-footnote]
4761 ["Kill element" markdown-kill-thing-at-point]
4762 "---"
4763 ["Jump" markdown-jump]
4764 ["Follow link" markdown-follow-thing-at-point]
4765 ("Outline"
4766 ["Next visible heading" markdown-next-visible-heading]
4767 ["Previous visible heading" markdown-previous-visible-heading]
4768 ["Forward same level" markdown-forward-same-level]
4769 ["Backward same level" markdown-backward-same-level]
4770 ["Up to parent heading" markdown-up-heading])
4771 "---"
4772 ("Completion and Cycling"
4773 ["Complete" markdown-complete]
4774 ["Promote" markdown-promote]
4775 ["Demote" markdown-demote])
4776 ("List editing"
4777 ["Indent list item" markdown-demote]
4778 ["Exdent list item" markdown-promote])
4779 ("Region shifting"
4780 ["Indent region" markdown-indent-region]
4781 ["Exdent region" markdown-exdent-region])
4782 "---"
4783 ["Toggle inline images" markdown-toggle-inline-images]
4784 ["Check references" markdown-check-refs]
4785 ["Clean up list numbering" markdown-cleanup-list-numbers]
4786 ["Complete markup" markdown-complete-buffer]
4787 "---"
4788 ["Version" markdown-show-version]
4792 ;;; imenu =====================================================================
4794 (defun markdown-imenu-create-nested-index ()
4795 "Create and return a nested imenu index alist for the current buffer.
4796 See `imenu-create-index-function' and `imenu--index-alist' for details."
4797 (let* ((root '(nil . nil))
4798 cur-alist
4799 (cur-level 0)
4800 (empty-heading "-")
4801 (self-heading ".")
4802 hashes pos level heading)
4803 (save-excursion
4804 (goto-char (point-min))
4805 (while (re-search-forward markdown-regex-header (point-max) t)
4806 (unless (markdown-code-block-at-point)
4807 (cond
4808 ((match-string-no-properties 2) ;; level 1 setext
4809 (setq heading (match-string-no-properties 1))
4810 (setq pos (match-beginning 1)
4811 level 1))
4812 ((match-string-no-properties 3) ;; level 2 setext
4813 (setq heading (match-string-no-properties 1))
4814 (setq pos (match-beginning 1)
4815 level 2))
4816 ((setq hashes (match-string-no-properties 4))
4817 (setq heading (match-string-no-properties 5)
4818 pos (match-beginning 4)
4819 level (length hashes))))
4820 (let ((alist (list (cons heading pos))))
4821 (cond
4822 ((= cur-level level) ; new sibling
4823 (setcdr cur-alist alist)
4824 (setq cur-alist alist))
4825 ((< cur-level level) ; first child
4826 (dotimes (_ (- level cur-level 1))
4827 (setq alist (list (cons empty-heading alist))))
4828 (if cur-alist
4829 (let* ((parent (car cur-alist))
4830 (self-pos (cdr parent)))
4831 (setcdr parent (cons (cons self-heading self-pos) alist)))
4832 (setcdr root alist)) ; primogenitor
4833 (setq cur-alist alist)
4834 (setq cur-level level))
4835 (t ; new sibling of an ancestor
4836 (let ((sibling-alist (last (cdr root))))
4837 (dotimes (_ (1- level))
4838 (setq sibling-alist (last (cdar sibling-alist))))
4839 (setcdr sibling-alist alist)
4840 (setq cur-alist alist))
4841 (setq cur-level level))))))
4842 (cdr root))))
4844 (defun markdown-imenu-create-flat-index ()
4845 "Create and return a flat imenu index alist for the current buffer.
4846 See `imenu-create-index-function' and `imenu--index-alist' for details."
4847 (let* ((empty-heading "-") index heading pos)
4848 (save-excursion
4849 (goto-char (point-min))
4850 (while (re-search-forward markdown-regex-header (point-max) t)
4851 (cond
4852 ((setq heading (match-string-no-properties 1))
4853 (setq pos (match-beginning 1)))
4854 ((setq heading (match-string-no-properties 5))
4855 (setq pos (match-beginning 4))))
4856 (or (> (length heading) 0)
4857 (setq heading empty-heading))
4858 (setq index (append index (list (cons heading pos)))))
4859 index)))
4862 ;;; References ================================================================
4864 (defun markdown-reference-goto-definition ()
4865 "Jump to the definition of the reference at point or create it."
4866 (interactive)
4867 (when (thing-at-point-looking-at markdown-regex-link-reference)
4868 (let* ((text (match-string-no-properties 3))
4869 (reference (match-string-no-properties 6))
4870 (target (downcase (if (string= reference "") text reference)))
4871 (loc (cadr (markdown-reference-definition target))))
4872 (if loc
4873 (goto-char loc)
4874 (goto-char (match-beginning 0))
4875 (markdown-insert-reference-definition target)))))
4877 (defun markdown-reference-find-links (reference)
4878 "Return a list of all links for REFERENCE.
4879 REFERENCE should not include the surrounding square brackets.
4880 Elements of the list have the form (text start line), where
4881 text is the link text, start is the location at the beginning of
4882 the link, and line is the line number on which the link appears."
4883 (let* ((ref-quote (regexp-quote reference))
4884 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4885 ref-quote ref-quote))
4886 links)
4887 (save-excursion
4888 (goto-char (point-min))
4889 (while (re-search-forward regexp nil t)
4890 (let* ((text (or (match-string-no-properties 1)
4891 (match-string-no-properties 2)))
4892 (start (match-beginning 0))
4893 (line (markdown-line-number-at-pos)))
4894 (cl-pushnew (list text start line) links :test #'equal))))
4895 links))
4897 (defun markdown-get-undefined-refs ()
4898 "Return a list of undefined Markdown references.
4899 Result is an alist of pairs (reference . occurrences), where
4900 occurrences is itself another alist of pairs (label . line-number).
4901 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4902 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4903 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4904 (let ((missing))
4905 (save-excursion
4906 (goto-char (point-min))
4907 (while
4908 (re-search-forward markdown-regex-link-reference nil t)
4909 (let* ((text (match-string-no-properties 3))
4910 (reference (match-string-no-properties 6))
4911 (target (downcase (if (string= reference "") text reference))))
4912 (unless (markdown-reference-definition target)
4913 (let ((entry (assoc target missing)))
4914 (if (not entry)
4915 (cl-pushnew
4916 (cons target (list (cons text (markdown-line-number-at-pos))))
4917 missing :test #'equal)
4918 (setcdr entry
4919 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
4920 (reverse missing))))
4922 (defconst markdown-reference-check-buffer
4923 "*Undefined references for %buffer%*"
4924 "Pattern for name of buffer for listing undefined references.
4925 The string %buffer% will be replaced by the corresponding
4926 `markdown-mode' buffer name.")
4928 (defun markdown-reference-check-buffer (&optional buffer-name)
4929 "Name and return buffer for reference checking.
4930 BUFFER-NAME is the name of the main buffer being visited."
4931 (or buffer-name (setq buffer-name (buffer-name)))
4932 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
4933 "%buffer%" buffer-name
4934 markdown-reference-check-buffer))))
4935 (with-current-buffer refbuf
4936 (when view-mode
4937 (View-exit-and-edit))
4938 (use-local-map button-buffer-map)
4939 (erase-buffer))
4940 refbuf))
4942 (defconst markdown-reference-links-buffer
4943 "*Reference links for %buffer%*"
4944 "Pattern for name of buffer for listing references.
4945 The string %buffer% will be replaced by the corresponding buffer name.")
4947 (defun markdown-reference-links-buffer (&optional buffer-name)
4948 "Name, setup, and return a buffer for listing links.
4949 BUFFER-NAME is the name of the main buffer being visited."
4950 (or buffer-name (setq buffer-name (buffer-name)))
4951 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
4952 "%buffer%" buffer-name
4953 markdown-reference-links-buffer))))
4954 (with-current-buffer linkbuf
4955 (when view-mode
4956 (View-exit-and-edit))
4957 (use-local-map button-buffer-map)
4958 (erase-buffer))
4959 linkbuf))
4961 (when (markdown-use-buttons-p)
4962 ;; Add an empty Markdown reference definition to buffer
4963 ;; specified in the 'target-buffer property. The reference name is
4964 ;; the button's label.
4965 (define-button-type 'markdown-undefined-reference-button
4966 'help-echo "mouse-1, RET: create definition for undefined reference"
4967 'follow-link t
4968 'face 'bold
4969 'action (lambda (b)
4970 (let ((buffer (button-get b 'target-buffer))
4971 (line (button-get b 'target-line))
4972 (label (button-label b)))
4973 (switch-to-buffer-other-window buffer)
4974 (goto-char (point-min))
4975 (forward-line line)
4976 (markdown-insert-reference-definition label)
4977 (markdown-check-refs t))))
4979 ;; Jump to line in buffer specified by 'target-buffer property.
4980 ;; Line number is button's 'line property.
4981 (define-button-type 'markdown-goto-line-button
4982 'help-echo "mouse-1, RET: go to line"
4983 'follow-link t
4984 'face 'italic
4985 'action (lambda (b)
4986 (message (button-get b 'buffer))
4987 (switch-to-buffer-other-window (button-get b 'target-buffer))
4988 ;; use call-interactively to silence compiler
4989 (let ((current-prefix-arg (button-get b 'target-line)))
4990 (call-interactively 'goto-line))))
4992 ;; Jumps to a particular link at location given by 'target-char
4993 ;; property in buffer given by 'target-buffer property.
4994 (define-button-type 'markdown-link-button
4995 'help-echo "mouse-1, RET: jump to location of link"
4996 'follow-link t
4997 'face 'bold
4998 'action (lambda (b)
4999 (let ((target (button-get b 'target-buffer))
5000 (loc (button-get b 'target-char)))
5001 (kill-buffer-and-window)
5002 (switch-to-buffer target)
5003 (goto-char loc)))))
5005 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5006 "Insert a button for creating REFERENCE in buffer OLDBUF.
5007 REFERENCE should be a list of the form (reference . occurrences),
5008 as by `markdown-get-undefined-refs'."
5009 (let ((label (car reference)))
5010 (if (markdown-use-buttons-p)
5011 ;; Create a reference button in Emacs 22
5012 (insert-button label
5013 :type 'markdown-undefined-reference-button
5014 'target-buffer oldbuf
5015 'target-line (cdr (car (cdr reference))))
5016 ;; Insert reference as text in Emacs < 22
5017 (insert label))
5018 (insert " (")
5019 (dolist (occurrence (cdr reference))
5020 (let ((line (cdr occurrence)))
5021 (if (markdown-use-buttons-p)
5022 ;; Create a line number button in Emacs 22
5023 (insert-button (number-to-string line)
5024 :type 'markdown-goto-line-button
5025 'target-buffer oldbuf
5026 'target-line line)
5027 ;; Insert line number as text in Emacs < 22
5028 (insert (number-to-string line)))
5029 (insert " ")))
5030 (delete-char -1)
5031 (insert ")")
5032 (newline)))
5034 (defun markdown-insert-link-button (link oldbuf)
5035 "Insert a button for jumping to LINK in buffer OLDBUF.
5036 LINK should be a list of the form (text char line) containing
5037 the link text, location, and line number."
5038 (let ((label (cl-first link))
5039 (char (cl-second link))
5040 (line (cl-third link)))
5041 (if (markdown-use-buttons-p)
5042 ;; Create a reference button in Emacs 22
5043 (insert-button label
5044 :type 'markdown-link-button
5045 'target-buffer oldbuf
5046 'target-char char)
5047 ;; Insert reference as text in Emacs < 22
5048 (insert label))
5049 (insert (format " (line %d)\n" line))))
5051 (defun markdown-reference-goto-link (&optional reference)
5052 "Jump to the location of the first use of REFERENCE."
5053 (interactive)
5054 (unless reference
5055 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5056 (setq reference (match-string-no-properties 2))
5057 (error "No reference definition at point")))
5058 (let ((links (markdown-reference-find-links reference)))
5059 (cond ((= (length links) 1)
5060 (goto-char (cadr (car links))))
5061 ((> (length links) 1)
5062 (let ((oldbuf (current-buffer))
5063 (linkbuf (markdown-reference-links-buffer)))
5064 (with-current-buffer linkbuf
5065 (insert "Links using reference " reference ":\n\n")
5066 (dolist (link (reverse links))
5067 (markdown-insert-link-button link oldbuf)))
5068 (view-buffer-other-window linkbuf)
5069 (goto-char (point-min))
5070 (forward-line 2)))
5072 (error "No links for reference %s" reference)))))
5074 (defun markdown-check-refs (&optional silent)
5075 "Show all undefined Markdown references in current `markdown-mode' buffer.
5076 If SILENT is non-nil, do not message anything when no undefined
5077 references found.
5078 Links which have empty reference definitions are considered to be
5079 defined."
5080 (interactive "P")
5081 (when (not (eq major-mode 'markdown-mode))
5082 (error "Not available in current mode"))
5083 (let ((oldbuf (current-buffer))
5084 (refs (markdown-get-undefined-refs))
5085 (refbuf (markdown-reference-check-buffer)))
5086 (if (null refs)
5087 (progn
5088 (when (not silent)
5089 (message "No undefined references found"))
5090 (kill-buffer refbuf))
5091 (with-current-buffer refbuf
5092 (insert "The following references are undefined:\n\n")
5093 (dolist (ref refs)
5094 (markdown-insert-undefined-reference-button ref oldbuf))
5095 (view-buffer-other-window refbuf)
5096 (goto-char (point-min))
5097 (forward-line 2)))))
5100 ;;; Lists =====================================================================
5102 (defun markdown-insert-list-item (&optional arg)
5103 "Insert a new list item.
5104 If the point is inside unordered list, insert a bullet mark. If
5105 the point is inside ordered list, insert the next number followed
5106 by a period. Use the previous list item to determine the amount
5107 of whitespace to place before and after list markers.
5109 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5110 decrease the indentation by one level.
5112 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5113 increase the indentation by one level."
5114 (interactive "p")
5115 (let (bounds cur-indent marker indent new-indent new-loc)
5116 (save-match-data
5117 ;; Look for a list item on current or previous non-blank line
5118 (save-excursion
5119 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5120 (not (bobp))
5121 (markdown-cur-line-blank-p))
5122 (forward-line -1)))
5123 (when bounds
5124 (cond ((save-excursion
5125 (skip-chars-backward " \t")
5126 (looking-at-p markdown-regex-list))
5127 (beginning-of-line)
5128 (insert "\n")
5129 (forward-line -1))
5130 ((not (markdown-cur-line-blank-p))
5131 (newline)))
5132 (setq new-loc (point)))
5133 ;; Look ahead for a list item on next non-blank line
5134 (unless bounds
5135 (save-excursion
5136 (while (and (null bounds)
5137 (not (eobp))
5138 (markdown-cur-line-blank-p))
5139 (forward-line)
5140 (setq bounds (markdown-cur-list-item-bounds))))
5141 (when bounds
5142 (setq new-loc (point))
5143 (unless (markdown-cur-line-blank-p)
5144 (newline))))
5145 (if (not bounds)
5146 ;; When not in a list, start a new unordered one
5147 (progn
5148 (unless (markdown-cur-line-blank-p)
5149 (insert "\n"))
5150 (insert markdown-unordered-list-item-prefix))
5151 ;; Compute indentation and marker for new list item
5152 (setq cur-indent (nth 2 bounds))
5153 (setq marker (nth 4 bounds))
5154 (cond
5155 ;; Dedent: decrement indentation, find previous marker.
5156 ((= arg 4)
5157 (setq indent (max (- cur-indent 4) 0))
5158 (let ((prev-bounds
5159 (save-excursion
5160 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5161 (markdown-cur-list-item-bounds)))))
5162 (when prev-bounds
5163 (setq marker (nth 4 prev-bounds)))))
5164 ;; Indent: increment indentation by 4, use same marker.
5165 ((= arg 16) (setq indent (+ cur-indent 4)))
5166 ;; Same level: keep current indentation and marker.
5167 (t (setq indent cur-indent)))
5168 (setq new-indent (make-string indent 32))
5169 (goto-char new-loc)
5170 (cond
5171 ;; Ordered list
5172 ((string-match-p "[0-9]" marker)
5173 (if (= arg 16) ;; starting a new column indented one more level
5174 (insert (concat new-indent "1. "))
5175 ;; Don't use previous match-data
5176 (set-match-data nil)
5177 ;; travel up to the last item and pick the correct number. If
5178 ;; the argument was nil, "new-indent = cur-indent" is the same,
5179 ;; so we don't need special treatment. Neat.
5180 (save-excursion
5181 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5182 (>= (forward-line -1) 0))))
5183 (let* ((old-prefix (match-string 1))
5184 (old-spacing (match-string 2))
5185 (new-prefix (if old-prefix
5186 (int-to-string (1+ (string-to-number old-prefix)))
5187 "1"))
5188 (space-adjust (- (length old-prefix) (length new-prefix)))
5189 (new-spacing (if (and (match-string 2)
5190 (not (string-match-p "\t" old-spacing))
5191 (< space-adjust 0)
5192 (> space-adjust (- 1 (length (match-string 2)))))
5193 (substring (match-string 2) 0 space-adjust)
5194 (or old-spacing ". "))))
5195 (insert (concat new-indent new-prefix new-spacing)))))
5196 ;; Unordered list, or ordered list with hash mark
5197 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5198 (insert new-indent marker)))))))
5200 (defun markdown-move-list-item-up ()
5201 "Move the current list item up in the list when possible."
5202 (interactive)
5203 (let (cur prev old)
5204 (when (setq cur (markdown-cur-list-item-bounds))
5205 (setq old (point))
5206 (goto-char (nth 0 cur))
5207 (if (markdown-prev-list-item (nth 3 cur))
5208 (progn
5209 (setq prev (markdown-cur-list-item-bounds))
5210 (condition-case nil
5211 (progn
5212 (transpose-regions (nth 0 prev) (nth 1 prev)
5213 (nth 0 cur) (nth 1 cur) t)
5214 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5215 ;; Catch error in case regions overlap.
5216 (error (goto-char old))))
5217 (goto-char old)))))
5219 (defun markdown-move-list-item-down ()
5220 "Move the current list item down in the list when possible."
5221 (interactive)
5222 (let (cur next old)
5223 (when (setq cur (markdown-cur-list-item-bounds))
5224 (setq old (point))
5225 (if (markdown-next-list-item (nth 3 cur))
5226 (progn
5227 (setq next (markdown-cur-list-item-bounds))
5228 (condition-case nil
5229 (progn
5230 (transpose-regions (nth 0 cur) (nth 1 cur)
5231 (nth 0 next) (nth 1 next) nil)
5232 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5233 ;; Catch error in case regions overlap.
5234 (error (goto-char old))))
5235 (goto-char old)))))
5237 (defun markdown-demote-list-item (&optional bounds)
5238 "Indent (or demote) the current list item.
5239 Optionally, BOUNDS of the current list item may be provided if available."
5240 (interactive)
5241 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5242 (save-excursion
5243 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5244 (goto-char (nth 0 bounds))
5245 (while (< (point) end-marker)
5246 (unless (markdown-cur-line-blank-p)
5247 (insert (make-string markdown-list-indent-width ? )))
5248 (forward-line))))))
5250 (defun markdown-promote-list-item (&optional bounds)
5251 "Unindent (or promote) the current list item.
5252 Optionally, BOUNDS of the current list item may be provided if available."
5253 (interactive)
5254 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5255 (save-excursion
5256 (save-match-data
5257 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5258 num regexp)
5259 (goto-char (nth 0 bounds))
5260 (when (looking-at (format "^[ ]\\{1,%d\\}"
5261 markdown-list-indent-width))
5262 (setq num (- (match-end 0) (match-beginning 0)))
5263 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5264 (while (and (< (point) end-marker)
5265 (re-search-forward regexp end-marker t))
5266 (replace-match "" nil nil)
5267 (forward-line))))))))
5269 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5270 "Update the numbering for level PFX (as a string of spaces).
5272 Assume that the previously found match was for a numbered item in
5273 a list."
5274 (let ((cpfx pfx)
5275 (idx 0)
5276 (continue t)
5277 (step t)
5278 (sep nil))
5279 (while (and continue (not (eobp)))
5280 (setq step t)
5281 (cond
5282 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5283 (setq cpfx (match-string-no-properties 1))
5284 (cond
5285 ((string= cpfx pfx)
5286 (save-excursion
5287 (replace-match
5288 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5289 (setq sep nil))
5290 ;; indented a level
5291 ((string< pfx cpfx)
5292 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5293 (setq step nil))
5294 ;; exit the loop
5296 (setq step nil)
5297 (setq continue nil))))
5299 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5300 (setq cpfx (match-string-no-properties 1))
5301 (cond
5302 ;; reset if separated before
5303 ((string= cpfx pfx) (when sep (setq idx 0)))
5304 ((string< cpfx pfx)
5305 (setq step nil)
5306 (setq continue nil))))
5307 (t (setq sep t)))
5309 (when step
5310 (beginning-of-line)
5311 (setq continue (= (forward-line) 0))))
5312 sep))
5314 (defun markdown-cleanup-list-numbers ()
5315 "Update the numbering of ordered lists."
5316 (interactive)
5317 (save-excursion
5318 (goto-char (point-min))
5319 (markdown-cleanup-list-numbers-level "")))
5322 ;;; Movement ==================================================================
5324 (defun markdown-beginning-of-defun (&optional arg)
5325 "`beginning-of-defun-function' for Markdown.
5326 Move backward to the beginning of the current or previous section.
5327 When ARG is non-nil, repeat that many times. When ARG is negative,
5328 move forward to the ARG-th following section."
5329 (interactive "P")
5330 (or arg (setq arg 1))
5331 (forward-char 1)
5332 (or (re-search-backward markdown-regex-header nil t arg)
5333 (goto-char (point-min))))
5335 (defun markdown-end-of-defun (&optional arg)
5336 "`end-of-defun-function' for Markdown.
5337 Move forward to the end of the current or following section.
5338 When ARG is non-nil, repeat that many times. When ARG is negative,
5339 move back to the ARG-th preceding section."
5340 (interactive "P")
5341 (or arg (setq arg 1))
5342 (when (looking-at markdown-regex-header)
5343 (goto-char (match-beginning 0))
5344 (forward-char 1))
5345 (if (re-search-forward markdown-regex-header nil t arg)
5346 (goto-char (match-beginning 0))
5347 (goto-char (point-max)))
5348 (skip-syntax-backward "-"))
5350 (defun markdown-beginning-of-block ()
5351 "Move the point to the start of the previous text block."
5352 (interactive)
5353 (if (re-search-backward markdown-regex-block-separator nil t)
5354 (goto-char (or (match-end 2) (match-end 0)))
5355 (goto-char (point-min))))
5357 (defun markdown-end-of-block ()
5358 "Move the point to the start of the next text block."
5359 (interactive)
5360 (beginning-of-line)
5361 (skip-syntax-forward "-")
5362 (when (= (point) (point-min))
5363 (forward-char))
5364 (if (re-search-forward markdown-regex-block-separator nil t)
5365 (goto-char (or (match-end 2) (match-end 0)))
5366 (goto-char (point-max)))
5367 (skip-syntax-backward "-")
5368 (forward-line))
5370 (defun markdown-forward-paragraph (arg)
5371 "Move forward one or more paragraphs or by one block.
5372 When ARG is nil or a numeric prefix, call `forward-paragraph'
5373 with ARG. When called with \\[universal-argument], call
5374 `markdown-end-of-block' instead."
5375 (interactive "P")
5376 (or arg (setq arg 1))
5377 (cond ((integerp arg)
5378 (forward-paragraph arg))
5379 ((equal arg '(4))
5380 (markdown-end-of-block))))
5382 (defun markdown-backward-paragraph (arg)
5383 "Move backward one or more paragraphs or by one block.
5384 When ARG is nil or a numeric prefix, call `backward-paragraph'
5385 with ARG. When called with \\[universal-argument], call
5386 `markdown-beginning-of-block' instead."
5387 (interactive "P")
5388 (or arg (setq arg 1))
5389 (cond ((integerp arg)
5390 (backward-paragraph arg))
5391 ((equal arg '(4))
5392 (markdown-beginning-of-block))))
5394 (defun markdown-end-of-block-element ()
5395 "Move the point to the start of the next block unit.
5396 Stops at blank lines, list items, headers, and horizontal rules."
5397 (interactive)
5398 (forward-line)
5399 (while (and (or (not (markdown-prev-line-blank-p))
5400 (markdown-cur-line-blank-p))
5401 (not (or (looking-at-p markdown-regex-list)
5402 (looking-at-p markdown-regex-header)
5403 (looking-at-p markdown-regex-hr)))
5404 (not (eobp)))
5405 (forward-line)))
5407 (defun markdown-next-link ()
5408 "Jump to next inline, reference, or wiki link.
5409 If successful, return point. Otherwise, return nil.
5410 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5411 (interactive)
5412 (let ((opoint (point)))
5413 (when (or (markdown-link-p) (markdown-wiki-link-p))
5414 ;; At a link already, move past it.
5415 (goto-char (+ (match-end 0) 1)))
5416 ;; Search for the next wiki link and move to the beginning.
5417 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5418 (markdown-code-block-at-point)
5419 (< (point) (point-max))))
5420 (if (and (not (eq (point) opoint))
5421 (or (markdown-link-p) (markdown-wiki-link-p)))
5422 ;; Group 1 will move past non-escape character in wiki link regexp.
5423 ;; Go to beginning of group zero for all other link types.
5424 (goto-char (or (match-beginning 1) (match-beginning 0)))
5425 (goto-char opoint)
5426 nil)))
5428 (defun markdown-previous-link ()
5429 "Jump to previous wiki link.
5430 If successful, return point. Otherwise, return nil.
5431 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5432 (interactive)
5433 (let ((opoint (point)))
5434 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5435 (markdown-code-block-at-point)
5436 (> (point) (point-min))))
5437 (if (and (not (eq (point) opoint))
5438 (or (markdown-link-p) (markdown-wiki-link-p)))
5439 (goto-char (or (match-beginning 1) (match-beginning 0)))
5440 (goto-char opoint)
5441 nil)))
5443 (defun markdown-next-heading ()
5444 "Move to the next heading line of any level.
5445 With argument, repeats or can move backward if negative."
5446 (let ((pos (outline-next-heading)))
5447 (while (markdown-code-block-at-point)
5448 (setq pos (outline-next-heading)))
5449 pos))
5451 (defun markdown-previous-heading ()
5452 "Move to the previous heading line of any level.
5453 With argument, repeats or can move backward if negative."
5454 (let ((pos (outline-previous-heading)))
5455 (while (markdown-code-block-at-point)
5456 (setq pos (outline-previous-heading)))
5457 pos))
5460 ;;; Outline ===================================================================
5462 (defun markdown-move-heading-common (move-fn &optional arg)
5463 "Wrapper for `outline-mode' functions to skip false positives.
5464 MOVE-FN is a function and ARG is its argument. For example,
5465 headings inside preformatted code blocks may match
5466 `outline-regexp' but should not be considered as headings."
5467 (funcall move-fn arg)
5468 (let ((prev -1))
5469 (while (and (/= prev (point)) (markdown-code-block-at-point))
5470 (setq prev (point))
5471 (funcall move-fn arg))))
5473 (defun markdown-next-visible-heading (arg)
5474 "Move to the next visible heading line of any level.
5475 With argument, repeats or can move backward if negative. ARG is
5476 passed to `outline-next-visible-heading'."
5477 (interactive "p")
5478 (markdown-move-heading-common 'outline-next-visible-heading arg))
5480 (defun markdown-previous-visible-heading (arg)
5481 "Move to the previous visible heading line of any level.
5482 With argument, repeats or can move backward if negative. ARG is
5483 passed to `outline-previous-visible-heading'."
5484 (interactive "p")
5485 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5487 (defun markdown-forward-same-level (arg)
5488 "Move forward to the ARG'th heading at same level as this one.
5489 Stop at the first and last headings of a superior heading."
5490 (interactive "p")
5491 (markdown-move-heading-common 'outline-forward-same-level arg))
5493 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5494 (beginning-of-line)
5495 (or (and (outline-on-heading-p invisible-ok)
5496 (not (markdown-code-block-at-point)))
5497 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5498 found)
5499 (save-excursion
5500 (while (not found)
5501 (let (finish)
5502 (while (and (not finish) (re-search-backward header-re nil t))
5503 (when (and (or invisible-ok (not (outline-invisible-p)))
5504 (not (markdown-code-block-at-point)))
5505 (setq finish t)))
5506 (if (not finish)
5507 (error "Before first heading")
5508 (setq found (point))))))
5509 (goto-char found)
5510 found)))
5512 (defun markdown-backward-same-level (arg)
5513 "Move backward to the ARG'th heading at same level as this one.
5514 Stop at the first and last headings of a superior heading."
5515 (interactive "p")
5516 (markdown-back-to-heading-over-code-block)
5517 (while (> arg 0)
5518 (let ((point-to-move-to (save-excursion
5519 (outline-get-last-sibling))))
5520 (if point-to-move-to
5521 (progn
5522 (goto-char point-to-move-to)
5523 (setq arg (1- arg)))
5524 (error "No previous same-level heading")))))
5526 (defun markdown-up-heading (arg)
5527 "Move to the visible heading line of which the present line is a subheading.
5528 With argument, move up ARG levels."
5529 (interactive "p")
5530 (markdown-move-heading-common 'outline-up-heading arg))
5532 (defun markdown-back-to-heading (&optional invisible-ok)
5533 "Move to previous heading line, or beg of this line if it's a heading.
5534 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5535 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5537 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5539 (defun markdown-on-heading-p ()
5540 "Return t if point is on a (visible) heading line."
5541 (get-text-property (point) 'markdown-heading))
5543 (defun markdown-end-of-subtree (&optional invisible-OK)
5544 "Move to the end of the current subtree.
5545 Only visible heading lines are considered, unless INVISIBLE-OK is
5546 non-nil.
5547 Derived from `org-end-of-subtree'."
5548 (markdown-back-to-heading invisible-OK)
5549 (let ((first t)
5550 (level (funcall outline-level)))
5551 (while (and (not (eobp))
5552 (or first (> (funcall outline-level) level)))
5553 (setq first nil)
5554 (markdown-next-heading))
5555 (if (memq (preceding-char) '(?\n ?\^M))
5556 (progn
5557 ;; Go to end of line before heading
5558 (forward-char -1)
5559 (if (memq (preceding-char) '(?\n ?\^M))
5560 ;; leave blank line before heading
5561 (forward-char -1)))))
5562 (point))
5564 (defun markdown-outline-fix-visibility ()
5565 "Hide any false positive headings that should not be shown.
5566 For example, headings inside preformatted code blocks may match
5567 `outline-regexp' but should not be shown as headings when cycling.
5568 Also, the ending --- line in metadata blocks appears to be a
5569 setext header, but should not be folded."
5570 (save-excursion
5571 (goto-char (point-min))
5572 ;; Unhide any false positives in metadata blocks
5573 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
5574 (let* ((body (progn (forward-line)
5575 (markdown-text-property-at-point
5576 'markdown-yaml-metadata-section)))
5577 (end (progn (goto-char (cl-second body))
5578 (markdown-text-property-at-point
5579 'markdown-yaml-metadata-end))))
5580 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))
5581 ;; Hide any false positives in code blocks
5582 (unless (outline-on-heading-p)
5583 (outline-next-visible-heading 1))
5584 (while (< (point) (point-max))
5585 (when (markdown-code-block-at-point)
5586 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5587 (outline-next-visible-heading 1))))
5589 (defvar markdown-cycle-global-status 1)
5590 (defvar markdown-cycle-subtree-status nil)
5592 (defun markdown-next-preface ()
5593 (let (finish)
5594 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5595 nil 'move))
5596 (unless (markdown-code-block-at-point)
5597 (goto-char (match-beginning 0))
5598 (setq finish t))))
5599 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5600 (forward-char -1)))
5602 (defun markdown-show-entry ()
5603 (save-excursion
5604 (outline-back-to-heading t)
5605 (outline-flag-region (1- (point))
5606 (progn
5607 (markdown-next-preface)
5608 (if (= 1 (- (point-max) (point)))
5609 (point-max)
5610 (point)))
5611 nil)))
5613 (defun markdown-cycle (&optional arg)
5614 "Visibility cycling for Markdown mode.
5615 If ARG is t, perform global visibility cycling. If the point is
5616 at an atx-style header, cycle visibility of the corresponding
5617 subtree. Otherwise, insert a tab using `indent-relative'.
5618 Derived from `org-cycle'."
5619 (interactive "P")
5620 (cond
5621 ((eq arg t) ;; Global cycling
5622 (cond
5623 ((and (eq last-command this-command)
5624 (eq markdown-cycle-global-status 2))
5625 ;; Move from overview to contents
5626 (markdown-hide-sublevels 1)
5627 (message "CONTENTS")
5628 (setq markdown-cycle-global-status 3)
5629 (markdown-outline-fix-visibility))
5631 ((and (eq last-command this-command)
5632 (eq markdown-cycle-global-status 3))
5633 ;; Move from contents to all
5634 (markdown-show-all)
5635 (message "SHOW ALL")
5636 (setq markdown-cycle-global-status 1))
5639 ;; Defaults to overview
5640 (markdown-hide-body)
5641 (message "OVERVIEW")
5642 (setq markdown-cycle-global-status 2)
5643 (markdown-outline-fix-visibility))))
5645 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5646 ;; At a heading: rotate between three different views
5647 (markdown-back-to-heading)
5648 (let ((goal-column 0) eoh eol eos)
5649 ;; Determine boundaries
5650 (save-excursion
5651 (markdown-back-to-heading)
5652 (save-excursion
5653 (beginning-of-line 2)
5654 (while (and (not (eobp)) ;; this is like `next-line'
5655 (get-char-property (1- (point)) 'invisible))
5656 (beginning-of-line 2)) (setq eol (point)))
5657 (markdown-end-of-heading) (setq eoh (point))
5658 (markdown-end-of-subtree t)
5659 (skip-chars-forward " \t\n")
5660 (beginning-of-line 1) ; in case this is an item
5661 (setq eos (1- (point))))
5662 ;; Find out what to do next and set `this-command'
5663 (cond
5664 ((= eos eoh)
5665 ;; Nothing is hidden behind this heading
5666 (message "EMPTY ENTRY")
5667 (setq markdown-cycle-subtree-status nil))
5668 ((>= eol eos)
5669 ;; Entire subtree is hidden in one line: open it
5670 (markdown-show-entry)
5671 (markdown-show-children)
5672 (message "CHILDREN")
5673 (setq markdown-cycle-subtree-status 'children))
5674 ((and (eq last-command this-command)
5675 (eq markdown-cycle-subtree-status 'children))
5676 ;; We just showed the children, now show everything.
5677 (markdown-show-subtree)
5678 (message "SUBTREE")
5679 (setq markdown-cycle-subtree-status 'subtree))
5681 ;; Default action: hide the subtree.
5682 (markdown-hide-subtree)
5683 (message "FOLDED")
5684 (setq markdown-cycle-subtree-status 'folded)))))
5687 (indent-for-tab-command))))
5689 (defun markdown-shifttab ()
5690 "Global visibility cycling.
5691 Calls `markdown-cycle' with argument t."
5692 (interactive)
5693 (markdown-cycle t))
5695 (defun markdown-outline-level ()
5696 "Return the depth to which a statement is nested in the outline."
5697 (cond
5698 ((markdown-code-block-at-point) 7)
5699 ((match-end 2) 1)
5700 ((match-end 3) 2)
5701 ((- (match-end 4) (match-beginning 4)))))
5703 (defun markdown-promote-subtree (&optional arg)
5704 "Promote the current subtree of ATX headings.
5705 Note that Markdown does not support heading levels higher than
5706 six and therefore level-six headings will not be promoted
5707 further. If ARG is non-nil promote the heading, otherwise
5708 demote."
5709 (interactive "*P")
5710 (save-excursion
5711 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5712 (re-search-backward markdown-regex-header-atx nil t))
5713 (not (markdown-code-block-at-point)))
5714 (let ((level (length (match-string 1)))
5715 (promote-or-demote (if arg 1 -1))
5716 (remove 't))
5717 (markdown-cycle-atx promote-or-demote remove)
5718 (catch 'end-of-subtree
5719 (while (markdown-next-heading)
5720 ;; Exit if this not a higher level heading; promote otherwise.
5721 (if (and (looking-at markdown-regex-header-atx)
5722 (<= (length (match-string-no-properties 1)) level))
5723 (throw 'end-of-subtree nil)
5724 (markdown-cycle-atx promote-or-demote remove))))))))
5726 (defun markdown-demote-subtree ()
5727 "Demote the current subtree of ATX headings."
5728 (interactive)
5729 (markdown-promote-subtree t))
5731 (defun markdown-move-subtree-up ()
5732 "Move the current subtree of ATX headings up."
5733 (interactive)
5734 (outline-move-subtree-up 1))
5736 (defun markdown-move-subtree-down ()
5737 "Move the current subtree of ATX headings down."
5738 (interactive)
5739 (outline-move-subtree-down 1))
5742 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5744 (defun markdown-move-up ()
5745 "Move list item up.
5746 Calls `markdown-move-list-item-up'."
5747 (interactive)
5748 (markdown-move-list-item-up))
5750 (defun markdown-move-down ()
5751 "Move list item down.
5752 Calls `markdown-move-list-item-down'."
5753 (interactive)
5754 (markdown-move-list-item-down))
5756 (defun markdown-promote ()
5757 "Either promote header or list item at point or cycle markup.
5758 See `markdown-cycle-atx', `markdown-cycle-setext', and
5759 `markdown-promote-list-item'."
5760 (interactive)
5761 (let (bounds)
5762 (cond
5763 ;; Promote atx header
5764 ((thing-at-point-looking-at markdown-regex-header-atx)
5765 (markdown-cycle-atx -1))
5766 ;; Promote setext header
5767 ((thing-at-point-looking-at markdown-regex-header-setext)
5768 (markdown-cycle-setext -1))
5769 ;; Promote horizonal rule
5770 ((thing-at-point-looking-at markdown-regex-hr)
5771 (markdown-cycle-hr -1))
5772 ;; Promote list item
5773 ((setq bounds (markdown-cur-list-item-bounds))
5774 (markdown-promote-list-item bounds))
5775 ;; Promote bold
5776 ((thing-at-point-looking-at markdown-regex-bold)
5777 (markdown-cycle-bold))
5778 ;; Promote italic
5779 ((thing-at-point-looking-at markdown-regex-italic)
5780 (markdown-cycle-italic))
5782 (error "Nothing to promote at point")))))
5784 (defun markdown-demote ()
5785 "Either demote header or list item at point or cycle or remove markup.
5786 See `markdown-cycle-atx', `markdown-cycle-setext', and
5787 `markdown-demote-list-item'."
5788 (interactive)
5789 (let (bounds)
5790 (cond
5791 ;; Demote atx header
5792 ((thing-at-point-looking-at markdown-regex-header-atx)
5793 (markdown-cycle-atx 1))
5794 ;; Demote setext header
5795 ((thing-at-point-looking-at markdown-regex-header-setext)
5796 (markdown-cycle-setext 1))
5797 ;; Demote horizonal rule
5798 ((thing-at-point-looking-at markdown-regex-hr)
5799 (markdown-cycle-hr 1))
5800 ;; Demote list item
5801 ((setq bounds (markdown-cur-list-item-bounds))
5802 (markdown-demote-list-item bounds))
5803 ;; Demote bold
5804 ((thing-at-point-looking-at markdown-regex-bold)
5805 (markdown-cycle-bold))
5806 ;; Demote italic
5807 ((thing-at-point-looking-at markdown-regex-italic)
5808 (markdown-cycle-italic))
5810 (error "Nothing to demote at point")))))
5813 ;;; Commands ==================================================================
5815 (defun markdown (&optional output-buffer-name)
5816 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5817 The output buffer name defaults to `markdown-output-buffer-name'.
5818 Return the name of the output buffer used."
5819 (interactive)
5820 (save-window-excursion
5821 (let ((begin-region)
5822 (end-region))
5823 (if (markdown-use-region-p)
5824 (setq begin-region (region-beginning)
5825 end-region (region-end))
5826 (setq begin-region (point-min)
5827 end-region (point-max)))
5829 (unless output-buffer-name
5830 (setq output-buffer-name markdown-output-buffer-name))
5831 (cond
5832 ;; Handle case when `markdown-command' does not read from stdin
5833 (markdown-command-needs-filename
5834 (if (not buffer-file-name)
5835 (error "Must be visiting a file")
5836 (shell-command (concat markdown-command " "
5837 (shell-quote-argument buffer-file-name))
5838 output-buffer-name)))
5839 ;; Pass region to `markdown-command' via stdin
5841 (let ((buf (get-buffer-create output-buffer-name)))
5842 (with-current-buffer buf
5843 (setq buffer-read-only nil)
5844 (erase-buffer))
5845 (call-process-region begin-region end-region
5846 shell-file-name nil buf nil
5847 shell-command-switch markdown-command)))))
5848 output-buffer-name))
5850 (defun markdown-standalone (&optional output-buffer-name)
5851 "Special function to provide standalone HTML output.
5852 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5853 (interactive)
5854 (setq output-buffer-name (markdown output-buffer-name))
5855 (with-current-buffer output-buffer-name
5856 (set-buffer output-buffer-name)
5857 (unless (markdown-output-standalone-p)
5858 (markdown-add-xhtml-header-and-footer output-buffer-name))
5859 (goto-char (point-min))
5860 (html-mode))
5861 output-buffer-name)
5863 (defun markdown-other-window (&optional output-buffer-name)
5864 "Run `markdown-command' on current buffer and display in other window.
5865 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5866 that name."
5867 (interactive)
5868 (markdown-display-buffer-other-window
5869 (markdown-standalone output-buffer-name)))
5871 (defun markdown-output-standalone-p ()
5872 "Determine whether `markdown-command' output is standalone XHTML.
5873 Standalone XHTML output is identified by an occurrence of
5874 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5875 (save-excursion
5876 (goto-char (point-min))
5877 (re-search-forward
5878 markdown-xhtml-standalone-regexp
5879 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5880 t)))
5882 (defun markdown-stylesheet-link-string (stylesheet-path)
5883 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5884 stylesheet-path
5885 "\" />"))
5887 (defun markdown-add-xhtml-header-and-footer (title)
5888 "Wrap XHTML header and footer with given TITLE around current buffer."
5889 (goto-char (point-min))
5890 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5891 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5892 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5893 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5894 "<head>\n<title>")
5895 (insert title)
5896 (insert "</title>\n")
5897 (when (> (length markdown-content-type) 0)
5898 (insert
5899 (format
5900 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5901 markdown-content-type
5902 (or (and markdown-coding-system
5903 (fboundp 'coding-system-get)
5904 (coding-system-get markdown-coding-system
5905 'mime-charset))
5906 (and (fboundp 'coding-system-get)
5907 (coding-system-get buffer-file-coding-system
5908 'mime-charset))
5909 "iso-8859-1"))))
5910 (if (> (length markdown-css-paths) 0)
5911 (insert (mapconcat 'markdown-stylesheet-link-string markdown-css-paths "\n")))
5912 (when (> (length markdown-xhtml-header-content) 0)
5913 (insert markdown-xhtml-header-content))
5914 (insert "\n</head>\n\n"
5915 "<body>\n\n")
5916 (goto-char (point-max))
5917 (insert "\n"
5918 "</body>\n"
5919 "</html>\n"))
5921 (defun markdown-preview (&optional output-buffer-name)
5922 "Run `markdown-command' on the current buffer and view output in browser.
5923 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5924 that name."
5925 (interactive)
5926 (browse-url-of-buffer
5927 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
5929 (defun markdown-export-file-name (&optional extension)
5930 "Attempt to generate a filename for Markdown output.
5931 The file extension will be EXTENSION if given, or .html by default.
5932 If the current buffer is visiting a file, we construct a new
5933 output filename based on that filename. Otherwise, return nil."
5934 (when (buffer-file-name)
5935 (unless extension
5936 (setq extension ".html"))
5937 (let ((candidate
5938 (concat
5939 (cond
5940 ((buffer-file-name)
5941 (file-name-sans-extension (buffer-file-name)))
5942 (t (buffer-name)))
5943 extension)))
5944 (cond
5945 ((equal candidate (buffer-file-name))
5946 (concat candidate extension))
5948 candidate)))))
5950 (defun markdown-export (&optional output-file)
5951 "Run Markdown on the current buffer, save to file, and return the filename.
5952 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
5953 generated by `markdown-export-file-name', which will be constructed using the
5954 current filename, but with the extension removed and replaced with .html."
5955 (interactive)
5956 (unless output-file
5957 (setq output-file (markdown-export-file-name ".html")))
5958 (when output-file
5959 (let* ((init-buf (current-buffer))
5960 (init-point (point))
5961 (init-buf-string (buffer-string))
5962 (output-buffer (find-file-noselect output-file))
5963 (output-buffer-name (buffer-name output-buffer)))
5964 (run-hooks 'markdown-before-export-hook)
5965 (markdown-standalone output-buffer-name)
5966 (with-current-buffer output-buffer
5967 (run-hooks 'markdown-after-export-hook)
5968 (save-buffer))
5969 ;; if modified, restore initial buffer
5970 (when (buffer-modified-p init-buf)
5971 (erase-buffer)
5972 (insert init-buf-string)
5973 (save-buffer)
5974 (goto-char init-point))
5975 output-file)))
5977 (defun markdown-export-and-preview ()
5978 "Export to XHTML using `markdown-export' and browse the resulting file."
5979 (interactive)
5980 (browse-url-of-file (markdown-export)))
5982 (defvar markdown-live-preview-buffer nil
5983 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
5984 (make-variable-buffer-local 'markdown-live-preview-buffer)
5986 (defvar markdown-live-preview-source-buffer nil
5987 "Source buffer from which current buffer was generated.
5988 This is the inverse of `markdown-live-preview-buffer'.")
5989 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
5991 (defvar markdown-live-preview-currently-exporting nil)
5993 (defun markdown-live-preview-get-filename ()
5994 "Standardize the filename exported by `markdown-live-preview-export'."
5995 (markdown-export-file-name ".html"))
5997 (defun markdown-live-preview-window-eww (file)
5998 "Preview FILE with eww.
5999 To be used with `markdown-live-preview-window-function'."
6000 (if (require 'eww nil t)
6001 (progn
6002 (eww-open-file file)
6003 (get-buffer "*eww*"))
6004 (error "EWW is not present or not loaded on this version of Emacs")))
6006 (defun markdown-visual-lines-between-points (beg end)
6007 (save-excursion
6008 (goto-char beg)
6009 (cl-loop with count = 0
6010 while (progn (end-of-visual-line)
6011 (and (< (point) end) (line-move-visual 1 t)))
6012 do (cl-incf count)
6013 finally return count)))
6015 (defun markdown-live-preview-window-serialize (buf)
6016 "Get window point and scroll data for all windows displaying BUF."
6017 (when (buffer-live-p buf)
6018 (with-current-buffer buf
6019 (mapcar
6020 (lambda (win)
6021 (with-selected-window win
6022 (let* ((start (window-start))
6023 (pt (window-point))
6024 (pt-or-sym (cond ((= pt (point-min)) 'min)
6025 ((= pt (point-max)) 'max)
6026 (t pt)))
6027 (diff (markdown-visual-lines-between-points
6028 start pt)))
6029 (list win pt-or-sym diff))))
6030 (get-buffer-window-list buf)))))
6032 (defun markdown-get-point-back-lines (pt num-lines)
6033 (save-excursion
6034 (goto-char pt)
6035 (line-move-visual (- num-lines) t)
6036 ;; in testing, can occasionally overshoot the number of lines to traverse
6037 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
6038 (when (> actual-num-lines num-lines)
6039 (line-move-visual (- actual-num-lines num-lines) t)))
6040 (point)))
6042 (defun markdown-live-preview-window-deserialize (window-posns)
6043 "Apply window point and scroll data from WINDOW-POSNS.
6044 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
6045 (cl-destructuring-bind (win pt-or-sym diff) window-posns
6046 (when (window-live-p win)
6047 (with-current-buffer markdown-live-preview-buffer
6048 (set-window-buffer win (current-buffer))
6049 (cl-destructuring-bind (actual-pt actual-diff)
6050 (cl-case pt-or-sym
6051 (min (list (point-min) 0))
6052 (max (list (point-max) diff))
6053 (t (list pt-or-sym diff)))
6054 (set-window-start
6055 win (markdown-get-point-back-lines actual-pt actual-diff))
6056 (set-window-point win actual-pt))))))
6058 (defun markdown-live-preview-export ()
6059 "Export to XHTML using `markdown-export'.
6060 Browse the resulting file within Emacs using
6061 `markdown-live-preview-window-function' Return the buffer
6062 displaying the rendered output."
6063 (interactive)
6064 (let* ((markdown-live-preview-currently-exporting t)
6065 (cur-buf (current-buffer))
6066 (export-file (markdown-export (markdown-live-preview-get-filename)))
6067 ;; get positions in all windows currently displaying output buffer
6068 (window-data
6069 (markdown-live-preview-window-serialize
6070 markdown-live-preview-buffer)))
6071 (save-window-excursion
6072 (let ((output-buffer
6073 (funcall markdown-live-preview-window-function export-file)))
6074 (with-current-buffer output-buffer
6075 (setq markdown-live-preview-source-buffer cur-buf)
6076 (add-hook 'kill-buffer-hook
6077 #'markdown-live-preview-remove-on-kill t t))
6078 (with-current-buffer cur-buf
6079 (setq markdown-live-preview-buffer output-buffer))))
6080 (with-current-buffer cur-buf
6081 ;; reset all windows displaying output buffer to where they were,
6082 ;; now with the new output
6083 (mapc #'markdown-live-preview-window-deserialize window-data)
6084 ;; delete html editing buffer
6085 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
6086 (when (and export-file (file-exists-p export-file)
6087 (eq markdown-live-preview-delete-export
6088 'delete-on-export))
6089 (delete-file export-file))
6090 markdown-live-preview-buffer)))
6092 (defun markdown-live-preview-remove ()
6093 (when (buffer-live-p markdown-live-preview-buffer)
6094 (kill-buffer markdown-live-preview-buffer))
6095 (setq markdown-live-preview-buffer nil)
6096 ;; if set to 'delete-on-export, the output has already been deleted
6097 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
6098 (let ((outfile-name (markdown-live-preview-get-filename)))
6099 (when (file-exists-p outfile-name)
6100 (delete-file outfile-name)))))
6102 (defun markdown-display-buffer-other-window (buf)
6103 (let ((cur-buf (current-buffer)))
6104 (switch-to-buffer-other-window buf)
6105 (set-buffer cur-buf)))
6107 (defun markdown-live-preview-if-markdown ()
6108 (when (and (derived-mode-p 'markdown-mode)
6109 markdown-live-preview-mode)
6110 (unless markdown-live-preview-currently-exporting
6111 (if (buffer-live-p markdown-live-preview-buffer)
6112 (markdown-live-preview-export)
6113 (markdown-display-buffer-other-window
6114 (markdown-live-preview-export))))))
6116 (defun markdown-live-preview-remove-on-kill ()
6117 (cond ((and (derived-mode-p 'markdown-mode)
6118 markdown-live-preview-mode)
6119 (markdown-live-preview-remove))
6120 (markdown-live-preview-source-buffer
6121 (with-current-buffer markdown-live-preview-source-buffer
6122 (setq markdown-live-preview-buffer nil))
6123 (setq markdown-live-preview-source-buffer nil))))
6125 (defun markdown-live-preview-switch-to-output ()
6126 "Switch to output buffer."
6127 (interactive)
6128 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6129 output buffer in another window."
6130 (if markdown-live-preview-mode
6131 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6132 (markdown-live-preview-mode))
6134 (defun markdown-live-preview-re-export ()
6135 "Re export source buffer."
6136 (interactive)
6137 "If the current buffer is a buffer displaying the exported version of a
6138 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6139 update this buffer's contents."
6140 (when markdown-live-preview-source-buffer
6141 (with-current-buffer markdown-live-preview-source-buffer
6142 (markdown-live-preview-export))))
6144 (defun markdown-open ()
6145 "Open file for the current buffer with `markdown-open-command'."
6146 (interactive)
6147 (if (not markdown-open-command)
6148 (error "Variable `markdown-open-command' must be set")
6149 (if (not buffer-file-name)
6150 (error "Must be visiting a file")
6151 (call-process markdown-open-command
6152 nil nil nil buffer-file-name))))
6154 (defun markdown-kill-ring-save ()
6155 "Run Markdown on file and store output in the kill ring."
6156 (interactive)
6157 (save-window-excursion
6158 (markdown)
6159 (with-current-buffer markdown-output-buffer-name
6160 (kill-ring-save (point-min) (point-max)))))
6163 ;;; Links =====================================================================
6165 (defun markdown-link-p ()
6166 "Return non-nil when `point' is at a non-wiki link.
6167 See `markdown-wiki-link-p' for more information."
6168 (let ((case-fold-search nil))
6169 (and (not (markdown-wiki-link-p))
6170 (not (markdown-code-block-at-point))
6171 (or (thing-at-point-looking-at markdown-regex-link-inline)
6172 (thing-at-point-looking-at markdown-regex-link-reference)
6173 (thing-at-point-looking-at markdown-regex-uri)
6174 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6176 (defun markdown-link-link ()
6177 "Return the link part of the regular (non-wiki) link at point.
6178 Works with both inline and reference style links. If point is
6179 not at a link or the link reference is not defined returns nil."
6180 (cond
6181 ((thing-at-point-looking-at markdown-regex-link-inline)
6182 (match-string-no-properties 6))
6183 ((thing-at-point-looking-at markdown-regex-link-reference)
6184 (let* ((text (match-string-no-properties 3))
6185 (reference (match-string-no-properties 6))
6186 (target (downcase (if (string= reference "") text reference))))
6187 (car (markdown-reference-definition target))))
6188 ((thing-at-point-looking-at markdown-regex-uri)
6189 (match-string-no-properties 0))
6190 ((thing-at-point-looking-at markdown-regex-angle-uri)
6191 (match-string-no-properties 2))
6192 (t nil)))
6194 (defun markdown-follow-link-at-point ()
6195 "Open the current non-wiki link.
6196 If the link is a complete URL, open in browser with `browse-url'.
6197 Otherwise, open with `find-file' after stripping anchor and/or query string."
6198 (interactive)
6199 (if (markdown-link-p)
6200 (let* ((link (markdown-link-link)) (struct nil) (full t) (file link))
6201 ;; Parse URL, determine fullness, strip query string
6202 (when (featurep 'url-parse)
6203 (setq struct (url-generic-parse-url link)
6204 full (url-fullness struct)
6205 file (car (url-path-and-query struct))))
6206 ;; Open full URLs in browser, files in Emacs
6207 (if full (browse-url link) (find-file file)))
6208 (error "Point is not at a Markdown link or URI")))
6211 ;;; WikiLink Following/Markup =================================================
6213 (defun markdown-wiki-link-p ()
6214 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6215 A true wiki link name matches `markdown-regex-wiki-link' but does
6216 not match the current file name after conversion. This modifies
6217 the data returned by `match-data'. Note that the potential wiki
6218 link name must be available via `match-string'."
6219 (when markdown-enable-wiki-links
6220 (let ((case-fold-search nil))
6221 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6222 (not (markdown-code-block-at-point))
6223 (or (not buffer-file-name)
6224 (not (string-equal (buffer-file-name)
6225 (markdown-convert-wiki-link-to-filename
6226 (markdown-wiki-link-link)))))))))
6228 (defun markdown-wiki-link-link ()
6229 "Return the link part of the wiki link using current match data.
6230 The location of the link component depends on the value of
6231 `markdown-wiki-link-alias-first'."
6232 (if markdown-wiki-link-alias-first
6233 (or (match-string-no-properties 5) (match-string-no-properties 3))
6234 (match-string-no-properties 3)))
6236 (defun markdown-wiki-link-alias ()
6237 "Return the alias or text part of the wiki link using current match data.
6238 The location of the alias component depends on the value of
6239 `markdown-wiki-link-alias-first'."
6240 (if markdown-wiki-link-alias-first
6241 (match-string-no-properties 3)
6242 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6244 (defun markdown-convert-wiki-link-to-filename (name)
6245 "Generate a filename from the wiki link NAME.
6246 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6247 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6248 and [[test test]] both map to Test-test.ext."
6249 (let ((basename (markdown-replace-regexp-in-string
6250 "[[:space:]\n]" markdown-link-space-sub-char name)))
6251 (when (eq major-mode 'gfm-mode)
6252 (setq basename (concat (upcase (substring basename 0 1))
6253 (downcase (substring basename 1 nil)))))
6254 (let* ((default
6255 (concat basename
6256 (if (and (buffer-file-name)
6257 (file-name-extension (buffer-file-name)))
6258 (concat "."
6259 (file-name-extension (buffer-file-name))))))
6260 (current default))
6261 (catch 'done
6262 (condition-case nil
6263 (cl-loop
6264 (if (or (not markdown-wiki-link-search-parent-directories)
6265 (file-exists-p current))
6266 (throw 'done current))
6267 (if (string-equal (expand-file-name current)
6268 (concat "/" default))
6269 (throw 'done default))
6270 (setq current (concat "../" current)))
6271 (error default))))))
6273 (defun markdown-follow-wiki-link (name &optional other)
6274 "Follow the wiki link NAME.
6275 Convert the name to a file name and call `find-file'. Ensure that
6276 the new buffer remains in `markdown-mode'. Open the link in another
6277 window when OTHER is non-nil."
6278 (let ((filename (markdown-convert-wiki-link-to-filename name))
6279 (wp (file-name-directory buffer-file-name)))
6280 (when other (other-window 1))
6281 (let ((default-directory wp))
6282 (find-file filename)))
6283 (when (not (eq major-mode 'markdown-mode))
6284 (markdown-mode)))
6286 (defun markdown-follow-wiki-link-at-point (&optional arg)
6287 "Find Wiki Link at point.
6288 With prefix argument ARG, open the file in other window.
6289 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6290 (interactive "P")
6291 (if (markdown-wiki-link-p)
6292 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6293 (error "Point is not at a Wiki Link")))
6295 (defun markdown-highlight-wiki-link (from to face)
6296 "Highlight the wiki link in the region between FROM and TO using FACE."
6297 (put-text-property from to 'font-lock-face face))
6299 (defun markdown-unfontify-region-wiki-links (from to)
6300 "Remove wiki link faces from the region specified by FROM and TO."
6301 (interactive "*r")
6302 (remove-text-properties from to '(font-lock-face markdown-link-face))
6303 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
6305 (defun markdown-fontify-region-wiki-links (from to)
6306 "Search region given by FROM and TO for wiki links and fontify them.
6307 If a wiki link is found check to see if the backing file exists
6308 and highlight accordingly."
6309 (goto-char from)
6310 (save-match-data
6311 (while (re-search-forward markdown-regex-wiki-link to t)
6312 (when (not (markdown-code-block-at-point))
6313 (let ((highlight-beginning (match-beginning 1))
6314 (highlight-end (match-end 1))
6315 (file-name
6316 (markdown-convert-wiki-link-to-filename
6317 (markdown-wiki-link-link))))
6318 (if (condition-case nil (file-exists-p file-name) (error nil))
6319 (markdown-highlight-wiki-link
6320 highlight-beginning highlight-end markdown-link-face)
6321 (markdown-highlight-wiki-link
6322 highlight-beginning highlight-end markdown-missing-link-face)))))))
6324 (defun markdown-extend-changed-region (from to)
6325 "Extend region given by FROM and TO so that we can fontify all links.
6326 The region is extended to the first newline before and the first
6327 newline after."
6328 ;; start looking for the first new line before 'from
6329 (goto-char from)
6330 (re-search-backward "\n" nil t)
6331 (let ((new-from (point-min))
6332 (new-to (point-max)))
6333 (if (not (= (point) from))
6334 (setq new-from (point)))
6335 ;; do the same thing for the first new line after 'to
6336 (goto-char to)
6337 (re-search-forward "\n" nil t)
6338 (if (not (= (point) to))
6339 (setq new-to (point)))
6340 (cl-values new-from new-to)))
6342 (defun markdown-check-change-for-wiki-link (from to)
6343 "Check region between FROM and TO for wiki links and re-fontify as needed."
6344 (interactive "*r")
6345 (let* ((modified (buffer-modified-p))
6346 (buffer-undo-list t)
6347 (inhibit-read-only t)
6348 (inhibit-point-motion-hooks t)
6349 deactivate-mark
6350 buffer-file-truename)
6351 (unwind-protect
6352 (save-excursion
6353 (save-match-data
6354 (save-restriction
6355 ;; Extend the region to fontify so that it starts
6356 ;; and ends at safe places.
6357 (cl-multiple-value-bind (new-from new-to)
6358 (markdown-extend-changed-region from to)
6359 (goto-char new-from)
6360 ;; Only refontify when the range contains text with a
6361 ;; wiki link face or if the wiki link regexp matches.
6362 (when (or (markdown-range-property-any
6363 new-from new-to 'font-lock-face
6364 (list markdown-link-face
6365 markdown-missing-link-face))
6366 (re-search-forward
6367 markdown-regex-wiki-link new-to t))
6368 ;; Unfontify existing fontification (start from scratch)
6369 (markdown-unfontify-region-wiki-links new-from new-to)
6370 ;; Now do the fontification.
6371 (markdown-fontify-region-wiki-links new-from new-to))))))
6372 (and (not modified)
6373 (buffer-modified-p)
6374 (set-buffer-modified-p nil)))))
6376 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6377 "Check region between FROM and TO for wiki links and re-fontify as needed.
6378 Designed to be used with the `after-change-functions' hook."
6379 (markdown-check-change-for-wiki-link from to))
6381 (defun markdown-fontify-buffer-wiki-links ()
6382 "Refontify all wiki links in the buffer."
6383 (interactive)
6384 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6387 ;;; Following and Jumping =====================================================
6389 (defun markdown-follow-thing-at-point (arg)
6390 "Follow thing at point if possible, such as a reference link or wiki link.
6391 Opens inline and reference links in a browser. Opens wiki links
6392 to other files in the current window, or the another window if
6393 ARG is non-nil.
6394 See `markdown-follow-link-at-point' and
6395 `markdown-follow-wiki-link-at-point'."
6396 (interactive "P")
6397 (cond ((markdown-link-p)
6398 (markdown-follow-link-at-point))
6399 ((markdown-wiki-link-p)
6400 (markdown-follow-wiki-link-at-point arg))
6402 (error "Nothing to follow at point"))))
6404 (defun markdown-jump ()
6405 "Jump to another location based on context at point.
6406 Jumps between reference links and definitions; between footnote
6407 markers and footnote text."
6408 (interactive)
6409 (cond ((markdown-footnote-text-positions)
6410 (markdown-footnote-return))
6411 ((markdown-footnote-marker-positions)
6412 (markdown-footnote-goto-text))
6413 ((thing-at-point-looking-at markdown-regex-link-reference)
6414 (markdown-reference-goto-definition))
6415 ((thing-at-point-looking-at markdown-regex-reference-definition)
6416 (markdown-reference-goto-link (match-string-no-properties 2)))
6418 (error "Nothing to jump to from context at point"))))
6421 ;;; Miscellaneous =============================================================
6423 (defun markdown-compress-whitespace-string (str)
6424 "Compress whitespace in STR and return result.
6425 Leading and trailing whitespace is removed. Sequences of multiple
6426 spaces, tabs, and newlines are replaced with single spaces."
6427 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6428 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6430 (defun markdown-line-number-at-pos (&optional pos)
6431 "Return (narrowed) buffer line number at position POS.
6432 If POS is nil, use current buffer location.
6433 This is an exact copy of `line-number-at-pos' for use in emacs21."
6434 (let ((opoint (or pos (point))) start)
6435 (save-excursion
6436 (goto-char (point-min))
6437 (setq start (point))
6438 (goto-char opoint)
6439 (forward-line 0)
6440 (1+ (count-lines start (point))))))
6442 (defun markdown-inside-link-text-p ()
6443 "Return nil if not currently within link anchor text."
6444 (looking-back "\\[[^]]*" nil))
6446 (defun markdown-line-is-reference-definition-p ()
6447 "Return whether the current line is a (non-footnote) reference defition."
6448 (save-excursion
6449 (move-beginning-of-line 1)
6450 (and (looking-at-p markdown-regex-reference-definition)
6451 (not (looking-at-p "[ \t]*\\[^")))))
6453 (defun markdown-adaptive-fill-function ()
6454 "Return prefix for filling paragraph or nil if not determined."
6455 (cond
6456 ;; List item inside blockquote
6457 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+-]\\)[ \t]+")
6458 (markdown-replace-regexp-in-string
6459 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6460 ;; Blockquote
6461 ((looking-at "^[ \t]*>[ \t]*")
6462 (match-string-no-properties 0))
6463 ;; List items
6464 ((looking-at markdown-regex-list)
6465 (match-string-no-properties 0))
6466 ((looking-at-p markdown-regex-footnote-definition)
6467 " ") ; four spaces
6468 ;; No match
6469 (t nil)))
6471 (defun markdown-fill-forward-paragraph-function (&optional arg)
6472 (let* ((arg (or arg 1))
6473 (paragraphs-remaining (forward-paragraph arg))
6474 (start (point)))
6475 (when (< arg 0)
6476 (while (and (not (eobp))
6477 (progn (move-to-left-margin) (not (eobp)))
6478 (looking-at-p paragraph-separate))
6479 (forward-line 1))
6480 (if (looking-at markdown-regex-list)
6481 (forward-char (length (match-string 0)))
6482 (goto-char start)))
6483 paragraphs-remaining))
6486 ;;; Extension Framework =======================================================
6488 (defun markdown-reload-extensions ()
6489 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6490 (interactive)
6491 (when (eq major-mode 'markdown-mode)
6492 ;; Update font lock keywords with extensions
6493 (setq markdown-mode-font-lock-keywords
6494 (append
6495 markdown-mode-font-lock-keywords-basic
6496 (markdown-mode-font-lock-keywords-wiki-links)
6497 (markdown-mode-font-lock-keywords-math)))
6498 ;; Update font lock defaults
6499 (setq font-lock-defaults
6500 '(markdown-mode-font-lock-keywords
6501 nil nil nil nil
6502 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6503 ;; Refontify buffer
6504 (when (fboundp 'font-lock-refresh-defaults) (font-lock-refresh-defaults))
6505 ;; Add or remove hooks related to extensions
6506 (markdown-setup-wiki-link-hooks)))
6508 (defun markdown-handle-local-variables ()
6509 "Run in `hack-local-variables-hook' to update font lock rules.
6510 Checks to see if there is actually a ‘markdown-mode’ file local variable
6511 before regenerating font-lock rules for extensions."
6512 (when (and (boundp 'file-local-variables-alist)
6513 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6514 (assoc 'markdown-enable-math file-local-variables-alist))
6515 (markdown-reload-extensions)))
6517 ;;; Wiki Links ================================================================
6519 (defun markdown-toggle-wiki-links (&optional arg)
6520 "Toggle support for wiki links.
6521 With a prefix argument ARG, enable wiki link support if ARG is positive,
6522 and disable it otherwise."
6523 (interactive (list (or current-prefix-arg 'toggle)))
6524 (setq markdown-enable-wiki-links
6525 (if (eq arg 'toggle)
6526 (not markdown-enable-wiki-links)
6527 (> (prefix-numeric-value arg) 0)))
6528 (if markdown-enable-wiki-links
6529 (message "markdown-mode wiki link support enabled")
6530 (message "markdown-mode wiki link support disabled"))
6531 (markdown-reload-extensions))
6533 (defun markdown-setup-wiki-link-hooks ()
6534 "Add or remove hooks for fontifying wiki links.
6535 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6536 ;; Anytime text changes make sure it gets fontified correctly
6537 (if (and markdown-enable-wiki-links
6538 markdown-wiki-link-fontify-missing)
6539 (add-hook 'after-change-functions
6540 'markdown-check-change-for-wiki-link-after-change t t)
6541 (remove-hook 'after-change-functions
6542 'markdown-check-change-for-wiki-link-after-change t))
6543 ;; If we left the buffer there is a really good chance we were
6544 ;; creating one of the wiki link documents. Make sure we get
6545 ;; refontified when we come back.
6546 (if (and markdown-enable-wiki-links
6547 markdown-wiki-link-fontify-missing)
6548 (progn
6549 (add-hook 'window-configuration-change-hook
6550 'markdown-fontify-buffer-wiki-links t t)
6551 (markdown-fontify-buffer-wiki-links))
6552 (remove-hook 'window-configuration-change-hook
6553 'markdown-fontify-buffer-wiki-links t)
6554 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6556 (defun markdown-mode-font-lock-keywords-wiki-links ()
6557 "Return wiki-link lock keywords if support is enabled.
6558 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6559 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6560 (when (and markdown-enable-wiki-links
6561 (not markdown-wiki-link-fontify-missing))
6562 (list
6563 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6565 ;;; Math Support ==============================================================
6567 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6569 (defun markdown-toggle-math (&optional arg)
6570 "Toggle support for inline and display LaTeX math expressions.
6571 With a prefix argument ARG, enable math mode if ARG is positive,
6572 and disable it otherwise. If called from Lisp, enable the mode
6573 if ARG is omitted or nil."
6574 (interactive (list (or current-prefix-arg 'toggle)))
6575 (setq markdown-enable-math
6576 (if (eq arg 'toggle)
6577 (not markdown-enable-math)
6578 (> (prefix-numeric-value arg) 0)))
6579 (if markdown-enable-math
6580 (message "markdown-mode math support enabled")
6581 (message "markdown-mode math support disabled"))
6582 (markdown-reload-extensions))
6584 (defun markdown-mode-font-lock-keywords-math ()
6585 "Return math font lock keywords if support is enabled."
6586 (when markdown-enable-math
6587 (list
6588 ;; Display mode equations with brackets: \[ \]
6589 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6590 (2 markdown-math-face append)
6591 (3 markdown-markup-face prepend)))
6592 ;; Equation reference (eq:foo)
6593 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6594 (2 markdown-reference-face)
6595 (3 markdown-markup-face)))
6596 ;; Equation reference \eqref{foo}
6597 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6598 (2 markdown-reference-face)
6599 (3 markdown-markup-face))))))
6602 ;;; GFM Checkboxes as Buttons =================================================
6604 (require 'button)
6606 (define-button-type 'markdown-gfm-checkbox-button
6607 'follow-link t
6608 'face 'markdown-gfm-checkbox-face
6609 'mouse-face 'markdown-highlight-face
6610 'action #'markdown-toggle-gfm-checkbox)
6612 (defun markdown-toggle-gfm-checkbox (button)
6613 "Toggle GFM checkbox BUTTON on click."
6614 (save-match-data
6615 (save-excursion
6616 (goto-char (button-start button))
6617 (cond ((looking-at "\\[ \\]")
6618 (replace-match "[x]" nil t))
6619 ((looking-at "\\[[xX]\\]")
6620 (replace-match "[ ]" nil t))))))
6622 (defun markdown-make-gfm-checkboxes-buttons (start end)
6623 "Make GFM checkboxes buttons in region between START and END."
6624 (save-excursion
6625 (goto-char start)
6626 (let ((case-fold-search t))
6627 (save-excursion
6628 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6629 (make-button (match-beginning 1) (match-end 1)
6630 :type 'markdown-gfm-checkbox-button))))))
6632 ;; Called when any modification is made to buffer text.
6633 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6634 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6635 BEG and END are the limits of scanned region."
6636 (save-excursion
6637 (save-match-data
6638 ;; Rescan between start of line from `beg' and start of line after `end'.
6639 (markdown-make-gfm-checkboxes-buttons
6640 (progn (goto-char beg) (beginning-of-line) (point))
6641 (progn (goto-char end) (forward-line 1) (point))))))
6644 ;;; Display inline image =================================================
6646 (defvar markdown-inline-image-overlays nil)
6647 (make-variable-buffer-local 'markdown-inline-image-overlays)
6649 (defun markdown-remove-inline-images ()
6650 "Remove inline image overlays from image links in the buffer.
6651 This can be toggled with `markdown-toggle-inline-images'
6652 or \\[markdown-toggle-inline-images]."
6653 (interactive)
6654 (mapc 'delete-overlay markdown-inline-image-overlays)
6655 (setq markdown-inline-image-overlays nil))
6657 (defun markdown-display-inline-images ()
6658 "Add inline image overlays to image links in the buffer.
6659 This can be toggled with `markdown-toggle-inline-images'
6660 or \\[markdown-toggle-inline-images]."
6661 (interactive)
6662 (unless (display-graphic-p)
6663 (error "Cannot show images"))
6664 (save-excursion
6665 (save-restriction
6666 (widen)
6667 (goto-char (point-min))
6668 (while (re-search-forward markdown-regex-link-inline nil t)
6669 (let ((start (match-beginning 0))
6670 (end (match-end 0))
6671 (file (match-string-no-properties 6)))
6672 (when (file-exists-p file)
6673 (let* ((abspath (if (file-name-absolute-p file)
6674 file
6675 (concat default-directory file)))
6676 (image (create-image abspath)))
6677 (when image
6678 (let ((ov (make-overlay start end)))
6679 (overlay-put ov 'display image)
6680 (overlay-put ov 'face 'default)
6681 (push ov markdown-inline-image-overlays))))))))))
6683 (defun markdown-toggle-inline-images ()
6684 "Toggle inline image overlays in the buffer."
6685 (interactive)
6686 (if markdown-inline-image-overlays
6687 (markdown-remove-inline-images)
6688 (markdown-display-inline-images)))
6691 ;;; Mode Definition ==========================================================
6693 (defun markdown-show-version ()
6694 "Show the version number in the minibuffer."
6695 (interactive)
6696 (message "markdown-mode, version %s" markdown-mode-version))
6698 ;;;###autoload
6699 (define-derived-mode markdown-mode text-mode "Markdown"
6700 "Major mode for editing Markdown files."
6701 ;; Natural Markdown tab width
6702 (setq tab-width 4)
6703 ;; Comments
6704 (make-local-variable 'comment-start)
6705 (setq comment-start "<!-- ")
6706 (make-local-variable 'comment-end)
6707 (setq comment-end " -->")
6708 (make-local-variable 'comment-start-skip)
6709 (setq comment-start-skip "<!--[ \t]*")
6710 (make-local-variable 'comment-column)
6711 (setq comment-column 0)
6712 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
6713 ;; Syntax
6714 (add-hook 'syntax-propertize-extend-region-functions
6715 'markdown-syntax-propertize-extend-region)
6716 (add-hook 'jit-lock-after-change-extend-region-functions
6717 'markdown-font-lock-extend-region-function t t)
6718 (set (make-local-variable 'syntax-propertize-function)
6719 'markdown-syntax-propertize)
6720 ;; Font lock.
6721 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
6722 (set (make-local-variable 'font-lock-defaults) nil)
6723 (set (make-local-variable 'font-lock-multiline) t)
6724 ;; Extensions
6725 (make-local-variable 'markdown-enable-math)
6726 ;; Reload extensions
6727 (markdown-reload-extensions)
6728 ;; Add a buffer-local hook to reload after file-local variables are read
6729 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
6730 ;; For imenu support
6731 (setq imenu-create-index-function
6732 (if markdown-nested-imenu-heading-index
6733 'markdown-imenu-create-nested-index
6734 'markdown-imenu-create-flat-index))
6735 ;; For menu support in XEmacs
6736 (easy-menu-add markdown-mode-menu markdown-mode-map)
6737 ;; Defun movement
6738 (set (make-local-variable 'beginning-of-defun-function)
6739 'markdown-beginning-of-defun)
6740 (set (make-local-variable 'end-of-defun-function)
6741 'markdown-end-of-defun)
6742 ;; Paragraph filling
6743 (set
6744 ; Should match start of lines that start or separate paragraphs
6745 (make-local-variable 'paragraph-start)
6746 (mapconcat 'identity
6748 "\f" ; starts with a literal line-feed
6749 "[ \t\f]*$" ; space-only line
6750 "[ \t]*[*+-][ \t]+" ; unordered list item
6751 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6752 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6753 "[ \t]*:[ \t]+" ; definition
6755 "\\|"))
6756 (set
6757 ; Should match lines that separate paragraphs without being
6758 ; part of any paragraph:
6759 (make-local-variable 'paragraph-separate)
6760 (mapconcat 'identity
6761 '("[ \t\f]*$" ; space-only line
6762 ; The following is not ideal, but the Fill customization
6763 ; options really only handle paragraph-starting prefixes,
6764 ; not paragraph-ending suffixes:
6765 ".* $" ; line ending in two spaces
6766 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6767 "\\|"))
6768 (set (make-local-variable 'adaptive-fill-first-line-regexp)
6769 "\\`[ \t]*>[ \t]*?\\'")
6770 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
6771 (set (make-local-variable 'adaptive-fill-function)
6772 'markdown-adaptive-fill-function)
6773 (set (make-local-variable 'fill-forward-paragraph-function)
6774 'markdown-fill-forward-paragraph-function)
6775 ;; Outline mode
6776 (make-local-variable 'outline-regexp)
6777 (setq outline-regexp markdown-regex-header)
6778 (make-local-variable 'outline-level)
6779 (setq outline-level 'markdown-outline-level)
6780 ;; Cause use of ellipses for invisible text.
6781 (add-to-invisibility-spec '(outline . t))
6783 ;; Inhibiting line-breaking:
6784 ;; Separating out each condition into a separate function so that users can
6785 ;; override if desired (with remove-hook)
6786 (add-hook 'fill-nobreak-predicate
6787 'markdown-inside-link-text-p nil t)
6788 (add-hook 'fill-nobreak-predicate
6789 'markdown-line-is-reference-definition-p nil t)
6791 ;; Indentation
6792 (setq indent-line-function markdown-indent-function)
6794 ;; Backwards compatibility with markdown-css-path
6795 (when (boundp 'markdown-css-path)
6796 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6797 (add-to-list 'markdown-css-paths markdown-css-path))
6799 ;; Prepare hooks for XEmacs compatibility
6800 (when (featurep 'xemacs)
6801 (make-local-hook 'after-change-functions)
6802 (make-local-hook 'font-lock-extend-region-functions)
6803 (make-local-hook 'window-configuration-change-hook))
6805 ;; Make checkboxes buttons
6806 (when markdown-make-gfm-checkboxes-buttons
6807 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6808 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
6810 ;; add live preview export hook
6811 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
6812 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
6814 ;;;###autoload
6815 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
6816 ;;;###autoload
6817 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
6820 ;;; GitHub Flavored Markdown Mode ============================================
6822 (defvar gfm-mode-hook nil
6823 "Hook run when entering GFM mode.")
6825 (defvar gfm-font-lock-keywords
6826 (append
6827 ;; GFM features to match first
6828 (list
6829 (cons markdown-regex-strike-through '((3 markdown-markup-face)
6830 (4 markdown-strike-through-face)
6831 (5 markdown-markup-face))))
6832 ;; Basic Markdown features (excluding possibly overridden ones)
6833 markdown-mode-font-lock-keywords-basic)
6834 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6836 ;;;###autoload
6837 (define-derived-mode gfm-mode markdown-mode "GFM"
6838 "Major mode for editing GitHub Flavored Markdown files."
6839 (setq markdown-link-space-sub-char "-")
6840 (set (make-local-variable 'font-lock-defaults)
6841 '(gfm-font-lock-keywords))
6842 ;; do the initial link fontification
6843 (markdown-gfm-parse-buffer-for-languages))
6846 ;;; Live Preview Mode ============================================
6847 (define-minor-mode markdown-live-preview-mode
6848 "Toggle native previewing on save for a specific markdown file."
6849 :lighter " MD-Preview"
6850 (if markdown-live-preview-mode
6851 (markdown-display-buffer-other-window (markdown-live-preview-export))
6852 (markdown-live-preview-remove)))
6855 (provide 'markdown-mode)
6856 ;; Local Variables:
6857 ;; indent-tabs-mode: nil
6858 ;; End:
6859 ;;; markdown-mode.el ends here