Basic font lock and filling for definition lists
[markdown-mode.git] / markdown-mode.el
blobf0edc758ab6880ef91a0ad6fbe8fb7ac6e5a5ebe
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'.
300 ;; To summarize:
302 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
303 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
304 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
305 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
306 ;; - `C-c C-c w`: `markdown-command' > kill ring.
307 ;; - `C-c C-c o`: `markdown-open-command'.
308 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
310 ;; `C-c C-c c` will check for undefined references. If there are
311 ;; any, a small buffer will open with a list of undefined
312 ;; references and the line numbers on which they appear. In Emacs
313 ;; 22 and greater, selecting a reference from this list and
314 ;; pressing `RET` will insert an empty reference definition at the
315 ;; end of the buffer. Similarly, selecting the line number will
316 ;; jump to the corresponding line.
318 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
319 ;; out of sequence.
321 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
322 ;; rules in the buffer.
324 ;; * Following Links: `C-c C-o`
326 ;; Press `C-c C-o` when the point is on an inline or reference
327 ;; link to open the URL in a browser. When the point is at a
328 ;; wiki link, open it in another buffer (in the current window,
329 ;; or in the other window with the `C-u` prefix). Use `M-p` and
330 ;; `M-n` to quickly jump to the previous or next link of any type.
332 ;; * Jumping: `C-c C-l`
334 ;; Use `C-c C-l` to jump from the object at point to its counterpart
335 ;; elsewhere in the text, when possible. Jumps between reference
336 ;; links and definitions; between footnote markers and footnote
337 ;; text. If more than one link uses the same reference name, a
338 ;; new buffer will be created containing clickable buttons for jumping
339 ;; to each link. You may press `TAB` or `S-TAB` to jump between
340 ;; buttons in this window.
342 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
344 ;; Headings, horizontal rules, and list items can be promoted and
345 ;; demoted, as well as bold and italic text. For headings,
346 ;; "promotion" means *decreasing* the level (i.e., moving from
347 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
348 ;; level. For horizontal rules, promotion and demotion means
349 ;; moving backward or forward through the list of rule strings in
350 ;; `markdown-hr-strings'. For bold and italic text, promotion and
351 ;; demotion means changing the markup from underscores to asterisks.
352 ;; Press `C-c C--` or `M-LEFT` to promote the element at the point
353 ;; if possible.
355 ;; To remember these commands, note that `-` is for decreasing the
356 ;; level (promoting), and `=` (on the same key as `+`) is for
357 ;; increasing the level (demoting). Similarly, the left and right
358 ;; arrow keys indicate the direction that the atx heading markup
359 ;; is moving in when promoting or demoting.
361 ;; * Completion: `C-c C-]`
363 ;; Complete markup is in normalized form, which means, for
364 ;; example, that the underline portion of a setext header is the
365 ;; same length as the heading text, or that the number of leading
366 ;; and trailing hash marks of an atx header are equal and that
367 ;; there is no extra whitespace in the header text. `C-c C-]`
368 ;; completes the markup at the point, if it is determined to be
369 ;; incomplete.
371 ;; * Editing Lists: `M-RET`, `M-UP`, `M-DOWN`, `M-LEFT`, and `M-RIGHT`
373 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
374 ;; command determines the appropriate marker (one of the possible
375 ;; unordered list markers or the next number in sequence for an
376 ;; ordered list) and indentation level by examining nearby list
377 ;; items. If there is no list before or after the point, start a
378 ;; new list. Prefix this command by `C-u` to decrease the
379 ;; indentation by one level. Prefix this command by `C-u C-u` to
380 ;; increase the indentation by one level.
382 ;; Existing list items can be moved up or down with `M-UP` or
383 ;; `M-DOWN` and indented or exdented with `M-RIGHT` or `M-LEFT`.
385 ;; * Editing Subtrees: `M-S-UP`, `M-S-DOWN`, `M-S-LEFT`, and `M-S-RIGHT`
387 ;; Entire subtrees of ATX headings can be promoted and demoted
388 ;; with `M-S-LEFT` and `M-S-RIGHT`, which mirror the bindings
389 ;; for promotion and demotion of list items. Similarly, subtrees
390 ;; can be moved up and down with `M-S-UP` and `M-S-DOWN`.
392 ;; Please note the following "boundary" behavior for promotion and
393 ;; demotion. Any level-six headings will not be demoted further
394 ;; (i.e., they remain at level six, since Markdown and HTML define
395 ;; only six levels) and any level-one headings will promoted away
396 ;; entirely (i.e., heading markup will be removed, since a
397 ;; level-zero heading is not defined).
399 ;; * Shifting the Region: `C-c <` and `C-c >`
401 ;; Text in the region can be indented or exdented as a group using
402 ;; `C-c >` to indent to the next indentation point (calculated in
403 ;; the current context), and `C-c <` to exdent to the previous
404 ;; indentation point. These keybindings are the same as those for
405 ;; similar commands in `python-mode'.
407 ;; * Killing Elements: `C-c C-k`
409 ;; Press `C-c C-k` to kill the thing at point and add important
410 ;; text, without markup, to the kill ring. Possible things to
411 ;; kill include (roughly in order of precedece): inline code,
412 ;; headings, horizonal rules, links (add link text to kill ring),
413 ;; images (add alt text to kill ring), angle URIs, email
414 ;; addresses, bold, italics, reference definitions (add URI to
415 ;; kill ring), footnote markers and text (kill both marker and
416 ;; text, add text to kill ring), and list items.
418 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
420 ;; Navigation between headings is possible using `outline-mode'.
421 ;; Use `C-c C-n` and `C-c C-p` to move between the next and previous
422 ;; visible headings. Similarly, `C-c C-f` and `C-c C-b` move to the
423 ;; next and previous visible headings at the same level as the one
424 ;; at the point. Finally, `C-c C-u` will move up to a lower-level
425 ;; (higher precedence) visible heading.
427 ;; * Movement by Paragraph or Block: `M-{` and `M-}`
429 ;; The definition of a "paragraph" is slightly different in
430 ;; markdown-mode than, say, text-mode, because markdown-mode
431 ;; supports filling for list items and respects hard line breaks,
432 ;; both of which break paragraphs. So, markdown-mode overrides
433 ;; the usual paragraph navigation commands `M-{` and `M-}` so that
434 ;; with a `C-u` prefix, these commands jump to the beginning or
435 ;; end of an entire block of text, respectively, where "blocks"
436 ;; are separated by one or more lines.
438 ;; * Movement by Defun: `C-M-a`, `C-M-e`, and `C-M-h`
440 ;; The usual Emacs commands can be used to move by defuns
441 ;; (top-level major definitions). In markdown-mode, a defun is a
442 ;; section. As usual, `C-M-a` will move the point to the
443 ;; beginning of the current or preceding defun, `C-M-e` will move
444 ;; to the end of the current or following defun, and `C-M-h` will
445 ;; put the region around the entire defun.
447 ;; As noted, many of the commands above behave differently depending
448 ;; on whether Transient Mark mode is enabled or not. When it makes
449 ;; sense, if Transient Mark mode is on and the region is active, the
450 ;; command applies to the text in the region (e.g., `C-c C-s s` makes the
451 ;; region bold). For users who prefer to work outside of Transient
452 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
453 ;; `C-SPC C-SPC`. When this is not the case, many commands then
454 ;; proceed to look work with the word or line at the point.
456 ;; When applicable, commands that specifically act on the region even
457 ;; outside of Transient Mark mode have the same keybinding as their
458 ;; standard counterpart, but the letter is uppercase. For example,
459 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
460 ;; the region in Transient Mark mode while `markdown-blockquote-region'
461 ;; is bound to `C-c C-s B` and always applies to the region (when nonempty).
463 ;; Note that these region-specific functions are useful in many
464 ;; cases where it may not be obvious. For example, yanking text from
465 ;; the kill ring sets the mark at the beginning of the yanked text
466 ;; and moves the point to the end. Therefore, the (inactive) region
467 ;; contains the yanked text. So, `C-y` followed by `C-c C-s C-b` will
468 ;; yank text and turn it into a blockquote.
470 ;; markdown-mode attempts to be flexible in how it handles
471 ;; indentation. When you press `TAB` repeatedly, the point will cycle
472 ;; through several possible indentation levels corresponding to things
473 ;; you might have in mind when you press `RET` at the end of a line or
474 ;; `TAB`. For example, you may want to start a new list item,
475 ;; continue a list item with hanging indentation, indent for a nested
476 ;; pre block, and so on. Exdention is handled similarly when backspace
477 ;; is pressed at the beginning of the non-whitespace portion of a line.
479 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
480 ;; visibility cycling for atx- or hash-style headings. There are two
481 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
482 ;; the table of contents view (headings only), outline view (top-level
483 ;; headings only), and the full document view. Pressing `TAB` while the
484 ;; point is at a heading will cycle through levels of visibility for the
485 ;; subtree: completely folded, visible children, and fully visible.
486 ;; Note that mixing hash and underline style headings will give undesired
487 ;; results.
489 ;;; Customization:
491 ;; Although no configuration is *necessary* there are a few things
492 ;; that can be customized. The `M-x customize-mode` command
493 ;; provides an interface to all of the possible customizations:
495 ;; * `markdown-command' - the command used to run Markdown (default:
496 ;; `markdown`). This variable may be customized to pass
497 ;; command-line options to your Markdown processor of choice.
499 ;; * `markdown-command-needs-filename' - set to `t' if
500 ;; `markdown-command' does not accept standard input (default:
501 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
502 ;; content to `markdown-command' using standard input (`stdin`).
503 ;; When set to `t', `markdown-mode' will pass the name of the file
504 ;; as the final command-line argument to `markdown-command'. Note
505 ;; that in the latter case, you will only be able to run
506 ;; `markdown-command' from buffers which are visiting a file.
508 ;; * `markdown-open-command' - the command used for calling a standalone
509 ;; Markdown previewer which is capable of opening Markdown source files
510 ;; directly (default: `nil'). This command will be called
511 ;; with a single argument, the filename of the current buffer.
512 ;; A representative program is the Mac app [Marked 2][], a
513 ;; live-updating Markdown previewer which can be [called from a
514 ;; simple shell script](http://jblevins.org/log/marked-2-command).
516 ;; * `markdown-hr-strings' - list of strings to use when inserting
517 ;; horizontal rules. Different strings will not be distinguished
518 ;; when converted to HTML--they will all be converted to
519 ;; `<hr/>`--but they may add visual distinction and style to plain
520 ;; text documents. To maintain some notion of promotion and
521 ;; demotion, keep these sorted from largest to smallest.
523 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
524 ;; underscores when inserting bold text instead of two asterisks
525 ;; (default: `nil').
527 ;; * `markdown-italic-underscore' - set to a non-nil value to use
528 ;; underscores when inserting italic text instead of asterisks
529 ;; (default: `nil').
531 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
532 ;; asymmetric header styling, placing header characters only on
533 ;; the left of headers (default: `nil').
535 ;; * `markdown-header-scaling' - set to a non-nil value to use
536 ;; a variable-pitch font for headings where the size corresponds
537 ;; to the level of the heading (default: `nil').
539 ;; * `markdown-header-scaling-values' - list of scaling values,
540 ;; relative to baseline, for headers of levels one through six,
541 ;; used when `markdown-header-scaling' is non-nil
542 ;; (default: `(list 1.8 1.4 1.2 1.0 1.0 1.0)`).
544 ;; * `markdown-list-indent-width' - depth of indentation for lists
545 ;; when inserting, promoting, and demoting list items (default: 4).
547 ;; * `markdown-indent-function' - the function to use for automatic
548 ;; indentation (default: `markdown-indent-line').
550 ;; * `markdown-indent-on-enter' - set to a non-nil value to
551 ;; automatically indent new lines when the enter key is pressed
552 ;; (default: `t')
554 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
555 ;; links (default: `nil'). Set this to a non-nil value to turn on
556 ;; wiki link support by default. Wiki link support can be toggled
557 ;; later using the function `markdown-toggle-wiki-links'."
559 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
560 ;; treat aliased wiki links like `[[link text|PageName]]`
561 ;; (default: `t'). When set to nil, they will be treated as
562 ;; `[[PageName|link text]]'.
564 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
565 ;; for URIs that `markdown-mode' should highlight.
567 ;; * `markdown-enable-math' - syntax highlighting for LaTeX
568 ;; fragments (default: `nil'). Set this to `t' to turn on math
569 ;; support by default. Math support can be enabled, disabled, or
570 ;; toggled later using the function `markdown-toggle-math'."
572 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
573 ;; (default: `nil`).
575 ;; * `markdown-content-type' - when set to a nonempty string, an
576 ;; `http-equiv` attribute will be included in the XHTML `<head>`
577 ;; block (default: `""`). If needed, the suggested values are
578 ;; `application/xhtml+xml` or `text/html`. See also:
579 ;; `markdown-coding-system'.
581 ;; * `markdown-coding-system' - used for specifying the character
582 ;; set identifier in the `http-equiv` attribute when included
583 ;; (default: `nil'). See `markdown-content-type', which must
584 ;; be set before this variable has any effect. When set to `nil',
585 ;; `buffer-file-coding-system' will be used to automatically
586 ;; determine the coding system string (falling back to
587 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
588 ;; and `iso-latin-1'.
590 ;; * `markdown-xhtml-header-content' - additional content to include
591 ;; in the XHTML `<head>` block (default: `""`).
593 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
594 ;; `markdown-mode' uses to determine whether the output of
595 ;; `markdown-command' is a standalone XHTML document or an XHTML
596 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
597 ;; this regular expression not matched in the first five lines of
598 ;; output, `markdown-mode' assumes the output is a fragment and
599 ;; adds a header and footer.
601 ;; * `markdown-link-space-sub-char' - a character to replace spaces
602 ;; when mapping wiki links to filenames (default: `"_"`).
603 ;; For example, use an underscore for compatibility with the
604 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
605 ;; set to `"-"` to conform with GitHub wiki links.
607 ;; * `markdown-reference-location' - where to insert reference
608 ;; definitions (default: `header`). The possible locations are
609 ;; the end of the document (`end`), after the current block
610 ;; (`immediately`), before the next header (`header`).
612 ;; * `markdown-footnote-location' - where to insert footnote text
613 ;; (default: `end`). The set of location options is the same as
614 ;; for `markdown-reference-location'.
616 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
617 ;; heading instead of a flat index (default: `nil'). A nested
618 ;; index may provide more natural browsing from the menu, but a
619 ;; flat list may allow for faster keyboard navigation via tab
620 ;; completion.
622 ;; * `comment-auto-fill-only-comments' - variable is made
623 ;; buffer-local and set to `nil' by default. In programming
624 ;; language modes, when this variable is non-nil, only comments
625 ;; will be filled by auto-fill-mode. However, comments in
626 ;; Markdown documents are rare and the most users probably intend
627 ;; for the actual content of the document to be filled. Making
628 ;; this variable buffer-local allows `markdown-mode' to override
629 ;; the default behavior induced when the global variable is non-nil.
631 ;; * `markdown-gfm-additional-languages', - additional languages to
632 ;; make available, aside from those predefined in
633 ;; `markdown-gfm-recognized-languages', when inserting GFM code
634 ;; blocks (default: `nil`). Language strings must have be trimmed
635 ;; of whitespace and not contain any curly braces. They may be of
636 ;; arbitrary capitalization, though.
638 ;; * `markdown-gfm-use-electric-backquote' - use
639 ;; `markdown-electric-backquote' for interactive insertion of GFM
640 ;; code blocks when backquote is pressed three times (default: `t`).
642 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
643 ;; Flavored Markdown style task lists (checkboxes) should be
644 ;; turned into buttons that can be toggled with mouse-1 or RET. If
645 ;; non-nil (default), then buttons are enabled. This works in
646 ;; `markdown-mode' as well as `gfm-mode'.
648 ;; Additionally, the faces used for syntax highlighting can be modified to
649 ;; your liking by issuing `M-x customize-group RET markdown-faces`
650 ;; or by using the "Markdown Faces" link at the bottom of the mode
651 ;; customization screen.
653 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
655 ;;; Extensions:
657 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
658 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
659 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
660 ;; Wiki links may be followed by pressing `C-c C-o` when the point
661 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
662 ;; previous and next links (including links of other types).
663 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
664 ;; are also supported. Since some wikis reverse these components, set
665 ;; `markdown-wiki-link-alias-first' to nil to treat them as
666 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
667 ;; is also non-nil, Markdown Mode will highlight wiki links with
668 ;; missing target file in a different color. By default, Markdown
669 ;; Mode only searches for target files in the current directory.
670 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
671 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
672 ;; to a non-nil value.
674 ;; [Ikiwiki]: https://ikiwiki.info
676 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
677 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
678 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
679 ;; You can do this either by using `M-x customize-group markdown`
680 ;; or by placing the following in your `.emacs` file:
682 ;; (setq markdown-command "markdown | smartypants")
684 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
686 ;; Syntax highlighting for mathematical expressions written
687 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
688 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
689 ;; either via customize or by placing `(setq markdown-enable-math t)`
690 ;; in `.emacs`, and then restarting Emacs or calling
691 ;; `markdown-reload-extensions'.
693 ;;; GitHub Flavored Markdown (GFM):
695 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
696 ;; available. The GitHub implementation differs slightly from
697 ;; standard Markdown in that it supports things like different
698 ;; behavior for underscores inside of words, automatic linking of
699 ;; URLs, strikethrough text, and fenced code blocks with an optional
700 ;; language keyword.
702 ;; The GFM-specific features above apply to `README.md` files, wiki
703 ;; pages, and other Markdown-formatted files in repositories on
704 ;; GitHub. GitHub also enables [additional features][GFM comments] for
705 ;; writing on the site (for issues, pull requests, messages, etc.)
706 ;; that are further extensions of GFM. These features include task
707 ;; lists (checkboxes), newlines corresponding to hard line breaks,
708 ;; auto-linked references to issues and commits, wiki links, and so
709 ;; on. To make matters more confusing, although task lists are not
710 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
711 ;; read-only fashion) in all Markdown documents in repositories on the
712 ;; site. These additional extensions are supported to varying degrees
713 ;; by `markdown-mode' and `gfm-mode' as described below.
715 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
716 ;; highlighting of URLs without angle brackets.
718 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
719 ;; toggle support for underscores inside of words. In this mode
720 ;; variable names such as `a_test_variable` will not trigger
721 ;; emphasis (italics).
723 ;; * **Fenced code blocks:** Code blocks quoted with backticks, with
724 ;; optional programming language keywords, are highlighted in
725 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
726 ;; `C-c C-s P`. If there is an active region, the text in the
727 ;; region will be placed inside the code block. You will be
728 ;; prompted for the name of the language, but may press enter to
729 ;; continue without naming a language.
731 ;; * **Strikethrough:** Strikethrough text is only supported in
732 ;; `gfm-mode' and can be inserted (and toggled) using `C-c C-s d`.
733 ;; Following the mnemonics for the other style keybindings, the
734 ;; letter `d` coincides with the HTML tag `<del>`.
736 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
737 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
738 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
739 ;; (and it is set to t by default). These checkboxes can be
740 ;; toggled by clicking `mouse-1` or pressing `RET` over the button.
742 ;; * **Wiki links:** Generic wiki links are supported in
743 ;; `markdown-mode', but in `gfm-mode' specifically they will be
744 ;; treated as they are on GitHub: spaces will be replaced by hyphens
745 ;; in filenames and the first letter of the filename will be
746 ;; capitalized. For example, `[[wiki link]]' will map to a file
747 ;; named `Wiki-link` with the same extension as the current file.
749 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
750 ;; specifically with respect to newline behavior. If you use
751 ;; `gfm-mode' mostly to write text for comments or issues on the
752 ;; GitHub site--where newlines are significant and correspond to
753 ;; hard line breaks--then you may want to enable `visual-line-mode'
754 ;; for line wrapping in buffers. You can do this with a
755 ;; `gfm-mode-hook' as follows:
757 ;; ;; Use visual-line-mode in gfm-mode
758 ;; (defun my-gfm-mode-hook ()
759 ;; (visual-line-mode 1))
760 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
762 ;; * **Preview:** GFM-specific preview can be powered by setting
763 ;; `markdown-command' to use [Docter][]. This may also be
764 ;; configured to work with [Marked 2][] for `markdown-open-command'.
766 ;; [GFM]: http://github.github.com/github-flavored-markdown/
767 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
768 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
769 ;; [Docter]: https://github.com/alampros/Docter
771 ;;; Acknowledgments:
773 ;; markdown-mode has benefited greatly from the efforts of the many
774 ;; volunteers who have sent patches, test cases, bug reports,
775 ;; suggestions, helped with packaging, etc. Thank you for your
776 ;; contributions! See the [contributors graph][contrib] for details.
778 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
780 ;;; Bugs:
782 ;; markdown-mode is developed and tested primarily for compatibility
783 ;; with GNU Emacs 24.3 and later. If you find any bugs in
784 ;; markdown-mode, please construct a test case or a patch and open a
785 ;; ticket on the [GitHub issue tracker][issues].
787 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
789 ;;; History:
791 ;; markdown-mode was written and is maintained by Jason Blevins. The
792 ;; first version was released on May 24, 2007.
794 ;; * 2007-05-24: [Version 1.1][]
795 ;; * 2007-05-25: [Version 1.2][]
796 ;; * 2007-06-05: [Version 1.3][]
797 ;; * 2007-06-29: [Version 1.4][]
798 ;; * 2007-10-11: [Version 1.5][]
799 ;; * 2008-06-04: [Version 1.6][]
800 ;; * 2009-10-01: [Version 1.7][]
801 ;; * 2011-08-12: [Version 1.8][]
802 ;; * 2011-08-15: [Version 1.8.1][]
803 ;; * 2013-01-25: [Version 1.9][]
804 ;; * 2013-03-24: [Version 2.0][]
805 ;; * 2016-01-09: [Version 2.1][]
807 ;; [Version 1.1]: http://jblevins.org/projects/markdown-mode/rev-1-1
808 ;; [Version 1.2]: http://jblevins.org/projects/markdown-mode/rev-1-2
809 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
810 ;; [Version 1.4]: http://jblevins.org/projects/markdown-mode/rev-1-4
811 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
812 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
813 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
814 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
815 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
816 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
817 ;; [Version 2.0]: http://jblevins.org/projects/markdown-mode/rev-2-0
818 ;; [Version 2.1]: http://jblevins.org/projects/markdown-mode/rev-2-1
821 ;;; Code:
823 (require 'easymenu)
824 (require 'outline)
825 (require 'thingatpt)
826 (require 'cl-lib)
827 (require 'url-parse)
829 (defvar jit-lock-start)
830 (defvar jit-lock-end)
832 (declare-function eww-open-file "eww")
833 (declare-function url-path-and-query "url-parse")
836 ;;; Constants =================================================================
838 (defconst markdown-mode-version "2.1"
839 "Markdown mode version number.")
841 (defconst markdown-output-buffer-name "*markdown-output*"
842 "Name of temporary buffer for markdown command output.")
845 ;;; Global Variables ==========================================================
847 (defvar markdown-reference-label-history nil
848 "History of used reference labels.")
850 (defvar markdown-live-preview-mode nil
851 "Sentinel variable for command `markdown-live-preview-mode'.")
853 (defvar markdown-gfm-language-history nil
854 "History list of languages used in the current buffer in GFM code blocks.")
857 ;;; Customizable Variables ====================================================
859 (defvar markdown-mode-hook nil
860 "Hook run when entering Markdown mode.")
862 (defvar markdown-before-export-hook nil
863 "Hook run before running Markdown to export XHTML output.
864 The hook may modify the buffer, which will be restored to it's
865 original state after exporting is complete.")
867 (defvar markdown-after-export-hook nil
868 "Hook run after XHTML output has been saved.
869 Any changes to the output buffer made by this hook will be saved.")
871 (defgroup markdown nil
872 "Major mode for editing text files in Markdown format."
873 :prefix "markdown-"
874 :group 'wp
875 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
877 (defcustom markdown-command "markdown"
878 "Command to run markdown."
879 :group 'markdown
880 :type 'string)
882 (defcustom markdown-command-needs-filename nil
883 "Set to non-nil if `markdown-command' does not accept input from stdin.
884 Instead, it will be passed a filename as the final command line
885 option. As a result, you will only be able to run Markdown from
886 buffers which are visiting a file."
887 :group 'markdown
888 :type 'boolean)
890 (defcustom markdown-open-command nil
891 "Command used for opening Markdown files directly.
892 For example, a standalone Markdown previewer. This command will
893 be called with a single argument: the filename of the current
894 buffer."
895 :group 'markdown
896 :type 'string)
898 (defcustom markdown-hr-strings
899 '("-------------------------------------------------------------------------------"
900 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
901 "---------------------------------------"
902 "* * * * * * * * * * * * * * * * * * * *"
903 "---------"
904 "* * * * *")
905 "Strings to use when inserting horizontal rules.
906 The first string in the list will be the default when inserting a
907 horizontal rule. Strings should be listed in decreasing order of
908 prominence (as in headings from level one to six) for use with
909 promotion and demotion functions."
910 :group 'markdown
911 :type 'list)
913 (defcustom markdown-bold-underscore nil
914 "Use two underscores when inserting bold text instead of two asterisks."
915 :group 'markdown
916 :type 'boolean)
918 (defcustom markdown-italic-underscore nil
919 "Use underscores when inserting italic text instead of asterisks."
920 :group 'markdown
921 :type 'boolean)
923 (defcustom markdown-asymmetric-header nil
924 "Determines if atx header style will be asymmetric.
925 Set to a non-nil value to use asymmetric header styling, placing
926 header markup only at the beginning of the line. By default,
927 balanced markup will be inserted at the beginning and end of the
928 line around the header title."
929 :group 'markdown
930 :type 'boolean)
932 (defcustom markdown-indent-function 'markdown-indent-line
933 "Function to use to indent."
934 :group 'markdown
935 :type 'function)
937 (defcustom markdown-indent-on-enter t
938 "Automatically indent new lines when enter key is pressed.
939 When this variable is set to t, pressing RET will call
940 `newline-and-indent'. When set to nil, define RET to call
941 `newline' as usual. In the latter case, you can still use
942 auto-indentation by pressing \\[newline-and-indent]."
943 :group 'markdown
944 :type 'boolean)
946 (defcustom markdown-enable-wiki-links nil
947 "Syntax highlighting for wiki links.
948 Set this to a non-nil value to turn on wiki link support by default.
949 Support can be toggled later using the `markdown-toggle-wiki-links'
950 function or \\[markdown-toggle-wiki-links]."
951 :group 'markdown
952 :type 'boolean
953 :safe 'booleanp)
955 (defcustom markdown-wiki-link-alias-first t
956 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
957 Otherwise, they will be treated as [[PageName|alias text]]."
958 :group 'markdown
959 :type 'boolean
960 :safe 'booleanp)
962 (defcustom markdown-wiki-link-search-parent-directories nil
963 "When non-nil, search for wiki link targets in parent directories.
964 This is the default search behavior of Ikiwiki."
965 :group 'markdown
966 :type 'boolean
967 :safe 'booleanp)
969 (defcustom markdown-wiki-link-fontify-missing nil
970 "When non-nil, change wiki link face according to existence of target files.
971 This is expensive because it requires checking for the file each time the buffer
972 changes or the user switches windows. It is disabled by default because it may
973 cause lag when typing on slower machines."
974 :group 'markdown
975 :type 'boolean
976 :safe 'booleanp)
978 (defcustom markdown-uri-types
979 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
980 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
981 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
982 "Link types for syntax highlighting of URIs."
983 :group 'markdown
984 :type 'list)
986 (defcustom markdown-enable-math nil
987 "Syntax highlighting for inline LaTeX and itex expressions.
988 Set this to a non-nil value to turn on math support by default.
989 Math support can be enabled, disabled, or toggled later using
990 `markdown-toggle-math' or \\[markdown-toggle-math]."
991 :group 'markdown
992 :type 'boolean
993 :safe 'booleanp)
995 (defcustom markdown-css-paths nil
996 "URL of CSS file to link to in the output XHTML."
997 :group 'markdown
998 :type 'list)
1000 (defcustom markdown-content-type ""
1001 "Content type string for the http-equiv header in XHTML output.
1002 When set to a non-empty string, insert the http-equiv attribute.
1003 Otherwise, this attribute is omitted."
1004 :group 'markdown
1005 :type 'string)
1007 (defcustom markdown-coding-system nil
1008 "Character set string for the http-equiv header in XHTML output.
1009 Defaults to `buffer-file-coding-system' (and falling back to
1010 `iso-8859-1' when not available). Common settings are `utf-8'
1011 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1012 :group 'markdown
1013 :type 'coding-system)
1015 (defcustom markdown-xhtml-header-content ""
1016 "Additional content to include in the XHTML <head> block."
1017 :group 'markdown
1018 :type 'string)
1020 (defcustom markdown-xhtml-standalone-regexp
1021 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1022 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1023 :group 'markdown
1024 :type 'regexp)
1026 (defcustom markdown-link-space-sub-char "_"
1027 "Character to use instead of spaces when mapping wiki links to filenames."
1028 :group 'markdown
1029 :type 'string)
1031 (defcustom markdown-reference-location 'header
1032 "Position where new reference definitions are inserted in the document."
1033 :group 'markdown
1034 :type '(choice (const :tag "At the end of the document" end)
1035 (const :tag "Immediately after the current block" immediately)
1036 (const :tag "Before next header" header)))
1038 (defcustom markdown-footnote-location 'end
1039 "Position where new footnotes are inserted in the document."
1040 :group 'markdown
1041 :type '(choice (const :tag "At the end of the document" end)
1042 (const :tag "Immediately after the current block" immediately)
1043 (const :tag "Before next header" header)))
1045 (defcustom markdown-unordered-list-item-prefix " * "
1046 "String inserted before unordered list items."
1047 :group 'markdown
1048 :type 'string)
1050 (defcustom markdown-nested-imenu-heading-index nil
1051 "Use nested or flat imenu heading index.
1052 A nested index may provide more natural browsing from the menu,
1053 but a flat list may allow for faster keyboard navigation via tab
1054 completion."
1055 :group 'markdown
1056 :type 'boolean)
1058 (defcustom markdown-make-gfm-checkboxes-buttons t
1059 "When non-nil, make GFM checkboxes into buttons."
1060 :group 'markdown
1061 :type 'boolean)
1063 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1064 "When non-nil, allow yaml metadata anywhere in the document."
1065 :group 'markdown
1066 :type 'boolean)
1068 (defcustom markdown-live-preview-window-function
1069 'markdown-live-preview-window-eww
1070 "Function to display preview of Markdown output within Emacs.
1071 Function must update the buffer containing the preview and return
1072 the buffer."
1073 :group 'markdown
1074 :type 'function)
1076 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1077 "Delete exported html file when using `markdown-live-preview-export'.
1078 If set to 'delete-on-export, delete on every export. When set to
1079 'delete-on-destroy delete when quitting from command
1080 `markdown-live-preview-mode'. Never delete if set to nil."
1081 :group 'markdown
1082 :type 'symbol)
1084 (defcustom markdown-list-indent-width 4
1085 "Depth of indentation for markdown lists.
1086 Used in `markdown-demote-list-item' and
1087 `markdown-promote-list-item'."
1088 :group 'markdown
1089 :type 'integer)
1091 (defcustom markdown-gfm-additional-languages nil
1092 "Extra languages made available when inserting GFM code blocks.
1093 Language strings must have be trimmed of whitespace and not
1094 contain any curly braces. They may be of arbitrary
1095 capitalization, though."
1096 :group 'markdown
1097 :type '(repeat (string :validate markdown-validate-language-string)))
1099 (defcustom markdown-gfm-use-electric-backquote t
1100 "Use `markdown-electric-backquote' when backquote is hit three times."
1101 :group 'markdown
1102 :type 'boolean)
1104 (defcustom markdown-gfm-downcase-languages t
1105 "If non-nil, downcase suggested languages.
1106 This applies to insertions done with
1107 `markdown-electric-backquote'."
1108 :group 'markdown
1109 :type 'boolean)
1112 ;;; Regular Expressions =======================================================
1114 (defconst markdown-regex-comment-start
1115 "<!--"
1116 "Regular expression matches HTML comment opening.")
1118 (defconst markdown-regex-comment-end
1119 "--[ \t]*>"
1120 "Regular expression matches HTML comment closing.")
1122 (defconst markdown-regex-link-inline
1123 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1124 "Regular expression for a [text](file) or an image link ![text](file).
1125 Group 1 matches the leading exclamation point (optional).
1126 Group 2 matches the opening square bracket.
1127 Group 3 matches the text inside the square brackets.
1128 Group 4 matches the closing square bracket.
1129 Group 5 matches the opening parenthesis.
1130 Group 6 matches the URL.
1131 Group 7 matches the title (optional).
1132 Group 8 matches the closing parenthesis.")
1134 (defconst markdown-regex-link-reference
1135 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1136 "Regular expression for a reference link [text][id].
1137 Group 1 matches the leading exclamation point (optional).
1138 Group 2 matches the opening square bracket for the link text.
1139 Group 3 matches the text inside the square brackets.
1140 Group 4 matches the closing square bracket for the link text.
1141 Group 5 matches the opening square bracket for the reference label.
1142 Group 6 matches the reference label.
1143 Group 7 matches the closing square bracket for the reference label.")
1145 (defconst markdown-regex-reference-definition
1146 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1147 "Regular expression for a reference definition.
1148 Group 1 matches the opening square bracket.
1149 Group 2 matches the reference label.
1150 Group 3 matches the closing square bracket.
1151 Group 4 matches the colon.
1152 Group 5 matches the URL.
1153 Group 6 matches the title attribute (optional).")
1155 (defconst markdown-regex-footnote
1156 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1157 "Regular expression for a footnote marker [^fn].
1158 Group 1 matches the opening square bracket and carat.
1159 Group 2 matches only the label, without the surrounding markup.
1160 Group 3 matches the closing square bracket.")
1162 (defconst markdown-regex-header
1163 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)\\)$"
1164 "Regexp identifying Markdown headings.
1165 Group 1 matches the text of a setext heading.
1166 Group 2 matches the underline of a level-1 setext heading.
1167 Group 3 matches the underline of a level-2 setext heading.
1168 Group 4 matches the opening hash marks of an atx heading.
1169 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1170 Group 6 matches the closing hash marks of an atx heading.")
1172 (defconst markdown-regex-header-setext
1173 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1174 "Regular expression for generic setext-style (underline) headers.")
1176 (defconst markdown-regex-header-atx
1177 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1178 "Regular expression for generic atx-style (hash mark) headers.")
1180 (defconst markdown-regex-hr
1181 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1182 "Regular expression for matching Markdown horizontal rules.")
1184 (defconst markdown-regex-code
1185 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1186 "Regular expression for matching inline code fragments.
1188 Group 1 matches the entire code fragment including the backticks.
1189 Group 2 matches the opening backticks.
1190 Group 3 matches the code fragment itself, without backticks.
1191 Group 4 matches the closing backticks.
1193 The leading, unnumbered group ensures that the leading backquote
1194 character is not escaped.
1195 The last group, also unnumbered, requires that the character
1196 following the code fragment is not a backquote.
1197 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1198 but not two newlines in a row.")
1200 (defconst markdown-regex-kbd
1201 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1202 "Regular expression for matching <kbd> tags.
1203 Groups 1 and 3 match the opening and closing tags.
1204 Group 2 matches the key sequence.")
1206 (defconst markdown-regex-gfm-code-block-open
1207 "^[[:blank:]]*\\(```\\)[ ]?\\([^[:space:]]+\\|{[^}]*}\\)?\\([[:space:]]*?\\)$"
1208 "Regular expression matching opening of GFM code blocks.
1209 Group 1 matches the opening three backticks.
1210 Group 2 matches the language identifier (optional).")
1212 (defconst markdown-regex-gfm-code-block-close
1213 "^[[:blank:]]*\\(```\\)\\s *?$"
1214 "Regular expression matching closing of GFM code blocks.
1215 Group 1 matches the closing three backticks.")
1217 (defconst markdown-regex-pre
1218 "^\\( \\|\t\\).*$"
1219 "Regular expression for matching preformatted text sections.")
1221 (defconst markdown-regex-list
1222 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1223 "Regular expression for matching list items.")
1225 (defconst markdown-regex-bold
1226 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1227 "Regular expression for matching bold text.
1228 Group 1 matches the character before the opening asterisk or
1229 underscore, if any, ensuring that it is not a backslash escape.
1230 Group 2 matches the entire expression, including delimiters.
1231 Groups 3 and 5 matches the opening and closing delimiters.
1232 Group 4 matches the text inside the delimiters.")
1234 (defconst markdown-regex-italic
1235 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1236 "Regular expression for matching italic text.
1237 The leading unnumbered matches the character before the opening
1238 asterisk or underscore, if any, ensuring that it is not a
1239 backslash escape.
1240 Group 1 matches the entire expression, including delimiters.
1241 Groups 2 and 4 matches the opening and closing delimiters.
1242 Group 3 matches the text inside the delimiters.")
1244 (defconst markdown-regex-strike-through
1245 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1246 "Regular expression for matching strike-through text.
1247 Group 1 matches the character before the opening tilde, if any,
1248 ensuring that it is not a backslash escape.
1249 Group 2 matches the entire expression, including delimiters.
1250 Groups 3 and 5 matches the opening and closing delimiters.
1251 Group 4 matches the text inside the delimiters.")
1253 (defconst markdown-regex-gfm-italic
1254 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1255 "Regular expression for matching italic text in GitHub Flavored Markdown.
1256 Underscores in words are not treated as special.
1257 Group 1 matches the entire expression, including delimiters.
1258 Groups 2 and 4 matches the opening and closing delimiters.
1259 Group 3 matches the text inside the delimiters.")
1261 (defconst markdown-regex-blockquote
1262 "^[ \t]*\\(>\\)\\(.*\\)$"
1263 "Regular expression for matching blockquote lines.
1264 Group 1 matches the leading angle bracket.
1265 Group 2 matches the text.")
1267 (defconst markdown-regex-line-break
1268 "[^ \n\t][ \t]*\\( \\)$"
1269 "Regular expression for matching line breaks.")
1271 (defconst markdown-regex-wiki-link
1272 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1273 "Regular expression for matching wiki links.
1274 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1275 wiki links of the form [[PageName|link text]].
1276 The meanings of the first and second components depend
1277 on the value of `markdown-wiki-link-alias-first'.
1279 Group 1 matches the entire link.
1280 Group 2 matches the opening square brackets.
1281 Group 3 matches the first component of the wiki link.
1282 Group 4 matches the pipe separator, when present.
1283 Group 5 matches the second component of the wiki link, when present.
1284 Group 6 matches the closing square brackets.")
1286 (defconst markdown-regex-uri
1287 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1288 "Regular expression for matching inline URIs.")
1290 (defconst markdown-regex-angle-uri
1291 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1292 "Regular expression for matching inline URIs in angle brackets.")
1294 (defconst markdown-regex-email
1295 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1296 "Regular expression for matching inline email addresses.")
1298 (defsubst markdown-make-regex-link-generic ()
1299 "Make regular expression for matching any recognized link."
1300 (concat "\\(?:" markdown-regex-link-inline
1301 (when markdown-enable-wiki-links
1302 (concat "\\|" markdown-regex-wiki-link))
1303 "\\|" markdown-regex-link-reference
1304 "\\|" markdown-regex-angle-uri "\\)"))
1306 (defconst markdown-regex-gfm-checkbox
1307 " \\(\\[[ xX]\\]\\) "
1308 "Regular expression for matching GFM checkboxes.
1309 Group 1 matches the text to become a button.")
1311 (defconst markdown-regex-block-separator
1312 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1313 "Regular expression for matching block boundaries.")
1315 (defconst markdown-regex-math-inline-single
1316 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1317 "Regular expression for itex $..$ math mode expressions.
1318 Groups 1 and 3 match the opening and closing dollar signs.
1319 Group 3 matches the mathematical expression contained within.")
1321 (defconst markdown-regex-math-inline-double
1322 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1323 "Regular expression for itex $$..$$ math mode expressions.
1324 Groups 1 and 3 match opening and closing dollar signs.
1325 Group 3 matches the mathematical expression contained within.")
1327 (defconst markdown-regex-math-display
1328 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1329 "Regular expression for itex \[..\] display mode expressions.
1330 Groups 1 and 3 match the opening and closing delimiters.
1331 Group 2 matches the mathematical expression contained within.")
1333 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1334 "Return regexp matching a Pandoc code fence at least NUM-TILDES long.
1335 END-OF-LINE is the regexp construct to indicate end of line; $ if
1336 missing."
1337 (format "%s%d%s%s" "^\\([~]\\{" num-tildes ",\\}\\)" (or end-of-line "$")))
1339 (defconst markdown-regex-tilde-fence-begin
1340 (markdown-make-tilde-fence-regex
1341 3 "[ ]?\\([^[:space:]]+\\|{[^}]*}\\)?\\([[:space:]]*?\\)$")
1342 "Regular expression for matching Pandoc tildes.")
1344 (defconst markdown-regex-declarative-metadata
1345 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1346 "Regular expression for matching declarative metadata statements.
1347 This matches MultiMarkdown metadata as well as YAML and TOML
1348 assignments such as the following:
1350 variable: value
1354 variable = value")
1356 (defconst markdown-regex-pandoc-metadata
1357 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1358 "Regular expression for matching Pandoc metadata.")
1360 (defconst markdown-regex-yaml-metadata-border
1361 "\\(-\\{3\\}\\)$"
1362 "Regular expression for matching yaml metadata.")
1364 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1365 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1366 "Regular expression for matching yaml metadata end borders.")
1368 (defsubst markdown-get-yaml-metadata-start-border ()
1369 "Return yaml metadata start border depending upon whether Pandoc is used."
1370 (concat
1371 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1372 markdown-regex-yaml-metadata-border))
1374 (defsubst markdown-get-yaml-metadata-end-border (_)
1375 "Return yaml metadata end border depending upon whether Pandoc is used."
1376 (if markdown-use-pandoc-style-yaml-metadata
1377 markdown-regex-yaml-pandoc-metadata-end-border
1378 markdown-regex-yaml-metadata-border))
1381 ;;; Syntax ====================================================================
1383 (defun markdown-syntax-propertize-extend-region (start end)
1384 "Extend START to END region to include an entire block of text.
1385 This helps improve syntax analysis for block constructs.
1386 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1387 Function is called repeatedly until it returns nil. For details, see
1388 `syntax-propertize-extend-region-functions'."
1389 (save-match-data
1390 (save-excursion
1391 (let* ((new-start (progn (goto-char start)
1392 (skip-chars-forward "\n")
1393 (if (re-search-backward "\n\n" nil t)
1394 (min start (match-end 0))
1395 (point-min))))
1396 (new-end (progn (goto-char end)
1397 (skip-chars-backward "\n")
1398 (if (re-search-forward "\n\n" nil t)
1399 (max end (match-beginning 0))
1400 (point-max))))
1401 (code-match (markdown-code-block-at-pos new-start))
1402 (new-start (or (and code-match (cl-first code-match)) new-start))
1403 (code-match (markdown-code-block-at-pos end))
1404 (new-end (or (and code-match (cl-second code-match)) new-end)))
1405 (unless (and (eq new-start start) (eq new-end end))
1406 (cons new-start (min new-end (point-max))))))))
1408 (defun markdown-font-lock-extend-region-function (start end _)
1409 "Used in `jit-lock-after-change-extend-region-functions'.
1410 Delegates to `markdown-syntax-propertize-extend-region'. START
1411 and END are the previous region to refontify."
1412 (let ((res (markdown-syntax-propertize-extend-region start end)))
1413 (when res
1414 (setq jit-lock-start (car res)
1415 jit-lock-end (cdr res)))))
1417 (defun markdown-syntax-propertize-pre-blocks (start end)
1418 "Match preformatted text blocks from START to END."
1419 (save-excursion
1420 (goto-char start)
1421 (let ((levels (markdown-calculate-list-levels))
1422 indent pre-regexp close-regexp open close)
1423 (while (and (< (point) end) (not close))
1424 ;; Search for a region with sufficient indentation
1425 (if (null levels)
1426 (setq indent 1)
1427 (setq indent (1+ (length levels))))
1428 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1429 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1431 (cond
1432 ;; If not at the beginning of a line, move forward
1433 ((not (bolp)) (forward-line))
1434 ;; Move past blank lines
1435 ((markdown-cur-line-blank-p) (forward-line))
1436 ;; At headers and horizontal rules, reset levels
1437 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1438 ;; If the current line has sufficient indentation, mark out pre block
1439 ;; The opening should be preceded by a blank line.
1440 ((and (looking-at pre-regexp)
1441 (save-match-data (markdown-prev-line-blank-p)))
1442 (setq open (match-beginning 0))
1443 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
1444 (not (eobp)))
1445 (forward-line))
1446 (skip-syntax-backward "-")
1447 (setq close (point)))
1448 ;; If current line has a list marker, update levels, move to end of block
1449 ((looking-at markdown-regex-list)
1450 (setq levels (markdown-update-list-levels
1451 (match-string 2) (current-indentation) levels))
1452 (markdown-end-of-block-element))
1453 ;; If this is the end of the indentation level, adjust levels accordingly.
1454 ;; Only match end of indentation level if levels is not the empty list.
1455 ((and (car levels) (looking-at-p close-regexp))
1456 (setq levels (markdown-update-list-levels
1457 nil (current-indentation) levels))
1458 (markdown-end-of-block-element))
1459 (t (markdown-end-of-block-element))))
1461 (when (and open close)
1462 ;; Set text property data
1463 (put-text-property open close 'markdown-pre (list open close))
1464 ;; Recursively search again
1465 (markdown-syntax-propertize-pre-blocks (point) end)))))
1467 (defconst markdown-fenced-block-pairs
1468 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1469 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1470 markdown-fenced-code)
1471 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1472 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1473 markdown-yaml-metadata-section)
1474 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1475 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1476 markdown-gfm-code))
1477 "Mapping of regular expressions to \"fenced-block\" constructs.
1478 These constructs are distinguished by having a distinctive start
1479 and end pattern, both of which take up an entire line of text,
1480 but no special pattern to identify text within the fenced
1481 blocks (unlike blockquotes and indented-code sections).
1483 Each element within this list takes the form:
1485 ((START-REGEX-OR-FUN START-PROPERTY)
1486 (END-REGEX-OR-FUN END-PROPERTY)
1487 MIDDLE-PROPERTY)
1489 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1490 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1491 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1492 which is the length of the first group of the START-REGEX-OR-FUN match, which
1493 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1494 evaluate these into \"real\" regexps.
1496 The *-PROPERTY elements are the text properties applied to each part of the
1497 block construct when it is matched using
1498 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1499 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1500 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1501 `match-data' when the regexp was matched to the text. In the case of
1502 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1503 begin and end set to the edges of the \"middle\" text. This makes fontification
1504 easier.")
1506 (defun markdown-text-property-at-point (prop)
1507 (get-text-property (point) prop))
1509 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1510 (cond ((functionp object)
1511 (if arg (funcall object arg) (funcall object)))
1512 ((stringp object) object)
1513 (t (error "Object cannot be turned into regex"))))
1515 (defsubst markdown-get-start-fence-regexp ()
1516 "Return regexp to find all \"start\" sections of fenced block constructs.
1517 Which construct is actually contained in the match must be found separately."
1518 (mapconcat
1519 #'identity
1520 ;; FIXME: Why `cl-mapcar' rather than `mapcar'?
1521 (cl-mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1522 markdown-fenced-block-pairs)
1523 "\\|"))
1525 (defun markdown-get-fenced-block-begin-properties ()
1526 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1528 (defun markdown-get-fenced-block-end-properties ()
1529 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1531 (defun markdown-get-fenced-block-middle-properties ()
1532 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1534 (defun markdown-find-previous-prop (prop &optional lim)
1535 "Find previous place where property PROP is non-nil, up to LIM.
1536 Return a cons of (pos . property). pos is point if point contains
1537 non-nil PROP."
1538 (let ((res
1539 (if (get-text-property (point) prop) (point)
1540 (previous-single-property-change
1541 (point) prop nil (or lim (point-min))))))
1542 (when (and (not (get-text-property res prop))
1543 (> res (point-min))
1544 (get-text-property (1- res) prop))
1545 (cl-decf res))
1546 (when (and res (get-text-property res prop)) (cons res prop))))
1548 (defun markdown-find-next-prop (prop &optional lim)
1549 "Find next place where property PROP is non-nil, up to LIM.
1550 Return a cons of (POS . PROPERTY) where POS is point if point
1551 contains non-nil PROP."
1552 (let ((res
1553 (if (get-text-property (point) prop) (point)
1554 (next-single-property-change
1555 (point) prop nil (or lim (point-max))))))
1556 (when (and res (get-text-property res prop)) (cons res prop))))
1558 (defun markdown-min-of-seq (map-fn seq)
1559 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1560 (cl-loop for el in seq
1561 with min = 1.0e+INF ; infinity
1562 with min-el = nil
1563 do (let ((res (funcall map-fn el)))
1564 (when (< res min)
1565 (setq min res)
1566 (setq min-el el)))
1567 finally return min-el))
1569 (defun markdown-find-previous-block ()
1570 "Find previous block.
1571 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1572 unable to propertize the entire block, but was able to propertize the beginning
1573 of the block. If so, return a cons of (pos . property) where the beginning of
1574 the block was propertized."
1575 (let ((start-pt (point))
1576 (closest-open
1577 (markdown-min-of-seq
1578 #'car
1579 (cl-remove-if
1580 #'null
1581 (cl-mapcar
1582 #'markdown-find-previous-prop
1583 (markdown-get-fenced-block-begin-properties))))))
1584 (when closest-open
1585 (let* ((length-of-open-match
1586 (let ((match-d
1587 (get-text-property (car closest-open) (cdr closest-open))))
1588 (- (cl-fourth match-d) (cl-third match-d))))
1589 (end-regexp
1590 (markdown-maybe-funcall-regexp
1591 (cl-caadr
1592 (cl-find-if
1593 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1594 markdown-fenced-block-pairs))
1595 length-of-open-match))
1596 (end-prop-loc
1597 (save-excursion
1598 (save-match-data
1599 (goto-char (car closest-open))
1600 (and (re-search-forward end-regexp start-pt t)
1601 (match-beginning 0))))))
1602 (and (not end-prop-loc) closest-open)))))
1604 (defun markdown-get-fenced-block-from-start (prop)
1605 "Return limits of an enclosing fenced block from its start, using PROP.
1606 Return value is a list usable as `match-data'."
1607 (catch 'no-rest-of-block
1608 (let* ((correct-entry
1609 (cl-find-if
1610 (lambda (entry) (eq (cl-cadar entry) prop))
1611 markdown-fenced-block-pairs))
1612 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
1613 (middle-prop (cl-third correct-entry))
1614 (end-prop (cl-cadadr correct-entry))
1615 (end-of-end
1616 (save-excursion
1617 (goto-char (match-end 0)) ; end of begin
1618 (unless (eobp) (forward-char))
1619 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1620 (if (not mid-prop-v) ; no middle
1621 (progn
1622 ;; try to find end by advancing one
1623 (let ((end-prop-v
1624 (markdown-text-property-at-point end-prop)))
1625 (if end-prop-v (cl-second end-prop-v)
1626 (throw 'no-rest-of-block nil))))
1627 (set-match-data mid-prop-v)
1628 (goto-char (match-end 0)) ; end of middle
1629 (beginning-of-line) ; into end
1630 (cl-second (markdown-text-property-at-point end-prop)))))))
1631 (list begin-of-begin end-of-end))))
1633 (defun markdown-get-fenced-block-from-middle (prop)
1634 "Return limits of an enclosing fenced block from its middle, using PROP.
1635 Return value is a list usable as `match-data'."
1636 (let* ((correct-entry
1637 (cl-find-if
1638 (lambda (entry) (eq (cl-third entry) prop))
1639 markdown-fenced-block-pairs))
1640 (begin-prop (cl-cadar correct-entry))
1641 (begin-of-begin
1642 (save-excursion
1643 (goto-char (match-beginning 0))
1644 (unless (bobp) (forward-line -1))
1645 (beginning-of-line)
1646 (cl-first (markdown-text-property-at-point begin-prop))))
1647 (end-prop (cl-cadadr correct-entry))
1648 (end-of-end
1649 (save-excursion
1650 (goto-char (match-end 0))
1651 (beginning-of-line)
1652 (cl-second (markdown-text-property-at-point end-prop)))))
1653 (list begin-of-begin end-of-end)))
1655 (defun markdown-get-fenced-block-from-end (prop)
1656 "Return limits of an enclosing fenced block from its end, using PROP.
1657 Return value is a list usable as `match-data'."
1658 (let* ((correct-entry
1659 (cl-find-if
1660 (lambda (entry) (eq (cl-cadadr entry) prop))
1661 markdown-fenced-block-pairs))
1662 (end-of-end (cl-second (markdown-text-property-at-point prop)))
1663 (middle-prop (cl-third correct-entry))
1664 (begin-prop (cl-cadar correct-entry))
1665 (begin-of-begin
1666 (save-excursion
1667 (goto-char (match-beginning 0)) ; beginning of end
1668 (unless (bobp) (backward-char)) ; into middle
1669 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
1670 (if (not mid-prop-v)
1671 (progn
1672 (beginning-of-line)
1673 (cl-first (markdown-text-property-at-point begin-prop)))
1674 (set-match-data mid-prop-v)
1675 (goto-char (match-beginning 0)) ; beginning of middle
1676 (unless (bobp) (forward-line -1)) ; into beginning
1677 (beginning-of-line)
1678 (cl-first (markdown-text-property-at-point begin-prop)))))))
1679 (list begin-of-begin end-of-end)))
1681 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
1682 "Get \"fake\" match data for block enclosing POS.
1683 Returns fake match data which encloses the start, middle, and end
1684 of the block construct enclosing POS, if it exists. Used in
1685 `markdown-code-block-at-pos'."
1686 (save-excursion
1687 (when pos (goto-char pos))
1688 (beginning-of-line)
1689 (car
1690 (cl-remove-if
1691 #'null
1692 (cl-mapcar
1693 (lambda (fun-and-prop)
1694 (cl-destructuring-bind (fun prop) fun-and-prop
1695 (when prop
1696 (save-match-data
1697 (set-match-data (markdown-text-property-at-point prop))
1698 (funcall fun prop)))))
1699 `((markdown-get-fenced-block-from-start
1700 ,(cl-find-if
1701 #'markdown-text-property-at-point
1702 (markdown-get-fenced-block-begin-properties)))
1703 (markdown-get-fenced-block-from-middle
1704 ,(cl-find-if
1705 #'markdown-text-property-at-point
1706 (markdown-get-fenced-block-middle-properties)))
1707 (markdown-get-fenced-block-from-end
1708 ,(cl-find-if
1709 #'markdown-text-property-at-point
1710 (markdown-get-fenced-block-end-properties)))))))))
1712 (defun markdown-propertize-end-match (reg end correct-entry enclosed-text-start)
1713 "Get match for REG up to END, if exists, and propertize appropriately.
1714 CORRECT-ENTRY is an entry in `markdown-fenced-block-pairs' and
1715 ENCLOSED-TEXT-START is the start of the \"middle\" section of the block."
1716 (when (re-search-forward reg end t)
1717 (put-text-property (match-beginning 0) (match-end 0)
1718 (cl-cadadr correct-entry) (match-data t))
1719 (put-text-property
1720 enclosed-text-start (match-beginning 0) (cl-third correct-entry)
1721 (list enclosed-text-start (match-beginning 0)))))
1723 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
1724 "Propertize according to `markdown-fenced-block-pairs' from START to END.
1725 If unable to propertize an entire block (if the start of a block is within START
1726 and END, but the end of the block is not), propertize the start section of a
1727 block, then in a subsequent call propertize both middle and end by finding the
1728 start which was previously propertized."
1729 (let ((start-reg (markdown-get-start-fence-regexp)))
1730 (save-excursion
1731 (goto-char start)
1732 ;; start from previous unclosed block, if exists
1733 (let ((prev-begin-block (markdown-find-previous-block)))
1734 (when prev-begin-block
1735 (let* ((correct-entry
1736 (cl-find-if (lambda (entry)
1737 (eq (cdr prev-begin-block) (cl-cadar entry)))
1738 markdown-fenced-block-pairs))
1739 (enclosed-text-start (1+ (car prev-begin-block)))
1740 (start-length
1741 (save-excursion
1742 (goto-char (car prev-begin-block))
1743 (string-match
1744 (markdown-maybe-funcall-regexp
1745 (caar correct-entry))
1746 (buffer-substring
1747 (point-at-bol) (point-at-eol)))
1748 (- (match-end 1) (match-beginning 1))))
1749 (end-reg (markdown-maybe-funcall-regexp
1750 (cl-caadr correct-entry) start-length)))
1751 (markdown-propertize-end-match
1752 end-reg end correct-entry enclosed-text-start))))
1753 ;; find all new blocks within region
1754 (while (re-search-forward start-reg end t)
1755 ;; we assume the opening constructs take up (only) an entire line,
1756 ;; so we re-check the current line
1757 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
1758 ;; find entry in `markdown-fenced-block-pairs' corresponding
1759 ;; to regex which was matched
1760 (correct-entry
1761 (cl-find-if
1762 (lambda (fenced-pair)
1763 (string-match-p
1764 (markdown-maybe-funcall-regexp (caar fenced-pair))
1765 cur-line))
1766 markdown-fenced-block-pairs))
1767 (enclosed-text-start
1768 (save-excursion (1+ (point-at-eol))))
1769 (end-reg
1770 (markdown-maybe-funcall-regexp
1771 (cl-caadr correct-entry)
1772 (if (and (match-beginning 1) (match-end 1))
1773 (- (match-end 1) (match-beginning 1))
1774 0))))
1775 ;; get correct match data
1776 (save-excursion
1777 (beginning-of-line)
1778 (re-search-forward
1779 (markdown-maybe-funcall-regexp (caar correct-entry))
1780 (point-at-eol)))
1781 ;; mark starting, even if ending is outside of region
1782 (put-text-property (match-beginning 0) (match-end 0)
1783 (cl-cadar correct-entry) (match-data t))
1784 (markdown-propertize-end-match
1785 end-reg end correct-entry enclosed-text-start))))))
1787 (defun markdown-syntax-propertize-blockquotes (start end)
1788 "Match blockquotes from START to END."
1789 (save-excursion
1790 (goto-char start)
1791 (while (and (re-search-forward markdown-regex-blockquote end t)
1792 (not (markdown-code-block-at-pos (match-beginning 0))))
1793 (put-text-property (match-beginning 0) (match-end 0)
1794 'markdown-blockquote
1795 (match-data t)))))
1797 (defun markdown-syntax-propertize-yaml-metadata (start end)
1798 (save-excursion
1799 (goto-char start)
1800 (cl-loop
1801 while (re-search-forward markdown-regex-declarative-metadata end t)
1802 do (when (get-text-property (match-beginning 0)
1803 'markdown-yaml-metadata-section)
1804 (put-text-property (match-beginning 1) (match-end 1)
1805 'markdown-metadata-key (match-data t))
1806 (put-text-property (match-beginning 2) (match-end 2)
1807 'markdown-metadata-markup (match-data t))
1808 (put-text-property (match-beginning 3) (match-end 3)
1809 'markdown-metadata-value (match-data t))))))
1811 (defun markdown-syntax-propertize-headings (start end)
1812 "Match headings of type SYMBOL with REGEX from START to END."
1813 (goto-char start)
1814 (while (re-search-forward markdown-regex-header end t)
1815 (unless (markdown-code-block-at-pos (match-beginning 0))
1816 (put-text-property
1817 (match-beginning 0) (match-end 0) 'markdown-heading t)
1818 (put-text-property
1819 (match-beginning 0) (match-end 0)
1820 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
1821 ((match-string-no-properties 3) 'markdown-heading-2-setext)
1822 (t (let ((atx-level (length (match-string-no-properties 4))))
1823 (intern (format "markdown-heading-%d-atx" atx-level)))))
1824 (match-data t)))))
1826 (defun markdown-syntax-propertize-comments (start end)
1827 "Match HTML comments from the START to END."
1828 (let* ((state (syntax-ppss)) (in-comment (nth 4 state)))
1829 (goto-char start)
1830 (cond
1831 ;; Comment start
1832 ((and (not in-comment)
1833 (re-search-forward markdown-regex-comment-start end t)
1834 (save-match-data (not (markdown-code-at-point-p)))
1835 (save-match-data (not (markdown-code-block-at-point))))
1836 (let ((open-beg (match-beginning 0)))
1837 (put-text-property open-beg (1+ open-beg)
1838 'syntax-table (string-to-syntax "<"))
1839 (markdown-syntax-propertize-comments
1840 (min (1+ (match-end 0)) end (point-max)) end)))
1841 ;; Comment end
1842 ((and in-comment
1843 (re-search-forward markdown-regex-comment-end end t))
1844 (put-text-property (1- (match-end 0)) (match-end 0)
1845 'syntax-table (string-to-syntax ">"))
1846 (markdown-syntax-propertize-comments
1847 (min (1+ (match-end 0)) end (point-max)) end))
1848 ;; Nothing found
1849 (t nil))))
1851 (defvar markdown--syntax-properties
1852 (list 'markdown-tilde-fence-begin nil
1853 'markdown-tilde-fence-end nil
1854 'markdown-fenced-code nil
1855 'markdown-yaml-metadata-begin nil
1856 'markdown-yaml-metadata-end nil
1857 'markdown-yaml-metadata-section nil
1858 'markdown-gfm-block-begin nil
1859 'markdown-gfm-block-end nil
1860 'markdown-gfm-code nil
1861 'markdown-pre nil
1862 'markdown-blockquote nil
1863 'markdown-heading nil
1864 'markdown-heading-1-setext nil
1865 'markdown-heading-2-setext nil
1866 'markdown-heading-1-atx nil
1867 'markdown-heading-2-atx nil
1868 'markdown-heading-3-atx nil
1869 'markdown-heading-4-atx nil
1870 'markdown-heading-5-atx nil
1871 'markdown-heading-6-atx nil
1872 'markdown-metadata-key nil
1873 'markdown-metadata-value nil
1874 'markdown-metadata-markup nil)
1875 "Property list of all known markdown syntactic properties.")
1877 (defun markdown-syntax-propertize (start end)
1878 "Function used as `syntax-propertize-function'.
1879 START and END delimit region to propertize."
1880 (remove-text-properties start end markdown--syntax-properties)
1881 (markdown-syntax-propertize-fenced-block-constructs start end)
1882 (markdown-syntax-propertize-yaml-metadata start end)
1883 (markdown-syntax-propertize-pre-blocks start end)
1884 (markdown-syntax-propertize-blockquotes start end)
1885 (markdown-syntax-propertize-headings start end)
1886 (markdown-syntax-propertize-comments start end))
1889 ;;; Font Lock =================================================================
1891 (require 'font-lock)
1893 (defvar markdown-italic-face 'markdown-italic-face
1894 "Face name to use for italic text.")
1896 (defvar markdown-bold-face 'markdown-bold-face
1897 "Face name to use for bold text.")
1899 (defvar markdown-strike-through-face 'markdown-strike-through-face
1900 "Face name to use for strike-through text.")
1902 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1903 "Face name to use as a base for header delimiters.")
1905 (defvar markdown-header-rule-face 'markdown-header-rule-face
1906 "Face name to use as a base for header rules.")
1908 (defvar markdown-header-face 'markdown-header-face
1909 "Face name to use as a base for headers.")
1911 (defvar markdown-header-face-1 'markdown-header-face-1
1912 "Face name to use for level-1 headers.")
1914 (defvar markdown-header-face-2 'markdown-header-face-2
1915 "Face name to use for level-2 headers.")
1917 (defvar markdown-header-face-3 'markdown-header-face-3
1918 "Face name to use for level-3 headers.")
1920 (defvar markdown-header-face-4 'markdown-header-face-4
1921 "Face name to use for level-4 headers.")
1923 (defvar markdown-header-face-5 'markdown-header-face-5
1924 "Face name to use for level-5 headers.")
1926 (defvar markdown-header-face-6 'markdown-header-face-6
1927 "Face name to use for level-6 headers.")
1929 (defvar markdown-inline-code-face 'markdown-inline-code-face
1930 "Face name to use for inline code.")
1932 (defvar markdown-list-face 'markdown-list-face
1933 "Face name to use for list markers.")
1935 (defvar markdown-blockquote-face 'markdown-blockquote-face
1936 "Face name to use for blockquote.")
1938 (defvar markdown-pre-face 'markdown-pre-face
1939 "Face name to use for preformatted text.")
1941 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1942 "Face name to use for programming language identifiers.")
1944 (defvar markdown-link-face 'markdown-link-face
1945 "Face name to use for links.")
1947 (defvar markdown-missing-link-face 'markdown-missing-link-face
1948 "Face name to use for links where the linked file does not exist.")
1950 (defvar markdown-reference-face 'markdown-reference-face
1951 "Face name to use for reference.")
1953 (defvar markdown-footnote-face 'markdown-footnote-face
1954 "Face name to use for footnote identifiers.")
1956 (defvar markdown-url-face 'markdown-url-face
1957 "Face name to use for URLs.")
1959 (defvar markdown-link-title-face 'markdown-link-title-face
1960 "Face name to use for reference link titles.")
1962 (defvar markdown-line-break-face 'markdown-line-break-face
1963 "Face name to use for hard line breaks.")
1965 (defvar markdown-comment-face 'markdown-comment-face
1966 "Face name to use for HTML comments.")
1968 (defvar markdown-math-face 'markdown-math-face
1969 "Face name to use for LaTeX expressions.")
1971 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
1972 "Face name to use for metadata keys.")
1974 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
1975 "Face name to use for metadata values.")
1977 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
1978 "Face name to use for GFM checkboxes.")
1980 (defvar markdown-highlight-face 'markdown-highlight-face
1981 "Face name to use for mouse highlighting.")
1983 (defvar markdown-markup-face 'markdown-markup-face
1984 "Face name to use for markup elements.")
1986 (defgroup markdown-faces nil
1987 "Faces used in Markdown Mode"
1988 :group 'markdown
1989 :group 'faces)
1991 (defface markdown-italic-face
1992 '((t (:inherit font-lock-variable-name-face :slant italic :weight normal)))
1993 "Face for italic text."
1994 :group 'markdown-faces)
1996 (defface markdown-bold-face
1997 '((t (:inherit font-lock-variable-name-face :weight bold :slant normal)))
1998 "Face for bold text."
1999 :group 'markdown-faces)
2001 (defface markdown-strike-through-face
2002 '((t (:inherit font-lock-variable-name-face :strike-through t)))
2003 "Face for strike-through text."
2004 :group 'markdown-faces)
2006 (defface markdown-markup-face
2007 '((t (:inherit shadow :slant normal :weight normal)))
2008 "Face for markup elements."
2009 :group 'markdown-faces)
2011 (defface markdown-header-rule-face
2012 '((t (:inherit markdown-markup-face)))
2013 "Base face for headers rules."
2014 :group 'markdown-faces)
2016 (defface markdown-header-delimiter-face
2017 '((t (:inherit markdown-markup-face)))
2018 "Base face for headers hash delimiter."
2019 :group 'markdown-faces)
2021 (defface markdown-inline-code-face
2022 '((t (:inherit font-lock-constant-face)))
2023 "Face for inline code."
2024 :group 'markdown-faces)
2026 (defface markdown-list-face
2027 '((t (:inherit markdown-markup-face)))
2028 "Face for list item markers."
2029 :group 'markdown-faces)
2031 (defface markdown-blockquote-face
2032 '((t (:inherit font-lock-doc-face)))
2033 "Face for blockquote sections."
2034 :group 'markdown-faces)
2036 (defface markdown-pre-face
2037 '((t (:inherit font-lock-constant-face)))
2038 "Face for preformatted text."
2039 :group 'markdown-faces)
2041 (defface markdown-language-keyword-face
2042 '((t (:inherit font-lock-type-face)))
2043 "Face for programming language identifiers."
2044 :group 'markdown-faces)
2046 (defface markdown-link-face
2047 '((t (:inherit font-lock-keyword-face)))
2048 "Face for links."
2049 :group 'markdown-faces)
2051 (defface markdown-missing-link-face
2052 '((t (:inherit font-lock-warning-face)))
2053 "Face for missing links."
2054 :group 'markdown-faces)
2056 (defface markdown-reference-face
2057 '((t (:inherit markdown-markup-face)))
2058 "Face for link references."
2059 :group 'markdown-faces)
2061 (defface markdown-footnote-face
2062 '((t (:inherit markdown-markup-face)))
2063 "Face for footnote markers."
2064 :group 'markdown-faces)
2066 (defface markdown-url-face
2067 '((t (:inherit font-lock-string-face)))
2068 "Face for URLs."
2069 :group 'markdown-faces)
2071 (defface markdown-link-title-face
2072 '((t (:inherit font-lock-comment-face)))
2073 "Face for reference link titles."
2074 :group 'markdown-faces)
2076 (defface markdown-line-break-face
2077 '((t (:inherit font-lock-constant-face :underline t)))
2078 "Face for hard line breaks."
2079 :group 'markdown-faces)
2081 (defface markdown-comment-face
2082 '((t (:inherit font-lock-comment-face)))
2083 "Face for HTML comments."
2084 :group 'markdown-faces)
2086 (defface markdown-math-face
2087 '((t (:inherit font-lock-string-face)))
2088 "Face for LaTeX expressions."
2089 :group 'markdown-faces)
2091 (defface markdown-metadata-key-face
2092 '((t (:inherit font-lock-variable-name-face)))
2093 "Face for metadata keys."
2094 :group 'markdown-faces)
2096 (defface markdown-metadata-value-face
2097 '((t (:inherit font-lock-string-face)))
2098 "Face for metadata values."
2099 :group 'markdown-faces)
2101 (defface markdown-gfm-checkbox-face
2102 '((t (:inherit font-lock-builtin-face)))
2103 "Face for GFM checkboxes."
2104 :group 'markdown-faces)
2106 (defface markdown-highlight-face
2107 '((t (:inherit highlight)))
2108 "Face for mouse highlighting."
2109 :group 'markdown-faces)
2111 (defcustom markdown-header-scaling nil
2112 "Whether to use variable-height faces for headers.
2113 When non-nil, `markdown-header-face' will inherit from
2114 `variable-pitch' and the scaling values in
2115 `markdown-header-scaling-values' will be applied to
2116 headers of levels one through six respectively."
2117 :type 'boolean
2118 :initialize 'custom-initialize-default
2119 :set (lambda (symbol value)
2120 (set-default symbol value)
2121 (markdown-update-header-faces value))
2122 :group 'markdown-faces)
2124 (defcustom markdown-header-scaling-values
2125 '(1.8 1.4 1.2 1.0 1.0 1.0)
2126 "List of scaling values for headers of level one through six.
2127 Used when `markdown-header-scaling' is non-nil."
2128 :type 'list
2129 :initialize 'custom-initialize-default
2130 :set (lambda (symbol value)
2131 (set-default symbol value)
2132 (markdown-update-header-faces markdown-header-scaling value))
2133 :group 'markdown-faces)
2135 (defun markdown-make-header-faces ()
2136 "Build the faces used for Markdown headers."
2137 (defface markdown-header-face
2138 `((t (:inherit (,(when markdown-header-scaling 'variable-pitch)
2139 font-lock-function-name-face)
2140 :weight bold)))
2141 "Base face for headers."
2142 :group 'markdown-faces)
2143 (dotimes (num 6)
2144 (let* ((num1 (1+ num))
2145 (face-name (intern (format "markdown-header-face-%s" num1)))
2146 (scale (if markdown-header-scaling
2147 (float (nth num markdown-header-scaling-values))
2148 1.0)))
2149 (eval
2150 `(defface ,face-name
2151 '((t (:inherit markdown-header-face :height ,scale)))
2152 (format "Face for level %s headers.
2154 You probably don't want to customize this face directly. Instead
2155 you can customize the base face `markdown-header-face' or the
2156 variable-height variable `markdown-header-scaling'." ,num1)
2157 :group 'markdown-faces)))))
2159 (markdown-make-header-faces)
2161 (defun markdown-update-header-faces (&optional scaling scaling-values)
2162 "Update header faces, depending on if header SCALING is desired.
2163 If so, use given list of SCALING-VALUES relative to the baseline
2164 size of `markdown-header-face'."
2165 (dotimes (num 6)
2166 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2167 (scale (cond ((not scaling) 1.0)
2168 (scaling-values (float (nth num scaling-values)))
2169 (t (float (nth num markdown-header-scaling-values))))))
2170 (unless (get face-name 'saved-face) ; Don't update customized faces
2171 (set-face-attribute face-name nil :height scale)))))
2173 (defun markdown-syntactic-face (state)
2174 "Return font-lock face for characters with given STATE.
2175 See `font-lock-syntactic-face-function' for details."
2176 (let ((in-comment (nth 4 state)))
2177 (cond
2178 (in-comment 'markdown-comment-face)
2179 (t nil))))
2181 (defvar markdown-mode-font-lock-keywords-basic
2182 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2183 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2184 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2185 (2 markdown-markup-face)
2186 (3 markdown-metadata-value-face)))
2187 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-face)
2188 (2 markdown-language-keyword-face nil t)))
2189 (markdown-match-gfm-close-code-blocks . ((1 markdown-markup-face)))
2190 (markdown-match-gfm-code-blocks . ((0 markdown-pre-face)))
2191 (markdown-match-fenced-start-code-block . ((1 markdown-markup-face)
2192 (2 markdown-language-keyword-face nil t)))
2193 (markdown-match-fenced-end-code-block . ((0 markdown-markup-face)))
2194 (markdown-match-fenced-code-blocks . ((0 markdown-pre-face)))
2195 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2196 (markdown-match-blockquotes . ((1 markdown-markup-face)
2197 (2 markdown-blockquote-face)))
2198 (markdown-match-heading-1-setext . ((1 markdown-header-face-1)
2199 (2 markdown-header-rule-face)))
2200 (markdown-match-heading-2-setext . ((1 markdown-header-face-2)
2201 (3 markdown-header-rule-face)))
2202 (markdown-match-heading-6-atx . ((4 markdown-header-delimiter-face)
2203 (5 markdown-header-face-6)
2204 (6 markdown-header-delimiter-face)))
2205 (markdown-match-heading-5-atx . ((4 markdown-header-delimiter-face)
2206 (5 markdown-header-face-5)
2207 (6 markdown-header-delimiter-face)))
2208 (markdown-match-heading-4-atx . ((4 markdown-header-delimiter-face)
2209 (5 markdown-header-face-4)
2210 (6 markdown-header-delimiter-face)))
2211 (markdown-match-heading-3-atx . ((4 markdown-header-delimiter-face)
2212 (5 markdown-header-face-3)
2213 (6 markdown-header-delimiter-face)))
2214 (markdown-match-heading-2-atx . ((4 markdown-header-delimiter-face)
2215 (5 markdown-header-face-2)
2216 (6 markdown-header-delimiter-face)))
2217 (markdown-match-heading-1-atx . ((4 markdown-header-delimiter-face)
2218 (5 markdown-header-face-1)
2219 (6 markdown-header-delimiter-face)))
2220 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2221 (2 markdown-markup-face)
2222 (3 markdown-metadata-value-face)))
2223 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2224 (2 markdown-markup-face)
2225 (3 markdown-metadata-value-face)))
2226 (markdown-match-hr . markdown-header-delimiter-face)
2227 (markdown-match-code . ((1 markdown-markup-face)
2228 (2 markdown-inline-code-face)
2229 (3 markdown-markup-face)))
2230 (,markdown-regex-kbd . ((1 markdown-markup-face)
2231 (2 markdown-inline-code-face)
2232 (3 markdown-markup-face)))
2233 (,markdown-regex-angle-uri . ((1 markdown-markup-face)
2234 (2 markdown-link-face)
2235 (3 markdown-markup-face)))
2236 (,markdown-regex-list . (2 markdown-list-face))
2237 (,markdown-regex-footnote . ((1 markdown-markup-face) ; [^
2238 (2 markdown-footnote-face) ; label
2239 (3 markdown-markup-face))) ; ]
2240 (,markdown-regex-link-inline . ((1 markdown-markup-face nil t) ; ! (optional)
2241 (2 markdown-markup-face) ; [
2242 (3 markdown-link-face) ; text
2243 (4 markdown-markup-face) ; ]
2244 (5 markdown-markup-face) ; (
2245 (6 markdown-url-face) ; url
2246 (7 markdown-link-title-face nil t) ; "title" (optional)
2247 (8 markdown-markup-face))) ; )
2248 (,markdown-regex-link-reference . ((1 markdown-markup-face nil t) ; ! (optional)
2249 (2 markdown-markup-face) ; [
2250 (3 markdown-link-face) ; text
2251 (4 markdown-markup-face) ; ]
2252 (5 markdown-markup-face) ; [
2253 (6 markdown-reference-face) ; label
2254 (7 markdown-markup-face))) ; ]
2255 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2256 (2 markdown-reference-face) ; label
2257 (3 markdown-markup-face) ; ]
2258 (4 markdown-markup-face) ; :
2259 (5 markdown-url-face) ; url
2260 (6 markdown-link-title-face))) ; "title" (optional)
2261 ;; Math mode $..$
2262 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2263 (2 markdown-math-face append)
2264 (3 markdown-markup-face prepend)))
2265 ;; Math mode $$..$$
2266 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2267 (2 markdown-math-face append)
2268 (3 markdown-markup-face prepend)))
2269 (markdown-match-bold . ((1 markdown-markup-face prepend)
2270 (2 markdown-bold-face append)
2271 (3 markdown-markup-face prepend)))
2272 (markdown-match-italic . ((1 markdown-markup-face prepend)
2273 (2 markdown-italic-face append)
2274 (3 markdown-markup-face prepend)))
2275 (,markdown-regex-uri . markdown-link-face)
2276 (,markdown-regex-email . markdown-link-face)
2277 (,markdown-regex-line-break . (1 markdown-line-break-face prepend)))
2279 "Syntax highlighting for Markdown files.")
2281 (defvar markdown-mode-font-lock-keywords nil
2282 "Default highlighting expressions for Markdown mode.
2283 This variable is defined as a buffer-local variable for dynamic
2284 extension support.")
2286 ;; Footnotes
2287 (defvar markdown-footnote-counter 0
2288 "Counter for footnote numbers.")
2289 (make-variable-buffer-local 'markdown-footnote-counter)
2291 (defconst markdown-footnote-chars
2292 "[[:alnum:]-]"
2293 "Regular expression matching any character that is allowed in a footnote identifier.")
2295 (defconst markdown-regex-footnote-definition
2296 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2297 "Regular expression matching a footnote definition, capturing the label.")
2300 ;;; Compatibility =============================================================
2302 (defun markdown-replace-regexp-in-string (regexp rep string)
2303 "Replace ocurrences of REGEXP with REP in STRING.
2304 This is a compatibility wrapper to provide `replace-regexp-in-string'
2305 in XEmacs 21."
2306 (if (featurep 'xemacs)
2307 (replace-in-string string regexp rep)
2308 (replace-regexp-in-string regexp rep string)))
2310 ;; `markdown-use-region-p' is a compatibility function which checks
2311 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2312 (eval-and-compile
2313 (cond
2314 ;; Emacs 24 and newer
2315 ((fboundp 'use-region-p)
2316 (defalias 'markdown-use-region-p 'use-region-p))
2317 ;; XEmacs
2318 ((fboundp 'region-active-p)
2319 (defalias 'markdown-use-region-p 'region-active-p))))
2321 (defun markdown-use-buttons-p ()
2322 "Determine whether this Emacs supports buttons."
2323 (or (featurep 'button) (locate-library "button")))
2325 ;; Use new names for outline-mode functions in Emacs 25 and later.
2326 (eval-and-compile
2327 (defalias 'markdown-hide-sublevels
2328 (if (fboundp 'outline-hide-sublevels)
2329 'outline-hide-sublevels
2330 'hide-sublevels))
2331 (defalias 'markdown-show-all
2332 (if (fboundp 'outline-show-all)
2333 'outline-show-all
2334 'show-all))
2335 (defalias 'markdown-hide-body
2336 (if (fboundp 'outline-hide-body)
2337 'outline-hide-body
2338 'hide-body))
2339 (defalias 'markdown-show-children
2340 (if (fboundp 'outline-show-children)
2341 'outline-show-children
2342 'show-children))
2343 (defalias 'markdown-show-subtree
2344 (if (fboundp 'outline-show-subtree)
2345 'outline-show-subtree
2346 'show-subtree))
2347 (defalias 'markdown-hide-subtree
2348 (if (fboundp 'outline-hide-subtree)
2349 'outline-hide-subtree
2350 'hide-subtree)))
2353 ;;; Markdown Parsing Functions ================================================
2355 (defun markdown-cur-line-blank-p ()
2356 "Return t if the current line is blank and nil otherwise."
2357 (save-excursion
2358 (beginning-of-line)
2359 (looking-at-p "^\\s *$")))
2361 (defun markdown-prev-line-blank-p ()
2362 "Return t if the previous line is blank and nil otherwise.
2363 If we are at the first line, then consider the previous line to be blank."
2364 (or (= (line-beginning-position) (point-min))
2365 (save-excursion
2366 (forward-line -1)
2367 (markdown-cur-line-blank-p))))
2369 (defun markdown-next-line-blank-p ()
2370 "Return t if the next line is blank and nil otherwise.
2371 If we are at the last line, then consider the next line to be blank."
2372 (or (= (line-end-position) (point-max))
2373 (save-excursion
2374 (forward-line 1)
2375 (markdown-cur-line-blank-p))))
2377 (defun markdown-prev-line-indent ()
2378 "Return the number of leading whitespace characters in the previous line.
2379 Return 0 if the current line is the first line in the buffer."
2380 (save-excursion
2381 (if (= (line-beginning-position) (point-min))
2383 (forward-line -1)
2384 (current-indentation))))
2386 (defun markdown-next-line-indent ()
2387 "Return the number of leading whitespace characters in the next line.
2388 Return 0 if line is the last line in the buffer."
2389 (save-excursion
2390 (if (= (line-end-position) (point-max))
2392 (forward-line 1)
2393 (current-indentation))))
2395 (defun markdown-cur-non-list-indent ()
2396 "Return beginning position of list item text (not including the list marker).
2397 Return nil if the current line is not the beginning of a list item."
2398 (save-match-data
2399 (save-excursion
2400 (beginning-of-line)
2401 (when (re-search-forward markdown-regex-list (line-end-position) t)
2402 (current-column)))))
2404 (defun markdown-prev-non-list-indent ()
2405 "Return position of the first non-list-marker on the previous line."
2406 (save-excursion
2407 (forward-line -1)
2408 (markdown-cur-non-list-indent)))
2410 (defun markdown-new-baseline-p ()
2411 "Determine if the current line begins a new baseline level."
2412 (save-excursion
2413 (beginning-of-line)
2414 (or (looking-at-p markdown-regex-header)
2415 (looking-at-p markdown-regex-hr)
2416 (and (null (markdown-cur-non-list-indent))
2417 (= (current-indentation) 0)
2418 (markdown-prev-line-blank-p)))))
2420 (defun markdown-search-backward-baseline ()
2421 "Search backward baseline point with no indentation and not a list item."
2422 (end-of-line)
2423 (let (stop)
2424 (while (not (or stop (bobp)))
2425 (re-search-backward markdown-regex-block-separator nil t)
2426 (when (match-end 2)
2427 (goto-char (match-end 2))
2428 (cond
2429 ((markdown-new-baseline-p)
2430 (setq stop t))
2431 ((looking-at-p markdown-regex-list)
2432 (setq stop nil))
2433 (t (setq stop t)))))))
2435 (defun markdown-update-list-levels (marker indent levels)
2436 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2437 Here, MARKER is a string representing the type of list, INDENT is an integer
2438 giving the indentation, in spaces, of the current block, and LEVELS is a
2439 list of the indentation levels of parent list items. When LEVELS is nil,
2440 it means we are at baseline (not inside of a nested list)."
2441 (cond
2442 ;; New list item at baseline.
2443 ((and marker (null levels))
2444 (setq levels (list indent)))
2445 ;; List item with greater indentation (four or more spaces).
2446 ;; Increase list level.
2447 ((and marker (>= indent (+ (car levels) 4)))
2448 (setq levels (cons indent levels)))
2449 ;; List item with greater or equal indentation (less than four spaces).
2450 ;; Do not increase list level.
2451 ((and marker (>= indent (car levels)))
2452 levels)
2453 ;; Lesser indentation level.
2454 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2455 ;; indentation could move back more than one list level). Note
2456 ;; that this block need not be the beginning of list item.
2457 ((< indent (car levels))
2458 (while (and (> (length levels) 1)
2459 (< indent (+ (cadr levels) 4)))
2460 (setq levels (cdr levels)))
2461 levels)
2462 ;; Otherwise, do nothing.
2463 (t levels)))
2465 (defun markdown-calculate-list-levels ()
2466 "Calculate list levels at point.
2467 Return a list of the form (n1 n2 n3 ...) where n1 is the
2468 indentation of the deepest nested list item in the branch of
2469 the list at the point, n2 is the indentation of the parent
2470 list item, and so on. The depth of the list item is therefore
2471 the length of the returned list. If the point is not at or
2472 immediately after a list item, return nil."
2473 (save-excursion
2474 (let ((first (point)) levels indent pre-regexp)
2475 ;; Find a baseline point with zero list indentation
2476 (markdown-search-backward-baseline)
2477 ;; Search for all list items between baseline and LOC
2478 (while (and (< (point) first)
2479 (re-search-forward markdown-regex-list first t))
2480 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2481 (beginning-of-line)
2482 (cond
2483 ;; Make sure this is not a header or hr
2484 ((markdown-new-baseline-p) (setq levels nil))
2485 ;; Make sure this is not a line from a pre block
2486 ((looking-at-p pre-regexp))
2487 ;; If not, then update levels
2489 (setq indent (current-indentation))
2490 (setq levels (markdown-update-list-levels (match-string 2)
2491 indent levels))))
2492 (end-of-line))
2493 levels)))
2495 (defun markdown-prev-list-item (level)
2496 "Search backward from point for a list item with indentation LEVEL.
2497 Set point to the beginning of the item, and return point, or nil
2498 upon failure."
2499 (let (bounds indent prev)
2500 (setq prev (point))
2501 (forward-line -1)
2502 (setq indent (current-indentation))
2503 (while
2504 (cond
2505 ;; List item
2506 ((and (looking-at-p markdown-regex-list)
2507 (setq bounds (markdown-cur-list-item-bounds)))
2508 (cond
2509 ;; Stop and return point at item of lesser or equal indentation
2510 ((<= (nth 3 bounds) level)
2511 (setq prev (point))
2512 nil)
2513 ;; Stop at beginning of buffer
2514 ((bobp) (setq prev nil))
2515 ;; Continue at item with greater indentation
2516 ((> (nth 3 bounds) level) t)))
2517 ;; Stop at beginning of buffer
2518 ((bobp) (setq prev nil))
2519 ;; Continue if current line is blank
2520 ((markdown-cur-line-blank-p) t)
2521 ;; Continue while indentation is the same or greater
2522 ((>= indent level) t)
2523 ;; Stop if current indentation is less than list item
2524 ;; and the next is blank
2525 ((and (< indent level)
2526 (markdown-next-line-blank-p))
2527 (setq prev nil))
2528 ;; Stop at a header
2529 ((looking-at-p markdown-regex-header) (setq prev nil))
2530 ;; Stop at a horizontal rule
2531 ((looking-at-p markdown-regex-hr) (setq prev nil))
2532 ;; Otherwise, continue.
2533 (t t))
2534 (forward-line -1)
2535 (setq indent (current-indentation)))
2536 prev))
2538 (defun markdown-next-list-item (level)
2539 "Search forward from point for the next list item with indentation LEVEL.
2540 Set point to the beginning of the item, and return point, or nil
2541 upon failure."
2542 (let (bounds indent next)
2543 (setq next (point))
2544 (forward-line)
2545 (setq indent (current-indentation))
2546 (while
2547 (cond
2548 ;; Stop at end of the buffer.
2549 ((eobp) nil)
2550 ;; Continue if the current line is blank
2551 ((markdown-cur-line-blank-p) t)
2552 ;; List item
2553 ((and (looking-at-p markdown-regex-list)
2554 (setq bounds (markdown-cur-list-item-bounds)))
2555 (cond
2556 ;; Continue at item with greater indentation
2557 ((> (nth 3 bounds) level) t)
2558 ;; Stop and return point at item of equal indentation
2559 ((= (nth 3 bounds) level)
2560 (setq next (point))
2561 nil)
2562 ;; Stop and return nil at item with lesser indentation
2563 ((< (nth 3 bounds) level)
2564 (setq next nil)
2565 nil)))
2566 ;; Continue while indentation is the same or greater
2567 ((>= indent level) t)
2568 ;; Stop if current indentation is less than list item
2569 ;; and the previous line was blank.
2570 ((and (< indent level)
2571 (markdown-prev-line-blank-p))
2572 (setq next nil))
2573 ;; Stop at a header
2574 ((looking-at-p markdown-regex-header) (setq next nil))
2575 ;; Stop at a horizontal rule
2576 ((looking-at-p markdown-regex-hr) (setq next nil))
2577 ;; Otherwise, continue.
2578 (t t))
2579 (forward-line)
2580 (setq indent (current-indentation)))
2581 next))
2583 (defun markdown-cur-list-item-end (level)
2584 "Move to the end of the current list item with nonlist indentation LEVEL.
2585 If the point is not in a list item, do nothing."
2586 (let (indent)
2587 (forward-line)
2588 (setq indent (current-indentation))
2589 (while
2590 (cond
2591 ;; Stop at end of the buffer.
2592 ((eobp) nil)
2593 ;; Continue if the current line is blank
2594 ((markdown-cur-line-blank-p) t)
2595 ;; Continue while indentation is the same or greater
2596 ((>= indent level) t)
2597 ;; Stop if current indentation is less than list item
2598 ;; and the previous line was blank.
2599 ((and (< indent level)
2600 (markdown-prev-line-blank-p))
2601 nil)
2602 ;; Stop at a new list item of the same or lesser indentation
2603 ((looking-at-p markdown-regex-list) nil)
2604 ;; Stop at a header
2605 ((looking-at-p markdown-regex-header) nil)
2606 ;; Stop at a horizontal rule
2607 ((looking-at-p markdown-regex-hr) nil)
2608 ;; Otherwise, continue.
2609 (t t))
2610 (forward-line)
2611 (setq indent (current-indentation)))
2612 ;; Don't skip over whitespace for empty list items (marker and
2613 ;; whitespace only), just move to end of whitespace.
2614 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
2615 (goto-char (match-end 3))
2616 (skip-syntax-backward "-"))))
2618 (defun markdown-cur-list-item-bounds ()
2619 "Return bounds and indentation of the current list item.
2620 Return a list of the form (begin end indent nonlist-indent marker).
2621 If the point is not inside a list item, return nil.
2622 Leave match data intact for `markdown-regex-list'."
2623 (let (cur prev-begin prev-end indent nonlist-indent marker)
2624 ;; Store current location
2625 (setq cur (point))
2626 ;; Verify that cur is between beginning and end of item
2627 (save-excursion
2628 (end-of-line)
2629 (when (re-search-backward markdown-regex-list nil t)
2630 (setq prev-begin (match-beginning 0))
2631 (setq indent (length (match-string 1)))
2632 (setq nonlist-indent (length (match-string 0)))
2633 (setq marker (concat (match-string 2) (match-string 3)))
2634 (save-match-data
2635 (markdown-cur-list-item-end nonlist-indent)
2636 (setq prev-end (point)))
2637 (when (and (>= cur prev-begin)
2638 (<= cur prev-end)
2639 nonlist-indent)
2640 (list prev-begin prev-end indent nonlist-indent marker))))))
2642 (defun markdown-bounds-of-thing-at-point (thing)
2643 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2644 Does not include trailing newlines when THING is 'line. Handles the
2645 end of buffer case by setting both endpoints equal to the value of
2646 `point-max', since an empty region will trigger empty markup insertion.
2647 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2648 (let* ((bounds (bounds-of-thing-at-point thing))
2649 (a (car bounds))
2650 (b (cdr bounds)))
2651 (when bounds
2652 (when (eq thing 'line)
2653 (cond ((and (eobp) (markdown-cur-line-blank-p))
2654 (setq a b))
2655 ((char-equal (char-before b) ?\^J)
2656 (setq b (1- b)))))
2657 (cons a b))))
2659 (defun markdown-reference-definition (reference)
2660 "Find out whether Markdown REFERENCE is defined.
2661 REFERENCE should not include the square brackets.
2662 When REFERENCE is defined, return a list of the form (text start end)
2663 containing the definition text itself followed by the start and end
2664 locations of the text. Otherwise, return nil.
2665 Leave match data for `markdown-regex-reference-definition'
2666 intact additional processing."
2667 (let ((reference (downcase reference)))
2668 (save-excursion
2669 (goto-char (point-min))
2670 (catch 'found
2671 (while (re-search-forward markdown-regex-reference-definition nil t)
2672 (when (string= reference (downcase (match-string-no-properties 2)))
2673 (throw 'found
2674 (list (match-string-no-properties 5)
2675 (match-beginning 5) (match-end 5)))))))))
2677 (defun markdown-get-defined-references ()
2678 "Return a list of all defined reference labels (not including square brackets)."
2679 (save-excursion
2680 (goto-char (point-min))
2681 (let (refs)
2682 (while (re-search-forward markdown-regex-reference-definition nil t)
2683 (let ((target (match-string-no-properties 2)))
2684 (cl-pushnew target refs :test #'equal)))
2685 (reverse refs))))
2687 (defun markdown-code-at-point-p ()
2688 "Return non-nil if the point is at an inline code fragment.
2689 Return nil otherwise. Set match data according to
2690 `markdown-match-code' upon success.
2691 This function searches the block for a code fragment that
2692 contains the point using `markdown-match-code'. We do this
2693 because `thing-at-point-looking-at' does not work reliably with
2694 `markdown-regex-code'.
2696 The match data is set as follows:
2697 Group 1 matches the opening backticks.
2698 Group 2 matches the code fragment itself, without backticks.
2699 Group 3 matches the closing backticks."
2700 (interactive)
2701 (save-excursion
2702 (let ((old-point (point))
2703 (end-of-block (progn (markdown-end-of-block) (point)))
2704 found)
2705 (markdown-beginning-of-block)
2706 (while (and (markdown-match-code end-of-block)
2707 (setq found t)
2708 (< (match-end 0) old-point)))
2709 (and found ; matched something
2710 (<= (match-beginning 0) old-point) ; match contains old-point
2711 (>= (match-end 0) old-point)))))
2713 (defun markdown-code-block-at-pos (pos)
2714 "Return match data list if there is a code block at POS.
2715 This includes pre blocks, tilde-fenced code blocks, and GFM
2716 quoted code blocks. Return nil otherwise."
2717 (or (get-text-property pos 'markdown-pre)
2718 (markdown-get-enclosing-fenced-block-construct pos)
2719 ;; polymode removes text properties set by markdown-mode, so
2720 ;; check if `poly-markdown-mode' is active and whether the
2721 ;; `chunkmode' property is non-nil at POS.
2722 (and (bound-and-true-p poly-markdown-mode)
2723 (get-text-property pos 'chunkmode))))
2725 (defun markdown-code-block-at-point ()
2726 "Return match data if the point is inside a code block.
2727 This includes pre blocks, tilde-fenced code blocks, and
2728 GFM quoted code blocks. Calls `markdown-code-block-at-pos'."
2729 (markdown-code-block-at-pos (point)))
2732 ;;; Markdown Font Lock Matching Functions =====================================
2734 (defun markdown-range-property-any (begin end prop prop-values)
2735 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2736 Also returns t if PROP is a list containing one of the PROP-VALUES.
2737 Return nil otherwise."
2738 (let (props)
2739 (catch 'found
2740 (dolist (loc (number-sequence begin end))
2741 (when (setq props (get-char-property loc prop))
2742 (cond ((listp props)
2743 ;; props is a list, check for membership
2744 (dolist (val prop-values)
2745 (when (memq val props) (throw 'found loc))))
2747 ;; props is a scalar, check for equality
2748 (dolist (val prop-values)
2749 (when (eq val props) (throw 'found loc))))))))))
2751 (defun markdown-range-properties-exist (begin end props)
2752 (cl-loop
2753 for loc in (number-sequence begin end)
2754 with result = nil
2755 while (not
2756 (setq result
2757 (cl-some (lambda (prop) (get-char-property loc prop)) props)))
2758 finally return result))
2760 (defun markdown-match-inline-generic (regex last)
2761 "Match inline REGEX from the point to LAST."
2762 (when (re-search-forward regex last t)
2763 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2764 (if (null bounds)
2765 ;; Not in a code block: keep match data and return t when in bounds
2766 (<= (match-end 0) last)
2767 ;; In code block: move past it and recursively search again
2768 (when (< (goto-char (nth 1 bounds)) last)
2769 (markdown-match-inline-generic regex last))))))
2771 (defun markdown-match-code (last)
2772 "Match inline code fragments from point to LAST."
2773 (unless (bobp)
2774 (backward-char 1))
2775 (when (markdown-match-inline-generic markdown-regex-code last)
2776 (set-match-data (list (match-beginning 1) (match-end 1)
2777 (match-beginning 2) (match-end 2)
2778 (match-beginning 3) (match-end 3)
2779 (match-beginning 4) (match-end 4)))
2780 (goto-char (1+ (match-end 0)))))
2782 (defun markdown-match-bold (last)
2783 "Match inline bold from the point to LAST."
2784 (when (markdown-match-inline-generic markdown-regex-bold last)
2785 (let ((begin (match-beginning 2)) (end (match-end 2)))
2786 (cond
2787 ((markdown-range-property-any
2788 begin end 'face (list markdown-inline-code-face
2789 markdown-math-face))
2790 (goto-char (1+ (match-end 0)))
2791 (markdown-match-bold last))
2793 (set-match-data (list (match-beginning 2) (match-end 2)
2794 (match-beginning 3) (match-end 3)
2795 (match-beginning 4) (match-end 4)
2796 (match-beginning 5) (match-end 5)))
2797 (goto-char (1+ (match-end 0))))))))
2799 (defun markdown-match-italic (last)
2800 "Match inline italics from the point to LAST."
2801 (let ((regex (if (eq major-mode 'gfm-mode)
2802 markdown-regex-gfm-italic markdown-regex-italic)))
2803 (when (markdown-match-inline-generic regex last)
2804 (let ((begin (match-beginning 1)) (end (match-end 1)))
2805 (cond
2806 ((markdown-range-property-any
2807 begin begin 'face (list markdown-url-face))
2808 ;; Italics shouldn't begin inside a URL due to an underscore
2809 (goto-char (min (1+ (match-end 0)) last))
2810 (markdown-match-italic last))
2811 ((markdown-range-property-any
2812 begin end 'face (list markdown-inline-code-face
2813 markdown-bold-face
2814 markdown-list-face
2815 markdown-math-face))
2816 (goto-char (1+ (match-end 0)))
2817 (markdown-match-italic last))
2819 (set-match-data (list (match-beginning 1) (match-end 1)
2820 (match-beginning 2) (match-end 2)
2821 (match-beginning 3) (match-end 3)
2822 (match-beginning 4) (match-end 4)))
2823 (goto-char (1+ (match-end 0)))))))))
2825 (defun markdown-match-math-generic (regex last)
2826 "Match REGEX from point to LAST.
2827 REGEX is either `markdown-regex-math-inline-single' for matching
2828 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2829 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
2830 (let ((begin (match-beginning 1)) (end (match-end 1)))
2831 (prog1
2832 (if (or (markdown-range-property-any
2833 begin end 'face (list markdown-inline-code-face
2834 markdown-bold-face))
2835 (markdown-range-properties-exist
2836 begin end
2837 (markdown-get-fenced-block-middle-properties)))
2838 (markdown-match-math-generic regex last)
2840 (goto-char (1+ (match-end 0)))))))
2842 (defun markdown-match-math-single (last)
2843 "Match single quoted $..$ math from point to LAST."
2844 (markdown-match-math-generic markdown-regex-math-inline-single last))
2846 (defun markdown-match-math-double (last)
2847 "Match double quoted $$..$$ math from point to LAST."
2848 (markdown-match-math-generic markdown-regex-math-inline-double last))
2850 (defun markdown-match-propertized-text (property last)
2851 "Match text with PROPERTY from point to LAST.
2852 Restore match data previously stored in PROPERTY."
2853 (let ((saved (get-text-property (point) property))
2854 pos)
2855 (unless saved
2856 (setq pos (next-single-char-property-change (point) property nil last))
2857 (setq saved (get-text-property pos property)))
2858 (when saved
2859 (set-match-data saved)
2860 ;; Step at least one character beyond point. Otherwise
2861 ;; `font-lock-fontify-keywords-region' infloops.
2862 (goto-char (min (1+ (max (match-end 0) (point)))
2863 (point-max)))
2864 saved)))
2866 (defun markdown-match-pre-blocks (last)
2867 "Match preformatted blocks from point to LAST.
2868 Use data stored in 'markdown-pre text property during syntax
2869 analysis."
2870 (markdown-match-propertized-text 'markdown-pre last))
2872 (defun markdown-match-gfm-code-blocks (last)
2873 "Match GFM quoted code blocks from point to LAST.
2874 Use data stored in 'markdown-gfm-code text property during syntax
2875 analysis."
2876 (markdown-match-propertized-text 'markdown-gfm-code last))
2878 (defun markdown-match-gfm-open-code-blocks (last)
2879 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
2881 (defun markdown-match-gfm-close-code-blocks (last)
2882 (markdown-match-propertized-text 'markdown-gfm-block-end last))
2884 (defun markdown-match-fenced-code-blocks (last)
2885 "Match fenced code blocks from the point to LAST."
2886 (markdown-match-propertized-text 'markdown-fenced-code last))
2888 (defun markdown-match-fenced-start-code-block (last)
2889 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
2891 (defun markdown-match-fenced-end-code-block (last)
2892 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
2894 (defun markdown-match-blockquotes (last)
2895 "Match blockquotes from point to LAST.
2896 Use data stored in 'markdown-blockquote text property during syntax
2897 analysis."
2898 (markdown-match-propertized-text 'markdown-blockquote last))
2900 (defun markdown-match-heading-1-setext (last)
2901 "Match level 1 setext headings from point to LAST."
2902 (markdown-match-propertized-text 'markdown-heading-1-setext last))
2904 (defun markdown-match-heading-2-setext (last)
2905 "Match level 2 setext headings from point to LAST."
2906 (markdown-match-propertized-text 'markdown-heading-2-setext last))
2908 (defun markdown-match-heading-1-atx (last)
2909 "Match level 1 ATX headings from point to LAST."
2910 (markdown-match-propertized-text 'markdown-heading-1-atx last))
2912 (defun markdown-match-heading-2-atx (last)
2913 "Match level 2 ATX headings from point to LAST."
2914 (markdown-match-propertized-text 'markdown-heading-2-atx last))
2916 (defun markdown-match-heading-3-atx (last)
2917 "Match level 3 ATX headings from point to LAST."
2918 (markdown-match-propertized-text 'markdown-heading-3-atx last))
2920 (defun markdown-match-heading-4-atx (last)
2921 "Match level 4 ATX headings from point to LAST."
2922 (markdown-match-propertized-text 'markdown-heading-4-atx last))
2924 (defun markdown-match-heading-5-atx (last)
2925 "Match level 5 ATX headings from point to LAST."
2926 (markdown-match-propertized-text 'markdown-heading-5-atx last))
2928 (defun markdown-match-heading-6-atx (last)
2929 "Match level 6 ATX headings from point to LAST."
2930 (markdown-match-propertized-text 'markdown-heading-6-atx last))
2932 (defun markdown-match-hr (last)
2933 "Match horizontal rules comments from the point to LAST."
2934 (while (and (re-search-forward markdown-regex-hr last t)
2935 (or (markdown-on-heading-p)
2936 (markdown-code-block-at-point))
2937 (< (match-end 0) last))
2938 (forward-line))
2939 (beginning-of-line)
2940 (cond ((looking-at-p markdown-regex-hr)
2941 (forward-line)
2943 (t nil)))
2945 (defun markdown-match-comments (last)
2946 "Match HTML comments from the point to LAST."
2947 (when (and (skip-syntax-forward "^<" last))
2948 (let ((beg (point)))
2949 (when (and (skip-syntax-forward "^>" last) (< (point) last))
2950 (forward-char)
2951 (set-match-data (list beg (point)))
2952 t))))
2954 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
2955 (save-excursion
2956 (goto-char (or pos (point-min)))
2957 (cl-loop
2958 with cur-result = nil
2959 and st-hdr = (or start-header "\\`")
2960 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
2961 while (and (< (point) last)
2962 (re-search-forward st-hdr last t)
2963 (progn
2964 (setq cur-result (match-data))
2965 (re-search-forward end-hdr nil t)))
2966 collect (list cur-result (match-data)))))
2968 (defvar markdown-conditional-search-function #'re-search-forward
2969 "Conditional search function used in `markdown-search-until-condition'.
2970 Made into a variable to allow for dynamic let-binding.")
2972 (defun markdown-search-until-condition (condition &rest args)
2973 (let (ret)
2974 (while (and (not ret) (apply markdown-conditional-search-function args))
2975 (setq ret (funcall condition)))
2976 ret))
2978 (defun markdown-match-generic-metadata
2979 (regexp last &optional start-header end-header)
2980 "Match generic metadata specified by REGEXP from the point to LAST.
2981 If START-HEADER is nil, we assume metadata can only occur at the
2982 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
2983 is \"\n\n\""
2984 (let* ((header-bounds
2985 (markdown-get-match-boundaries start-header end-header last))
2986 (enclosing-header
2987 (cl-find-if ; just take first if multiple
2988 (lambda (match-bounds)
2989 (cl-destructuring-bind (begin end) (cl-second match-bounds)
2990 (and (< (point) begin)
2991 (save-excursion (re-search-forward regexp end t)))))
2992 header-bounds))
2993 (header-begin
2994 (when enclosing-header (cl-second (cl-first enclosing-header))))
2995 (header-end
2996 (when enclosing-header (cl-first (cl-second enclosing-header)))))
2997 (cond ((null enclosing-header)
2998 ;; Don't match anything outside of a header.
2999 nil)
3000 ((markdown-search-until-condition
3001 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3002 ;; If a metadata item is found, it may span several lines.
3003 (let ((key-beginning (match-beginning 1))
3004 (key-end (match-end 1))
3005 (markup-begin (match-beginning 2))
3006 (markup-end (match-end 2))
3007 (value-beginning (match-beginning 3)))
3008 (set-match-data (list key-beginning (point) ; complete metadata
3009 key-beginning key-end ; key
3010 markup-begin markup-end ; markup
3011 value-beginning (point))) ; value
3013 (t nil))))
3015 (defun markdown-match-declarative-metadata (last)
3016 "Match declarative metadata from the point to LAST."
3017 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3019 (defun markdown-match-pandoc-metadata (last)
3020 "Match Pandoc metadata from the point to LAST."
3021 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3023 (defun markdown-match-yaml-metadata-begin (last)
3024 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3026 (defun markdown-match-yaml-metadata-end (last)
3027 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3029 (defun markdown-match-yaml-metadata-key (last)
3030 (markdown-match-propertized-text 'markdown-metadata-key last))
3033 ;;; Syntax Table ==============================================================
3035 (defvar markdown-mode-syntax-table
3036 (let ((tab (make-syntax-table text-mode-syntax-table)))
3037 (modify-syntax-entry ?\" "." tab)
3038 tab)
3039 "Syntax table for `markdown-mode'.")
3042 ;;; Element Insertion =========================================================
3044 (defun markdown-ensure-blank-line-before ()
3045 "If previous line is not already blank, insert a blank line before point."
3046 (unless (bolp) (insert "\n"))
3047 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3049 (defun markdown-ensure-blank-line-after ()
3050 "If following line is not already blank, insert a blank line after point.
3051 Return the point where it was originally."
3052 (save-excursion
3053 (unless (eolp) (insert "\n"))
3054 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3056 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3057 "Insert the strings S1 and S2, wrapping around region or THING.
3058 If a region is specified by the optional BEG and END arguments,
3059 wrap the strings S1 and S2 around that region.
3060 If there is an active region, wrap the strings S1 and S2 around
3061 the region. If there is not an active region but the point is at
3062 THING, wrap that thing (which defaults to word). Otherwise, just
3063 insert S1 and S2 and place the cursor in between. Return the
3064 bounds of the entire wrapped string, or nil if nothing was wrapped
3065 and S1 and S2 were only inserted."
3066 (let (a b bounds new-point)
3067 (cond
3068 ;; Given region
3069 ((and beg end)
3070 (setq a beg
3071 b end
3072 new-point (+ (point) (length s1))))
3073 ;; Active region
3074 ((markdown-use-region-p)
3075 (setq a (region-beginning)
3076 b (region-end)
3077 new-point (+ (point) (length s1))))
3078 ;; Thing (word) at point
3079 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3080 (setq a (car bounds)
3081 b (cdr bounds)
3082 new-point (+ (point) (length s1))))
3083 ;; No active region and no word
3085 (setq a (point)
3086 b (point))))
3087 (goto-char b)
3088 (insert s2)
3089 (goto-char a)
3090 (insert s1)
3091 (when new-point (goto-char new-point))
3092 (if (= a b)
3094 (setq b (+ b (length s1) (length s2)))
3095 (cons a b))))
3097 (defun markdown-point-after-unwrap (cur prefix suffix)
3098 "Return desired position of point after an unwrapping operation.
3099 CUR gives the position of the point before the operation.
3100 Additionally, two cons cells must be provided. PREFIX gives the
3101 bounds of the prefix string and SUFFIX gives the bounds of the
3102 suffix string."
3103 (cond ((< cur (cdr prefix)) (car prefix))
3104 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3105 ((<= cur (cdr suffix))
3106 (- cur (+ (- (cdr prefix) (car prefix))
3107 (- cur (car suffix)))))
3108 (t cur)))
3110 (defun markdown-unwrap-thing-at-point (regexp all text)
3111 "Remove prefix and suffix of thing at point and reposition the point.
3112 When the thing at point matches REGEXP, replace the subexpression
3113 ALL with the string in subexpression TEXT. Reposition the point
3114 in an appropriate location accounting for the removal of prefix
3115 and suffix strings. Return new bounds of string from group TEXT.
3116 When REGEXP is nil, assumes match data is already set."
3117 (when (or (null regexp)
3118 (thing-at-point-looking-at regexp))
3119 (let ((cur (point))
3120 (prefix (cons (match-beginning all) (match-beginning text)))
3121 (suffix (cons (match-end text) (match-end all)))
3122 (bounds (cons (match-beginning text) (match-end text))))
3123 ;; Replace the thing at point
3124 (replace-match (match-string text) t t nil all)
3125 ;; Reposition the point
3126 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3127 ;; Adjust bounds
3128 (setq bounds (cons (car prefix)
3129 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3131 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3132 "Remove prefix and suffix of all things in region from BEG to END.
3133 When a thing in the region matches REGEXP, replace the
3134 subexpression ALL with the string in subexpression TEXT.
3135 Return a cons cell containing updated bounds for the region."
3136 (save-excursion
3137 (goto-char beg)
3138 (let ((removed 0) len-all len-text)
3139 (while (re-search-forward regexp (- end removed) t)
3140 (setq len-all (length (match-string-no-properties all)))
3141 (setq len-text (length (match-string-no-properties text)))
3142 (setq removed (+ removed (- len-all len-text)))
3143 (replace-match (match-string text) t t nil all))
3144 (cons beg (- end removed)))))
3146 (defun markdown-insert-hr (arg)
3147 "Insert or replace a horizonal rule.
3148 By default, use the first element of `markdown-hr-strings'. When
3149 ARG is non-nil, as when given a prefix, select a different
3150 element as follows. When prefixed with \\[universal-argument],
3151 use the last element of `markdown-hr-strings' instead. When
3152 prefixed with an integer from 1 to the length of
3153 `markdown-hr-strings', use the element in that position instead."
3154 (interactive "*P")
3155 (when (thing-at-point-looking-at markdown-regex-hr)
3156 (delete-region (match-beginning 0) (match-end 0)))
3157 (markdown-ensure-blank-line-before)
3158 (cond ((equal arg '(4))
3159 (insert (car (reverse markdown-hr-strings))))
3160 ((and (integerp arg) (> arg 0)
3161 (<= arg (length markdown-hr-strings)))
3162 (insert (nth (1- arg) markdown-hr-strings)))
3164 (insert (car markdown-hr-strings))))
3165 (markdown-ensure-blank-line-after))
3167 (defun markdown-insert-bold ()
3168 "Insert markup to make a region or word bold.
3169 If there is an active region, make the region bold. If the point
3170 is at a non-bold word, make the word bold. If the point is at a
3171 bold word or phrase, remove the bold markup. Otherwise, simply
3172 insert bold delimiters and place the cursor in between them."
3173 (interactive)
3174 (let ((delim (if markdown-bold-underscore "__" "**")))
3175 (if (markdown-use-region-p)
3176 ;; Active region
3177 (let ((bounds (markdown-unwrap-things-in-region
3178 (region-beginning) (region-end)
3179 markdown-regex-bold 2 4)))
3180 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3181 ;; Bold markup removal, bold word at point, or empty markup insertion
3182 (if (thing-at-point-looking-at markdown-regex-bold)
3183 (markdown-unwrap-thing-at-point nil 2 4)
3184 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3186 (defun markdown-insert-italic ()
3187 "Insert markup to make a region or word italic.
3188 If there is an active region, make the region italic. If the point
3189 is at a non-italic word, make the word italic. If the point is at an
3190 italic word or phrase, remove the italic markup. Otherwise, simply
3191 insert italic delimiters and place the cursor in between them."
3192 (interactive)
3193 (let ((delim (if markdown-italic-underscore "_" "*")))
3194 (if (markdown-use-region-p)
3195 ;; Active region
3196 (let ((bounds (markdown-unwrap-things-in-region
3197 (region-beginning) (region-end)
3198 markdown-regex-italic 1 3)))
3199 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3200 ;; Italic markup removal, italic word at point, or empty markup insertion
3201 (if (thing-at-point-looking-at markdown-regex-italic)
3202 (markdown-unwrap-thing-at-point nil 1 3)
3203 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3205 (defun markdown-insert-strike-through ()
3206 "Insert markup to make a region or word strikethrough.
3207 If there is an active region, make the region strikethrough. If the point
3208 is at a non-bold word, make the word strikethrough. If the point is at a
3209 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3210 simply insert bold delimiters and place the cursor in between them."
3211 (interactive)
3212 (let ((delim "~~"))
3213 (if (markdown-use-region-p)
3214 ;; Active region
3215 (let ((bounds (markdown-unwrap-things-in-region
3216 (region-beginning) (region-end)
3217 markdown-regex-strike-through 2 4)))
3218 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3219 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3220 (if (thing-at-point-looking-at markdown-regex-strike-through)
3221 (markdown-unwrap-thing-at-point nil 2 4)
3222 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3224 (defun markdown-insert-code ()
3225 "Insert markup to make a region or word an inline code fragment.
3226 If there is an active region, make the region an inline code
3227 fragment. If the point is at a word, make the word an inline
3228 code fragment. Otherwise, simply insert code delimiters and
3229 place the cursor in between them."
3230 (interactive)
3231 (if (markdown-use-region-p)
3232 ;; Active region
3233 (let ((bounds (markdown-unwrap-things-in-region
3234 (region-beginning) (region-end)
3235 markdown-regex-code 1 3)))
3236 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3237 ;; Code markup removal, code markup for word, or empty markup insertion
3238 (if (markdown-code-at-point-p)
3239 (markdown-unwrap-thing-at-point nil 0 2)
3240 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3242 (defun markdown-insert-kbd ()
3243 "Insert markup to wrap region or word in <kbd> tags.
3244 If there is an active region, use the region. If the point is at
3245 a word, use the word. Otherwise, simply insert <kbd> tags and
3246 place the cursor in between them."
3247 (interactive)
3248 (if (markdown-use-region-p)
3249 ;; Active region
3250 (let ((bounds (markdown-unwrap-things-in-region
3251 (region-beginning) (region-end)
3252 markdown-regex-kbd 0 2)))
3253 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3254 ;; Markup removal, markup for word, or empty markup insertion
3255 (if (thing-at-point-looking-at markdown-regex-kbd)
3256 (markdown-unwrap-thing-at-point nil 0 2)
3257 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3259 (defun markdown-insert-link ()
3260 "Insert an inline link, using region or word as link text if possible.
3261 If there is an active region, use the region as the link text. If the
3262 point is at a word, use the word as the link text. In these cases, the
3263 point will be left at the position for inserting a URL. If there is no
3264 active region and the point is not at word, simply insert link markup and
3265 place the point in the position to enter link text."
3266 (interactive)
3267 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3268 (when bounds
3269 (goto-char (- (cdr bounds) 1)))))
3271 (defun markdown-insert-reference-link (text label &optional url title)
3272 "Insert a reference link and, optionally, a reference definition.
3273 The link TEXT will be inserted followed by the optional LABEL.
3274 If a URL is given, also insert a definition for the reference
3275 LABEL according to `markdown-reference-location'. If a TITLE is
3276 given, it will be added to the end of the reference definition
3277 and will be used to populate the title attribute when converted
3278 to XHTML. If URL is nil, insert only the link portion (for
3279 example, when a reference label is already defined)."
3280 (insert (concat "[" text "][" label "]"))
3281 (when url
3282 (markdown-insert-reference-definition
3283 (if (string-equal label "") text label)
3284 url title)))
3286 (defun markdown-insert-reference-definition (label &optional url title)
3287 "Add definition for reference LABEL with URL and TITLE.
3288 LABEL is a Markdown reference label without square brackets.
3289 URL and TITLE are optional. When given, the TITLE will
3290 be used to populate the title attribute when converted to XHTML."
3291 ;; END specifies where to leave the point upon return
3292 (let ((end (point)))
3293 (cl-case markdown-reference-location
3294 (end (goto-char (point-max)))
3295 (immediately (markdown-end-of-block))
3296 (header (markdown-end-of-defun)))
3297 (unless (markdown-cur-line-blank-p) (insert "\n"))
3298 (insert "\n[" label "]: ")
3299 (if url
3300 (insert url)
3301 ;; When no URL is given, leave cursor at END following the colon
3302 (setq end (point)))
3303 (when (> (length title) 0)
3304 (insert " \"" title "\""))
3305 (unless (looking-at-p "\n")
3306 (insert "\n"))
3307 (goto-char end)
3308 (when url
3309 (message
3310 (substitute-command-keys
3311 "Defined reference [%s], press \\[markdown-jump] to jump there")
3312 label))))
3314 (defun markdown-insert-reference-link-dwim ()
3315 "Insert a reference link of the form [text][label] at point.
3316 If there is an active region, the text in the region will be used
3317 as the link text. If the point is at an inline link, it will be
3318 converted to a reference link. If the point is at a word, it will
3319 be used as the link text. Otherwise, the link text will be read from
3320 the minibuffer. The link label will be read from the minibuffer in
3321 both cases, with completion from the set of currently defined
3322 references. To create an implicit reference link, press RET to
3323 accept the default, an empty label. If the entered referenced
3324 label is not defined, additionally prompt for the URL
3325 and (optional) title. The reference definition is placed at the
3326 location determined by `markdown-reference-location'."
3327 (interactive)
3328 (let* ((defined-labels (markdown-get-defined-references))
3329 (switch (thing-at-point-looking-at markdown-regex-link-inline))
3330 (bounds (cond ((markdown-use-region-p)
3331 (cons (region-beginning) (region-end)))
3332 (switch
3333 (cons (match-beginning 0) (match-end 0)))
3335 (markdown-bounds-of-thing-at-point 'word))))
3336 (text (cond (switch (match-string 3))
3337 (bounds (buffer-substring (car bounds) (cdr bounds)))
3338 (t (read-string "Link Text: "))))
3339 (label (completing-read
3340 "Link Label (default: none): " defined-labels
3341 nil nil nil 'markdown-reference-label-history nil))
3342 (ref (save-match-data
3343 (markdown-reference-definition
3344 (if (> (length label) 0) label text))))
3345 (url (cond (ref nil)
3346 (switch (match-string 6))
3347 (t (read-string "Link URL: "))))
3348 (title (cond
3349 ((= (length url) 0) nil)
3350 (switch (if (> (length (match-string 7)) 2)
3351 (substring (match-string 7) 1 -1)
3352 nil))
3353 (t (read-string "Link Title (optional): ")))))
3354 (when bounds (delete-region (car bounds) (cdr bounds)))
3355 (markdown-insert-reference-link text label url title)))
3357 (defun markdown-insert-uri ()
3358 "Insert markup for an inline URI.
3359 If there is an active region, use it as the URI. If the point is
3360 at a URI, wrap it with angle brackets. If the point is at an
3361 inline URI, remove the angle brackets. Otherwise, simply insert
3362 angle brackets place the point between them."
3363 (interactive)
3364 (if (markdown-use-region-p)
3365 ;; Active region
3366 (let ((bounds (markdown-unwrap-things-in-region
3367 (region-beginning) (region-end)
3368 markdown-regex-angle-uri 0 2)))
3369 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
3370 ;; Markup removal, URI at point, or empty markup insertion
3371 (if (thing-at-point-looking-at markdown-regex-angle-uri)
3372 (markdown-unwrap-thing-at-point nil 0 2)
3373 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
3375 (defun markdown-insert-wiki-link ()
3376 "Insert a wiki link of the form [[WikiLink]].
3377 If there is an active region, use the region as the link text.
3378 If the point is at a word, use the word as the link text. If
3379 there is no active region and the point is not at word, simply
3380 insert link markup."
3381 (interactive)
3382 (if (markdown-use-region-p)
3383 ;; Active region
3384 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
3385 ;; Markup removal, wiki link at at point, or empty markup insertion
3386 (if (thing-at-point-looking-at markdown-regex-wiki-link)
3387 (if (or markdown-wiki-link-alias-first
3388 (null (match-string 5)))
3389 (markdown-unwrap-thing-at-point nil 1 3)
3390 (markdown-unwrap-thing-at-point nil 1 5))
3391 (markdown-wrap-or-insert "[[" "]]"))))
3393 (defun markdown-insert-image (&optional arg)
3394 "Insert image markup using region or word as alt text if possible.
3395 If there is an active region, use the region as the alt text. If the
3396 point is at a word, use the word as the alt text. In these cases, the
3397 point will be left at the position for inserting a URL. If there is no
3398 active region and the point is not at word, simply insert image markup and
3399 place the point in the position to enter alt text. If ARG is nil, insert
3400 inline image markup. Otherwise, insert reference image markup."
3401 (interactive "*P")
3402 (let ((bounds (if arg
3403 (markdown-wrap-or-insert "![" "][]")
3404 (markdown-wrap-or-insert "![" "]()"))))
3405 (when bounds
3406 (goto-char (- (cdr bounds) 1)))))
3408 (defun markdown-insert-reference-image ()
3409 "Insert reference-style image markup using region or word as alt text.
3410 Calls `markdown-insert-image' with prefix argument."
3411 (interactive)
3412 (markdown-insert-image t))
3414 (defun markdown-remove-header ()
3415 "Remove header markup if point is at a header.
3416 Return bounds of remaining header text if a header was removed
3417 and nil otherwise."
3418 (interactive "*")
3419 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
3420 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
3422 (defun markdown-insert-header (&optional level text setext)
3423 "Insert or replace header markup.
3424 The level of the header is specified by LEVEL and header text is
3425 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3426 default value is 1.
3427 When TEXT is nil, the header text is obtained as follows.
3428 If there is an active region, it is used as the header text.
3429 Otherwise, the current line will be used as the header text.
3430 If there is not an active region and the point is at a header,
3431 remove the header markup and replace with level N header.
3432 Otherwise, insert empty header markup and place the cursor in
3433 between.
3434 The style of the header will be atx (hash marks) unless
3435 SETEXT is non-nil, in which case a setext-style (underlined)
3436 header will be inserted."
3437 (interactive "p\nsHeader text: ")
3438 (setq level (min (max (or level 1) 1) (if setext 2 6)))
3439 ;; Determine header text if not given
3440 (when (null text)
3441 (if (markdown-use-region-p)
3442 ;; Active region
3443 (setq text (delete-and-extract-region (region-beginning) (region-end)))
3444 ;; No active region
3445 (markdown-remove-header)
3446 (setq text (delete-and-extract-region
3447 (line-beginning-position) (line-end-position)))
3448 (when (and setext (string-match-p "^[ \t]*$" text))
3449 (setq text (read-string "Header text: "))))
3450 (setq text (markdown-compress-whitespace-string text)))
3451 ;; Insertion with given text
3452 (markdown-ensure-blank-line-before)
3453 (let (hdr)
3454 (cond (setext
3455 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
3456 (insert text "\n" hdr))
3458 (setq hdr (make-string level ?#))
3459 (insert hdr " " text)
3460 (when (null markdown-asymmetric-header) (insert " " hdr)))))
3461 (markdown-ensure-blank-line-after)
3462 ;; Leave point at end of text
3463 (cond (setext
3464 (backward-char (1+ (string-width text))))
3465 ((null markdown-asymmetric-header)
3466 (backward-char (1+ level)))))
3468 (defun markdown-insert-header-dwim (&optional arg setext)
3469 "Insert or replace header markup.
3470 The level and type of the header are determined automatically by
3471 the type and level of the previous header, unless a prefix
3472 argument is given via ARG.
3473 With a numeric prefix valued 1 to 6, insert a header of the given
3474 level, with the type being determined automatically (note that
3475 only level 1 or 2 setext headers are possible).
3477 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3478 promote the heading by one level.
3479 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3480 demote the heading by one level.
3481 When SETEXT is non-nil, prefer setext-style headers when
3482 possible (levels one and two).
3484 When there is an active region, use it for the header text. When
3485 the point is at an existing header, change the type and level
3486 according to the rules above.
3487 Otherwise, if the line is not empty, create a header using the
3488 text on the current line as the header text.
3489 Finally, if the point is on a blank line, insert empty header
3490 markup (atx) or prompt for text (setext).
3491 See `markdown-insert-header' for more details about how the
3492 header text is determined."
3493 (interactive "*P")
3494 (let (level)
3495 (save-excursion
3496 (when (or (thing-at-point-looking-at markdown-regex-header)
3497 (re-search-backward markdown-regex-header nil t))
3498 ;; level of current or previous header
3499 (setq level (markdown-outline-level))
3500 ;; match group 1 indicates a setext header
3501 (setq setext (match-end 1))))
3502 ;; check prefix argument
3503 (cond
3504 ((and (equal arg '(4)) level (> level 1)) ;; C-u
3505 (cl-decf level))
3506 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
3507 (cl-incf level))
3508 (arg ;; numeric prefix
3509 (setq level (prefix-numeric-value arg))))
3510 ;; setext headers must be level one or two
3511 (and level (setq setext (and setext (<= level 2))))
3512 ;; insert the heading
3513 (markdown-insert-header level nil setext)))
3515 (defun markdown-insert-header-setext-dwim (&optional arg)
3516 "Insert or replace header markup, with preference for setext.
3517 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3518 (interactive "*P")
3519 (markdown-insert-header-dwim arg t))
3521 (defun markdown-insert-header-atx-1 ()
3522 "Insert a first level atx-style (hash mark) header.
3523 See `markdown-insert-header'."
3524 (interactive "*")
3525 (markdown-insert-header 1 nil nil))
3527 (defun markdown-insert-header-atx-2 ()
3528 "Insert a level two atx-style (hash mark) header.
3529 See `markdown-insert-header'."
3530 (interactive "*")
3531 (markdown-insert-header 2 nil nil))
3533 (defun markdown-insert-header-atx-3 ()
3534 "Insert a level three atx-style (hash mark) header.
3535 See `markdown-insert-header'."
3536 (interactive "*")
3537 (markdown-insert-header 3 nil nil))
3539 (defun markdown-insert-header-atx-4 ()
3540 "Insert a level four atx-style (hash mark) header.
3541 See `markdown-insert-header'."
3542 (interactive "*")
3543 (markdown-insert-header 4 nil nil))
3545 (defun markdown-insert-header-atx-5 ()
3546 "Insert a level five atx-style (hash mark) header.
3547 See `markdown-insert-header'."
3548 (interactive "*")
3549 (markdown-insert-header 5 nil nil))
3551 (defun markdown-insert-header-atx-6 ()
3552 "Insert a sixth level atx-style (hash mark) header.
3553 See `markdown-insert-header'."
3554 (interactive "*")
3555 (markdown-insert-header 6 nil nil))
3557 (defun markdown-insert-header-setext-1 ()
3558 "Insert a setext-style (underlined) first-level header.
3559 See `markdown-insert-header'."
3560 (interactive "*")
3561 (markdown-insert-header 1 nil t))
3563 (defun markdown-insert-header-setext-2 ()
3564 "Insert a setext-style (underlined) second-level header.
3565 See `markdown-insert-header'."
3566 (interactive "*")
3567 (markdown-insert-header 2 nil t))
3569 (defun markdown-blockquote-indentation (loc)
3570 "Return string containing necessary indentation for a blockquote at LOC.
3571 Also see `markdown-pre-indentation'."
3572 (save-excursion
3573 (goto-char loc)
3574 (let* ((list-level (length (markdown-calculate-list-levels)))
3575 (indent ""))
3576 (dotimes (_ list-level indent)
3577 (setq indent (concat indent " "))))))
3579 (defun markdown-insert-blockquote ()
3580 "Start a blockquote section (or blockquote the region).
3581 If Transient Mark mode is on and a region is active, it is used as
3582 the blockquote text."
3583 (interactive)
3584 (if (markdown-use-region-p)
3585 (markdown-blockquote-region (region-beginning) (region-end))
3586 (markdown-ensure-blank-line-before)
3587 (insert (markdown-blockquote-indentation (point)) "> ")
3588 (markdown-ensure-blank-line-after)))
3590 (defun markdown-block-region (beg end prefix)
3591 "Format the region using a block prefix.
3592 Arguments BEG and END specify the beginning and end of the
3593 region. The characters PREFIX will appear at the beginning
3594 of each line."
3595 (save-excursion
3596 (let* ((end-marker (make-marker))
3597 (beg-marker (make-marker)))
3598 ;; Ensure blank line after and remove extra whitespace
3599 (goto-char end)
3600 (skip-syntax-backward "-")
3601 (set-marker end-marker (point))
3602 (delete-horizontal-space)
3603 (markdown-ensure-blank-line-after)
3604 ;; Ensure blank line before and remove extra whitespace
3605 (goto-char beg)
3606 (skip-syntax-forward "-")
3607 (delete-horizontal-space)
3608 (markdown-ensure-blank-line-before)
3609 (set-marker beg-marker (point))
3610 ;; Insert PREFIX before each line
3611 (goto-char beg-marker)
3612 (while (and (< (line-beginning-position) end-marker)
3613 (not (eobp)))
3614 (insert prefix)
3615 (forward-line)))))
3617 (defun markdown-blockquote-region (beg end)
3618 "Blockquote the region.
3619 Arguments BEG and END specify the beginning and end of the region."
3620 (interactive "*r")
3621 (markdown-block-region
3622 beg end (concat (markdown-blockquote-indentation
3623 (max (point-min) (1- beg))) "> ")))
3625 (defun markdown-pre-indentation (loc)
3626 "Return string containing necessary whitespace for a pre block at LOC.
3627 Also see `markdown-blockquote-indentation'."
3628 (save-excursion
3629 (goto-char loc)
3630 (let* ((list-level (length (markdown-calculate-list-levels)))
3631 indent)
3632 (dotimes (_ (1+ list-level) indent)
3633 (setq indent (concat indent " "))))))
3635 (defun markdown-insert-pre ()
3636 "Start a preformatted section (or apply to the region).
3637 If Transient Mark mode is on and a region is active, it is marked
3638 as preformatted text."
3639 (interactive)
3640 (if (markdown-use-region-p)
3641 (markdown-pre-region (region-beginning) (region-end))
3642 (markdown-ensure-blank-line-before)
3643 (insert (markdown-pre-indentation (point)))
3644 (markdown-ensure-blank-line-after)))
3646 (defun markdown-pre-region (beg end)
3647 "Format the region as preformatted text.
3648 Arguments BEG and END specify the beginning and end of the region."
3649 (interactive "*r")
3650 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
3651 (markdown-block-region beg end indent)))
3653 (defun markdown-electric-backquote (arg)
3654 "Insert a backquote.
3655 The numeric prefix argument ARG says how many times to repeat the insertion.
3656 Call `markdown-insert-gfm-code-block' interactively
3657 if three backquotes inserted at the beginning of line."
3658 (interactive "*P")
3659 (self-insert-command (prefix-numeric-value arg))
3660 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
3661 (replace-match "")
3662 (call-interactively #'markdown-insert-gfm-code-block)))
3664 (defconst markdown-gfm-recognized-languages
3665 ;; to reproduce/update, evaluate the let-form in
3666 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3667 ;; but with appropriate use of a keyboard macro, indenting and filling it
3668 ;; properly is pretty fast.
3669 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3670 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3671 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3672 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3673 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3674 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3675 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3676 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3677 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3678 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3679 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3680 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3681 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3682 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3683 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3684 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3685 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3686 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3687 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3688 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3689 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3690 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3691 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3692 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3693 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3694 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3695 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3696 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3697 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3698 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3699 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3700 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3701 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3702 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3703 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3704 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3705 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3706 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3707 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3708 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3709 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3710 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3711 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3712 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3713 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3714 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3715 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3716 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3717 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3718 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3719 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3720 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3721 "Language specifiers recognized by GitHub's syntax highlighting features.")
3723 (defvar markdown-gfm-used-languages nil
3724 "Language names used in GFM code blocks.")
3725 (make-variable-buffer-local 'markdown-gfm-used-languages)
3727 (defun markdown-trim-whitespace (str)
3728 (markdown-replace-regexp-in-string
3729 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
3731 (defun markdown-clean-language-string (str)
3732 (markdown-replace-regexp-in-string
3733 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
3735 (defun markdown-validate-language-string (widget)
3736 (let ((str (widget-value widget)))
3737 (unless (string= str (markdown-clean-language-string str))
3738 (widget-put widget :error (format "Invalid language spec: '%s'" str))
3739 widget)))
3741 (defun markdown-gfm-get-corpus ()
3742 "Create corpus of recognized GFM code block languages for the given buffer."
3743 (let ((given-corpus (append markdown-gfm-additional-languages
3744 markdown-gfm-recognized-languages)))
3745 (append
3746 markdown-gfm-used-languages
3747 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
3748 given-corpus))))
3750 (defun markdown-gfm-add-used-language (lang)
3751 "Clean LANG and add to list of used languages."
3752 (add-to-list 'markdown-gfm-used-languages
3753 (markdown-clean-language-string lang)))
3755 (defun markdown-insert-gfm-code-block (&optional lang)
3756 "Insert GFM code block for language LANG.
3757 If LANG is nil, the language will be queried from user. If a
3758 region is active, wrap this region with the markup instead. If
3759 the region boundaries are not on empty lines, these are added
3760 automatically in order to have the correct markup."
3761 (interactive
3762 (list (let ((completion-ignore-case nil))
3763 (condition-case nil
3764 (markdown-clean-language-string
3765 (completing-read
3766 (format "Programming language [%s]: "
3767 (or (car markdown-gfm-used-languages) "none"))
3768 (markdown-gfm-get-corpus)
3769 nil 'confirm nil
3770 'markdown-gfm-language-history))
3771 (quit "")))))
3772 (unless (string= lang "") (markdown-gfm-add-used-language lang))
3773 (when (> (length lang) 0) (setq lang (concat " " lang)))
3774 (if (markdown-use-region-p)
3775 (let ((b (region-beginning)) (e (region-end)))
3776 (goto-char e)
3777 ;; if we're on a blank line, don't newline, otherwise the ```
3778 ;; should go on its own line
3779 (unless (looking-back "\n" nil)
3780 (newline))
3781 (insert "```")
3782 (markdown-ensure-blank-line-after)
3783 (goto-char b)
3784 ;; if we're on a blank line, insert the quotes here, otherwise
3785 ;; add a new line first
3786 (unless (looking-at-p "\n")
3787 (newline)
3788 (forward-line -1))
3789 (markdown-ensure-blank-line-before)
3790 (insert "```" lang))
3791 (markdown-ensure-blank-line-before)
3792 (insert "```" lang "\n\n```")
3793 (markdown-ensure-blank-line-after)
3794 (forward-line -1)))
3796 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
3797 (with-current-buffer (or buffer (current-buffer))
3798 (save-excursion
3799 (goto-char (point-min))
3800 (cl-loop
3801 with prop = 'markdown-gfm-block-begin
3802 for pos-prop = (markdown-find-next-prop prop)
3803 while pos-prop
3804 for lang = (progn
3805 (goto-char (car pos-prop))
3806 (save-match-data
3807 (set-match-data (get-text-property (point) prop))
3808 (when (and (match-beginning 2) (match-end 2))
3809 (buffer-substring-no-properties
3810 (match-beginning 2) (match-end 2)))))
3811 do (progn (when lang (markdown-gfm-add-used-language lang))
3812 (goto-char (next-single-property-change (point) prop)))))))
3815 ;;; Footnotes ==================================================================
3817 (defun markdown-footnote-counter-inc ()
3818 "Increment `markdown-footnote-counter' and return the new value."
3819 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
3820 (save-excursion
3821 (goto-char (point-min))
3822 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
3823 (point-max) t)
3824 (let ((fn (string-to-number (match-string 1))))
3825 (when (> fn markdown-footnote-counter)
3826 (setq markdown-footnote-counter fn))))))
3827 (cl-incf markdown-footnote-counter))
3829 (defun markdown-insert-footnote ()
3830 "Insert footnote with a new number and move point to footnote definition."
3831 (interactive)
3832 (let ((fn (markdown-footnote-counter-inc)))
3833 (insert (format "[^%d]" fn))
3834 (markdown-footnote-text-find-new-location)
3835 (markdown-ensure-blank-line-before)
3836 (unless (markdown-cur-line-blank-p)
3837 (insert "\n"))
3838 (insert (format "[^%d]: " fn))
3839 (markdown-ensure-blank-line-after)))
3841 (defun markdown-footnote-text-find-new-location ()
3842 "Position the cursor at the proper location for a new footnote text."
3843 (cond
3844 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
3845 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
3846 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
3848 (defun markdown-footnote-kill ()
3849 "Kill the footnote at point.
3850 The footnote text is killed (and added to the kill ring), the
3851 footnote marker is deleted. Point has to be either at the
3852 footnote marker or in the footnote text."
3853 (interactive)
3854 (let ((marker-pos nil)
3855 (skip-deleting-marker nil)
3856 (starting-footnote-text-positions
3857 (markdown-footnote-text-positions)))
3858 (when starting-footnote-text-positions
3859 ;; We're starting in footnote text, so mark our return position and jump
3860 ;; to the marker if possible.
3861 (let ((marker-pos (markdown-footnote-find-marker
3862 (cl-first starting-footnote-text-positions))))
3863 (if marker-pos
3864 (goto-char (1- marker-pos))
3865 ;; If there isn't a marker, we still want to kill the text.
3866 (setq skip-deleting-marker t))))
3867 ;; Either we didn't start in the text, or we started in the text and jumped
3868 ;; to the marker. We want to assume we're at the marker now and error if
3869 ;; we're not.
3870 (unless skip-deleting-marker
3871 (let ((marker (markdown-footnote-delete-marker)))
3872 (unless marker
3873 (error "Not at a footnote"))
3874 ;; Even if we knew the text position before, it changed when we deleted
3875 ;; the label.
3876 (setq marker-pos (cl-second marker))
3877 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
3878 (unless new-text-pos
3879 (error "No text for footnote `%s'" (cl-first marker)))
3880 (goto-char new-text-pos))))
3881 (let ((pos (markdown-footnote-kill-text)))
3882 (goto-char (if starting-footnote-text-positions
3884 marker-pos)))))
3886 (defun markdown-footnote-delete-marker ()
3887 "Delete a footnote marker at point.
3888 Returns a list (ID START) containing the footnote ID and the
3889 start position of the marker before deletion. If no footnote
3890 marker was deleted, this function returns NIL."
3891 (let ((marker (markdown-footnote-marker-positions)))
3892 (when marker
3893 (delete-region (cl-second marker) (cl-third marker))
3894 (butlast marker))))
3896 (defun markdown-footnote-kill-text ()
3897 "Kill footnote text at point.
3898 Returns the start position of the footnote text before deletion,
3899 or NIL if point was not inside a footnote text.
3901 The killed text is placed in the kill ring (without the footnote
3902 number)."
3903 (let ((fn (markdown-footnote-text-positions)))
3904 (when fn
3905 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
3906 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
3907 (kill-new (match-string 1 text))
3908 (when (and (markdown-cur-line-blank-p)
3909 (markdown-prev-line-blank-p)
3910 (not (bobp)))
3911 (delete-region (1- (point)) (point)))
3912 (cl-second fn)))))
3914 (defun markdown-footnote-goto-text ()
3915 "Jump to the text of the footnote at point."
3916 (interactive)
3917 (let ((fn (car (markdown-footnote-marker-positions))))
3918 (unless fn
3919 (error "Not at a footnote marker"))
3920 (let ((new-pos (markdown-footnote-find-text fn)))
3921 (unless new-pos
3922 (error "No definition found for footnote `%s'" fn))
3923 (goto-char new-pos))))
3925 (defun markdown-footnote-return ()
3926 "Return from a footnote to its footnote number in the main text."
3927 (interactive)
3928 (let ((fn (save-excursion
3929 (car (markdown-footnote-text-positions)))))
3930 (unless fn
3931 (error "Not in a footnote"))
3932 (let ((new-pos (markdown-footnote-find-marker fn)))
3933 (unless new-pos
3934 (error "Footnote marker `%s' not found" fn))
3935 (goto-char new-pos))))
3937 (defun markdown-footnote-find-marker (id)
3938 "Find the location of the footnote marker with ID.
3939 The actual buffer position returned is the position directly
3940 following the marker's closing bracket. If no marker is found,
3941 NIL is returned."
3942 (save-excursion
3943 (goto-char (point-min))
3944 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
3945 (skip-chars-backward "^]")
3946 (point))))
3948 (defun markdown-footnote-find-text (id)
3949 "Find the location of the text of footnote ID.
3950 The actual buffer position returned is the position of the first
3951 character of the text, after the footnote's identifier. If no
3952 footnote text is found, NIL is returned."
3953 (save-excursion
3954 (goto-char (point-min))
3955 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
3956 (skip-chars-forward "[ \t]")
3957 (point))))
3959 (defun markdown-footnote-marker-positions ()
3960 "Return the position and ID of the footnote marker point is on.
3961 The return value is a list (ID START END). If point is not on a
3962 footnote, NIL is returned."
3963 ;; first make sure we're at a footnote marker
3964 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
3965 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
3966 (save-excursion
3967 ;; move point between [ and ^:
3968 (if (looking-at-p "\\[")
3969 (forward-char 1)
3970 (skip-chars-backward "^["))
3971 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
3972 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
3974 (defun markdown-footnote-text-positions ()
3975 "Return the start and end positions of the footnote text point is in.
3976 The exact return value is a list of three elements: (ID START END).
3977 The start position is the position of the opening bracket
3978 of the footnote id. The end position is directly after the
3979 newline that ends the footnote. If point is not in a footnote,
3980 NIL is returned instead."
3981 (save-excursion
3982 (let (result)
3983 (move-beginning-of-line 1)
3984 ;; Try to find the label. If we haven't found the label and we're at a blank
3985 ;; or indented line, back up if possible.
3986 (while (and
3987 (not (and (looking-at markdown-regex-footnote-definition)
3988 (setq result (list (match-string 1) (point)))))
3989 (and (not (bobp))
3990 (or (markdown-cur-line-blank-p)
3991 (>= (current-indentation) 4))))
3992 (forward-line -1))
3993 (when result
3994 ;; Advance if there is a next line that is either blank or indented.
3995 ;; (Need to check if we're on the last line, because
3996 ;; markdown-next-line-blank-p returns true for last line in buffer.)
3997 (while (and (/= (line-end-position) (point-max))
3998 (or (markdown-next-line-blank-p)
3999 (>= (markdown-next-line-indent) 4)))
4000 (forward-line))
4001 ;; Move back while the current line is blank.
4002 (while (markdown-cur-line-blank-p)
4003 (forward-line -1))
4004 ;; Advance to capture this line and a single trailing newline (if there
4005 ;; is one).
4006 (forward-line)
4007 (append result (list (point)))))))
4010 ;;; Element Removal ===========================================================
4012 (defun markdown-kill-thing-at-point ()
4013 "Kill thing at point and add important text, without markup, to kill ring.
4014 Possible things to kill include (roughly in order of precedence):
4015 inline code, headers, horizonal rules, links (add link text to
4016 kill ring), images (add alt text to kill ring), angle uri, email
4017 addresses, bold, italics, reference definition (add URI to kill
4018 ring), footnote markers and text (kill both marker and text, add
4019 text to kill ring), and list items."
4020 (interactive "*")
4021 (let (val)
4022 (cond
4023 ;; Inline code
4024 ((markdown-code-at-point-p)
4025 (kill-new (match-string 2))
4026 (delete-region (match-beginning 0) (match-end 0)))
4027 ;; ATX header
4028 ((thing-at-point-looking-at markdown-regex-header-atx)
4029 (kill-new (match-string 2))
4030 (delete-region (match-beginning 0) (match-end 0)))
4031 ;; Setext header
4032 ((thing-at-point-looking-at markdown-regex-header-setext)
4033 (kill-new (match-string 1))
4034 (delete-region (match-beginning 0) (match-end 0)))
4035 ;; Horizonal rule
4036 ((thing-at-point-looking-at markdown-regex-hr)
4037 (kill-new (match-string 0))
4038 (delete-region (match-beginning 0) (match-end 0)))
4039 ;; Inline link or image (add link or alt text to kill ring)
4040 ((thing-at-point-looking-at markdown-regex-link-inline)
4041 (kill-new (match-string 3))
4042 (delete-region (match-beginning 0) (match-end 0)))
4043 ;; Reference link or image (add link or alt text to kill ring)
4044 ((thing-at-point-looking-at markdown-regex-link-reference)
4045 (kill-new (match-string 3))
4046 (delete-region (match-beginning 0) (match-end 0)))
4047 ;; Angle URI (add URL to kill ring)
4048 ((thing-at-point-looking-at markdown-regex-angle-uri)
4049 (kill-new (match-string 2))
4050 (delete-region (match-beginning 0) (match-end 0)))
4051 ;; Email address in angle brackets (add email address to kill ring)
4052 ((thing-at-point-looking-at markdown-regex-email)
4053 (kill-new (match-string 1))
4054 (delete-region (match-beginning 0) (match-end 0)))
4055 ;; Wiki link (add alias text to kill ring)
4056 ((and markdown-enable-wiki-links
4057 (thing-at-point-looking-at markdown-regex-wiki-link))
4058 (kill-new (markdown-wiki-link-alias))
4059 (delete-region (match-beginning 1) (match-end 1)))
4060 ;; Bold
4061 ((thing-at-point-looking-at markdown-regex-bold)
4062 (kill-new (match-string 4))
4063 (delete-region (match-beginning 2) (match-end 2)))
4064 ;; Italics
4065 ((thing-at-point-looking-at markdown-regex-italic)
4066 (kill-new (match-string 3))
4067 (delete-region (match-beginning 1) (match-end 1)))
4068 ;; Strikethrough
4069 ((thing-at-point-looking-at markdown-regex-strike-through)
4070 (kill-new (match-string 4))
4071 (delete-region (match-beginning 2) (match-end 2)))
4072 ;; Footnote marker (add footnote text to kill ring)
4073 ((thing-at-point-looking-at markdown-regex-footnote)
4074 (markdown-footnote-kill))
4075 ;; Footnote text (add footnote text to kill ring)
4076 ((setq val (markdown-footnote-text-positions))
4077 (markdown-footnote-kill))
4078 ;; Reference definition (add URL to kill ring)
4079 ((thing-at-point-looking-at markdown-regex-reference-definition)
4080 (kill-new (match-string 5))
4081 (delete-region (match-beginning 0) (match-end 0)))
4082 ;; List item
4083 ((setq val (markdown-cur-list-item-bounds))
4084 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4086 (error "Nothing found at point to kill")))))
4089 ;;; Indentation ====================================================================
4091 (defun markdown-indent-find-next-position (cur-pos positions)
4092 "Return the position after the index of CUR-POS in POSITIONS.
4093 Positions are calculated by `markdown-calc-indents'."
4094 (while (and positions
4095 (not (equal cur-pos (car positions))))
4096 (setq positions (cdr positions)))
4097 (or (cadr positions) 0))
4099 (defun markdown-exdent-find-next-position (cur-pos positions)
4100 "Return the maximal element that precedes CUR-POS from POSITIONS.
4101 Positions are calculated by `markdown-calc-indents'."
4102 (let ((result 0))
4103 (dolist (i positions)
4104 (when (< i cur-pos)
4105 (setq result (max result i))))
4106 result))
4108 (defun markdown-indent-line ()
4109 "Indent the current line using some heuristics.
4110 If the _previous_ command was either `markdown-enter-key' or
4111 `markdown-cycle', then we should cycle to the next
4112 reasonable indentation position. Otherwise, we could have been
4113 called directly by `markdown-enter-key', by an initial call of
4114 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4115 these cases, indent to the default position.
4116 Positions are calculated by `markdown-calc-indents'."
4117 (interactive)
4118 (let ((positions (markdown-calc-indents))
4119 (cursor-pos (current-column))
4120 (_ (back-to-indentation))
4121 (cur-pos (current-column)))
4122 (if (not (equal this-command 'markdown-cycle))
4123 (indent-line-to (car positions))
4124 (setq positions (sort (delete-dups positions) '<))
4125 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4126 (new-cursor-pos
4127 (if (< cur-pos next-pos)
4128 (+ cursor-pos (- next-pos cur-pos))
4129 (- cursor-pos cur-pos))))
4130 (indent-line-to next-pos)
4131 (move-to-column new-cursor-pos)))))
4133 (defun markdown-calc-indents ()
4134 "Return a list of indentation columns to cycle through.
4135 The first element in the returned list should be considered the
4136 default indentation level. This function does not worry about
4137 duplicate positions, which are handled up by calling functions."
4138 (let (pos prev-line-pos positions)
4140 ;; Indentation of previous line
4141 (setq prev-line-pos (markdown-prev-line-indent))
4142 (setq positions (cons prev-line-pos positions))
4144 ;; Indentation of previous non-list-marker text
4145 (when (setq pos (markdown-prev-non-list-indent))
4146 (setq positions (cons pos positions)))
4148 ;; Indentation required for a pre block in current context
4149 (setq pos (length (markdown-pre-indentation (point))))
4150 (setq positions (cons pos positions))
4152 ;; Indentation of the previous line + tab-width
4153 (if prev-line-pos
4154 (setq positions (cons (+ prev-line-pos tab-width) positions))
4155 (setq positions (cons tab-width positions)))
4157 ;; Indentation of the previous line - tab-width
4158 (if (and prev-line-pos (> prev-line-pos tab-width))
4159 (setq positions (cons (- prev-line-pos tab-width) positions)))
4161 ;; Indentation of all preceeding list markers (when in a list)
4162 (when (setq pos (markdown-calculate-list-levels))
4163 (setq positions (append pos positions)))
4165 ;; First column
4166 (setq positions (cons 0 positions))
4168 ;; Return reversed list
4169 (reverse positions)))
4171 (defun markdown-enter-key ()
4172 "Handle RET according to to the value of `markdown-indent-on-enter'."
4173 (interactive)
4174 (newline)
4175 (when markdown-indent-on-enter
4176 (markdown-indent-line)))
4178 (defun markdown-exdent-or-delete (arg)
4179 "Handle BACKSPACE by cycling through indentation points.
4180 When BACKSPACE is pressed, if there is only whitespace
4181 before the current point, then exdent the line one level.
4182 Otherwise, do normal delete by repeating
4183 `backward-delete-char-untabify' ARG times."
4184 (interactive "*p")
4185 (if (use-region-p)
4186 (backward-delete-char-untabify arg)
4187 (let ((cur-pos (current-column))
4188 (start-of-indention (save-excursion
4189 (back-to-indentation)
4190 (current-column)))
4191 (positions (markdown-calc-indents)))
4192 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4193 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
4194 (backward-delete-char-untabify arg)))))
4196 (defun markdown-find-leftmost-column (beg end)
4197 "Find the leftmost column in the region from BEG to END."
4198 (let ((mincol 1000))
4199 (save-excursion
4200 (goto-char beg)
4201 (while (< (point) end)
4202 (back-to-indentation)
4203 (unless (looking-at-p "[ \t]*$")
4204 (setq mincol (min mincol (current-column))))
4205 (forward-line 1)
4207 mincol))
4209 (defun markdown-indent-region (beg end arg)
4210 "Indent the region from BEG to END using some heuristics.
4211 When ARG is non-nil, exdent the region instead.
4212 See `markdown-indent-line' and `markdown-indent-line'."
4213 (interactive "*r\nP")
4214 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4215 (leftmostcol (markdown-find-leftmost-column beg end))
4216 (next-pos (if arg
4217 (markdown-exdent-find-next-position leftmostcol positions)
4218 (markdown-indent-find-next-position leftmostcol positions))))
4219 (indent-rigidly beg end (- next-pos leftmostcol))
4220 (setq deactivate-mark nil)))
4222 (defun markdown-exdent-region (beg end)
4223 "Call `markdown-indent-region' on region from BEG to END with prefix."
4224 (interactive "*r")
4225 (markdown-indent-region beg end t))
4228 ;;; Markup Completion =========================================================
4230 (defconst markdown-complete-alist
4231 '((markdown-regex-header-atx . markdown-complete-atx)
4232 (markdown-regex-header-setext . markdown-complete-setext)
4233 (markdown-regex-hr . markdown-complete-hr))
4234 "Association list of form (regexp . function) for markup completion.")
4236 (defun markdown-incomplete-atx-p ()
4237 "Return t if ATX header markup is incomplete and nil otherwise.
4238 Assumes match data is available for `markdown-regex-header-atx'.
4239 Checks that the number of trailing hash marks equals the number of leading
4240 hash marks, that there is only a single space before and after the text,
4241 and that there is no extraneous whitespace in the text."
4243 ;; Number of starting and ending hash marks differs
4244 (not (= (length (match-string 1)) (length (match-string 3))))
4245 ;; When the header text is not empty...
4246 (and (> (length (match-string 2)) 0)
4247 ;; ...if there are extra leading, trailing, or interior spaces
4248 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4249 (not (= (match-beginning 3) (1+ (match-end 2))))
4250 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4251 ;; When the header text is empty...
4252 (and (= (length (match-string 2)) 0)
4253 ;; ...if there are too many or too few spaces
4254 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4256 (defun markdown-complete-atx ()
4257 "Complete and normalize ATX headers.
4258 Add or remove hash marks to the end of the header to match the
4259 beginning. Ensure that there is only a single space between hash
4260 marks and header text. Removes extraneous whitespace from header text.
4261 Assumes match data is available for `markdown-regex-header-atx'.
4262 Return nil if markup was complete and non-nil if markup was completed."
4263 (when (markdown-incomplete-atx-p)
4264 (let* ((new-marker (make-marker))
4265 (new-marker (set-marker new-marker (match-end 2))))
4266 ;; Hash marks and spacing at end
4267 (goto-char (match-end 2))
4268 (delete-region (match-end 2) (match-end 3))
4269 (insert " " (match-string 1))
4270 ;; Remove extraneous whitespace from title
4271 (replace-match (markdown-compress-whitespace-string (match-string 2))
4272 t t nil 2)
4273 ;; Spacing at beginning
4274 (goto-char (match-end 1))
4275 (delete-region (match-end 1) (match-beginning 2))
4276 (insert " ")
4277 ;; Leave point at end of text
4278 (goto-char new-marker))))
4280 (defun markdown-incomplete-setext-p ()
4281 "Return t if setext header markup is incomplete and nil otherwise.
4282 Assumes match data is available for `markdown-regex-header-setext'.
4283 Checks that length of underline matches text and that there is no
4284 extraneous whitespace in the text."
4285 (or (not (= (length (match-string 1)) (length (match-string 2))))
4286 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4288 (defun markdown-complete-setext ()
4289 "Complete and normalize setext headers.
4290 Add or remove underline characters to match length of header
4291 text. Removes extraneous whitespace from header text. Assumes
4292 match data is available for `markdown-regex-header-setext'.
4293 Return nil if markup was complete and non-nil if markup was completed."
4294 (when (markdown-incomplete-setext-p)
4295 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4296 (char (char-after (match-beginning 2)))
4297 (level (if (char-equal char ?-) 2 1)))
4298 (goto-char (match-beginning 0))
4299 (delete-region (match-beginning 0) (match-end 0))
4300 (markdown-insert-header level text t)
4301 t)))
4303 (defun markdown-incomplete-hr-p ()
4304 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4305 Assumes match data is available for `markdown-regex-hr'."
4306 (not (member (match-string 0) markdown-hr-strings)))
4308 (defun markdown-complete-hr ()
4309 "Complete horizontal rules.
4310 If horizontal rule string is a member of `markdown-hr-strings',
4311 do nothing. Otherwise, replace with the car of
4312 `markdown-hr-strings'.
4313 Assumes match data is available for `markdown-regex-hr'.
4314 Return nil if markup was complete and non-nil if markup was completed."
4315 (when (markdown-incomplete-hr-p)
4316 (replace-match (car markdown-hr-strings))
4319 (defun markdown-complete ()
4320 "Complete markup of object near point or in region when active.
4321 Handle all objects in `markdown-complete-alist', in order.
4322 See `markdown-complete-at-point' and `markdown-complete-region'."
4323 (interactive "*")
4324 (if (markdown-use-region-p)
4325 (markdown-complete-region (region-beginning) (region-end))
4326 (markdown-complete-at-point)))
4328 (defun markdown-complete-at-point ()
4329 "Complete markup of object near point.
4330 Handle all elements of `markdown-complete-alist' in order."
4331 (interactive "*")
4332 (let ((list markdown-complete-alist) found changed)
4333 (while list
4334 (let ((regexp (eval (caar list)))
4335 (function (cdar list)))
4336 (setq list (cdr list))
4337 (when (thing-at-point-looking-at regexp)
4338 (setq found t)
4339 (setq changed (funcall function))
4340 (setq list nil))))
4341 (if found
4342 (or changed (error "Markup at point is complete"))
4343 (error "Nothing to complete at point"))))
4345 (defun markdown-complete-region (beg end)
4346 "Complete markup of objects in region from BEG to END.
4347 Handle all objects in `markdown-complete-alist', in order. Each
4348 match is checked to ensure that a previous regexp does not also
4349 match."
4350 (interactive "*r")
4351 (let ((end-marker (set-marker (make-marker) end))
4352 previous)
4353 (dolist (element markdown-complete-alist)
4354 (let ((regexp (eval (car element)))
4355 (function (cdr element)))
4356 (goto-char beg)
4357 (while (re-search-forward regexp end-marker 'limit)
4358 (when (match-string 0)
4359 ;; Make sure this is not a match for any of the preceding regexps.
4360 ;; This prevents mistaking an HR for a Setext subheading.
4361 (let (match)
4362 (save-match-data
4363 (dolist (prev-regexp previous)
4364 (or match (setq match (looking-back prev-regexp nil)))))
4365 (unless match
4366 (save-excursion (funcall function))))))
4367 (cl-pushnew regexp previous :test #'equal)))
4368 previous))
4370 (defun markdown-complete-buffer ()
4371 "Complete markup for all objects in the current buffer."
4372 (interactive "*")
4373 (markdown-complete-region (point-min) (point-max)))
4376 ;;; Markup Cycling ============================================================
4378 (defun markdown-cycle-atx (arg &optional remove)
4379 "Cycle ATX header markup.
4380 Promote header (decrease level) when ARG is 1 and demote
4381 header (increase level) if arg is -1. When REMOVE is non-nil,
4382 remove the header when the level reaches zero and stop cycling
4383 when it reaches six. Otherwise, perform a proper cycling through
4384 levels one through six. Assumes match data is available for
4385 `markdown-regex-header-atx'."
4386 (let* ((old-level (length (match-string 1)))
4387 (new-level (+ old-level arg))
4388 (text (match-string 2)))
4389 (when (not remove)
4390 (setq new-level (% new-level 6))
4391 (setq new-level (cond ((= new-level 0) 6)
4392 ((< new-level 0) (+ new-level 6))
4393 (t new-level))))
4394 (cond
4395 ((= new-level 0)
4396 (markdown-unwrap-thing-at-point nil 0 2))
4397 ((<= new-level 6)
4398 (goto-char (match-beginning 0))
4399 (delete-region (match-beginning 0) (match-end 0))
4400 (markdown-insert-header new-level text nil)))))
4402 (defun markdown-cycle-setext (arg &optional remove)
4403 "Cycle setext header markup.
4404 Promote header (increase level) when ARG is 1 and demote
4405 header (decrease level or remove) if arg is -1. When demoting a
4406 level-two setext header, replace with a level-three atx header.
4407 When REMOVE is non-nil, remove the header when the level reaches
4408 zero. Otherwise, cycle back to a level six atx header. Assumes
4409 match data is available for `markdown-regex-header-setext'."
4410 (let* ((char (char-after (match-beginning 2)))
4411 (old-level (if (char-equal char ?=) 1 2))
4412 (new-level (+ old-level arg)))
4413 (when (and (not remove) (= new-level 0))
4414 (setq new-level 6))
4415 (cond
4416 ((= new-level 0)
4417 (markdown-unwrap-thing-at-point nil 0 1))
4418 ((<= new-level 2)
4419 (markdown-insert-header new-level nil t))
4420 ((<= new-level 6)
4421 (markdown-insert-header new-level nil nil)))))
4423 (defun markdown-cycle-hr (arg &optional remove)
4424 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4425 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4426 backwards (promote). When REMOVE is non-nil, remove the hr instead
4427 of cycling when the end of the list is reached.
4428 Assumes match data is available for `markdown-regex-hr'."
4429 (let* ((strings (if (= arg -1)
4430 (reverse markdown-hr-strings)
4431 markdown-hr-strings))
4432 (tail (member (match-string 0) strings))
4433 (new (or (cadr tail)
4434 (if remove
4435 (if (= arg 1)
4437 (car tail))
4438 (car strings)))))
4439 (replace-match new)))
4441 (defun markdown-cycle-bold ()
4442 "Cycle bold markup between underscores and asterisks.
4443 Assumes match data is available for `markdown-regex-bold'."
4444 (save-excursion
4445 (let* ((old-delim (match-string 3))
4446 (new-delim (if (string-equal old-delim "**") "__" "**")))
4447 (replace-match new-delim t t nil 3)
4448 (replace-match new-delim t t nil 5))))
4450 (defun markdown-cycle-italic ()
4451 "Cycle italic markup between underscores and asterisks.
4452 Assumes match data is available for `markdown-regex-italic'."
4453 (save-excursion
4454 (let* ((old-delim (match-string 2))
4455 (new-delim (if (string-equal old-delim "*") "_" "*")))
4456 (replace-match new-delim t t nil 2)
4457 (replace-match new-delim t t nil 4))))
4460 ;;; Keymap ====================================================================
4462 (defvar markdown-mode-map
4463 (let ((map (make-keymap)))
4464 ;; Element insertion
4465 (define-key map "\C-c\C-al" 'markdown-insert-link)
4466 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
4467 (define-key map "\C-c\C-au" 'markdown-insert-uri)
4468 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
4469 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
4470 (define-key map "\C-c\C-ii" 'markdown-insert-image)
4471 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
4472 (define-key map "\C-c\C-i\C-t" 'markdown-toggle-inline-images)
4473 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
4474 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
4475 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
4476 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
4477 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
4478 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
4479 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
4480 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
4481 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
4482 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
4483 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
4484 (define-key map "\C-c\C-se" 'markdown-insert-italic)
4485 (define-key map "\C-c\C-sc" 'markdown-insert-code)
4486 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
4487 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
4488 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
4489 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
4490 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
4491 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
4492 (define-key map "\C-c-" 'markdown-insert-hr)
4493 ;; Element insertion (deprecated)
4494 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
4495 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
4496 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
4497 ;; Element removal
4498 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
4499 ;; Promotion, Demotion, Completion, and Cycling
4500 (define-key map (kbd "C-c C--") 'markdown-promote)
4501 (define-key map (kbd "C-c C-=") 'markdown-demote)
4502 (define-key map (kbd "C-c C-]") 'markdown-complete)
4503 ;; Following and Jumping
4504 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
4505 (define-key map (kbd "C-c C-l") 'markdown-jump)
4506 ;; Indentation
4507 (define-key map (kbd "C-m") 'markdown-enter-key)
4508 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
4509 (define-key map (kbd "C-c >") 'markdown-indent-region)
4510 (define-key map (kbd "C-c <") 'markdown-exdent-region)
4511 ;; Visibility cycling
4512 (define-key map (kbd "TAB") 'markdown-cycle)
4513 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
4514 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
4515 (define-key map (kbd "<backtab>") 'markdown-shifttab)
4516 ;; Header navigation
4517 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
4518 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
4519 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
4520 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
4521 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
4522 ;; Buffer-wide commands
4523 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
4524 (define-key map (kbd "C-c C-c p") 'markdown-preview)
4525 (define-key map (kbd "C-c C-c e") 'markdown-export)
4526 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
4527 (define-key map (kbd "C-c C-c o") 'markdown-open)
4528 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
4529 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
4530 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
4531 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
4532 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
4533 ;; List editing
4534 (define-key map (kbd "M-<up>") 'markdown-move-up)
4535 (define-key map (kbd "M-<down>") 'markdown-move-down)
4536 (define-key map (kbd "M-<left>") 'markdown-promote)
4537 (define-key map (kbd "M-<right>") 'markdown-demote)
4538 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
4539 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
4540 ;; Subtree editing
4541 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
4542 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
4543 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
4544 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
4545 ;; Movement
4546 (define-key map (kbd "M-{") 'markdown-backward-paragraph)
4547 (define-key map (kbd "M-}") 'markdown-forward-paragraph)
4548 (define-key map (kbd "M-n") 'markdown-next-link)
4549 (define-key map (kbd "M-p") 'markdown-previous-link)
4550 ;; Alternative keys (in case of problems with the arrow keys)
4551 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
4552 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
4553 (define-key map (kbd "C-c C-x l") 'markdown-promote)
4554 (define-key map (kbd "C-c C-x r") 'markdown-demote)
4555 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
4556 map)
4557 "Keymap for Markdown major mode.")
4559 (defvar gfm-mode-map
4560 (let ((map (make-sparse-keymap)))
4561 (set-keymap-parent map markdown-mode-map)
4562 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
4563 (define-key map "`" 'markdown-electric-backquote)
4564 map)
4565 "Keymap for `gfm-mode'.
4566 See also `markdown-mode-map'.")
4569 ;;; Menu ==================================================================
4571 (easy-menu-define markdown-mode-menu markdown-mode-map
4572 "Menu for Markdown mode"
4573 '("Markdown"
4574 ("Show/Hide"
4575 ["Cycle visibility" markdown-cycle (markdown-on-heading-p)]
4576 ["Cycle global visibility" markdown-shifttab])
4577 "---"
4578 ["Compile" markdown-other-window]
4579 ["Preview" markdown-preview]
4580 ["Export" markdown-export]
4581 ["Export & View" markdown-export-and-preview]
4582 ["Open" markdown-open]
4583 ["Live Export" markdown-live-preview-mode
4584 :style toggle :selected markdown-live-preview-mode]
4585 ["Kill ring save" markdown-kill-ring-save]
4586 "---"
4587 ("Headings"
4588 ["Automatic" markdown-insert-header-dwim]
4589 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
4590 "---"
4591 ["First level setext" markdown-insert-header-setext-1]
4592 ["Second level setext" markdown-insert-header-setext-2]
4593 "---"
4594 ["First level atx" markdown-insert-header-atx-1]
4595 ["Second level atx" markdown-insert-header-atx-2]
4596 ["Third level atx" markdown-insert-header-atx-3]
4597 ["Fourth level atx" markdown-insert-header-atx-4]
4598 ["Fifth level atx" markdown-insert-header-atx-5]
4599 ["Sixth level atx" markdown-insert-header-atx-6])
4600 "---"
4601 ["Bold" markdown-insert-bold]
4602 ["Italic" markdown-insert-italic]
4603 ["Strikethrough" markdown-insert-strike-through]
4604 ["Blockquote" markdown-insert-blockquote]
4605 ["Preformatted" markdown-insert-pre]
4606 ["Code" markdown-insert-code]
4607 "---"
4608 ["Insert inline link" markdown-insert-link]
4609 ["Insert reference link" markdown-insert-reference-link-dwim]
4610 ["Insert URL" markdown-insert-uri]
4611 ["Insert inline image" markdown-insert-image]
4612 ["Insert reference image" markdown-insert-reference-image]
4613 ["Insert list item" markdown-insert-list-item]
4614 ["Insert horizontal rule" markdown-insert-hr]
4615 ["Insert footnote" markdown-insert-footnote]
4616 ["Kill element" markdown-kill-thing-at-point]
4617 "---"
4618 ["Jump" markdown-jump]
4619 ["Follow link" markdown-follow-thing-at-point]
4620 ("Outline"
4621 ["Next visible heading" markdown-next-visible-heading]
4622 ["Previous visible heading" markdown-previous-visible-heading]
4623 ["Forward same level" markdown-forward-same-level]
4624 ["Backward same level" markdown-backward-same-level]
4625 ["Up to parent heading" markdown-up-heading])
4626 "---"
4627 ("Completion and Cycling"
4628 ["Complete" markdown-complete]
4629 ["Promote" markdown-promote]
4630 ["Demote" markdown-demote])
4631 ("List editing"
4632 ["Indent list item" markdown-demote]
4633 ["Exdent list item" markdown-promote])
4634 ("Region shifting"
4635 ["Indent region" markdown-indent-region]
4636 ["Exdent region" markdown-exdent-region])
4637 "---"
4638 ["Toggle inline images" markdown-toggle-inline-images]
4639 ["Check references" markdown-check-refs]
4640 ["Clean up list numbering" markdown-cleanup-list-numbers]
4641 ["Complete markup" markdown-complete-buffer]
4642 "---"
4643 ["Version" markdown-show-version]
4647 ;;; imenu =====================================================================
4649 (defun markdown-imenu-create-nested-index ()
4650 "Create and return a nested imenu index alist for the current buffer.
4651 See `imenu-create-index-function' and `imenu--index-alist' for details."
4652 (let* ((root '(nil . nil))
4653 cur-alist
4654 (cur-level 0)
4655 (empty-heading "-")
4656 (self-heading ".")
4657 hashes pos level heading)
4658 (save-excursion
4659 (goto-char (point-min))
4660 (while (re-search-forward markdown-regex-header (point-max) t)
4661 (unless (markdown-code-block-at-point)
4662 (cond
4663 ((match-string-no-properties 2) ;; level 1 setext
4664 (setq heading (match-string-no-properties 1))
4665 (setq pos (match-beginning 1)
4666 level 1))
4667 ((match-string-no-properties 3) ;; level 2 setext
4668 (setq heading (match-string-no-properties 1))
4669 (setq pos (match-beginning 1)
4670 level 2))
4671 ((setq hashes (match-string-no-properties 4))
4672 (setq heading (match-string-no-properties 5)
4673 pos (match-beginning 4)
4674 level (length hashes))))
4675 (let ((alist (list (cons heading pos))))
4676 (cond
4677 ((= cur-level level) ; new sibling
4678 (setcdr cur-alist alist)
4679 (setq cur-alist alist))
4680 ((< cur-level level) ; first child
4681 (dotimes (_ (- level cur-level 1))
4682 (setq alist (list (cons empty-heading alist))))
4683 (if cur-alist
4684 (let* ((parent (car cur-alist))
4685 (self-pos (cdr parent)))
4686 (setcdr parent (cons (cons self-heading self-pos) alist)))
4687 (setcdr root alist)) ; primogenitor
4688 (setq cur-alist alist)
4689 (setq cur-level level))
4690 (t ; new sibling of an ancestor
4691 (let ((sibling-alist (last (cdr root))))
4692 (dotimes (_ (1- level))
4693 (setq sibling-alist (last (cdar sibling-alist))))
4694 (setcdr sibling-alist alist)
4695 (setq cur-alist alist))
4696 (setq cur-level level))))))
4697 (cdr root))))
4699 (defun markdown-imenu-create-flat-index ()
4700 "Create and return a flat imenu index alist for the current buffer.
4701 See `imenu-create-index-function' and `imenu--index-alist' for details."
4702 (let* ((empty-heading "-") index heading pos)
4703 (save-excursion
4704 (goto-char (point-min))
4705 (while (re-search-forward markdown-regex-header (point-max) t)
4706 (when (and (not (markdown-code-block-at-point))
4707 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
4708 (cond
4709 ((setq heading (match-string-no-properties 1))
4710 (setq pos (match-beginning 1)))
4711 ((setq heading (match-string-no-properties 5))
4712 (setq pos (match-beginning 4))))
4713 (or (> (length heading) 0)
4714 (setq heading empty-heading))
4715 (setq index (append index (list (cons heading pos))))))
4716 index)))
4719 ;;; References ================================================================
4721 (defun markdown-reference-goto-definition ()
4722 "Jump to the definition of the reference at point or create it."
4723 (interactive)
4724 (when (thing-at-point-looking-at markdown-regex-link-reference)
4725 (let* ((text (match-string-no-properties 3))
4726 (reference (match-string-no-properties 6))
4727 (target (downcase (if (string= reference "") text reference)))
4728 (loc (cadr (markdown-reference-definition target))))
4729 (if loc
4730 (goto-char loc)
4731 (goto-char (match-beginning 0))
4732 (markdown-insert-reference-definition target)))))
4734 (defun markdown-reference-find-links (reference)
4735 "Return a list of all links for REFERENCE.
4736 REFERENCE should not include the surrounding square brackets.
4737 Elements of the list have the form (text start line), where
4738 text is the link text, start is the location at the beginning of
4739 the link, and line is the line number on which the link appears."
4740 (let* ((ref-quote (regexp-quote reference))
4741 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4742 ref-quote ref-quote))
4743 links)
4744 (save-excursion
4745 (goto-char (point-min))
4746 (while (re-search-forward regexp nil t)
4747 (let* ((text (or (match-string-no-properties 1)
4748 (match-string-no-properties 2)))
4749 (start (match-beginning 0))
4750 (line (markdown-line-number-at-pos)))
4751 (cl-pushnew (list text start line) links :test #'equal))))
4752 links))
4754 (defun markdown-get-undefined-refs ()
4755 "Return a list of undefined Markdown references.
4756 Result is an alist of pairs (reference . occurrences), where
4757 occurrences is itself another alist of pairs (label . line-number).
4758 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4759 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4760 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4761 (let ((missing))
4762 (save-excursion
4763 (goto-char (point-min))
4764 (while
4765 (re-search-forward markdown-regex-link-reference nil t)
4766 (let* ((text (match-string-no-properties 3))
4767 (reference (match-string-no-properties 6))
4768 (target (downcase (if (string= reference "") text reference))))
4769 (unless (markdown-reference-definition target)
4770 (let ((entry (assoc target missing)))
4771 (if (not entry)
4772 (cl-pushnew
4773 (cons target (list (cons text (markdown-line-number-at-pos))))
4774 missing :test #'equal)
4775 (setcdr entry
4776 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
4777 (reverse missing))))
4779 (defconst markdown-reference-check-buffer
4780 "*Undefined references for %buffer%*"
4781 "Pattern for name of buffer for listing undefined references.
4782 The string %buffer% will be replaced by the corresponding
4783 `markdown-mode' buffer name.")
4785 (defun markdown-reference-check-buffer (&optional buffer-name)
4786 "Name and return buffer for reference checking.
4787 BUFFER-NAME is the name of the main buffer being visited."
4788 (or buffer-name (setq buffer-name (buffer-name)))
4789 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
4790 "%buffer%" buffer-name
4791 markdown-reference-check-buffer))))
4792 (with-current-buffer refbuf
4793 (when view-mode
4794 (View-exit-and-edit))
4795 (use-local-map button-buffer-map)
4796 (erase-buffer))
4797 refbuf))
4799 (defconst markdown-reference-links-buffer
4800 "*Reference links for %buffer%*"
4801 "Pattern for name of buffer for listing references.
4802 The string %buffer% will be replaced by the corresponding buffer name.")
4804 (defun markdown-reference-links-buffer (&optional buffer-name)
4805 "Name, setup, and return a buffer for listing links.
4806 BUFFER-NAME is the name of the main buffer being visited."
4807 (or buffer-name (setq buffer-name (buffer-name)))
4808 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
4809 "%buffer%" buffer-name
4810 markdown-reference-links-buffer))))
4811 (with-current-buffer linkbuf
4812 (when view-mode
4813 (View-exit-and-edit))
4814 (use-local-map button-buffer-map)
4815 (erase-buffer))
4816 linkbuf))
4818 (when (markdown-use-buttons-p)
4819 ;; Add an empty Markdown reference definition to buffer
4820 ;; specified in the 'target-buffer property. The reference name is
4821 ;; the button's label.
4822 (define-button-type 'markdown-undefined-reference-button
4823 'help-echo "mouse-1, RET: create definition for undefined reference"
4824 'follow-link t
4825 'face 'bold
4826 'action (lambda (b)
4827 (let ((buffer (button-get b 'target-buffer))
4828 (line (button-get b 'target-line))
4829 (label (button-label b)))
4830 (switch-to-buffer-other-window buffer)
4831 (goto-char (point-min))
4832 (forward-line line)
4833 (markdown-insert-reference-definition label)
4834 (markdown-check-refs t))))
4836 ;; Jump to line in buffer specified by 'target-buffer property.
4837 ;; Line number is button's 'line property.
4838 (define-button-type 'markdown-goto-line-button
4839 'help-echo "mouse-1, RET: go to line"
4840 'follow-link t
4841 'face 'italic
4842 'action (lambda (b)
4843 (message (button-get b 'buffer))
4844 (switch-to-buffer-other-window (button-get b 'target-buffer))
4845 ;; use call-interactively to silence compiler
4846 (let ((current-prefix-arg (button-get b 'target-line)))
4847 (call-interactively 'goto-line))))
4849 ;; Jumps to a particular link at location given by 'target-char
4850 ;; property in buffer given by 'target-buffer property.
4851 (define-button-type 'markdown-link-button
4852 'help-echo "mouse-1, RET: jump to location of link"
4853 'follow-link t
4854 'face 'bold
4855 'action (lambda (b)
4856 (let ((target (button-get b 'target-buffer))
4857 (loc (button-get b 'target-char)))
4858 (kill-buffer-and-window)
4859 (switch-to-buffer target)
4860 (goto-char loc)))))
4862 (defun markdown-insert-undefined-reference-button (reference oldbuf)
4863 "Insert a button for creating REFERENCE in buffer OLDBUF.
4864 REFERENCE should be a list of the form (reference . occurrences),
4865 as by `markdown-get-undefined-refs'."
4866 (let ((label (car reference)))
4867 (if (markdown-use-buttons-p)
4868 ;; Create a reference button in Emacs 22
4869 (insert-button label
4870 :type 'markdown-undefined-reference-button
4871 'target-buffer oldbuf
4872 'target-line (cdr (car (cdr reference))))
4873 ;; Insert reference as text in Emacs < 22
4874 (insert label))
4875 (insert " (")
4876 (dolist (occurrence (cdr reference))
4877 (let ((line (cdr occurrence)))
4878 (if (markdown-use-buttons-p)
4879 ;; Create a line number button in Emacs 22
4880 (insert-button (number-to-string line)
4881 :type 'markdown-goto-line-button
4882 'target-buffer oldbuf
4883 'target-line line)
4884 ;; Insert line number as text in Emacs < 22
4885 (insert (number-to-string line)))
4886 (insert " ")))
4887 (delete-char -1)
4888 (insert ")")
4889 (newline)))
4891 (defun markdown-insert-link-button (link oldbuf)
4892 "Insert a button for jumping to LINK in buffer OLDBUF.
4893 LINK should be a list of the form (text char line) containing
4894 the link text, location, and line number."
4895 (let ((label (cl-first link))
4896 (char (cl-second link))
4897 (line (cl-third link)))
4898 (if (markdown-use-buttons-p)
4899 ;; Create a reference button in Emacs 22
4900 (insert-button label
4901 :type 'markdown-link-button
4902 'target-buffer oldbuf
4903 'target-char char)
4904 ;; Insert reference as text in Emacs < 22
4905 (insert label))
4906 (insert (format " (line %d)\n" line))))
4908 (defun markdown-reference-goto-link (&optional reference)
4909 "Jump to the location of the first use of REFERENCE."
4910 (interactive)
4911 (unless reference
4912 (if (thing-at-point-looking-at markdown-regex-reference-definition)
4913 (setq reference (match-string-no-properties 2))
4914 (error "No reference definition at point")))
4915 (let ((links (markdown-reference-find-links reference)))
4916 (cond ((= (length links) 1)
4917 (goto-char (cadr (car links))))
4918 ((> (length links) 1)
4919 (let ((oldbuf (current-buffer))
4920 (linkbuf (markdown-reference-links-buffer)))
4921 (with-current-buffer linkbuf
4922 (insert "Links using reference " reference ":\n\n")
4923 (dolist (link (reverse links))
4924 (markdown-insert-link-button link oldbuf)))
4925 (view-buffer-other-window linkbuf)
4926 (goto-char (point-min))
4927 (forward-line 2)))
4929 (error "No links for reference %s" reference)))))
4931 (defun markdown-check-refs (&optional silent)
4932 "Show all undefined Markdown references in current `markdown-mode' buffer.
4933 If SILENT is non-nil, do not message anything when no undefined
4934 references found.
4935 Links which have empty reference definitions are considered to be
4936 defined."
4937 (interactive "P")
4938 (when (not (eq major-mode 'markdown-mode))
4939 (error "Not available in current mode"))
4940 (let ((oldbuf (current-buffer))
4941 (refs (markdown-get-undefined-refs))
4942 (refbuf (markdown-reference-check-buffer)))
4943 (if (null refs)
4944 (progn
4945 (when (not silent)
4946 (message "No undefined references found"))
4947 (kill-buffer refbuf))
4948 (with-current-buffer refbuf
4949 (insert "The following references are undefined:\n\n")
4950 (dolist (ref refs)
4951 (markdown-insert-undefined-reference-button ref oldbuf))
4952 (view-buffer-other-window refbuf)
4953 (goto-char (point-min))
4954 (forward-line 2)))))
4957 ;;; Lists =====================================================================
4959 (defun markdown-insert-list-item (&optional arg)
4960 "Insert a new list item.
4961 If the point is inside unordered list, insert a bullet mark. If
4962 the point is inside ordered list, insert the next number followed
4963 by a period. Use the previous list item to determine the amount
4964 of whitespace to place before and after list markers.
4966 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4967 decrease the indentation by one level.
4969 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4970 increase the indentation by one level."
4971 (interactive "p")
4972 (let (bounds cur-indent marker indent new-indent new-loc)
4973 (save-match-data
4974 ;; Look for a list item on current or previous non-blank line
4975 (save-excursion
4976 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
4977 (not (bobp))
4978 (markdown-cur-line-blank-p))
4979 (forward-line -1)))
4980 (when bounds
4981 (cond ((save-excursion
4982 (skip-chars-backward " \t")
4983 (looking-at-p markdown-regex-list))
4984 (beginning-of-line)
4985 (insert "\n")
4986 (forward-line -1))
4987 ((not (markdown-cur-line-blank-p))
4988 (newline)))
4989 (setq new-loc (point)))
4990 ;; Look ahead for a list item on next non-blank line
4991 (unless bounds
4992 (save-excursion
4993 (while (and (null bounds)
4994 (not (eobp))
4995 (markdown-cur-line-blank-p))
4996 (forward-line)
4997 (setq bounds (markdown-cur-list-item-bounds))))
4998 (when bounds
4999 (setq new-loc (point))
5000 (unless (markdown-cur-line-blank-p)
5001 (newline))))
5002 (if (not bounds)
5003 ;; When not in a list, start a new unordered one
5004 (progn
5005 (unless (markdown-cur-line-blank-p)
5006 (insert "\n"))
5007 (insert markdown-unordered-list-item-prefix))
5008 ;; Compute indentation and marker for new list item
5009 (setq cur-indent (nth 2 bounds))
5010 (setq marker (nth 4 bounds))
5011 (cond
5012 ;; Dedent: decrement indentation, find previous marker.
5013 ((= arg 4)
5014 (setq indent (max (- cur-indent 4) 0))
5015 (let ((prev-bounds
5016 (save-excursion
5017 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5018 (markdown-cur-list-item-bounds)))))
5019 (when prev-bounds
5020 (setq marker (nth 4 prev-bounds)))))
5021 ;; Indent: increment indentation by 4, use same marker.
5022 ((= arg 16) (setq indent (+ cur-indent 4)))
5023 ;; Same level: keep current indentation and marker.
5024 (t (setq indent cur-indent)))
5025 (setq new-indent (make-string indent 32))
5026 (goto-char new-loc)
5027 (cond
5028 ;; Ordered list
5029 ((string-match-p "[0-9]" marker)
5030 (if (= arg 16) ;; starting a new column indented one more level
5031 (insert (concat new-indent "1. "))
5032 ;; Don't use previous match-data
5033 (set-match-data nil)
5034 ;; travel up to the last item and pick the correct number. If
5035 ;; the argument was nil, "new-indent = cur-indent" is the same,
5036 ;; so we don't need special treatment. Neat.
5037 (save-excursion
5038 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5039 (>= (forward-line -1) 0))))
5040 (let* ((old-prefix (match-string 1))
5041 (old-spacing (match-string 2))
5042 (new-prefix (if old-prefix
5043 (int-to-string (1+ (string-to-number old-prefix)))
5044 "1"))
5045 (space-adjust (- (length old-prefix) (length new-prefix)))
5046 (new-spacing (if (and (match-string 2)
5047 (not (string-match-p "\t" old-spacing))
5048 (< space-adjust 0)
5049 (> space-adjust (- 1 (length (match-string 2)))))
5050 (substring (match-string 2) 0 space-adjust)
5051 (or old-spacing ". "))))
5052 (insert (concat new-indent new-prefix new-spacing)))))
5053 ;; Unordered list, or ordered list with hash mark
5054 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5055 (insert new-indent marker)))))))
5057 (defun markdown-move-list-item-up ()
5058 "Move the current list item up in the list when possible."
5059 (interactive)
5060 (let (cur prev old)
5061 (when (setq cur (markdown-cur-list-item-bounds))
5062 (setq old (point))
5063 (goto-char (nth 0 cur))
5064 (if (markdown-prev-list-item (nth 3 cur))
5065 (progn
5066 (setq prev (markdown-cur-list-item-bounds))
5067 (condition-case nil
5068 (progn
5069 (transpose-regions (nth 0 prev) (nth 1 prev)
5070 (nth 0 cur) (nth 1 cur) t)
5071 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5072 ;; Catch error in case regions overlap.
5073 (error (goto-char old))))
5074 (goto-char old)))))
5076 (defun markdown-move-list-item-down ()
5077 "Move the current list item down in the list when possible."
5078 (interactive)
5079 (let (cur next old)
5080 (when (setq cur (markdown-cur-list-item-bounds))
5081 (setq old (point))
5082 (if (markdown-next-list-item (nth 3 cur))
5083 (progn
5084 (setq next (markdown-cur-list-item-bounds))
5085 (condition-case nil
5086 (progn
5087 (transpose-regions (nth 0 cur) (nth 1 cur)
5088 (nth 0 next) (nth 1 next) nil)
5089 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5090 ;; Catch error in case regions overlap.
5091 (error (goto-char old))))
5092 (goto-char old)))))
5094 (defun markdown-demote-list-item (&optional bounds)
5095 "Indent (or demote) the current list item.
5096 Optionally, BOUNDS of the current list item may be provided if available."
5097 (interactive)
5098 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5099 (save-excursion
5100 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5101 (goto-char (nth 0 bounds))
5102 (while (< (point) end-marker)
5103 (unless (markdown-cur-line-blank-p)
5104 (insert (make-string markdown-list-indent-width ? )))
5105 (forward-line))))))
5107 (defun markdown-promote-list-item (&optional bounds)
5108 "Unindent (or promote) the current list item.
5109 Optionally, BOUNDS of the current list item may be provided if available."
5110 (interactive)
5111 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5112 (save-excursion
5113 (save-match-data
5114 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5115 num regexp)
5116 (goto-char (nth 0 bounds))
5117 (when (looking-at (format "^[ ]\\{1,%d\\}"
5118 markdown-list-indent-width))
5119 (setq num (- (match-end 0) (match-beginning 0)))
5120 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5121 (while (and (< (point) end-marker)
5122 (re-search-forward regexp end-marker t))
5123 (replace-match "" nil nil)
5124 (forward-line))))))))
5126 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5127 "Update the numbering for level PFX (as a string of spaces).
5129 Assume that the previously found match was for a numbered item in
5130 a list."
5131 (let ((cpfx pfx)
5132 (idx 0)
5133 (continue t)
5134 (step t)
5135 (sep nil))
5136 (while (and continue (not (eobp)))
5137 (setq step t)
5138 (cond
5139 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5140 (setq cpfx (match-string-no-properties 1))
5141 (cond
5142 ((string= cpfx pfx)
5143 (save-excursion
5144 (replace-match
5145 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5146 (setq sep nil))
5147 ;; indented a level
5148 ((string< pfx cpfx)
5149 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5150 (setq step nil))
5151 ;; exit the loop
5153 (setq step nil)
5154 (setq continue nil))))
5156 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5157 (setq cpfx (match-string-no-properties 1))
5158 (cond
5159 ;; reset if separated before
5160 ((string= cpfx pfx) (when sep (setq idx 0)))
5161 ((string< cpfx pfx)
5162 (setq step nil)
5163 (setq continue nil))))
5164 (t (setq sep t)))
5166 (when step
5167 (beginning-of-line)
5168 (setq continue (= (forward-line) 0))))
5169 sep))
5171 (defun markdown-cleanup-list-numbers ()
5172 "Update the numbering of ordered lists."
5173 (interactive)
5174 (save-excursion
5175 (goto-char (point-min))
5176 (markdown-cleanup-list-numbers-level "")))
5179 ;;; Movement ==================================================================
5181 (defun markdown-beginning-of-defun (&optional arg)
5182 "`beginning-of-defun-function' for Markdown.
5183 Move backward to the beginning of the current or previous section.
5184 When ARG is non-nil, repeat that many times. When ARG is negative,
5185 move forward to the ARG-th following section."
5186 (interactive "P")
5187 (or arg (setq arg 1))
5188 (forward-char 1)
5189 (or (re-search-backward markdown-regex-header nil t arg)
5190 (goto-char (point-min))))
5192 (defun markdown-end-of-defun (&optional arg)
5193 "`end-of-defun-function' for Markdown.
5194 Move forward to the end of the current or following section.
5195 When ARG is non-nil, repeat that many times. When ARG is negative,
5196 move back to the ARG-th preceding section."
5197 (interactive "P")
5198 (or arg (setq arg 1))
5199 (when (looking-at markdown-regex-header)
5200 (goto-char (match-beginning 0))
5201 (forward-char 1))
5202 (if (re-search-forward markdown-regex-header nil t arg)
5203 (goto-char (match-beginning 0))
5204 (goto-char (point-max)))
5205 (skip-syntax-backward "-"))
5207 (defun markdown-beginning-of-block ()
5208 "Move the point to the start of the previous text block."
5209 (interactive)
5210 (if (re-search-backward markdown-regex-block-separator nil t)
5211 (goto-char (or (match-end 2) (match-end 0)))
5212 (goto-char (point-min))))
5214 (defun markdown-end-of-block ()
5215 "Move the point to the start of the next text block."
5216 (interactive)
5217 (beginning-of-line)
5218 (skip-syntax-forward "-")
5219 (when (= (point) (point-min))
5220 (forward-char))
5221 (if (re-search-forward markdown-regex-block-separator nil t)
5222 (goto-char (or (match-end 2) (match-end 0)))
5223 (goto-char (point-max)))
5224 (skip-syntax-backward "-")
5225 (forward-line))
5227 (defun markdown-forward-paragraph (arg)
5228 "Move forward one or more paragraphs or by one block.
5229 When ARG is nil or a numeric prefix, call `forward-paragraph'
5230 with ARG. When called with \\[universal-argument], call
5231 `markdown-end-of-block' instead."
5232 (interactive "P")
5233 (or arg (setq arg 1))
5234 (cond ((integerp arg)
5235 (forward-paragraph arg))
5236 ((equal arg '(4))
5237 (markdown-end-of-block))))
5239 (defun markdown-backward-paragraph (arg)
5240 "Move backward one or more paragraphs or by one block.
5241 When ARG is nil or a numeric prefix, call `backward-paragraph'
5242 with ARG. When called with \\[universal-argument], call
5243 `markdown-beginning-of-block' instead."
5244 (interactive "P")
5245 (or arg (setq arg 1))
5246 (cond ((integerp arg)
5247 (backward-paragraph arg))
5248 ((equal arg '(4))
5249 (markdown-beginning-of-block))))
5251 (defun markdown-end-of-block-element ()
5252 "Move the point to the start of the next block unit.
5253 Stops at blank lines, list items, headers, and horizontal rules."
5254 (interactive)
5255 (forward-line)
5256 (while (and (or (not (markdown-prev-line-blank-p))
5257 (markdown-cur-line-blank-p))
5258 (not (or (looking-at-p markdown-regex-list)
5259 (looking-at-p markdown-regex-header)
5260 (looking-at-p markdown-regex-hr)))
5261 (not (eobp)))
5262 (forward-line)))
5264 (defun markdown-next-link ()
5265 "Jump to next inline, reference, or wiki link.
5266 If successful, return point. Otherwise, return nil.
5267 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5268 (interactive)
5269 (let ((opoint (point)))
5270 (when (or (markdown-link-p) (markdown-wiki-link-p))
5271 ;; At a link already, move past it.
5272 (goto-char (+ (match-end 0) 1)))
5273 ;; Search for the next wiki link and move to the beginning.
5274 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5275 (markdown-code-block-at-point)
5276 (< (point) (point-max))))
5277 (if (and (not (eq (point) opoint))
5278 (or (markdown-link-p) (markdown-wiki-link-p)))
5279 ;; Group 1 will move past non-escape character in wiki link regexp.
5280 ;; Go to beginning of group zero for all other link types.
5281 (goto-char (or (match-beginning 1) (match-beginning 0)))
5282 (goto-char opoint)
5283 nil)))
5285 (defun markdown-previous-link ()
5286 "Jump to previous wiki link.
5287 If successful, return point. Otherwise, return nil.
5288 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5289 (interactive)
5290 (let ((opoint (point)))
5291 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5292 (markdown-code-block-at-point)
5293 (> (point) (point-min))))
5294 (if (and (not (eq (point) opoint))
5295 (or (markdown-link-p) (markdown-wiki-link-p)))
5296 (goto-char (or (match-beginning 1) (match-beginning 0)))
5297 (goto-char opoint)
5298 nil)))
5300 (defun markdown-next-heading ()
5301 "Move to the next heading line of any level.
5302 With argument, repeats or can move backward if negative."
5303 (let ((pos (outline-next-heading)))
5304 (while (markdown-code-block-at-point)
5305 (setq pos (outline-next-heading)))
5306 pos))
5308 (defun markdown-previous-heading ()
5309 "Move to the previous heading line of any level.
5310 With argument, repeats or can move backward if negative."
5311 (let ((pos (outline-previous-heading)))
5312 (while (markdown-code-block-at-point)
5313 (setq pos (outline-previous-heading)))
5314 pos))
5317 ;;; Outline ===================================================================
5319 (defun markdown-move-heading-common (move-fn &optional arg)
5320 "Wrapper for `outline-mode' functions to skip false positives.
5321 MOVE-FN is a function and ARG is its argument. For example,
5322 headings inside preformatted code blocks may match
5323 `outline-regexp' but should not be considered as headings."
5324 (funcall move-fn arg)
5325 (let ((prev -1))
5326 (while (and (/= prev (point)) (markdown-code-block-at-point))
5327 (setq prev (point))
5328 (funcall move-fn arg))))
5330 (defun markdown-next-visible-heading (arg)
5331 "Move to the next visible heading line of any level.
5332 With argument, repeats or can move backward if negative. ARG is
5333 passed to `outline-next-visible-heading'."
5334 (interactive "p")
5335 (markdown-move-heading-common 'outline-next-visible-heading arg))
5337 (defun markdown-previous-visible-heading (arg)
5338 "Move to the previous visible heading line of any level.
5339 With argument, repeats or can move backward if negative. ARG is
5340 passed to `outline-previous-visible-heading'."
5341 (interactive "p")
5342 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5344 (defun markdown-forward-same-level (arg)
5345 "Move forward to the ARG'th heading at same level as this one.
5346 Stop at the first and last headings of a superior heading."
5347 (interactive "p")
5348 (markdown-move-heading-common 'outline-forward-same-level arg))
5350 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5351 (beginning-of-line)
5352 (or (and (outline-on-heading-p invisible-ok)
5353 (not (markdown-code-block-at-point)))
5354 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5355 found)
5356 (save-excursion
5357 (while (not found)
5358 (let (finish)
5359 (while (and (not finish) (re-search-backward header-re nil t))
5360 (when (and (or invisible-ok (not (outline-invisible-p)))
5361 (not (markdown-code-block-at-point)))
5362 (setq finish t)))
5363 (if (not finish)
5364 (error "Before first heading")
5365 (setq found (point))))))
5366 (goto-char found)
5367 found)))
5369 (defun markdown-backward-same-level (arg)
5370 "Move backward to the ARG'th heading at same level as this one.
5371 Stop at the first and last headings of a superior heading."
5372 (interactive "p")
5373 (markdown-back-to-heading-over-code-block)
5374 (while (> arg 0)
5375 (let ((point-to-move-to (save-excursion
5376 (outline-get-last-sibling))))
5377 (if point-to-move-to
5378 (progn
5379 (goto-char point-to-move-to)
5380 (setq arg (1- arg)))
5381 (error "No previous same-level heading")))))
5383 (defun markdown-up-heading (arg)
5384 "Move to the visible heading line of which the present line is a subheading.
5385 With argument, move up ARG levels."
5386 (interactive "p")
5387 (markdown-move-heading-common 'outline-up-heading arg))
5389 (defun markdown-back-to-heading (&optional invisible-ok)
5390 "Move to previous heading line, or beg of this line if it's a heading.
5391 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5392 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5394 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5396 (defun markdown-on-heading-p ()
5397 "Return t if point is on a (visible) heading line."
5398 (get-text-property (point) 'markdown-heading))
5400 (defun markdown-end-of-subtree (&optional invisible-OK)
5401 "Move to the end of the current subtree.
5402 Only visible heading lines are considered, unless INVISIBLE-OK is
5403 non-nil.
5404 Derived from `org-end-of-subtree'."
5405 (markdown-back-to-heading invisible-OK)
5406 (let ((first t)
5407 (level (funcall outline-level)))
5408 (while (and (not (eobp))
5409 (or first (> (funcall outline-level) level)))
5410 (setq first nil)
5411 (markdown-next-heading))
5412 (if (memq (preceding-char) '(?\n ?\^M))
5413 (progn
5414 ;; Go to end of line before heading
5415 (forward-char -1)
5416 (if (memq (preceding-char) '(?\n ?\^M))
5417 ;; leave blank line before heading
5418 (forward-char -1)))))
5419 (point))
5421 (defun markdown-outline-fix-visibility ()
5422 "Hide any false positive headings that should not be shown.
5423 For example, headings inside preformatted code blocks may match
5424 `outline-regexp' but should not be shown as headings when cycling.
5425 Also, the ending --- line in metadata blocks appears to be a
5426 setext header, but should not be folded."
5427 (save-excursion
5428 (goto-char (point-min))
5429 ;; Unhide any false positives in metadata blocks
5430 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
5431 (let ((body (progn (forward-line)
5432 (markdown-text-property-at-point
5433 'markdown-yaml-metadata-section))))
5434 (when body
5435 (let ((end (progn (goto-char (cl-second body))
5436 (markdown-text-property-at-point
5437 'markdown-yaml-metadata-end))))
5438 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
5439 ;; Hide any false positives in code blocks
5440 (unless (outline-on-heading-p)
5441 (outline-next-visible-heading 1))
5442 (while (< (point) (point-max))
5443 (when (markdown-code-block-at-point)
5444 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5445 (outline-next-visible-heading 1))))
5447 (defvar markdown-cycle-global-status 1)
5448 (defvar markdown-cycle-subtree-status nil)
5450 (defun markdown-next-preface ()
5451 (let (finish)
5452 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5453 nil 'move))
5454 (unless (markdown-code-block-at-point)
5455 (goto-char (match-beginning 0))
5456 (setq finish t))))
5457 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5458 (forward-char -1)))
5460 (defun markdown-show-entry ()
5461 (save-excursion
5462 (outline-back-to-heading t)
5463 (outline-flag-region (1- (point))
5464 (progn
5465 (markdown-next-preface)
5466 (if (= 1 (- (point-max) (point)))
5467 (point-max)
5468 (point)))
5469 nil)))
5471 (defun markdown-cycle (&optional arg)
5472 "Visibility cycling for Markdown mode.
5473 If ARG is t, perform global visibility cycling. If the point is
5474 at an atx-style header, cycle visibility of the corresponding
5475 subtree. Otherwise, insert a tab using `indent-relative'.
5476 Derived from `org-cycle'."
5477 (interactive "P")
5478 (cond
5479 ((eq arg t) ;; Global cycling
5480 (cond
5481 ((and (eq last-command this-command)
5482 (eq markdown-cycle-global-status 2))
5483 ;; Move from overview to contents
5484 (markdown-hide-sublevels 1)
5485 (message "CONTENTS")
5486 (setq markdown-cycle-global-status 3)
5487 (markdown-outline-fix-visibility))
5489 ((and (eq last-command this-command)
5490 (eq markdown-cycle-global-status 3))
5491 ;; Move from contents to all
5492 (markdown-show-all)
5493 (message "SHOW ALL")
5494 (setq markdown-cycle-global-status 1))
5497 ;; Defaults to overview
5498 (markdown-hide-body)
5499 (message "OVERVIEW")
5500 (setq markdown-cycle-global-status 2)
5501 (markdown-outline-fix-visibility))))
5503 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5504 ;; At a heading: rotate between three different views
5505 (markdown-back-to-heading)
5506 (let ((goal-column 0) eoh eol eos)
5507 ;; Determine boundaries
5508 (save-excursion
5509 (markdown-back-to-heading)
5510 (save-excursion
5511 (beginning-of-line 2)
5512 (while (and (not (eobp)) ;; this is like `next-line'
5513 (get-char-property (1- (point)) 'invisible))
5514 (beginning-of-line 2)) (setq eol (point)))
5515 (markdown-end-of-heading) (setq eoh (point))
5516 (markdown-end-of-subtree t)
5517 (skip-chars-forward " \t\n")
5518 (beginning-of-line 1) ; in case this is an item
5519 (setq eos (1- (point))))
5520 ;; Find out what to do next and set `this-command'
5521 (cond
5522 ((= eos eoh)
5523 ;; Nothing is hidden behind this heading
5524 (message "EMPTY ENTRY")
5525 (setq markdown-cycle-subtree-status nil))
5526 ((>= eol eos)
5527 ;; Entire subtree is hidden in one line: open it
5528 (markdown-show-entry)
5529 (markdown-show-children)
5530 (message "CHILDREN")
5531 (setq markdown-cycle-subtree-status 'children))
5532 ((and (eq last-command this-command)
5533 (eq markdown-cycle-subtree-status 'children))
5534 ;; We just showed the children, now show everything.
5535 (markdown-show-subtree)
5536 (message "SUBTREE")
5537 (setq markdown-cycle-subtree-status 'subtree))
5539 ;; Default action: hide the subtree.
5540 (markdown-hide-subtree)
5541 (message "FOLDED")
5542 (setq markdown-cycle-subtree-status 'folded)))))
5545 (indent-for-tab-command))))
5547 (defun markdown-shifttab ()
5548 "Global visibility cycling.
5549 Calls `markdown-cycle' with argument t."
5550 (interactive)
5551 (markdown-cycle t))
5553 (defun markdown-outline-level ()
5554 "Return the depth to which a statement is nested in the outline."
5555 (cond
5556 ((markdown-code-block-at-point) 7)
5557 ((match-end 2) 1)
5558 ((match-end 3) 2)
5559 ((- (match-end 4) (match-beginning 4)))))
5561 (defun markdown-promote-subtree (&optional arg)
5562 "Promote the current subtree of ATX headings.
5563 Note that Markdown does not support heading levels higher than
5564 six and therefore level-six headings will not be promoted
5565 further. If ARG is non-nil promote the heading, otherwise
5566 demote."
5567 (interactive "*P")
5568 (save-excursion
5569 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5570 (re-search-backward markdown-regex-header-atx nil t))
5571 (not (markdown-code-block-at-point)))
5572 (let ((level (length (match-string 1)))
5573 (promote-or-demote (if arg 1 -1))
5574 (remove 't))
5575 (markdown-cycle-atx promote-or-demote remove)
5576 (catch 'end-of-subtree
5577 (while (markdown-next-heading)
5578 ;; Exit if this not a higher level heading; promote otherwise.
5579 (if (and (looking-at markdown-regex-header-atx)
5580 (<= (length (match-string-no-properties 1)) level))
5581 (throw 'end-of-subtree nil)
5582 (markdown-cycle-atx promote-or-demote remove))))))))
5584 (defun markdown-demote-subtree ()
5585 "Demote the current subtree of ATX headings."
5586 (interactive)
5587 (markdown-promote-subtree t))
5589 (defun markdown-move-subtree-up ()
5590 "Move the current subtree of ATX headings up."
5591 (interactive)
5592 (outline-move-subtree-up 1))
5594 (defun markdown-move-subtree-down ()
5595 "Move the current subtree of ATX headings down."
5596 (interactive)
5597 (outline-move-subtree-down 1))
5600 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5602 (defun markdown-move-up ()
5603 "Move list item up.
5604 Calls `markdown-move-list-item-up'."
5605 (interactive)
5606 (markdown-move-list-item-up))
5608 (defun markdown-move-down ()
5609 "Move list item down.
5610 Calls `markdown-move-list-item-down'."
5611 (interactive)
5612 (markdown-move-list-item-down))
5614 (defun markdown-promote ()
5615 "Either promote header or list item at point or cycle markup.
5616 See `markdown-cycle-atx', `markdown-cycle-setext', and
5617 `markdown-promote-list-item'."
5618 (interactive)
5619 (let (bounds)
5620 (cond
5621 ;; Promote atx header
5622 ((thing-at-point-looking-at markdown-regex-header-atx)
5623 (markdown-cycle-atx -1))
5624 ;; Promote setext header
5625 ((thing-at-point-looking-at markdown-regex-header-setext)
5626 (markdown-cycle-setext -1))
5627 ;; Promote horizonal rule
5628 ((thing-at-point-looking-at markdown-regex-hr)
5629 (markdown-cycle-hr -1))
5630 ;; Promote list item
5631 ((setq bounds (markdown-cur-list-item-bounds))
5632 (markdown-promote-list-item bounds))
5633 ;; Promote bold
5634 ((thing-at-point-looking-at markdown-regex-bold)
5635 (markdown-cycle-bold))
5636 ;; Promote italic
5637 ((thing-at-point-looking-at markdown-regex-italic)
5638 (markdown-cycle-italic))
5640 (error "Nothing to promote at point")))))
5642 (defun markdown-demote ()
5643 "Either demote header or list item at point or cycle or remove markup.
5644 See `markdown-cycle-atx', `markdown-cycle-setext', and
5645 `markdown-demote-list-item'."
5646 (interactive)
5647 (let (bounds)
5648 (cond
5649 ;; Demote atx header
5650 ((thing-at-point-looking-at markdown-regex-header-atx)
5651 (markdown-cycle-atx 1))
5652 ;; Demote setext header
5653 ((thing-at-point-looking-at markdown-regex-header-setext)
5654 (markdown-cycle-setext 1))
5655 ;; Demote horizonal rule
5656 ((thing-at-point-looking-at markdown-regex-hr)
5657 (markdown-cycle-hr 1))
5658 ;; Demote list item
5659 ((setq bounds (markdown-cur-list-item-bounds))
5660 (markdown-demote-list-item bounds))
5661 ;; Demote bold
5662 ((thing-at-point-looking-at markdown-regex-bold)
5663 (markdown-cycle-bold))
5664 ;; Demote italic
5665 ((thing-at-point-looking-at markdown-regex-italic)
5666 (markdown-cycle-italic))
5668 (error "Nothing to demote at point")))))
5671 ;;; Commands ==================================================================
5673 (defun markdown (&optional output-buffer-name)
5674 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5675 The output buffer name defaults to `markdown-output-buffer-name'.
5676 Return the name of the output buffer used."
5677 (interactive)
5678 (save-window-excursion
5679 (let ((begin-region)
5680 (end-region))
5681 (if (markdown-use-region-p)
5682 (setq begin-region (region-beginning)
5683 end-region (region-end))
5684 (setq begin-region (point-min)
5685 end-region (point-max)))
5687 (unless output-buffer-name
5688 (setq output-buffer-name markdown-output-buffer-name))
5689 (cond
5690 ;; Handle case when `markdown-command' does not read from stdin
5691 (markdown-command-needs-filename
5692 (if (not buffer-file-name)
5693 (error "Must be visiting a file")
5694 (shell-command (concat markdown-command " "
5695 (shell-quote-argument buffer-file-name))
5696 output-buffer-name)))
5697 ;; Pass region to `markdown-command' via stdin
5699 (let ((buf (get-buffer-create output-buffer-name)))
5700 (with-current-buffer buf
5701 (setq buffer-read-only nil)
5702 (erase-buffer))
5703 (call-process-region begin-region end-region
5704 shell-file-name nil buf nil
5705 shell-command-switch markdown-command)))))
5706 output-buffer-name))
5708 (defun markdown-standalone (&optional output-buffer-name)
5709 "Special function to provide standalone HTML output.
5710 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5711 (interactive)
5712 (setq output-buffer-name (markdown output-buffer-name))
5713 (with-current-buffer output-buffer-name
5714 (set-buffer output-buffer-name)
5715 (unless (markdown-output-standalone-p)
5716 (markdown-add-xhtml-header-and-footer output-buffer-name))
5717 (goto-char (point-min))
5718 (html-mode))
5719 output-buffer-name)
5721 (defun markdown-other-window (&optional output-buffer-name)
5722 "Run `markdown-command' on current buffer and display in other window.
5723 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5724 that name."
5725 (interactive)
5726 (markdown-display-buffer-other-window
5727 (markdown-standalone output-buffer-name)))
5729 (defun markdown-output-standalone-p ()
5730 "Determine whether `markdown-command' output is standalone XHTML.
5731 Standalone XHTML output is identified by an occurrence of
5732 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5733 (save-excursion
5734 (goto-char (point-min))
5735 (re-search-forward
5736 markdown-xhtml-standalone-regexp
5737 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5738 t)))
5740 (defun markdown-stylesheet-link-string (stylesheet-path)
5741 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5742 stylesheet-path
5743 "\" />"))
5745 (defun markdown-add-xhtml-header-and-footer (title)
5746 "Wrap XHTML header and footer with given TITLE around current buffer."
5747 (goto-char (point-min))
5748 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5749 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5750 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5751 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5752 "<head>\n<title>")
5753 (insert title)
5754 (insert "</title>\n")
5755 (when (> (length markdown-content-type) 0)
5756 (insert
5757 (format
5758 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5759 markdown-content-type
5760 (or (and markdown-coding-system
5761 (fboundp 'coding-system-get)
5762 (coding-system-get markdown-coding-system
5763 'mime-charset))
5764 (and (fboundp 'coding-system-get)
5765 (coding-system-get buffer-file-coding-system
5766 'mime-charset))
5767 "iso-8859-1"))))
5768 (if (> (length markdown-css-paths) 0)
5769 (insert (mapconcat #'markdown-stylesheet-link-string
5770 markdown-css-paths "\n")))
5771 (when (> (length markdown-xhtml-header-content) 0)
5772 (insert markdown-xhtml-header-content))
5773 (insert "\n</head>\n\n"
5774 "<body>\n\n")
5775 (goto-char (point-max))
5776 (insert "\n"
5777 "</body>\n"
5778 "</html>\n"))
5780 (defun markdown-preview (&optional output-buffer-name)
5781 "Run `markdown-command' on the current buffer and view output in browser.
5782 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5783 that name."
5784 (interactive)
5785 (browse-url-of-buffer
5786 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
5788 (defun markdown-export-file-name (&optional extension)
5789 "Attempt to generate a filename for Markdown output.
5790 The file extension will be EXTENSION if given, or .html by default.
5791 If the current buffer is visiting a file, we construct a new
5792 output filename based on that filename. Otherwise, return nil."
5793 (when (buffer-file-name)
5794 (unless extension
5795 (setq extension ".html"))
5796 (let ((candidate
5797 (concat
5798 (cond
5799 ((buffer-file-name)
5800 (file-name-sans-extension (buffer-file-name)))
5801 (t (buffer-name)))
5802 extension)))
5803 (cond
5804 ((equal candidate (buffer-file-name))
5805 (concat candidate extension))
5807 candidate)))))
5809 (defun markdown-export (&optional output-file)
5810 "Run Markdown on the current buffer, save to file, and return the filename.
5811 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
5812 generated by `markdown-export-file-name', which will be constructed using the
5813 current filename, but with the extension removed and replaced with .html."
5814 (interactive)
5815 (unless output-file
5816 (setq output-file (markdown-export-file-name ".html")))
5817 (when output-file
5818 (let* ((init-buf (current-buffer))
5819 (init-point (point))
5820 (init-buf-string (buffer-string))
5821 (output-buffer (find-file-noselect output-file))
5822 (output-buffer-name (buffer-name output-buffer)))
5823 (run-hooks 'markdown-before-export-hook)
5824 (markdown-standalone output-buffer-name)
5825 (with-current-buffer output-buffer
5826 (run-hooks 'markdown-after-export-hook)
5827 (save-buffer))
5828 ;; if modified, restore initial buffer
5829 (when (buffer-modified-p init-buf)
5830 (erase-buffer)
5831 (insert init-buf-string)
5832 (save-buffer)
5833 (goto-char init-point))
5834 output-file)))
5836 (defun markdown-export-and-preview ()
5837 "Export to XHTML using `markdown-export' and browse the resulting file."
5838 (interactive)
5839 (browse-url-of-file (markdown-export)))
5841 (defvar markdown-live-preview-buffer nil
5842 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
5843 (make-variable-buffer-local 'markdown-live-preview-buffer)
5845 (defvar markdown-live-preview-source-buffer nil
5846 "Source buffer from which current buffer was generated.
5847 This is the inverse of `markdown-live-preview-buffer'.")
5848 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
5850 (defvar markdown-live-preview-currently-exporting nil)
5852 (defun markdown-live-preview-get-filename ()
5853 "Standardize the filename exported by `markdown-live-preview-export'."
5854 (markdown-export-file-name ".html"))
5856 (defun markdown-live-preview-window-eww (file)
5857 "Preview FILE with eww.
5858 To be used with `markdown-live-preview-window-function'."
5859 (if (require 'eww nil t)
5860 (progn
5861 (eww-open-file file)
5862 (get-buffer "*eww*"))
5863 (error "EWW is not present or not loaded on this version of Emacs")))
5865 (defun markdown-visual-lines-between-points (beg end)
5866 (save-excursion
5867 (goto-char beg)
5868 (cl-loop with count = 0
5869 while (progn (end-of-visual-line)
5870 (and (< (point) end) (line-move-visual 1 t)))
5871 do (cl-incf count)
5872 finally return count)))
5874 (defun markdown-live-preview-window-serialize (buf)
5875 "Get window point and scroll data for all windows displaying BUF."
5876 (when (buffer-live-p buf)
5877 (with-current-buffer buf
5878 (mapcar
5879 (lambda (win)
5880 (with-selected-window win
5881 (let* ((start (window-start))
5882 (pt (window-point))
5883 (pt-or-sym (cond ((= pt (point-min)) 'min)
5884 ((= pt (point-max)) 'max)
5885 (t pt)))
5886 (diff (markdown-visual-lines-between-points
5887 start pt)))
5888 (list win pt-or-sym diff))))
5889 (get-buffer-window-list buf)))))
5891 (defun markdown-get-point-back-lines (pt num-lines)
5892 (save-excursion
5893 (goto-char pt)
5894 (line-move-visual (- num-lines) t)
5895 ;; in testing, can occasionally overshoot the number of lines to traverse
5896 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
5897 (when (> actual-num-lines num-lines)
5898 (line-move-visual (- actual-num-lines num-lines) t)))
5899 (point)))
5901 (defun markdown-live-preview-window-deserialize (window-posns)
5902 "Apply window point and scroll data from WINDOW-POSNS.
5903 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
5904 (cl-destructuring-bind (win pt-or-sym diff) window-posns
5905 (when (window-live-p win)
5906 (with-current-buffer markdown-live-preview-buffer
5907 (set-window-buffer win (current-buffer))
5908 (cl-destructuring-bind (actual-pt actual-diff)
5909 (cl-case pt-or-sym
5910 (min (list (point-min) 0))
5911 (max (list (point-max) diff))
5912 (t (list pt-or-sym diff)))
5913 (set-window-start
5914 win (markdown-get-point-back-lines actual-pt actual-diff))
5915 (set-window-point win actual-pt))))))
5917 (defun markdown-live-preview-export ()
5918 "Export to XHTML using `markdown-export'.
5919 Browse the resulting file within Emacs using
5920 `markdown-live-preview-window-function' Return the buffer
5921 displaying the rendered output."
5922 (interactive)
5923 (let* ((markdown-live-preview-currently-exporting t)
5924 (cur-buf (current-buffer))
5925 (export-file (markdown-export (markdown-live-preview-get-filename)))
5926 ;; get positions in all windows currently displaying output buffer
5927 (window-data
5928 (markdown-live-preview-window-serialize
5929 markdown-live-preview-buffer)))
5930 (save-window-excursion
5931 (let ((output-buffer
5932 (funcall markdown-live-preview-window-function export-file)))
5933 (with-current-buffer output-buffer
5934 (setq markdown-live-preview-source-buffer cur-buf)
5935 (add-hook 'kill-buffer-hook
5936 #'markdown-live-preview-remove-on-kill t t))
5937 (with-current-buffer cur-buf
5938 (setq markdown-live-preview-buffer output-buffer))))
5939 (with-current-buffer cur-buf
5940 ;; reset all windows displaying output buffer to where they were,
5941 ;; now with the new output
5942 (mapc #'markdown-live-preview-window-deserialize window-data)
5943 ;; delete html editing buffer
5944 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
5945 (when (and export-file (file-exists-p export-file)
5946 (eq markdown-live-preview-delete-export
5947 'delete-on-export))
5948 (delete-file export-file))
5949 markdown-live-preview-buffer)))
5951 (defun markdown-live-preview-remove ()
5952 (when (buffer-live-p markdown-live-preview-buffer)
5953 (kill-buffer markdown-live-preview-buffer))
5954 (setq markdown-live-preview-buffer nil)
5955 ;; if set to 'delete-on-export, the output has already been deleted
5956 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
5957 (let ((outfile-name (markdown-live-preview-get-filename)))
5958 (when (file-exists-p outfile-name)
5959 (delete-file outfile-name)))))
5961 (defun markdown-display-buffer-other-window (buf)
5962 (let ((cur-buf (current-buffer)))
5963 (switch-to-buffer-other-window buf)
5964 (set-buffer cur-buf)))
5966 (defun markdown-live-preview-if-markdown ()
5967 (when (and (derived-mode-p 'markdown-mode)
5968 markdown-live-preview-mode)
5969 (unless markdown-live-preview-currently-exporting
5970 (if (buffer-live-p markdown-live-preview-buffer)
5971 (markdown-live-preview-export)
5972 (markdown-display-buffer-other-window
5973 (markdown-live-preview-export))))))
5975 (defun markdown-live-preview-remove-on-kill ()
5976 (cond ((and (derived-mode-p 'markdown-mode)
5977 markdown-live-preview-mode)
5978 (markdown-live-preview-remove))
5979 (markdown-live-preview-source-buffer
5980 (with-current-buffer markdown-live-preview-source-buffer
5981 (setq markdown-live-preview-buffer nil))
5982 (setq markdown-live-preview-source-buffer nil))))
5984 (defun markdown-live-preview-switch-to-output ()
5985 "Switch to output buffer."
5986 (interactive)
5987 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
5988 output buffer in another window."
5989 (if markdown-live-preview-mode
5990 (markdown-display-buffer-other-window (markdown-live-preview-export)))
5991 (markdown-live-preview-mode))
5993 (defun markdown-live-preview-re-export ()
5994 "Re export source buffer."
5995 (interactive)
5996 "If the current buffer is a buffer displaying the exported version of a
5997 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
5998 update this buffer's contents."
5999 (when markdown-live-preview-source-buffer
6000 (with-current-buffer markdown-live-preview-source-buffer
6001 (markdown-live-preview-export))))
6003 (defun markdown-open ()
6004 "Open file for the current buffer with `markdown-open-command'."
6005 (interactive)
6006 (if (not markdown-open-command)
6007 (error "Variable `markdown-open-command' must be set")
6008 (if (not buffer-file-name)
6009 (error "Must be visiting a file")
6010 (call-process markdown-open-command
6011 nil nil nil buffer-file-name))))
6013 (defun markdown-kill-ring-save ()
6014 "Run Markdown on file and store output in the kill ring."
6015 (interactive)
6016 (save-window-excursion
6017 (markdown)
6018 (with-current-buffer markdown-output-buffer-name
6019 (kill-ring-save (point-min) (point-max)))))
6022 ;;; Links =====================================================================
6024 (defun markdown-link-p ()
6025 "Return non-nil when `point' is at a non-wiki link.
6026 See `markdown-wiki-link-p' for more information."
6027 (let ((case-fold-search nil))
6028 (and (not (markdown-wiki-link-p))
6029 (not (markdown-code-block-at-point))
6030 (or (thing-at-point-looking-at markdown-regex-link-inline)
6031 (thing-at-point-looking-at markdown-regex-link-reference)
6032 (thing-at-point-looking-at markdown-regex-uri)
6033 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6035 (defun markdown-link-link ()
6036 "Return the link part of the regular (non-wiki) link at point.
6037 Works with both inline and reference style links. If point is
6038 not at a link or the link reference is not defined returns nil."
6039 (cond
6040 ((thing-at-point-looking-at markdown-regex-link-inline)
6041 (match-string-no-properties 6))
6042 ((thing-at-point-looking-at markdown-regex-link-reference)
6043 (let* ((text (match-string-no-properties 3))
6044 (reference (match-string-no-properties 6))
6045 (target (downcase (if (string= reference "") text reference))))
6046 (car (markdown-reference-definition target))))
6047 ((thing-at-point-looking-at markdown-regex-uri)
6048 (match-string-no-properties 0))
6049 ((thing-at-point-looking-at markdown-regex-angle-uri)
6050 (match-string-no-properties 2))
6051 (t nil)))
6053 (defun markdown-follow-link-at-point ()
6054 "Open the current non-wiki link.
6055 If the link is a complete URL, open in browser with `browse-url'.
6056 Otherwise, open with `find-file' after stripping anchor and/or query string."
6057 (interactive)
6058 (if (markdown-link-p)
6059 (let* ((link (markdown-link-link))
6060 (struct (url-generic-parse-url link))
6061 (full (url-fullness struct))
6062 (file link))
6063 ;; Parse URL, determine fullness, strip query string
6064 (if (fboundp 'url-path-and-query)
6065 (setq file (car (url-path-and-query struct)))
6066 (when (and (setq file (url-filename struct))
6067 (string-match "\\?" file))
6068 (setq file (substring file 0 (match-beginning 0)))))
6069 ;; Open full URLs in browser, files in Emacs
6070 (if full
6071 (browse-url link)
6072 (when (and file (> (length file) 0)) (find-file file))))
6073 (error "Point is not at a Markdown link or URI")))
6076 ;;; WikiLink Following/Markup =================================================
6078 (defun markdown-wiki-link-p ()
6079 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6080 A true wiki link name matches `markdown-regex-wiki-link' but does
6081 not match the current file name after conversion. This modifies
6082 the data returned by `match-data'. Note that the potential wiki
6083 link name must be available via `match-string'."
6084 (when markdown-enable-wiki-links
6085 (let ((case-fold-search nil))
6086 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6087 (not (markdown-code-block-at-point))
6088 (or (not buffer-file-name)
6089 (not (string-equal (buffer-file-name)
6090 (markdown-convert-wiki-link-to-filename
6091 (markdown-wiki-link-link)))))))))
6093 (defun markdown-wiki-link-link ()
6094 "Return the link part of the wiki link using current match data.
6095 The location of the link component depends on the value of
6096 `markdown-wiki-link-alias-first'."
6097 (if markdown-wiki-link-alias-first
6098 (or (match-string-no-properties 5) (match-string-no-properties 3))
6099 (match-string-no-properties 3)))
6101 (defun markdown-wiki-link-alias ()
6102 "Return the alias or text part of the wiki link using current match data.
6103 The location of the alias component depends on the value of
6104 `markdown-wiki-link-alias-first'."
6105 (if markdown-wiki-link-alias-first
6106 (match-string-no-properties 3)
6107 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6109 (defun markdown-convert-wiki-link-to-filename (name)
6110 "Generate a filename from the wiki link NAME.
6111 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6112 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6113 and [[test test]] both map to Test-test.ext."
6114 (let ((basename (markdown-replace-regexp-in-string
6115 "[[:space:]\n]" markdown-link-space-sub-char name)))
6116 (when (eq major-mode 'gfm-mode)
6117 (setq basename (concat (upcase (substring basename 0 1))
6118 (downcase (substring basename 1 nil)))))
6119 (let* ((default
6120 (concat basename
6121 (if (and (buffer-file-name)
6122 (file-name-extension (buffer-file-name)))
6123 (concat "."
6124 (file-name-extension (buffer-file-name))))))
6125 (current default))
6126 (catch 'done
6127 (condition-case nil
6128 (cl-loop
6129 (if (or (not markdown-wiki-link-search-parent-directories)
6130 (file-exists-p current))
6131 (throw 'done current))
6132 (if (string-equal (expand-file-name current)
6133 (concat "/" default))
6134 (throw 'done default))
6135 (setq current (concat "../" current)))
6136 (error default))))))
6138 (defun markdown-follow-wiki-link (name &optional other)
6139 "Follow the wiki link NAME.
6140 Convert the name to a file name and call `find-file'. Ensure that
6141 the new buffer remains in `markdown-mode'. Open the link in another
6142 window when OTHER is non-nil."
6143 (let ((filename (markdown-convert-wiki-link-to-filename name))
6144 (wp (file-name-directory buffer-file-name)))
6145 (when other (other-window 1))
6146 (let ((default-directory wp))
6147 (find-file filename)))
6148 (when (not (eq major-mode 'markdown-mode))
6149 (markdown-mode)))
6151 (defun markdown-follow-wiki-link-at-point (&optional arg)
6152 "Find Wiki Link at point.
6153 With prefix argument ARG, open the file in other window.
6154 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6155 (interactive "P")
6156 (if (markdown-wiki-link-p)
6157 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6158 (error "Point is not at a Wiki Link")))
6160 (defun markdown-highlight-wiki-link (from to face)
6161 "Highlight the wiki link in the region between FROM and TO using FACE."
6162 (put-text-property from to 'font-lock-face face))
6164 (defun markdown-unfontify-region-wiki-links (from to)
6165 "Remove wiki link faces from the region specified by FROM and TO."
6166 (interactive "*r")
6167 (let ((modified (buffer-modified-p)))
6168 (remove-text-properties from to '(font-lock-face markdown-link-face))
6169 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
6170 ;; remove-text-properties marks the buffer modified in emacs 24.3,
6171 ;; undo that if it wasn't originally marked modified
6172 (set-buffer-modified-p modified)))
6174 (defun markdown-fontify-region-wiki-links (from to)
6175 "Search region given by FROM and TO for wiki links and fontify them.
6176 If a wiki link is found check to see if the backing file exists
6177 and highlight accordingly."
6178 (goto-char from)
6179 (save-match-data
6180 (while (re-search-forward markdown-regex-wiki-link to t)
6181 (when (not (markdown-code-block-at-point))
6182 (let ((highlight-beginning (match-beginning 1))
6183 (highlight-end (match-end 1))
6184 (file-name
6185 (markdown-convert-wiki-link-to-filename
6186 (markdown-wiki-link-link))))
6187 (if (condition-case nil (file-exists-p file-name) (error nil))
6188 (markdown-highlight-wiki-link
6189 highlight-beginning highlight-end markdown-link-face)
6190 (markdown-highlight-wiki-link
6191 highlight-beginning highlight-end markdown-missing-link-face)))))))
6193 (defun markdown-extend-changed-region (from to)
6194 "Extend region given by FROM and TO so that we can fontify all links.
6195 The region is extended to the first newline before and the first
6196 newline after."
6197 ;; start looking for the first new line before 'from
6198 (goto-char from)
6199 (re-search-backward "\n" nil t)
6200 (let ((new-from (point-min))
6201 (new-to (point-max)))
6202 (if (not (= (point) from))
6203 (setq new-from (point)))
6204 ;; do the same thing for the first new line after 'to
6205 (goto-char to)
6206 (re-search-forward "\n" nil t)
6207 (if (not (= (point) to))
6208 (setq new-to (point)))
6209 (cl-values new-from new-to)))
6211 (defun markdown-check-change-for-wiki-link (from to)
6212 "Check region between FROM and TO for wiki links and re-fontify as needed."
6213 (interactive "*r")
6214 (let* ((modified (buffer-modified-p))
6215 (buffer-undo-list t)
6216 (inhibit-read-only t)
6217 (inhibit-point-motion-hooks t)
6218 deactivate-mark
6219 buffer-file-truename)
6220 (unwind-protect
6221 (save-excursion
6222 (save-match-data
6223 (save-restriction
6224 ;; Extend the region to fontify so that it starts
6225 ;; and ends at safe places.
6226 (cl-multiple-value-bind (new-from new-to)
6227 (markdown-extend-changed-region from to)
6228 (goto-char new-from)
6229 ;; Only refontify when the range contains text with a
6230 ;; wiki link face or if the wiki link regexp matches.
6231 (when (or (markdown-range-property-any
6232 new-from new-to 'font-lock-face
6233 (list markdown-link-face
6234 markdown-missing-link-face))
6235 (re-search-forward
6236 markdown-regex-wiki-link new-to t))
6237 ;; Unfontify existing fontification (start from scratch)
6238 (markdown-unfontify-region-wiki-links new-from new-to)
6239 ;; Now do the fontification.
6240 (markdown-fontify-region-wiki-links new-from new-to))))))
6241 (and (not modified)
6242 (buffer-modified-p)
6243 (set-buffer-modified-p nil)))))
6245 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6246 "Check region between FROM and TO for wiki links and re-fontify as needed.
6247 Designed to be used with the `after-change-functions' hook."
6248 (markdown-check-change-for-wiki-link from to))
6250 (defun markdown-fontify-buffer-wiki-links ()
6251 "Refontify all wiki links in the buffer."
6252 (interactive)
6253 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6256 ;;; Following and Jumping =====================================================
6258 (defun markdown-follow-thing-at-point (arg)
6259 "Follow thing at point if possible, such as a reference link or wiki link.
6260 Opens inline and reference links in a browser. Opens wiki links
6261 to other files in the current window, or the another window if
6262 ARG is non-nil.
6263 See `markdown-follow-link-at-point' and
6264 `markdown-follow-wiki-link-at-point'."
6265 (interactive "P")
6266 (cond ((markdown-link-p)
6267 (markdown-follow-link-at-point))
6268 ((markdown-wiki-link-p)
6269 (markdown-follow-wiki-link-at-point arg))
6271 (error "Nothing to follow at point"))))
6273 (defun markdown-jump ()
6274 "Jump to another location based on context at point.
6275 Jumps between reference links and definitions; between footnote
6276 markers and footnote text."
6277 (interactive)
6278 (cond ((markdown-footnote-text-positions)
6279 (markdown-footnote-return))
6280 ((markdown-footnote-marker-positions)
6281 (markdown-footnote-goto-text))
6282 ((thing-at-point-looking-at markdown-regex-link-reference)
6283 (markdown-reference-goto-definition))
6284 ((thing-at-point-looking-at markdown-regex-reference-definition)
6285 (markdown-reference-goto-link (match-string-no-properties 2)))
6287 (error "Nothing to jump to from context at point"))))
6290 ;;; Miscellaneous =============================================================
6292 (defun markdown-compress-whitespace-string (str)
6293 "Compress whitespace in STR and return result.
6294 Leading and trailing whitespace is removed. Sequences of multiple
6295 spaces, tabs, and newlines are replaced with single spaces."
6296 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6297 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6299 (defun markdown-line-number-at-pos (&optional pos)
6300 "Return (narrowed) buffer line number at position POS.
6301 If POS is nil, use current buffer location.
6302 This is an exact copy of `line-number-at-pos' for use in emacs21."
6303 (let ((opoint (or pos (point))) start)
6304 (save-excursion
6305 (goto-char (point-min))
6306 (setq start (point))
6307 (goto-char opoint)
6308 (forward-line 0)
6309 (1+ (count-lines start (point))))))
6311 (defun markdown-inside-link-p ()
6312 "Return t if point is within a link."
6313 (thing-at-point-looking-at (markdown-make-regex-link-generic)))
6315 (defun markdown-line-is-reference-definition-p ()
6316 "Return whether the current line is a (non-footnote) reference defition."
6317 (save-excursion
6318 (move-beginning-of-line 1)
6319 (and (looking-at-p markdown-regex-reference-definition)
6320 (not (looking-at-p "[ \t]*\\[^")))))
6322 (defun markdown-adaptive-fill-function ()
6323 "Return prefix for filling paragraph or nil if not determined."
6324 (cond
6325 ;; List item inside blockquote
6326 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
6327 (markdown-replace-regexp-in-string
6328 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6329 ;; Blockquote
6330 ((looking-at "^[ \t]*>[ \t]*")
6331 (match-string-no-properties 0))
6332 ;; List items
6333 ((looking-at markdown-regex-list)
6334 (match-string-no-properties 0))
6335 ((looking-at-p markdown-regex-footnote-definition)
6336 " ") ; four spaces
6337 ;; No match
6338 (t nil)))
6340 (defun markdown-fill-forward-paragraph-function (&optional arg)
6341 (let* ((arg (or arg 1))
6342 (paragraphs-remaining (forward-paragraph arg))
6343 (start (point)))
6344 (when (< arg 0)
6345 (while (and (not (eobp))
6346 (progn (move-to-left-margin) (not (eobp)))
6347 (looking-at-p paragraph-separate))
6348 (forward-line 1))
6349 (if (looking-at markdown-regex-list)
6350 (forward-char (length (match-string 0)))
6351 (goto-char start)))
6352 paragraphs-remaining))
6355 ;;; Extension Framework =======================================================
6357 (defun markdown-reload-extensions ()
6358 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6359 (interactive)
6360 (when (eq major-mode 'markdown-mode)
6361 ;; Update font lock keywords with extensions
6362 (setq markdown-mode-font-lock-keywords
6363 (append
6364 (markdown-mode-font-lock-keywords-math)
6365 markdown-mode-font-lock-keywords-basic
6366 (markdown-mode-font-lock-keywords-wiki-links)))
6367 ;; Update font lock defaults
6368 (setq font-lock-defaults
6369 '(markdown-mode-font-lock-keywords
6370 nil nil nil nil
6371 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6372 ;; Refontify buffer
6373 (when (fboundp 'font-lock-refresh-defaults) (font-lock-refresh-defaults))
6374 ;; Add or remove hooks related to extensions
6375 (markdown-setup-wiki-link-hooks)))
6377 (defun markdown-handle-local-variables ()
6378 "Run in `hack-local-variables-hook' to update font lock rules.
6379 Checks to see if there is actually a ‘markdown-mode’ file local variable
6380 before regenerating font-lock rules for extensions."
6381 (when (and (boundp 'file-local-variables-alist)
6382 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6383 (assoc 'markdown-enable-math file-local-variables-alist))
6384 (markdown-reload-extensions)))
6386 ;;; Wiki Links ================================================================
6388 (defun markdown-toggle-wiki-links (&optional arg)
6389 "Toggle support for wiki links.
6390 With a prefix argument ARG, enable wiki link support if ARG is positive,
6391 and disable it otherwise."
6392 (interactive (list (or current-prefix-arg 'toggle)))
6393 (setq markdown-enable-wiki-links
6394 (if (eq arg 'toggle)
6395 (not markdown-enable-wiki-links)
6396 (> (prefix-numeric-value arg) 0)))
6397 (if markdown-enable-wiki-links
6398 (message "markdown-mode wiki link support enabled")
6399 (message "markdown-mode wiki link support disabled"))
6400 (markdown-reload-extensions))
6402 (defun markdown-setup-wiki-link-hooks ()
6403 "Add or remove hooks for fontifying wiki links.
6404 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6405 ;; Anytime text changes make sure it gets fontified correctly
6406 (if (and markdown-enable-wiki-links
6407 markdown-wiki-link-fontify-missing)
6408 (add-hook 'after-change-functions
6409 'markdown-check-change-for-wiki-link-after-change t t)
6410 (remove-hook 'after-change-functions
6411 'markdown-check-change-for-wiki-link-after-change t))
6412 ;; If we left the buffer there is a really good chance we were
6413 ;; creating one of the wiki link documents. Make sure we get
6414 ;; refontified when we come back.
6415 (if (and markdown-enable-wiki-links
6416 markdown-wiki-link-fontify-missing)
6417 (progn
6418 (add-hook 'window-configuration-change-hook
6419 'markdown-fontify-buffer-wiki-links t t)
6420 (markdown-fontify-buffer-wiki-links))
6421 (remove-hook 'window-configuration-change-hook
6422 'markdown-fontify-buffer-wiki-links t)
6423 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6425 (defun markdown-mode-font-lock-keywords-wiki-links ()
6426 "Return wiki-link lock keywords if support is enabled.
6427 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6428 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6429 (when (and markdown-enable-wiki-links
6430 (not markdown-wiki-link-fontify-missing))
6431 (list
6432 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6434 ;;; Math Support ==============================================================
6436 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6438 (defun markdown-toggle-math (&optional arg)
6439 "Toggle support for inline and display LaTeX math expressions.
6440 With a prefix argument ARG, enable math mode if ARG is positive,
6441 and disable it otherwise. If called from Lisp, enable the mode
6442 if ARG is omitted or nil."
6443 (interactive (list (or current-prefix-arg 'toggle)))
6444 (setq markdown-enable-math
6445 (if (eq arg 'toggle)
6446 (not markdown-enable-math)
6447 (> (prefix-numeric-value arg) 0)))
6448 (if markdown-enable-math
6449 (message "markdown-mode math support enabled")
6450 (message "markdown-mode math support disabled"))
6451 (markdown-reload-extensions))
6453 (defun markdown-mode-font-lock-keywords-math ()
6454 "Return math font lock keywords if support is enabled."
6455 (when markdown-enable-math
6456 (list
6457 ;; Display mode equations with brackets: \[ \]
6458 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6459 (2 markdown-math-face append)
6460 (3 markdown-markup-face prepend)))
6461 ;; Equation reference (eq:foo)
6462 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6463 (2 markdown-reference-face)
6464 (3 markdown-markup-face)))
6465 ;; Equation reference \eqref{foo}
6466 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6467 (2 markdown-reference-face)
6468 (3 markdown-markup-face))))))
6471 ;;; GFM Checkboxes as Buttons =================================================
6473 (require 'button)
6475 (define-button-type 'markdown-gfm-checkbox-button
6476 'follow-link t
6477 'face 'markdown-gfm-checkbox-face
6478 'mouse-face 'markdown-highlight-face
6479 'action #'markdown-toggle-gfm-checkbox)
6481 (defun markdown-toggle-gfm-checkbox (button)
6482 "Toggle GFM checkbox BUTTON on click."
6483 (save-match-data
6484 (save-excursion
6485 (goto-char (button-start button))
6486 (cond ((looking-at "\\[ \\]")
6487 (replace-match "[x]" nil t))
6488 ((looking-at "\\[[xX]\\]")
6489 (replace-match "[ ]" nil t))))))
6491 (defun markdown-make-gfm-checkboxes-buttons (start end)
6492 "Make GFM checkboxes buttons in region between START and END."
6493 (save-excursion
6494 (goto-char start)
6495 (let ((case-fold-search t))
6496 (save-excursion
6497 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6498 (make-button (match-beginning 1) (match-end 1)
6499 :type 'markdown-gfm-checkbox-button))))))
6501 ;; Called when any modification is made to buffer text.
6502 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6503 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6504 BEG and END are the limits of scanned region."
6505 (save-excursion
6506 (save-match-data
6507 ;; Rescan between start of line from `beg' and start of line after `end'.
6508 (markdown-make-gfm-checkboxes-buttons
6509 (progn (goto-char beg) (beginning-of-line) (point))
6510 (progn (goto-char end) (forward-line 1) (point))))))
6513 ;;; Display inline image =================================================
6515 (defvar markdown-inline-image-overlays nil)
6516 (make-variable-buffer-local 'markdown-inline-image-overlays)
6518 (defun markdown-remove-inline-images ()
6519 "Remove inline image overlays from image links in the buffer.
6520 This can be toggled with `markdown-toggle-inline-images'
6521 or \\[markdown-toggle-inline-images]."
6522 (interactive)
6523 (mapc #'delete-overlay markdown-inline-image-overlays)
6524 (setq markdown-inline-image-overlays nil))
6526 (defun markdown-display-inline-images ()
6527 "Add inline image overlays to image links in the buffer.
6528 This can be toggled with `markdown-toggle-inline-images'
6529 or \\[markdown-toggle-inline-images]."
6530 (interactive)
6531 (unless (display-graphic-p)
6532 (error "Cannot show images"))
6533 (save-excursion
6534 (save-restriction
6535 (widen)
6536 (goto-char (point-min))
6537 (while (re-search-forward markdown-regex-link-inline nil t)
6538 (let ((start (match-beginning 0))
6539 (end (match-end 0))
6540 (file (match-string-no-properties 6)))
6541 (when (file-exists-p file)
6542 (let* ((abspath (if (file-name-absolute-p file)
6543 file
6544 (concat default-directory file)))
6545 (image (create-image abspath)))
6546 (when image
6547 (let ((ov (make-overlay start end)))
6548 (overlay-put ov 'display image)
6549 (overlay-put ov 'face 'default)
6550 (push ov markdown-inline-image-overlays))))))))))
6552 (defun markdown-toggle-inline-images ()
6553 "Toggle inline image overlays in the buffer."
6554 (interactive)
6555 (if markdown-inline-image-overlays
6556 (markdown-remove-inline-images)
6557 (markdown-display-inline-images)))
6560 ;;; Mode Definition ==========================================================
6562 (defun markdown-show-version ()
6563 "Show the version number in the minibuffer."
6564 (interactive)
6565 (message "markdown-mode, version %s" markdown-mode-version))
6567 ;;;###autoload
6568 (define-derived-mode markdown-mode text-mode "Markdown"
6569 "Major mode for editing Markdown files."
6570 ;; Natural Markdown tab width
6571 (setq tab-width 4)
6572 ;; Comments
6573 (make-local-variable 'comment-start)
6574 (setq comment-start "<!-- ")
6575 (make-local-variable 'comment-end)
6576 (setq comment-end " -->")
6577 (make-local-variable 'comment-start-skip)
6578 (setq comment-start-skip "<!--[ \t]*")
6579 (make-local-variable 'comment-column)
6580 (setq comment-column 0)
6581 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
6582 ;; Syntax
6583 (add-hook 'syntax-propertize-extend-region-functions
6584 'markdown-syntax-propertize-extend-region)
6585 (add-hook 'jit-lock-after-change-extend-region-functions
6586 'markdown-font-lock-extend-region-function t t)
6587 (set (make-local-variable 'syntax-propertize-function)
6588 'markdown-syntax-propertize)
6589 ;; Font lock.
6590 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
6591 (set (make-local-variable 'font-lock-defaults) nil)
6592 (set (make-local-variable 'font-lock-multiline) t)
6593 ;; Extensions
6594 (make-local-variable 'markdown-enable-math)
6595 ;; Reload extensions
6596 (markdown-reload-extensions)
6597 ;; Add a buffer-local hook to reload after file-local variables are read
6598 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
6599 ;; For imenu support
6600 (setq imenu-create-index-function
6601 (if markdown-nested-imenu-heading-index
6602 'markdown-imenu-create-nested-index
6603 'markdown-imenu-create-flat-index))
6604 ;; For menu support in XEmacs
6605 (easy-menu-add markdown-mode-menu markdown-mode-map)
6606 ;; Defun movement
6607 (set (make-local-variable 'beginning-of-defun-function)
6608 'markdown-beginning-of-defun)
6609 (set (make-local-variable 'end-of-defun-function)
6610 'markdown-end-of-defun)
6611 ;; Paragraph filling
6612 (set
6613 ;; Should match start of lines that start or separate paragraphs
6614 (make-local-variable 'paragraph-start)
6615 (mapconcat #'identity
6617 "\f" ; starts with a literal line-feed
6618 "[ \t\f]*$" ; space-only line
6619 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6620 "[ \t]*[*+-][ \t]+" ; unordered list item
6621 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6622 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6623 "[ \t]*:[ \t]+" ; definition
6625 "\\|"))
6626 (set
6627 ;; Should match lines that separate paragraphs without being
6628 ;; part of any paragraph:
6629 (make-local-variable 'paragraph-separate)
6630 (mapconcat #'identity
6631 '("[ \t\f]*$" ; space-only line
6632 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6633 ;; The following is not ideal, but the Fill customization
6634 ;; options really only handle paragraph-starting prefixes,
6635 ;; not paragraph-ending suffixes:
6636 ".* $" ; line ending in two spaces
6637 "^#+"
6638 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6639 "\\|"))
6640 (set (make-local-variable 'adaptive-fill-first-line-regexp)
6641 "\\`[ \t]*>[ \t]*?\\'")
6642 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
6643 (set (make-local-variable 'adaptive-fill-function)
6644 'markdown-adaptive-fill-function)
6645 (set (make-local-variable 'fill-forward-paragraph-function)
6646 'markdown-fill-forward-paragraph-function)
6647 ;; Outline mode
6648 (make-local-variable 'outline-regexp)
6649 (setq outline-regexp markdown-regex-header)
6650 (make-local-variable 'outline-level)
6651 (setq outline-level 'markdown-outline-level)
6652 ;; Cause use of ellipses for invisible text.
6653 (add-to-invisibility-spec '(outline . t))
6655 ;; Inhibiting line-breaking:
6656 ;; Separating out each condition into a separate function so that users can
6657 ;; override if desired (with remove-hook)
6658 (add-hook 'fill-nobreak-predicate
6659 'markdown-inside-link-p nil t)
6660 (add-hook 'fill-nobreak-predicate
6661 'markdown-line-is-reference-definition-p nil t)
6663 ;; Indentation
6664 (setq indent-line-function markdown-indent-function)
6666 ;; Backwards compatibility with markdown-css-path
6667 (when (boundp 'markdown-css-path)
6668 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6669 (add-to-list 'markdown-css-paths markdown-css-path))
6671 ;; Prepare hooks for XEmacs compatibility
6672 (when (featurep 'xemacs)
6673 (make-local-hook 'after-change-functions)
6674 (make-local-hook 'font-lock-extend-region-functions)
6675 (make-local-hook 'window-configuration-change-hook))
6677 ;; Make checkboxes buttons
6678 (when markdown-make-gfm-checkboxes-buttons
6679 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6680 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
6682 ;; add live preview export hook
6683 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
6684 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
6686 ;;;###autoload
6687 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
6688 ;;;###autoload
6689 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
6692 ;;; GitHub Flavored Markdown Mode ============================================
6694 (defvar gfm-mode-hook nil
6695 "Hook run when entering GFM mode.")
6697 (defvar gfm-font-lock-keywords
6698 (append
6699 ;; GFM features to match first
6700 (list
6701 (cons markdown-regex-strike-through '((3 markdown-markup-face)
6702 (4 markdown-strike-through-face)
6703 (5 markdown-markup-face))))
6704 ;; Basic Markdown features (excluding possibly overridden ones)
6705 markdown-mode-font-lock-keywords-basic)
6706 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6708 ;;;###autoload
6709 (define-derived-mode gfm-mode markdown-mode "GFM"
6710 "Major mode for editing GitHub Flavored Markdown files."
6711 (setq markdown-link-space-sub-char "-")
6712 (set (make-local-variable 'font-lock-defaults)
6713 '(gfm-font-lock-keywords))
6714 ;; do the initial link fontification
6715 (markdown-gfm-parse-buffer-for-languages))
6718 ;;; Live Preview Mode ============================================
6719 (define-minor-mode markdown-live-preview-mode
6720 "Toggle native previewing on save for a specific markdown file."
6721 :lighter " MD-Preview"
6722 (if markdown-live-preview-mode
6723 (markdown-display-buffer-other-window (markdown-live-preview-export))
6724 (markdown-live-preview-remove)))
6727 (provide 'markdown-mode)
6728 ;; Local Variables:
6729 ;; indent-tabs-mode: nil
6730 ;; End:
6731 ;;; markdown-mode.el ends here