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