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