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