Fix check for point inside link
[markdown-mode.git] / markdown-mode.el
blobb6fb64f524082c69e165e4cc2d8221d4a3f194d2
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 "markdown-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 (min new-end (point-max))))))))
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 (when (and (not (markdown-code-block-at-point))
4821 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
4822 (cond
4823 ((setq heading (match-string-no-properties 1))
4824 (setq pos (match-beginning 1)))
4825 ((setq heading (match-string-no-properties 5))
4826 (setq pos (match-beginning 4))))
4827 (or (> (length heading) 0)
4828 (setq heading empty-heading))
4829 (setq index (append index (list (cons heading pos))))))
4830 index)))
4833 ;;; References ================================================================
4835 (defun markdown-reference-goto-definition ()
4836 "Jump to the definition of the reference at point or create it."
4837 (interactive)
4838 (when (thing-at-point-looking-at markdown-regex-link-reference)
4839 (let* ((text (match-string-no-properties 3))
4840 (reference (match-string-no-properties 6))
4841 (target (downcase (if (string= reference "") text reference)))
4842 (loc (cadr (markdown-reference-definition target))))
4843 (if loc
4844 (goto-char loc)
4845 (goto-char (match-beginning 0))
4846 (markdown-insert-reference-definition target)))))
4848 (defun markdown-reference-find-links (reference)
4849 "Return a list of all links for REFERENCE.
4850 REFERENCE should not include the surrounding square brackets.
4851 Elements of the list have the form (text start line), where
4852 text is the link text, start is the location at the beginning of
4853 the link, and line is the line number on which the link appears."
4854 (let* ((ref-quote (regexp-quote reference))
4855 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4856 ref-quote ref-quote))
4857 links)
4858 (save-excursion
4859 (goto-char (point-min))
4860 (while (re-search-forward regexp nil t)
4861 (let* ((text (or (match-string-no-properties 1)
4862 (match-string-no-properties 2)))
4863 (start (match-beginning 0))
4864 (line (markdown-line-number-at-pos)))
4865 (cl-pushnew (list text start line) links :test #'equal))))
4866 links))
4868 (defun markdown-get-undefined-refs ()
4869 "Return a list of undefined Markdown references.
4870 Result is an alist of pairs (reference . occurrences), where
4871 occurrences is itself another alist of pairs (label . line-number).
4872 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4873 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4874 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4875 (let ((missing))
4876 (save-excursion
4877 (goto-char (point-min))
4878 (while
4879 (re-search-forward markdown-regex-link-reference nil t)
4880 (let* ((text (match-string-no-properties 3))
4881 (reference (match-string-no-properties 6))
4882 (target (downcase (if (string= reference "") text reference))))
4883 (unless (markdown-reference-definition target)
4884 (let ((entry (assoc target missing)))
4885 (if (not entry)
4886 (cl-pushnew
4887 (cons target (list (cons text (markdown-line-number-at-pos))))
4888 missing :test #'equal)
4889 (setcdr entry
4890 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
4891 (reverse missing))))
4893 (defconst markdown-reference-check-buffer
4894 "*Undefined references for %buffer%*"
4895 "Pattern for name of buffer for listing undefined references.
4896 The string %buffer% will be replaced by the corresponding
4897 `markdown-mode' buffer name.")
4899 (defun markdown-reference-check-buffer (&optional buffer-name)
4900 "Name and return buffer for reference checking.
4901 BUFFER-NAME is the name of the main buffer being visited."
4902 (or buffer-name (setq buffer-name (buffer-name)))
4903 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
4904 "%buffer%" buffer-name
4905 markdown-reference-check-buffer))))
4906 (with-current-buffer refbuf
4907 (when view-mode
4908 (View-exit-and-edit))
4909 (use-local-map button-buffer-map)
4910 (erase-buffer))
4911 refbuf))
4913 (defconst markdown-reference-links-buffer
4914 "*Reference links for %buffer%*"
4915 "Pattern for name of buffer for listing references.
4916 The string %buffer% will be replaced by the corresponding buffer name.")
4918 (defun markdown-reference-links-buffer (&optional buffer-name)
4919 "Name, setup, and return a buffer for listing links.
4920 BUFFER-NAME is the name of the main buffer being visited."
4921 (or buffer-name (setq buffer-name (buffer-name)))
4922 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
4923 "%buffer%" buffer-name
4924 markdown-reference-links-buffer))))
4925 (with-current-buffer linkbuf
4926 (when view-mode
4927 (View-exit-and-edit))
4928 (use-local-map button-buffer-map)
4929 (erase-buffer))
4930 linkbuf))
4932 (when (markdown-use-buttons-p)
4933 ;; Add an empty Markdown reference definition to buffer
4934 ;; specified in the 'target-buffer property. The reference name is
4935 ;; the button's label.
4936 (define-button-type 'markdown-undefined-reference-button
4937 'help-echo "mouse-1, RET: create definition for undefined reference"
4938 'follow-link t
4939 'face 'bold
4940 'action (lambda (b)
4941 (let ((buffer (button-get b 'target-buffer))
4942 (line (button-get b 'target-line))
4943 (label (button-label b)))
4944 (switch-to-buffer-other-window buffer)
4945 (goto-char (point-min))
4946 (forward-line line)
4947 (markdown-insert-reference-definition label)
4948 (markdown-check-refs t))))
4950 ;; Jump to line in buffer specified by 'target-buffer property.
4951 ;; Line number is button's 'line property.
4952 (define-button-type 'markdown-goto-line-button
4953 'help-echo "mouse-1, RET: go to line"
4954 'follow-link t
4955 'face 'italic
4956 'action (lambda (b)
4957 (message (button-get b 'buffer))
4958 (switch-to-buffer-other-window (button-get b 'target-buffer))
4959 ;; use call-interactively to silence compiler
4960 (let ((current-prefix-arg (button-get b 'target-line)))
4961 (call-interactively 'goto-line))))
4963 ;; Jumps to a particular link at location given by 'target-char
4964 ;; property in buffer given by 'target-buffer property.
4965 (define-button-type 'markdown-link-button
4966 'help-echo "mouse-1, RET: jump to location of link"
4967 'follow-link t
4968 'face 'bold
4969 'action (lambda (b)
4970 (let ((target (button-get b 'target-buffer))
4971 (loc (button-get b 'target-char)))
4972 (kill-buffer-and-window)
4973 (switch-to-buffer target)
4974 (goto-char loc)))))
4976 (defun markdown-insert-undefined-reference-button (reference oldbuf)
4977 "Insert a button for creating REFERENCE in buffer OLDBUF.
4978 REFERENCE should be a list of the form (reference . occurrences),
4979 as by `markdown-get-undefined-refs'."
4980 (let ((label (car reference)))
4981 (if (markdown-use-buttons-p)
4982 ;; Create a reference button in Emacs 22
4983 (insert-button label
4984 :type 'markdown-undefined-reference-button
4985 'target-buffer oldbuf
4986 'target-line (cdr (car (cdr reference))))
4987 ;; Insert reference as text in Emacs < 22
4988 (insert label))
4989 (insert " (")
4990 (dolist (occurrence (cdr reference))
4991 (let ((line (cdr occurrence)))
4992 (if (markdown-use-buttons-p)
4993 ;; Create a line number button in Emacs 22
4994 (insert-button (number-to-string line)
4995 :type 'markdown-goto-line-button
4996 'target-buffer oldbuf
4997 'target-line line)
4998 ;; Insert line number as text in Emacs < 22
4999 (insert (number-to-string line)))
5000 (insert " ")))
5001 (delete-char -1)
5002 (insert ")")
5003 (newline)))
5005 (defun markdown-insert-link-button (link oldbuf)
5006 "Insert a button for jumping to LINK in buffer OLDBUF.
5007 LINK should be a list of the form (text char line) containing
5008 the link text, location, and line number."
5009 (let ((label (cl-first link))
5010 (char (cl-second link))
5011 (line (cl-third link)))
5012 (if (markdown-use-buttons-p)
5013 ;; Create a reference button in Emacs 22
5014 (insert-button label
5015 :type 'markdown-link-button
5016 'target-buffer oldbuf
5017 'target-char char)
5018 ;; Insert reference as text in Emacs < 22
5019 (insert label))
5020 (insert (format " (line %d)\n" line))))
5022 (defun markdown-reference-goto-link (&optional reference)
5023 "Jump to the location of the first use of REFERENCE."
5024 (interactive)
5025 (unless reference
5026 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5027 (setq reference (match-string-no-properties 2))
5028 (error "No reference definition at point")))
5029 (let ((links (markdown-reference-find-links reference)))
5030 (cond ((= (length links) 1)
5031 (goto-char (cadr (car links))))
5032 ((> (length links) 1)
5033 (let ((oldbuf (current-buffer))
5034 (linkbuf (markdown-reference-links-buffer)))
5035 (with-current-buffer linkbuf
5036 (insert "Links using reference " reference ":\n\n")
5037 (dolist (link (reverse links))
5038 (markdown-insert-link-button link oldbuf)))
5039 (view-buffer-other-window linkbuf)
5040 (goto-char (point-min))
5041 (forward-line 2)))
5043 (error "No links for reference %s" reference)))))
5045 (defun markdown-check-refs (&optional silent)
5046 "Show all undefined Markdown references in current `markdown-mode' buffer.
5047 If SILENT is non-nil, do not message anything when no undefined
5048 references found.
5049 Links which have empty reference definitions are considered to be
5050 defined."
5051 (interactive "P")
5052 (when (not (eq major-mode 'markdown-mode))
5053 (error "Not available in current mode"))
5054 (let ((oldbuf (current-buffer))
5055 (refs (markdown-get-undefined-refs))
5056 (refbuf (markdown-reference-check-buffer)))
5057 (if (null refs)
5058 (progn
5059 (when (not silent)
5060 (message "No undefined references found"))
5061 (kill-buffer refbuf))
5062 (with-current-buffer refbuf
5063 (insert "The following references are undefined:\n\n")
5064 (dolist (ref refs)
5065 (markdown-insert-undefined-reference-button ref oldbuf))
5066 (view-buffer-other-window refbuf)
5067 (goto-char (point-min))
5068 (forward-line 2)))))
5071 ;;; Lists =====================================================================
5073 (defun markdown-insert-list-item (&optional arg)
5074 "Insert a new list item.
5075 If the point is inside unordered list, insert a bullet mark. If
5076 the point is inside ordered list, insert the next number followed
5077 by a period. Use the previous list item to determine the amount
5078 of whitespace to place before and after list markers.
5080 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5081 decrease the indentation by one level.
5083 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5084 increase the indentation by one level."
5085 (interactive "p")
5086 (let (bounds cur-indent marker indent new-indent new-loc)
5087 (save-match-data
5088 ;; Look for a list item on current or previous non-blank line
5089 (save-excursion
5090 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5091 (not (bobp))
5092 (markdown-cur-line-blank-p))
5093 (forward-line -1)))
5094 (when bounds
5095 (cond ((save-excursion
5096 (skip-chars-backward " \t")
5097 (looking-at-p markdown-regex-list))
5098 (beginning-of-line)
5099 (insert "\n")
5100 (forward-line -1))
5101 ((not (markdown-cur-line-blank-p))
5102 (newline)))
5103 (setq new-loc (point)))
5104 ;; Look ahead for a list item on next non-blank line
5105 (unless bounds
5106 (save-excursion
5107 (while (and (null bounds)
5108 (not (eobp))
5109 (markdown-cur-line-blank-p))
5110 (forward-line)
5111 (setq bounds (markdown-cur-list-item-bounds))))
5112 (when bounds
5113 (setq new-loc (point))
5114 (unless (markdown-cur-line-blank-p)
5115 (newline))))
5116 (if (not bounds)
5117 ;; When not in a list, start a new unordered one
5118 (progn
5119 (unless (markdown-cur-line-blank-p)
5120 (insert "\n"))
5121 (insert markdown-unordered-list-item-prefix))
5122 ;; Compute indentation and marker for new list item
5123 (setq cur-indent (nth 2 bounds))
5124 (setq marker (nth 4 bounds))
5125 (cond
5126 ;; Dedent: decrement indentation, find previous marker.
5127 ((= arg 4)
5128 (setq indent (max (- cur-indent 4) 0))
5129 (let ((prev-bounds
5130 (save-excursion
5131 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5132 (markdown-cur-list-item-bounds)))))
5133 (when prev-bounds
5134 (setq marker (nth 4 prev-bounds)))))
5135 ;; Indent: increment indentation by 4, use same marker.
5136 ((= arg 16) (setq indent (+ cur-indent 4)))
5137 ;; Same level: keep current indentation and marker.
5138 (t (setq indent cur-indent)))
5139 (setq new-indent (make-string indent 32))
5140 (goto-char new-loc)
5141 (cond
5142 ;; Ordered list
5143 ((string-match-p "[0-9]" marker)
5144 (if (= arg 16) ;; starting a new column indented one more level
5145 (insert (concat new-indent "1. "))
5146 ;; Don't use previous match-data
5147 (set-match-data nil)
5148 ;; travel up to the last item and pick the correct number. If
5149 ;; the argument was nil, "new-indent = cur-indent" is the same,
5150 ;; so we don't need special treatment. Neat.
5151 (save-excursion
5152 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5153 (>= (forward-line -1) 0))))
5154 (let* ((old-prefix (match-string 1))
5155 (old-spacing (match-string 2))
5156 (new-prefix (if old-prefix
5157 (int-to-string (1+ (string-to-number old-prefix)))
5158 "1"))
5159 (space-adjust (- (length old-prefix) (length new-prefix)))
5160 (new-spacing (if (and (match-string 2)
5161 (not (string-match-p "\t" old-spacing))
5162 (< space-adjust 0)
5163 (> space-adjust (- 1 (length (match-string 2)))))
5164 (substring (match-string 2) 0 space-adjust)
5165 (or old-spacing ". "))))
5166 (insert (concat new-indent new-prefix new-spacing)))))
5167 ;; Unordered list, or ordered list with hash mark
5168 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5169 (insert new-indent marker)))))))
5171 (defun markdown-move-list-item-up ()
5172 "Move the current list item up in the list when possible."
5173 (interactive)
5174 (let (cur prev old)
5175 (when (setq cur (markdown-cur-list-item-bounds))
5176 (setq old (point))
5177 (goto-char (nth 0 cur))
5178 (if (markdown-prev-list-item (nth 3 cur))
5179 (progn
5180 (setq prev (markdown-cur-list-item-bounds))
5181 (condition-case nil
5182 (progn
5183 (transpose-regions (nth 0 prev) (nth 1 prev)
5184 (nth 0 cur) (nth 1 cur) t)
5185 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5186 ;; Catch error in case regions overlap.
5187 (error (goto-char old))))
5188 (goto-char old)))))
5190 (defun markdown-move-list-item-down ()
5191 "Move the current list item down in the list when possible."
5192 (interactive)
5193 (let (cur next old)
5194 (when (setq cur (markdown-cur-list-item-bounds))
5195 (setq old (point))
5196 (if (markdown-next-list-item (nth 3 cur))
5197 (progn
5198 (setq next (markdown-cur-list-item-bounds))
5199 (condition-case nil
5200 (progn
5201 (transpose-regions (nth 0 cur) (nth 1 cur)
5202 (nth 0 next) (nth 1 next) nil)
5203 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5204 ;; Catch error in case regions overlap.
5205 (error (goto-char old))))
5206 (goto-char old)))))
5208 (defun markdown-demote-list-item (&optional bounds)
5209 "Indent (or demote) the current list item.
5210 Optionally, BOUNDS of the current list item may be provided if available."
5211 (interactive)
5212 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5213 (save-excursion
5214 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5215 (goto-char (nth 0 bounds))
5216 (while (< (point) end-marker)
5217 (unless (markdown-cur-line-blank-p)
5218 (insert (make-string markdown-list-indent-width ? )))
5219 (forward-line))))))
5221 (defun markdown-promote-list-item (&optional bounds)
5222 "Unindent (or promote) the current list item.
5223 Optionally, BOUNDS of the current list item may be provided if available."
5224 (interactive)
5225 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5226 (save-excursion
5227 (save-match-data
5228 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5229 num regexp)
5230 (goto-char (nth 0 bounds))
5231 (when (looking-at (format "^[ ]\\{1,%d\\}"
5232 markdown-list-indent-width))
5233 (setq num (- (match-end 0) (match-beginning 0)))
5234 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5235 (while (and (< (point) end-marker)
5236 (re-search-forward regexp end-marker t))
5237 (replace-match "" nil nil)
5238 (forward-line))))))))
5240 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5241 "Update the numbering for level PFX (as a string of spaces).
5243 Assume that the previously found match was for a numbered item in
5244 a list."
5245 (let ((cpfx pfx)
5246 (idx 0)
5247 (continue t)
5248 (step t)
5249 (sep nil))
5250 (while (and continue (not (eobp)))
5251 (setq step t)
5252 (cond
5253 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5254 (setq cpfx (match-string-no-properties 1))
5255 (cond
5256 ((string= cpfx pfx)
5257 (save-excursion
5258 (replace-match
5259 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5260 (setq sep nil))
5261 ;; indented a level
5262 ((string< pfx cpfx)
5263 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5264 (setq step nil))
5265 ;; exit the loop
5267 (setq step nil)
5268 (setq continue nil))))
5270 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5271 (setq cpfx (match-string-no-properties 1))
5272 (cond
5273 ;; reset if separated before
5274 ((string= cpfx pfx) (when sep (setq idx 0)))
5275 ((string< cpfx pfx)
5276 (setq step nil)
5277 (setq continue nil))))
5278 (t (setq sep t)))
5280 (when step
5281 (beginning-of-line)
5282 (setq continue (= (forward-line) 0))))
5283 sep))
5285 (defun markdown-cleanup-list-numbers ()
5286 "Update the numbering of ordered lists."
5287 (interactive)
5288 (save-excursion
5289 (goto-char (point-min))
5290 (markdown-cleanup-list-numbers-level "")))
5293 ;;; Movement ==================================================================
5295 (defun markdown-beginning-of-defun (&optional arg)
5296 "`beginning-of-defun-function' for Markdown.
5297 Move backward to the beginning of the current or previous section.
5298 When ARG is non-nil, repeat that many times. When ARG is negative,
5299 move forward to the ARG-th following section."
5300 (interactive "P")
5301 (or arg (setq arg 1))
5302 (forward-char 1)
5303 (or (re-search-backward markdown-regex-header nil t arg)
5304 (goto-char (point-min))))
5306 (defun markdown-end-of-defun (&optional arg)
5307 "`end-of-defun-function' for Markdown.
5308 Move forward to the end of the current or following section.
5309 When ARG is non-nil, repeat that many times. When ARG is negative,
5310 move back to the ARG-th preceding section."
5311 (interactive "P")
5312 (or arg (setq arg 1))
5313 (when (looking-at markdown-regex-header)
5314 (goto-char (match-beginning 0))
5315 (forward-char 1))
5316 (if (re-search-forward markdown-regex-header nil t arg)
5317 (goto-char (match-beginning 0))
5318 (goto-char (point-max)))
5319 (skip-syntax-backward "-"))
5321 (defun markdown-beginning-of-block ()
5322 "Move the point to the start of the previous text block."
5323 (interactive)
5324 (if (re-search-backward markdown-regex-block-separator nil t)
5325 (goto-char (or (match-end 2) (match-end 0)))
5326 (goto-char (point-min))))
5328 (defun markdown-end-of-block ()
5329 "Move the point to the start of the next text block."
5330 (interactive)
5331 (beginning-of-line)
5332 (skip-syntax-forward "-")
5333 (when (= (point) (point-min))
5334 (forward-char))
5335 (if (re-search-forward markdown-regex-block-separator nil t)
5336 (goto-char (or (match-end 2) (match-end 0)))
5337 (goto-char (point-max)))
5338 (skip-syntax-backward "-")
5339 (forward-line))
5341 (defun markdown-forward-paragraph (arg)
5342 "Move forward one or more paragraphs or by one block.
5343 When ARG is nil or a numeric prefix, call `forward-paragraph'
5344 with ARG. When called with \\[universal-argument], call
5345 `markdown-end-of-block' instead."
5346 (interactive "P")
5347 (or arg (setq arg 1))
5348 (cond ((integerp arg)
5349 (forward-paragraph arg))
5350 ((equal arg '(4))
5351 (markdown-end-of-block))))
5353 (defun markdown-backward-paragraph (arg)
5354 "Move backward one or more paragraphs or by one block.
5355 When ARG is nil or a numeric prefix, call `backward-paragraph'
5356 with ARG. When called with \\[universal-argument], call
5357 `markdown-beginning-of-block' instead."
5358 (interactive "P")
5359 (or arg (setq arg 1))
5360 (cond ((integerp arg)
5361 (backward-paragraph arg))
5362 ((equal arg '(4))
5363 (markdown-beginning-of-block))))
5365 (defun markdown-end-of-block-element ()
5366 "Move the point to the start of the next block unit.
5367 Stops at blank lines, list items, headers, and horizontal rules."
5368 (interactive)
5369 (forward-line)
5370 (while (and (or (not (markdown-prev-line-blank-p))
5371 (markdown-cur-line-blank-p))
5372 (not (or (looking-at-p markdown-regex-list)
5373 (looking-at-p markdown-regex-header)
5374 (looking-at-p markdown-regex-hr)))
5375 (not (eobp)))
5376 (forward-line)))
5378 (defun markdown-next-link ()
5379 "Jump to next inline, reference, or wiki link.
5380 If successful, return point. Otherwise, return nil.
5381 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5382 (interactive)
5383 (let ((opoint (point)))
5384 (when (or (markdown-link-p) (markdown-wiki-link-p))
5385 ;; At a link already, move past it.
5386 (goto-char (+ (match-end 0) 1)))
5387 ;; Search for the next wiki link and move to the beginning.
5388 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5389 (markdown-code-block-at-point)
5390 (< (point) (point-max))))
5391 (if (and (not (eq (point) opoint))
5392 (or (markdown-link-p) (markdown-wiki-link-p)))
5393 ;; Group 1 will move past non-escape character in wiki link regexp.
5394 ;; Go to beginning of group zero for all other link types.
5395 (goto-char (or (match-beginning 1) (match-beginning 0)))
5396 (goto-char opoint)
5397 nil)))
5399 (defun markdown-previous-link ()
5400 "Jump to previous wiki link.
5401 If successful, return point. Otherwise, return nil.
5402 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5403 (interactive)
5404 (let ((opoint (point)))
5405 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5406 (markdown-code-block-at-point)
5407 (> (point) (point-min))))
5408 (if (and (not (eq (point) opoint))
5409 (or (markdown-link-p) (markdown-wiki-link-p)))
5410 (goto-char (or (match-beginning 1) (match-beginning 0)))
5411 (goto-char opoint)
5412 nil)))
5414 (defun markdown-next-heading ()
5415 "Move to the next heading line of any level.
5416 With argument, repeats or can move backward if negative."
5417 (let ((pos (outline-next-heading)))
5418 (while (markdown-code-block-at-point)
5419 (setq pos (outline-next-heading)))
5420 pos))
5422 (defun markdown-previous-heading ()
5423 "Move to the previous heading line of any level.
5424 With argument, repeats or can move backward if negative."
5425 (let ((pos (outline-previous-heading)))
5426 (while (markdown-code-block-at-point)
5427 (setq pos (outline-previous-heading)))
5428 pos))
5431 ;;; Outline ===================================================================
5433 (defun markdown-move-heading-common (move-fn &optional arg)
5434 "Wrapper for `outline-mode' functions to skip false positives.
5435 MOVE-FN is a function and ARG is its argument. For example,
5436 headings inside preformatted code blocks may match
5437 `outline-regexp' but should not be considered as headings."
5438 (funcall move-fn arg)
5439 (let ((prev -1))
5440 (while (and (/= prev (point)) (markdown-code-block-at-point))
5441 (setq prev (point))
5442 (funcall move-fn arg))))
5444 (defun markdown-next-visible-heading (arg)
5445 "Move to the next visible heading line of any level.
5446 With argument, repeats or can move backward if negative. ARG is
5447 passed to `outline-next-visible-heading'."
5448 (interactive "p")
5449 (markdown-move-heading-common 'outline-next-visible-heading arg))
5451 (defun markdown-previous-visible-heading (arg)
5452 "Move to the previous visible heading line of any level.
5453 With argument, repeats or can move backward if negative. ARG is
5454 passed to `outline-previous-visible-heading'."
5455 (interactive "p")
5456 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5458 (defun markdown-forward-same-level (arg)
5459 "Move forward to the ARG'th heading at same level as this one.
5460 Stop at the first and last headings of a superior heading."
5461 (interactive "p")
5462 (markdown-move-heading-common 'outline-forward-same-level arg))
5464 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5465 (beginning-of-line)
5466 (or (and (outline-on-heading-p invisible-ok)
5467 (not (markdown-code-block-at-point)))
5468 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5469 found)
5470 (save-excursion
5471 (while (not found)
5472 (let (finish)
5473 (while (and (not finish) (re-search-backward header-re nil t))
5474 (when (and (or invisible-ok (not (outline-invisible-p)))
5475 (not (markdown-code-block-at-point)))
5476 (setq finish t)))
5477 (if (not finish)
5478 (error "Before first heading")
5479 (setq found (point))))))
5480 (goto-char found)
5481 found)))
5483 (defun markdown-backward-same-level (arg)
5484 "Move backward to the ARG'th heading at same level as this one.
5485 Stop at the first and last headings of a superior heading."
5486 (interactive "p")
5487 (markdown-back-to-heading-over-code-block)
5488 (while (> arg 0)
5489 (let ((point-to-move-to (save-excursion
5490 (outline-get-last-sibling))))
5491 (if point-to-move-to
5492 (progn
5493 (goto-char point-to-move-to)
5494 (setq arg (1- arg)))
5495 (error "No previous same-level heading")))))
5497 (defun markdown-up-heading (arg)
5498 "Move to the visible heading line of which the present line is a subheading.
5499 With argument, move up ARG levels."
5500 (interactive "p")
5501 (markdown-move-heading-common 'outline-up-heading arg))
5503 (defun markdown-back-to-heading (&optional invisible-ok)
5504 "Move to previous heading line, or beg of this line if it's a heading.
5505 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5506 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5508 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5510 (defun markdown-on-heading-p ()
5511 "Return t if point is on a (visible) heading line."
5512 (get-text-property (point) 'markdown-heading))
5514 (defun markdown-end-of-subtree (&optional invisible-OK)
5515 "Move to the end of the current subtree.
5516 Only visible heading lines are considered, unless INVISIBLE-OK is
5517 non-nil.
5518 Derived from `org-end-of-subtree'."
5519 (markdown-back-to-heading invisible-OK)
5520 (let ((first t)
5521 (level (funcall outline-level)))
5522 (while (and (not (eobp))
5523 (or first (> (funcall outline-level) level)))
5524 (setq first nil)
5525 (markdown-next-heading))
5526 (if (memq (preceding-char) '(?\n ?\^M))
5527 (progn
5528 ;; Go to end of line before heading
5529 (forward-char -1)
5530 (if (memq (preceding-char) '(?\n ?\^M))
5531 ;; leave blank line before heading
5532 (forward-char -1)))))
5533 (point))
5535 (defun markdown-outline-fix-visibility ()
5536 "Hide any false positive headings that should not be shown.
5537 For example, headings inside preformatted code blocks may match
5538 `outline-regexp' but should not be shown as headings when cycling.
5539 Also, the ending --- line in metadata blocks appears to be a
5540 setext header, but should not be folded."
5541 (save-excursion
5542 (goto-char (point-min))
5543 ;; Unhide any false positives in metadata blocks
5544 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
5545 (let ((body (progn (forward-line)
5546 (markdown-text-property-at-point
5547 'markdown-yaml-metadata-section))))
5548 (when body
5549 (let ((end (progn (goto-char (cl-second body))
5550 (markdown-text-property-at-point
5551 'markdown-yaml-metadata-end))))
5552 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
5553 ;; Hide any false positives in code blocks
5554 (unless (outline-on-heading-p)
5555 (outline-next-visible-heading 1))
5556 (while (< (point) (point-max))
5557 (when (markdown-code-block-at-point)
5558 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5559 (outline-next-visible-heading 1))))
5561 (defvar markdown-cycle-global-status 1)
5562 (defvar markdown-cycle-subtree-status nil)
5564 (defun markdown-next-preface ()
5565 (let (finish)
5566 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5567 nil 'move))
5568 (unless (markdown-code-block-at-point)
5569 (goto-char (match-beginning 0))
5570 (setq finish t))))
5571 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5572 (forward-char -1)))
5574 (defun markdown-show-entry ()
5575 (save-excursion
5576 (outline-back-to-heading t)
5577 (outline-flag-region (1- (point))
5578 (progn
5579 (markdown-next-preface)
5580 (if (= 1 (- (point-max) (point)))
5581 (point-max)
5582 (point)))
5583 nil)))
5585 (defun markdown-cycle (&optional arg)
5586 "Visibility cycling for Markdown mode.
5587 If ARG is t, perform global visibility cycling. If the point is
5588 at an atx-style header, cycle visibility of the corresponding
5589 subtree. Otherwise, insert a tab using `indent-relative'.
5590 Derived from `org-cycle'."
5591 (interactive "P")
5592 (cond
5593 ((eq arg t) ;; Global cycling
5594 (cond
5595 ((and (eq last-command this-command)
5596 (eq markdown-cycle-global-status 2))
5597 ;; Move from overview to contents
5598 (markdown-hide-sublevels 1)
5599 (message "CONTENTS")
5600 (setq markdown-cycle-global-status 3)
5601 (markdown-outline-fix-visibility))
5603 ((and (eq last-command this-command)
5604 (eq markdown-cycle-global-status 3))
5605 ;; Move from contents to all
5606 (markdown-show-all)
5607 (message "SHOW ALL")
5608 (setq markdown-cycle-global-status 1))
5611 ;; Defaults to overview
5612 (markdown-hide-body)
5613 (message "OVERVIEW")
5614 (setq markdown-cycle-global-status 2)
5615 (markdown-outline-fix-visibility))))
5617 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5618 ;; At a heading: rotate between three different views
5619 (markdown-back-to-heading)
5620 (let ((goal-column 0) eoh eol eos)
5621 ;; Determine boundaries
5622 (save-excursion
5623 (markdown-back-to-heading)
5624 (save-excursion
5625 (beginning-of-line 2)
5626 (while (and (not (eobp)) ;; this is like `next-line'
5627 (get-char-property (1- (point)) 'invisible))
5628 (beginning-of-line 2)) (setq eol (point)))
5629 (markdown-end-of-heading) (setq eoh (point))
5630 (markdown-end-of-subtree t)
5631 (skip-chars-forward " \t\n")
5632 (beginning-of-line 1) ; in case this is an item
5633 (setq eos (1- (point))))
5634 ;; Find out what to do next and set `this-command'
5635 (cond
5636 ((= eos eoh)
5637 ;; Nothing is hidden behind this heading
5638 (message "EMPTY ENTRY")
5639 (setq markdown-cycle-subtree-status nil))
5640 ((>= eol eos)
5641 ;; Entire subtree is hidden in one line: open it
5642 (markdown-show-entry)
5643 (markdown-show-children)
5644 (message "CHILDREN")
5645 (setq markdown-cycle-subtree-status 'children))
5646 ((and (eq last-command this-command)
5647 (eq markdown-cycle-subtree-status 'children))
5648 ;; We just showed the children, now show everything.
5649 (markdown-show-subtree)
5650 (message "SUBTREE")
5651 (setq markdown-cycle-subtree-status 'subtree))
5653 ;; Default action: hide the subtree.
5654 (markdown-hide-subtree)
5655 (message "FOLDED")
5656 (setq markdown-cycle-subtree-status 'folded)))))
5659 (indent-for-tab-command))))
5661 (defun markdown-shifttab ()
5662 "Global visibility cycling.
5663 Calls `markdown-cycle' with argument t."
5664 (interactive)
5665 (markdown-cycle t))
5667 (defun markdown-outline-level ()
5668 "Return the depth to which a statement is nested in the outline."
5669 (cond
5670 ((markdown-code-block-at-point) 7)
5671 ((match-end 2) 1)
5672 ((match-end 3) 2)
5673 ((- (match-end 4) (match-beginning 4)))))
5675 (defun markdown-promote-subtree (&optional arg)
5676 "Promote the current subtree of ATX headings.
5677 Note that Markdown does not support heading levels higher than
5678 six and therefore level-six headings will not be promoted
5679 further. If ARG is non-nil promote the heading, otherwise
5680 demote."
5681 (interactive "*P")
5682 (save-excursion
5683 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5684 (re-search-backward markdown-regex-header-atx nil t))
5685 (not (markdown-code-block-at-point)))
5686 (let ((level (length (match-string 1)))
5687 (promote-or-demote (if arg 1 -1))
5688 (remove 't))
5689 (markdown-cycle-atx promote-or-demote remove)
5690 (catch 'end-of-subtree
5691 (while (markdown-next-heading)
5692 ;; Exit if this not a higher level heading; promote otherwise.
5693 (if (and (looking-at markdown-regex-header-atx)
5694 (<= (length (match-string-no-properties 1)) level))
5695 (throw 'end-of-subtree nil)
5696 (markdown-cycle-atx promote-or-demote remove))))))))
5698 (defun markdown-demote-subtree ()
5699 "Demote the current subtree of ATX headings."
5700 (interactive)
5701 (markdown-promote-subtree t))
5703 (defun markdown-move-subtree-up ()
5704 "Move the current subtree of ATX headings up."
5705 (interactive)
5706 (outline-move-subtree-up 1))
5708 (defun markdown-move-subtree-down ()
5709 "Move the current subtree of ATX headings down."
5710 (interactive)
5711 (outline-move-subtree-down 1))
5714 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5716 (defun markdown-move-up ()
5717 "Move list item up.
5718 Calls `markdown-move-list-item-up'."
5719 (interactive)
5720 (markdown-move-list-item-up))
5722 (defun markdown-move-down ()
5723 "Move list item down.
5724 Calls `markdown-move-list-item-down'."
5725 (interactive)
5726 (markdown-move-list-item-down))
5728 (defun markdown-promote ()
5729 "Either promote header or list item at point or cycle markup.
5730 See `markdown-cycle-atx', `markdown-cycle-setext', and
5731 `markdown-promote-list-item'."
5732 (interactive)
5733 (let (bounds)
5734 (cond
5735 ;; Promote atx header
5736 ((thing-at-point-looking-at markdown-regex-header-atx)
5737 (markdown-cycle-atx -1))
5738 ;; Promote setext header
5739 ((thing-at-point-looking-at markdown-regex-header-setext)
5740 (markdown-cycle-setext -1))
5741 ;; Promote horizonal rule
5742 ((thing-at-point-looking-at markdown-regex-hr)
5743 (markdown-cycle-hr -1))
5744 ;; Promote list item
5745 ((setq bounds (markdown-cur-list-item-bounds))
5746 (markdown-promote-list-item bounds))
5747 ;; Promote bold
5748 ((thing-at-point-looking-at markdown-regex-bold)
5749 (markdown-cycle-bold))
5750 ;; Promote italic
5751 ((thing-at-point-looking-at markdown-regex-italic)
5752 (markdown-cycle-italic))
5754 (error "Nothing to promote at point")))))
5756 (defun markdown-demote ()
5757 "Either demote header or list item at point or cycle or remove markup.
5758 See `markdown-cycle-atx', `markdown-cycle-setext', and
5759 `markdown-demote-list-item'."
5760 (interactive)
5761 (let (bounds)
5762 (cond
5763 ;; Demote atx header
5764 ((thing-at-point-looking-at markdown-regex-header-atx)
5765 (markdown-cycle-atx 1))
5766 ;; Demote setext header
5767 ((thing-at-point-looking-at markdown-regex-header-setext)
5768 (markdown-cycle-setext 1))
5769 ;; Demote horizonal rule
5770 ((thing-at-point-looking-at markdown-regex-hr)
5771 (markdown-cycle-hr 1))
5772 ;; Demote list item
5773 ((setq bounds (markdown-cur-list-item-bounds))
5774 (markdown-demote-list-item bounds))
5775 ;; Demote bold
5776 ((thing-at-point-looking-at markdown-regex-bold)
5777 (markdown-cycle-bold))
5778 ;; Demote italic
5779 ((thing-at-point-looking-at markdown-regex-italic)
5780 (markdown-cycle-italic))
5782 (error "Nothing to demote at point")))))
5785 ;;; Commands ==================================================================
5787 (defun markdown (&optional output-buffer-name)
5788 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5789 The output buffer name defaults to `markdown-output-buffer-name'.
5790 Return the name of the output buffer used."
5791 (interactive)
5792 (save-window-excursion
5793 (let ((begin-region)
5794 (end-region))
5795 (if (markdown-use-region-p)
5796 (setq begin-region (region-beginning)
5797 end-region (region-end))
5798 (setq begin-region (point-min)
5799 end-region (point-max)))
5801 (unless output-buffer-name
5802 (setq output-buffer-name markdown-output-buffer-name))
5803 (cond
5804 ;; Handle case when `markdown-command' does not read from stdin
5805 (markdown-command-needs-filename
5806 (if (not buffer-file-name)
5807 (error "Must be visiting a file")
5808 (shell-command (concat markdown-command " "
5809 (shell-quote-argument buffer-file-name))
5810 output-buffer-name)))
5811 ;; Pass region to `markdown-command' via stdin
5813 (let ((buf (get-buffer-create output-buffer-name)))
5814 (with-current-buffer buf
5815 (setq buffer-read-only nil)
5816 (erase-buffer))
5817 (call-process-region begin-region end-region
5818 shell-file-name nil buf nil
5819 shell-command-switch markdown-command)))))
5820 output-buffer-name))
5822 (defun markdown-standalone (&optional output-buffer-name)
5823 "Special function to provide standalone HTML output.
5824 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5825 (interactive)
5826 (setq output-buffer-name (markdown output-buffer-name))
5827 (with-current-buffer output-buffer-name
5828 (set-buffer output-buffer-name)
5829 (unless (markdown-output-standalone-p)
5830 (markdown-add-xhtml-header-and-footer output-buffer-name))
5831 (goto-char (point-min))
5832 (html-mode))
5833 output-buffer-name)
5835 (defun markdown-other-window (&optional output-buffer-name)
5836 "Run `markdown-command' on current buffer and display in other window.
5837 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5838 that name."
5839 (interactive)
5840 (markdown-display-buffer-other-window
5841 (markdown-standalone output-buffer-name)))
5843 (defun markdown-output-standalone-p ()
5844 "Determine whether `markdown-command' output is standalone XHTML.
5845 Standalone XHTML output is identified by an occurrence of
5846 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5847 (save-excursion
5848 (goto-char (point-min))
5849 (re-search-forward
5850 markdown-xhtml-standalone-regexp
5851 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5852 t)))
5854 (defun markdown-stylesheet-link-string (stylesheet-path)
5855 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5856 stylesheet-path
5857 "\" />"))
5859 (defun markdown-add-xhtml-header-and-footer (title)
5860 "Wrap XHTML header and footer with given TITLE around current buffer."
5861 (goto-char (point-min))
5862 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5863 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5864 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5865 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5866 "<head>\n<title>")
5867 (insert title)
5868 (insert "</title>\n")
5869 (when (> (length markdown-content-type) 0)
5870 (insert
5871 (format
5872 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5873 markdown-content-type
5874 (or (and markdown-coding-system
5875 (fboundp 'coding-system-get)
5876 (coding-system-get markdown-coding-system
5877 'mime-charset))
5878 (and (fboundp 'coding-system-get)
5879 (coding-system-get buffer-file-coding-system
5880 'mime-charset))
5881 "iso-8859-1"))))
5882 (if (> (length markdown-css-paths) 0)
5883 (insert (mapconcat 'markdown-stylesheet-link-string markdown-css-paths "\n")))
5884 (when (> (length markdown-xhtml-header-content) 0)
5885 (insert markdown-xhtml-header-content))
5886 (insert "\n</head>\n\n"
5887 "<body>\n\n")
5888 (goto-char (point-max))
5889 (insert "\n"
5890 "</body>\n"
5891 "</html>\n"))
5893 (defun markdown-preview (&optional output-buffer-name)
5894 "Run `markdown-command' on the current buffer and view output in browser.
5895 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5896 that name."
5897 (interactive)
5898 (browse-url-of-buffer
5899 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
5901 (defun markdown-export-file-name (&optional extension)
5902 "Attempt to generate a filename for Markdown output.
5903 The file extension will be EXTENSION if given, or .html by default.
5904 If the current buffer is visiting a file, we construct a new
5905 output filename based on that filename. Otherwise, return nil."
5906 (when (buffer-file-name)
5907 (unless extension
5908 (setq extension ".html"))
5909 (let ((candidate
5910 (concat
5911 (cond
5912 ((buffer-file-name)
5913 (file-name-sans-extension (buffer-file-name)))
5914 (t (buffer-name)))
5915 extension)))
5916 (cond
5917 ((equal candidate (buffer-file-name))
5918 (concat candidate extension))
5920 candidate)))))
5922 (defun markdown-export (&optional output-file)
5923 "Run Markdown on the current buffer, save to file, and return the filename.
5924 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
5925 generated by `markdown-export-file-name', which will be constructed using the
5926 current filename, but with the extension removed and replaced with .html."
5927 (interactive)
5928 (unless output-file
5929 (setq output-file (markdown-export-file-name ".html")))
5930 (when output-file
5931 (let* ((init-buf (current-buffer))
5932 (init-point (point))
5933 (init-buf-string (buffer-string))
5934 (output-buffer (find-file-noselect output-file))
5935 (output-buffer-name (buffer-name output-buffer)))
5936 (run-hooks 'markdown-before-export-hook)
5937 (markdown-standalone output-buffer-name)
5938 (with-current-buffer output-buffer
5939 (run-hooks 'markdown-after-export-hook)
5940 (save-buffer))
5941 ;; if modified, restore initial buffer
5942 (when (buffer-modified-p init-buf)
5943 (erase-buffer)
5944 (insert init-buf-string)
5945 (save-buffer)
5946 (goto-char init-point))
5947 output-file)))
5949 (defun markdown-export-and-preview ()
5950 "Export to XHTML using `markdown-export' and browse the resulting file."
5951 (interactive)
5952 (browse-url-of-file (markdown-export)))
5954 (defvar markdown-live-preview-buffer nil
5955 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
5956 (make-variable-buffer-local 'markdown-live-preview-buffer)
5958 (defvar markdown-live-preview-source-buffer nil
5959 "Source buffer from which current buffer was generated.
5960 This is the inverse of `markdown-live-preview-buffer'.")
5961 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
5963 (defvar markdown-live-preview-currently-exporting nil)
5965 (defun markdown-live-preview-get-filename ()
5966 "Standardize the filename exported by `markdown-live-preview-export'."
5967 (markdown-export-file-name ".html"))
5969 (defun markdown-live-preview-window-eww (file)
5970 "Preview FILE with eww.
5971 To be used with `markdown-live-preview-window-function'."
5972 (if (require 'eww nil t)
5973 (progn
5974 (eww-open-file file)
5975 (get-buffer "*eww*"))
5976 (error "EWW is not present or not loaded on this version of Emacs")))
5978 (defun markdown-visual-lines-between-points (beg end)
5979 (save-excursion
5980 (goto-char beg)
5981 (cl-loop with count = 0
5982 while (progn (end-of-visual-line)
5983 (and (< (point) end) (line-move-visual 1 t)))
5984 do (cl-incf count)
5985 finally return count)))
5987 (defun markdown-live-preview-window-serialize (buf)
5988 "Get window point and scroll data for all windows displaying BUF."
5989 (when (buffer-live-p buf)
5990 (with-current-buffer buf
5991 (mapcar
5992 (lambda (win)
5993 (with-selected-window win
5994 (let* ((start (window-start))
5995 (pt (window-point))
5996 (pt-or-sym (cond ((= pt (point-min)) 'min)
5997 ((= pt (point-max)) 'max)
5998 (t pt)))
5999 (diff (markdown-visual-lines-between-points
6000 start pt)))
6001 (list win pt-or-sym diff))))
6002 (get-buffer-window-list buf)))))
6004 (defun markdown-get-point-back-lines (pt num-lines)
6005 (save-excursion
6006 (goto-char pt)
6007 (line-move-visual (- num-lines) t)
6008 ;; in testing, can occasionally overshoot the number of lines to traverse
6009 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
6010 (when (> actual-num-lines num-lines)
6011 (line-move-visual (- actual-num-lines num-lines) t)))
6012 (point)))
6014 (defun markdown-live-preview-window-deserialize (window-posns)
6015 "Apply window point and scroll data from WINDOW-POSNS.
6016 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
6017 (cl-destructuring-bind (win pt-or-sym diff) window-posns
6018 (when (window-live-p win)
6019 (with-current-buffer markdown-live-preview-buffer
6020 (set-window-buffer win (current-buffer))
6021 (cl-destructuring-bind (actual-pt actual-diff)
6022 (cl-case pt-or-sym
6023 (min (list (point-min) 0))
6024 (max (list (point-max) diff))
6025 (t (list pt-or-sym diff)))
6026 (set-window-start
6027 win (markdown-get-point-back-lines actual-pt actual-diff))
6028 (set-window-point win actual-pt))))))
6030 (defun markdown-live-preview-export ()
6031 "Export to XHTML using `markdown-export'.
6032 Browse the resulting file within Emacs using
6033 `markdown-live-preview-window-function' Return the buffer
6034 displaying the rendered output."
6035 (interactive)
6036 (let* ((markdown-live-preview-currently-exporting t)
6037 (cur-buf (current-buffer))
6038 (export-file (markdown-export (markdown-live-preview-get-filename)))
6039 ;; get positions in all windows currently displaying output buffer
6040 (window-data
6041 (markdown-live-preview-window-serialize
6042 markdown-live-preview-buffer)))
6043 (save-window-excursion
6044 (let ((output-buffer
6045 (funcall markdown-live-preview-window-function export-file)))
6046 (with-current-buffer output-buffer
6047 (setq markdown-live-preview-source-buffer cur-buf)
6048 (add-hook 'kill-buffer-hook
6049 #'markdown-live-preview-remove-on-kill t t))
6050 (with-current-buffer cur-buf
6051 (setq markdown-live-preview-buffer output-buffer))))
6052 (with-current-buffer cur-buf
6053 ;; reset all windows displaying output buffer to where they were,
6054 ;; now with the new output
6055 (mapc #'markdown-live-preview-window-deserialize window-data)
6056 ;; delete html editing buffer
6057 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
6058 (when (and export-file (file-exists-p export-file)
6059 (eq markdown-live-preview-delete-export
6060 'delete-on-export))
6061 (delete-file export-file))
6062 markdown-live-preview-buffer)))
6064 (defun markdown-live-preview-remove ()
6065 (when (buffer-live-p markdown-live-preview-buffer)
6066 (kill-buffer markdown-live-preview-buffer))
6067 (setq markdown-live-preview-buffer nil)
6068 ;; if set to 'delete-on-export, the output has already been deleted
6069 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
6070 (let ((outfile-name (markdown-live-preview-get-filename)))
6071 (when (file-exists-p outfile-name)
6072 (delete-file outfile-name)))))
6074 (defun markdown-display-buffer-other-window (buf)
6075 (let ((cur-buf (current-buffer)))
6076 (switch-to-buffer-other-window buf)
6077 (set-buffer cur-buf)))
6079 (defun markdown-live-preview-if-markdown ()
6080 (when (and (derived-mode-p 'markdown-mode)
6081 markdown-live-preview-mode)
6082 (unless markdown-live-preview-currently-exporting
6083 (if (buffer-live-p markdown-live-preview-buffer)
6084 (markdown-live-preview-export)
6085 (markdown-display-buffer-other-window
6086 (markdown-live-preview-export))))))
6088 (defun markdown-live-preview-remove-on-kill ()
6089 (cond ((and (derived-mode-p 'markdown-mode)
6090 markdown-live-preview-mode)
6091 (markdown-live-preview-remove))
6092 (markdown-live-preview-source-buffer
6093 (with-current-buffer markdown-live-preview-source-buffer
6094 (setq markdown-live-preview-buffer nil))
6095 (setq markdown-live-preview-source-buffer nil))))
6097 (defun markdown-live-preview-switch-to-output ()
6098 "Switch to output buffer."
6099 (interactive)
6100 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6101 output buffer in another window."
6102 (if markdown-live-preview-mode
6103 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6104 (markdown-live-preview-mode))
6106 (defun markdown-live-preview-re-export ()
6107 "Re export source buffer."
6108 (interactive)
6109 "If the current buffer is a buffer displaying the exported version of a
6110 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6111 update this buffer's contents."
6112 (when markdown-live-preview-source-buffer
6113 (with-current-buffer markdown-live-preview-source-buffer
6114 (markdown-live-preview-export))))
6116 (defun markdown-open ()
6117 "Open file for the current buffer with `markdown-open-command'."
6118 (interactive)
6119 (if (not markdown-open-command)
6120 (error "Variable `markdown-open-command' must be set")
6121 (if (not buffer-file-name)
6122 (error "Must be visiting a file")
6123 (call-process markdown-open-command
6124 nil nil nil buffer-file-name))))
6126 (defun markdown-kill-ring-save ()
6127 "Run Markdown on file and store output in the kill ring."
6128 (interactive)
6129 (save-window-excursion
6130 (markdown)
6131 (with-current-buffer markdown-output-buffer-name
6132 (kill-ring-save (point-min) (point-max)))))
6135 ;;; Links =====================================================================
6137 (defun markdown-link-p ()
6138 "Return non-nil when `point' is at a non-wiki link.
6139 See `markdown-wiki-link-p' for more information."
6140 (let ((case-fold-search nil))
6141 (and (not (markdown-wiki-link-p))
6142 (not (markdown-code-block-at-point))
6143 (or (thing-at-point-looking-at markdown-regex-link-inline)
6144 (thing-at-point-looking-at markdown-regex-link-reference)
6145 (thing-at-point-looking-at markdown-regex-uri)
6146 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6148 (defun markdown-link-link ()
6149 "Return the link part of the regular (non-wiki) link at point.
6150 Works with both inline and reference style links. If point is
6151 not at a link or the link reference is not defined returns nil."
6152 (cond
6153 ((thing-at-point-looking-at markdown-regex-link-inline)
6154 (match-string-no-properties 6))
6155 ((thing-at-point-looking-at markdown-regex-link-reference)
6156 (let* ((text (match-string-no-properties 3))
6157 (reference (match-string-no-properties 6))
6158 (target (downcase (if (string= reference "") text reference))))
6159 (car (markdown-reference-definition target))))
6160 ((thing-at-point-looking-at markdown-regex-uri)
6161 (match-string-no-properties 0))
6162 ((thing-at-point-looking-at markdown-regex-angle-uri)
6163 (match-string-no-properties 2))
6164 (t nil)))
6166 (defun markdown-follow-link-at-point ()
6167 "Open the current non-wiki link.
6168 If the link is a complete URL, open in browser with `browse-url'.
6169 Otherwise, open with `find-file' after stripping anchor and/or query string."
6170 (interactive)
6171 (if (markdown-link-p)
6172 (let* ((link (markdown-link-link))
6173 (struct (url-generic-parse-url link))
6174 (full (url-fullness struct))
6175 (file link))
6176 ;; Parse URL, determine fullness, strip query string
6177 (if (fboundp 'url-path-and-query)
6178 (setq file (car (url-path-and-query struct)))
6179 (when (and (setq file (url-filename struct))
6180 (string-match "\\?" file))
6181 (setq file (substring file 0 (match-beginning 0)))))
6182 ;; Open full URLs in browser, files in Emacs
6183 (if full
6184 (browse-url link)
6185 (when (and file (> (length file) 0)) (find-file file))))
6186 (error "Point is not at a Markdown link or URI")))
6189 ;;; WikiLink Following/Markup =================================================
6191 (defun markdown-wiki-link-p ()
6192 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6193 A true wiki link name matches `markdown-regex-wiki-link' but does
6194 not match the current file name after conversion. This modifies
6195 the data returned by `match-data'. Note that the potential wiki
6196 link name must be available via `match-string'."
6197 (when markdown-enable-wiki-links
6198 (let ((case-fold-search nil))
6199 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6200 (not (markdown-code-block-at-point))
6201 (or (not buffer-file-name)
6202 (not (string-equal (buffer-file-name)
6203 (markdown-convert-wiki-link-to-filename
6204 (markdown-wiki-link-link)))))))))
6206 (defun markdown-wiki-link-link ()
6207 "Return the link part of the wiki link using current match data.
6208 The location of the link component depends on the value of
6209 `markdown-wiki-link-alias-first'."
6210 (if markdown-wiki-link-alias-first
6211 (or (match-string-no-properties 5) (match-string-no-properties 3))
6212 (match-string-no-properties 3)))
6214 (defun markdown-wiki-link-alias ()
6215 "Return the alias or text part of the wiki link using current match data.
6216 The location of the alias component depends on the value of
6217 `markdown-wiki-link-alias-first'."
6218 (if markdown-wiki-link-alias-first
6219 (match-string-no-properties 3)
6220 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6222 (defun markdown-convert-wiki-link-to-filename (name)
6223 "Generate a filename from the wiki link NAME.
6224 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6225 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6226 and [[test test]] both map to Test-test.ext."
6227 (let ((basename (markdown-replace-regexp-in-string
6228 "[[:space:]\n]" markdown-link-space-sub-char name)))
6229 (when (eq major-mode 'gfm-mode)
6230 (setq basename (concat (upcase (substring basename 0 1))
6231 (downcase (substring basename 1 nil)))))
6232 (let* ((default
6233 (concat basename
6234 (if (and (buffer-file-name)
6235 (file-name-extension (buffer-file-name)))
6236 (concat "."
6237 (file-name-extension (buffer-file-name))))))
6238 (current default))
6239 (catch 'done
6240 (condition-case nil
6241 (cl-loop
6242 (if (or (not markdown-wiki-link-search-parent-directories)
6243 (file-exists-p current))
6244 (throw 'done current))
6245 (if (string-equal (expand-file-name current)
6246 (concat "/" default))
6247 (throw 'done default))
6248 (setq current (concat "../" current)))
6249 (error default))))))
6251 (defun markdown-follow-wiki-link (name &optional other)
6252 "Follow the wiki link NAME.
6253 Convert the name to a file name and call `find-file'. Ensure that
6254 the new buffer remains in `markdown-mode'. Open the link in another
6255 window when OTHER is non-nil."
6256 (let ((filename (markdown-convert-wiki-link-to-filename name))
6257 (wp (file-name-directory buffer-file-name)))
6258 (when other (other-window 1))
6259 (let ((default-directory wp))
6260 (find-file filename)))
6261 (when (not (eq major-mode 'markdown-mode))
6262 (markdown-mode)))
6264 (defun markdown-follow-wiki-link-at-point (&optional arg)
6265 "Find Wiki Link at point.
6266 With prefix argument ARG, open the file in other window.
6267 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6268 (interactive "P")
6269 (if (markdown-wiki-link-p)
6270 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6271 (error "Point is not at a Wiki Link")))
6273 (defun markdown-highlight-wiki-link (from to face)
6274 "Highlight the wiki link in the region between FROM and TO using FACE."
6275 (put-text-property from to 'font-lock-face face))
6277 (defun markdown-unfontify-region-wiki-links (from to)
6278 "Remove wiki link faces from the region specified by FROM and TO."
6279 (interactive "*r")
6280 (let ((modified (buffer-modified-p)))
6281 (remove-text-properties from to '(font-lock-face markdown-link-face))
6282 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
6283 ;; remove-text-properties marks the buffer modified in emacs 24.3,
6284 ;; undo that if it wasn't originally marked modified
6285 (set-buffer-modified-p modified)))
6287 (defun markdown-fontify-region-wiki-links (from to)
6288 "Search region given by FROM and TO for wiki links and fontify them.
6289 If a wiki link is found check to see if the backing file exists
6290 and highlight accordingly."
6291 (goto-char from)
6292 (save-match-data
6293 (while (re-search-forward markdown-regex-wiki-link to t)
6294 (when (not (markdown-code-block-at-point))
6295 (let ((highlight-beginning (match-beginning 1))
6296 (highlight-end (match-end 1))
6297 (file-name
6298 (markdown-convert-wiki-link-to-filename
6299 (markdown-wiki-link-link))))
6300 (if (condition-case nil (file-exists-p file-name) (error nil))
6301 (markdown-highlight-wiki-link
6302 highlight-beginning highlight-end markdown-link-face)
6303 (markdown-highlight-wiki-link
6304 highlight-beginning highlight-end markdown-missing-link-face)))))))
6306 (defun markdown-extend-changed-region (from to)
6307 "Extend region given by FROM and TO so that we can fontify all links.
6308 The region is extended to the first newline before and the first
6309 newline after."
6310 ;; start looking for the first new line before 'from
6311 (goto-char from)
6312 (re-search-backward "\n" nil t)
6313 (let ((new-from (point-min))
6314 (new-to (point-max)))
6315 (if (not (= (point) from))
6316 (setq new-from (point)))
6317 ;; do the same thing for the first new line after 'to
6318 (goto-char to)
6319 (re-search-forward "\n" nil t)
6320 (if (not (= (point) to))
6321 (setq new-to (point)))
6322 (cl-values new-from new-to)))
6324 (defun markdown-check-change-for-wiki-link (from to)
6325 "Check region between FROM and TO for wiki links and re-fontify as needed."
6326 (interactive "*r")
6327 (let* ((modified (buffer-modified-p))
6328 (buffer-undo-list t)
6329 (inhibit-read-only t)
6330 (inhibit-point-motion-hooks t)
6331 deactivate-mark
6332 buffer-file-truename)
6333 (unwind-protect
6334 (save-excursion
6335 (save-match-data
6336 (save-restriction
6337 ;; Extend the region to fontify so that it starts
6338 ;; and ends at safe places.
6339 (cl-multiple-value-bind (new-from new-to)
6340 (markdown-extend-changed-region from to)
6341 (goto-char new-from)
6342 ;; Only refontify when the range contains text with a
6343 ;; wiki link face or if the wiki link regexp matches.
6344 (when (or (markdown-range-property-any
6345 new-from new-to 'font-lock-face
6346 (list markdown-link-face
6347 markdown-missing-link-face))
6348 (re-search-forward
6349 markdown-regex-wiki-link new-to t))
6350 ;; Unfontify existing fontification (start from scratch)
6351 (markdown-unfontify-region-wiki-links new-from new-to)
6352 ;; Now do the fontification.
6353 (markdown-fontify-region-wiki-links new-from new-to))))))
6354 (and (not modified)
6355 (buffer-modified-p)
6356 (set-buffer-modified-p nil)))))
6358 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6359 "Check region between FROM and TO for wiki links and re-fontify as needed.
6360 Designed to be used with the `after-change-functions' hook."
6361 (markdown-check-change-for-wiki-link from to))
6363 (defun markdown-fontify-buffer-wiki-links ()
6364 "Refontify all wiki links in the buffer."
6365 (interactive)
6366 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6369 ;;; Following and Jumping =====================================================
6371 (defun markdown-follow-thing-at-point (arg)
6372 "Follow thing at point if possible, such as a reference link or wiki link.
6373 Opens inline and reference links in a browser. Opens wiki links
6374 to other files in the current window, or the another window if
6375 ARG is non-nil.
6376 See `markdown-follow-link-at-point' and
6377 `markdown-follow-wiki-link-at-point'."
6378 (interactive "P")
6379 (cond ((markdown-link-p)
6380 (markdown-follow-link-at-point))
6381 ((markdown-wiki-link-p)
6382 (markdown-follow-wiki-link-at-point arg))
6384 (error "Nothing to follow at point"))))
6386 (defun markdown-jump ()
6387 "Jump to another location based on context at point.
6388 Jumps between reference links and definitions; between footnote
6389 markers and footnote text."
6390 (interactive)
6391 (cond ((markdown-footnote-text-positions)
6392 (markdown-footnote-return))
6393 ((markdown-footnote-marker-positions)
6394 (markdown-footnote-goto-text))
6395 ((thing-at-point-looking-at markdown-regex-link-reference)
6396 (markdown-reference-goto-definition))
6397 ((thing-at-point-looking-at markdown-regex-reference-definition)
6398 (markdown-reference-goto-link (match-string-no-properties 2)))
6400 (error "Nothing to jump to from context at point"))))
6403 ;;; Miscellaneous =============================================================
6405 (defun markdown-compress-whitespace-string (str)
6406 "Compress whitespace in STR and return result.
6407 Leading and trailing whitespace is removed. Sequences of multiple
6408 spaces, tabs, and newlines are replaced with single spaces."
6409 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6410 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6412 (defun markdown-line-number-at-pos (&optional pos)
6413 "Return (narrowed) buffer line number at position POS.
6414 If POS is nil, use current buffer location.
6415 This is an exact copy of `line-number-at-pos' for use in emacs21."
6416 (let ((opoint (or pos (point))) start)
6417 (save-excursion
6418 (goto-char (point-min))
6419 (setq start (point))
6420 (goto-char opoint)
6421 (forward-line 0)
6422 (1+ (count-lines start (point))))))
6424 (defun markdown-inside-link-p ()
6425 "Return t if point is within a link."
6426 (thing-at-point-looking-at (markdown-make-regex-link-generic)))
6428 (defun markdown-line-is-reference-definition-p ()
6429 "Return whether the current line is a (non-footnote) reference defition."
6430 (save-excursion
6431 (move-beginning-of-line 1)
6432 (and (looking-at-p markdown-regex-reference-definition)
6433 (not (looking-at-p "[ \t]*\\[^")))))
6435 (defun markdown-adaptive-fill-function ()
6436 "Return prefix for filling paragraph or nil if not determined."
6437 (cond
6438 ;; List item inside blockquote
6439 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+-]\\)[ \t]+")
6440 (markdown-replace-regexp-in-string
6441 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6442 ;; Blockquote
6443 ((looking-at "^[ \t]*>[ \t]*")
6444 (match-string-no-properties 0))
6445 ;; List items
6446 ((looking-at markdown-regex-list)
6447 (match-string-no-properties 0))
6448 ((looking-at-p markdown-regex-footnote-definition)
6449 " ") ; four spaces
6450 ;; No match
6451 (t nil)))
6453 (defun markdown-fill-forward-paragraph-function (&optional arg)
6454 (let* ((arg (or arg 1))
6455 (paragraphs-remaining (forward-paragraph arg))
6456 (start (point)))
6457 (when (< arg 0)
6458 (while (and (not (eobp))
6459 (progn (move-to-left-margin) (not (eobp)))
6460 (looking-at-p paragraph-separate))
6461 (forward-line 1))
6462 (if (looking-at markdown-regex-list)
6463 (forward-char (length (match-string 0)))
6464 (goto-char start)))
6465 paragraphs-remaining))
6468 ;;; Extension Framework =======================================================
6470 (defun markdown-reload-extensions ()
6471 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6472 (interactive)
6473 (when (eq major-mode 'markdown-mode)
6474 ;; Update font lock keywords with extensions
6475 (setq markdown-mode-font-lock-keywords
6476 (append
6477 markdown-mode-font-lock-keywords-basic
6478 (markdown-mode-font-lock-keywords-wiki-links)
6479 (markdown-mode-font-lock-keywords-math)))
6480 ;; Update font lock defaults
6481 (setq font-lock-defaults
6482 '(markdown-mode-font-lock-keywords
6483 nil nil nil nil
6484 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6485 ;; Refontify buffer
6486 (when (fboundp 'font-lock-refresh-defaults) (font-lock-refresh-defaults))
6487 ;; Add or remove hooks related to extensions
6488 (markdown-setup-wiki-link-hooks)))
6490 (defun markdown-handle-local-variables ()
6491 "Run in `hack-local-variables-hook' to update font lock rules.
6492 Checks to see if there is actually a ‘markdown-mode’ file local variable
6493 before regenerating font-lock rules for extensions."
6494 (when (and (boundp 'file-local-variables-alist)
6495 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6496 (assoc 'markdown-enable-math file-local-variables-alist))
6497 (markdown-reload-extensions)))
6499 ;;; Wiki Links ================================================================
6501 (defun markdown-toggle-wiki-links (&optional arg)
6502 "Toggle support for wiki links.
6503 With a prefix argument ARG, enable wiki link support if ARG is positive,
6504 and disable it otherwise."
6505 (interactive (list (or current-prefix-arg 'toggle)))
6506 (setq markdown-enable-wiki-links
6507 (if (eq arg 'toggle)
6508 (not markdown-enable-wiki-links)
6509 (> (prefix-numeric-value arg) 0)))
6510 (if markdown-enable-wiki-links
6511 (message "markdown-mode wiki link support enabled")
6512 (message "markdown-mode wiki link support disabled"))
6513 (markdown-reload-extensions))
6515 (defun markdown-setup-wiki-link-hooks ()
6516 "Add or remove hooks for fontifying wiki links.
6517 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6518 ;; Anytime text changes make sure it gets fontified correctly
6519 (if (and markdown-enable-wiki-links
6520 markdown-wiki-link-fontify-missing)
6521 (add-hook 'after-change-functions
6522 'markdown-check-change-for-wiki-link-after-change t t)
6523 (remove-hook 'after-change-functions
6524 'markdown-check-change-for-wiki-link-after-change t))
6525 ;; If we left the buffer there is a really good chance we were
6526 ;; creating one of the wiki link documents. Make sure we get
6527 ;; refontified when we come back.
6528 (if (and markdown-enable-wiki-links
6529 markdown-wiki-link-fontify-missing)
6530 (progn
6531 (add-hook 'window-configuration-change-hook
6532 'markdown-fontify-buffer-wiki-links t t)
6533 (markdown-fontify-buffer-wiki-links))
6534 (remove-hook 'window-configuration-change-hook
6535 'markdown-fontify-buffer-wiki-links t)
6536 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6538 (defun markdown-mode-font-lock-keywords-wiki-links ()
6539 "Return wiki-link lock keywords if support is enabled.
6540 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6541 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6542 (when (and markdown-enable-wiki-links
6543 (not markdown-wiki-link-fontify-missing))
6544 (list
6545 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6547 ;;; Math Support ==============================================================
6549 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6551 (defun markdown-toggle-math (&optional arg)
6552 "Toggle support for inline and display LaTeX math expressions.
6553 With a prefix argument ARG, enable math mode if ARG is positive,
6554 and disable it otherwise. If called from Lisp, enable the mode
6555 if ARG is omitted or nil."
6556 (interactive (list (or current-prefix-arg 'toggle)))
6557 (setq markdown-enable-math
6558 (if (eq arg 'toggle)
6559 (not markdown-enable-math)
6560 (> (prefix-numeric-value arg) 0)))
6561 (if markdown-enable-math
6562 (message "markdown-mode math support enabled")
6563 (message "markdown-mode math support disabled"))
6564 (markdown-reload-extensions))
6566 (defun markdown-mode-font-lock-keywords-math ()
6567 "Return math font lock keywords if support is enabled."
6568 (when markdown-enable-math
6569 (list
6570 ;; Display mode equations with brackets: \[ \]
6571 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6572 (2 markdown-math-face append)
6573 (3 markdown-markup-face prepend)))
6574 ;; Equation reference (eq:foo)
6575 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6576 (2 markdown-reference-face)
6577 (3 markdown-markup-face)))
6578 ;; Equation reference \eqref{foo}
6579 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6580 (2 markdown-reference-face)
6581 (3 markdown-markup-face))))))
6584 ;;; GFM Checkboxes as Buttons =================================================
6586 (require 'button)
6588 (define-button-type 'markdown-gfm-checkbox-button
6589 'follow-link t
6590 'face 'markdown-gfm-checkbox-face
6591 'mouse-face 'markdown-highlight-face
6592 'action #'markdown-toggle-gfm-checkbox)
6594 (defun markdown-toggle-gfm-checkbox (button)
6595 "Toggle GFM checkbox BUTTON on click."
6596 (save-match-data
6597 (save-excursion
6598 (goto-char (button-start button))
6599 (cond ((looking-at "\\[ \\]")
6600 (replace-match "[x]" nil t))
6601 ((looking-at "\\[[xX]\\]")
6602 (replace-match "[ ]" nil t))))))
6604 (defun markdown-make-gfm-checkboxes-buttons (start end)
6605 "Make GFM checkboxes buttons in region between START and END."
6606 (save-excursion
6607 (goto-char start)
6608 (let ((case-fold-search t))
6609 (save-excursion
6610 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6611 (make-button (match-beginning 1) (match-end 1)
6612 :type 'markdown-gfm-checkbox-button))))))
6614 ;; Called when any modification is made to buffer text.
6615 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6616 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6617 BEG and END are the limits of scanned region."
6618 (save-excursion
6619 (save-match-data
6620 ;; Rescan between start of line from `beg' and start of line after `end'.
6621 (markdown-make-gfm-checkboxes-buttons
6622 (progn (goto-char beg) (beginning-of-line) (point))
6623 (progn (goto-char end) (forward-line 1) (point))))))
6626 ;;; Display inline image =================================================
6628 (defvar markdown-inline-image-overlays nil)
6629 (make-variable-buffer-local 'markdown-inline-image-overlays)
6631 (defun markdown-remove-inline-images ()
6632 "Remove inline image overlays from image links in the buffer.
6633 This can be toggled with `markdown-toggle-inline-images'
6634 or \\[markdown-toggle-inline-images]."
6635 (interactive)
6636 (mapc 'delete-overlay markdown-inline-image-overlays)
6637 (setq markdown-inline-image-overlays nil))
6639 (defun markdown-display-inline-images ()
6640 "Add inline image overlays to image links in the buffer.
6641 This can be toggled with `markdown-toggle-inline-images'
6642 or \\[markdown-toggle-inline-images]."
6643 (interactive)
6644 (unless (display-graphic-p)
6645 (error "Cannot show images"))
6646 (save-excursion
6647 (save-restriction
6648 (widen)
6649 (goto-char (point-min))
6650 (while (re-search-forward markdown-regex-link-inline nil t)
6651 (let ((start (match-beginning 0))
6652 (end (match-end 0))
6653 (file (match-string-no-properties 6)))
6654 (when (file-exists-p file)
6655 (let* ((abspath (if (file-name-absolute-p file)
6656 file
6657 (concat default-directory file)))
6658 (image (create-image abspath)))
6659 (when image
6660 (let ((ov (make-overlay start end)))
6661 (overlay-put ov 'display image)
6662 (overlay-put ov 'face 'default)
6663 (push ov markdown-inline-image-overlays))))))))))
6665 (defun markdown-toggle-inline-images ()
6666 "Toggle inline image overlays in the buffer."
6667 (interactive)
6668 (if markdown-inline-image-overlays
6669 (markdown-remove-inline-images)
6670 (markdown-display-inline-images)))
6673 ;;; Mode Definition ==========================================================
6675 (defun markdown-show-version ()
6676 "Show the version number in the minibuffer."
6677 (interactive)
6678 (message "markdown-mode, version %s" markdown-mode-version))
6680 ;;;###autoload
6681 (define-derived-mode markdown-mode text-mode "Markdown"
6682 "Major mode for editing Markdown files."
6683 ;; Natural Markdown tab width
6684 (setq tab-width 4)
6685 ;; Comments
6686 (make-local-variable 'comment-start)
6687 (setq comment-start "<!-- ")
6688 (make-local-variable 'comment-end)
6689 (setq comment-end " -->")
6690 (make-local-variable 'comment-start-skip)
6691 (setq comment-start-skip "<!--[ \t]*")
6692 (make-local-variable 'comment-column)
6693 (setq comment-column 0)
6694 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
6695 ;; Syntax
6696 (add-hook 'syntax-propertize-extend-region-functions
6697 'markdown-syntax-propertize-extend-region)
6698 (add-hook 'jit-lock-after-change-extend-region-functions
6699 'markdown-font-lock-extend-region-function t t)
6700 (set (make-local-variable 'syntax-propertize-function)
6701 'markdown-syntax-propertize)
6702 ;; Font lock.
6703 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
6704 (set (make-local-variable 'font-lock-defaults) nil)
6705 (set (make-local-variable 'font-lock-multiline) t)
6706 ;; Extensions
6707 (make-local-variable 'markdown-enable-math)
6708 ;; Reload extensions
6709 (markdown-reload-extensions)
6710 ;; Add a buffer-local hook to reload after file-local variables are read
6711 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
6712 ;; For imenu support
6713 (setq imenu-create-index-function
6714 (if markdown-nested-imenu-heading-index
6715 'markdown-imenu-create-nested-index
6716 'markdown-imenu-create-flat-index))
6717 ;; For menu support in XEmacs
6718 (easy-menu-add markdown-mode-menu markdown-mode-map)
6719 ;; Defun movement
6720 (set (make-local-variable 'beginning-of-defun-function)
6721 'markdown-beginning-of-defun)
6722 (set (make-local-variable 'end-of-defun-function)
6723 'markdown-end-of-defun)
6724 ;; Paragraph filling
6725 (set
6726 ; Should match start of lines that start or separate paragraphs
6727 (make-local-variable 'paragraph-start)
6728 (mapconcat 'identity
6730 "\f" ; starts with a literal line-feed
6731 "[ \t\f]*$" ; space-only line
6732 "[ \t]*[*+-][ \t]+" ; unordered list item
6733 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6734 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6735 "[ \t]*:[ \t]+" ; definition
6737 "\\|"))
6738 (set
6739 ; Should match lines that separate paragraphs without being
6740 ; part of any paragraph:
6741 (make-local-variable 'paragraph-separate)
6742 (mapconcat 'identity
6743 '("[ \t\f]*$" ; space-only line
6744 ; The following is not ideal, but the Fill customization
6745 ; options really only handle paragraph-starting prefixes,
6746 ; not paragraph-ending suffixes:
6747 ".* $" ; line ending in two spaces
6748 "^#+"
6749 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6750 "\\|"))
6751 (set (make-local-variable 'adaptive-fill-first-line-regexp)
6752 "\\`[ \t]*>[ \t]*?\\'")
6753 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
6754 (set (make-local-variable 'adaptive-fill-function)
6755 'markdown-adaptive-fill-function)
6756 (set (make-local-variable 'fill-forward-paragraph-function)
6757 'markdown-fill-forward-paragraph-function)
6758 ;; Outline mode
6759 (make-local-variable 'outline-regexp)
6760 (setq outline-regexp markdown-regex-header)
6761 (make-local-variable 'outline-level)
6762 (setq outline-level 'markdown-outline-level)
6763 ;; Cause use of ellipses for invisible text.
6764 (add-to-invisibility-spec '(outline . t))
6766 ;; Inhibiting line-breaking:
6767 ;; Separating out each condition into a separate function so that users can
6768 ;; override if desired (with remove-hook)
6769 (add-hook 'fill-nobreak-predicate
6770 'markdown-inside-link-p nil t)
6771 (add-hook 'fill-nobreak-predicate
6772 'markdown-line-is-reference-definition-p nil t)
6774 ;; Indentation
6775 (setq indent-line-function markdown-indent-function)
6777 ;; Backwards compatibility with markdown-css-path
6778 (when (boundp 'markdown-css-path)
6779 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6780 (add-to-list 'markdown-css-paths markdown-css-path))
6782 ;; Prepare hooks for XEmacs compatibility
6783 (when (featurep 'xemacs)
6784 (make-local-hook 'after-change-functions)
6785 (make-local-hook 'font-lock-extend-region-functions)
6786 (make-local-hook 'window-configuration-change-hook))
6788 ;; Make checkboxes buttons
6789 (when markdown-make-gfm-checkboxes-buttons
6790 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6791 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
6793 ;; add live preview export hook
6794 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
6795 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
6797 ;;;###autoload
6798 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
6799 ;;;###autoload
6800 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
6803 ;;; GitHub Flavored Markdown Mode ============================================
6805 (defvar gfm-mode-hook nil
6806 "Hook run when entering GFM mode.")
6808 (defvar gfm-font-lock-keywords
6809 (append
6810 ;; GFM features to match first
6811 (list
6812 (cons markdown-regex-strike-through '((3 markdown-markup-face)
6813 (4 markdown-strike-through-face)
6814 (5 markdown-markup-face))))
6815 ;; Basic Markdown features (excluding possibly overridden ones)
6816 markdown-mode-font-lock-keywords-basic)
6817 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6819 ;;;###autoload
6820 (define-derived-mode gfm-mode markdown-mode "GFM"
6821 "Major mode for editing GitHub Flavored Markdown files."
6822 (setq markdown-link-space-sub-char "-")
6823 (set (make-local-variable 'font-lock-defaults)
6824 '(gfm-font-lock-keywords))
6825 ;; do the initial link fontification
6826 (markdown-gfm-parse-buffer-for-languages))
6829 ;;; Live Preview Mode ============================================
6830 (define-minor-mode markdown-live-preview-mode
6831 "Toggle native previewing on save for a specific markdown file."
6832 :lighter " MD-Preview"
6833 (if markdown-live-preview-mode
6834 (markdown-display-buffer-other-window (markdown-live-preview-export))
6835 (markdown-live-preview-remove)))
6838 (provide 'markdown-mode)
6839 ;; Local Variables:
6840 ;; indent-tabs-mode: nil
6841 ;; End:
6842 ;;; markdown-mode.el ends here