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