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