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