Document markdown-fill-forward-paragraph-function
[markdown-mode.git] / markdown-mode.el
blob460b0798bcc0382fb9b0bbf3038d702f738a8c77
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 (skip-chars-forward "\n")
1434 (if (re-search-backward "\n\n" nil t)
1435 (min start (match-end 0))
1436 (point-min))))
1437 (new-end (progn (goto-char end)
1438 (skip-chars-backward "\n")
1439 (if (re-search-forward "\n\n" 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 (remove-text-properties start end markdown--syntax-properties)
1922 (markdown-syntax-propertize-fenced-block-constructs start end)
1923 (markdown-syntax-propertize-yaml-metadata start end)
1924 (markdown-syntax-propertize-pre-blocks start end)
1925 (markdown-syntax-propertize-blockquotes start end)
1926 (markdown-syntax-propertize-headings start end)
1927 (markdown-syntax-propertize-comments start end))
1930 ;;; Font Lock =================================================================
1932 (require 'font-lock)
1934 (defvar markdown-italic-face 'markdown-italic-face
1935 "Face name to use for italic text.")
1937 (defvar markdown-bold-face 'markdown-bold-face
1938 "Face name to use for bold text.")
1940 (defvar markdown-strike-through-face 'markdown-strike-through-face
1941 "Face name to use for strike-through text.")
1943 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
1944 "Face name to use as a base for header delimiters.")
1946 (defvar markdown-header-rule-face 'markdown-header-rule-face
1947 "Face name to use as a base for header rules.")
1949 (defvar markdown-header-face 'markdown-header-face
1950 "Face name to use as a base for headers.")
1952 (defvar markdown-header-face-1 'markdown-header-face-1
1953 "Face name to use for level-1 headers.")
1955 (defvar markdown-header-face-2 'markdown-header-face-2
1956 "Face name to use for level-2 headers.")
1958 (defvar markdown-header-face-3 'markdown-header-face-3
1959 "Face name to use for level-3 headers.")
1961 (defvar markdown-header-face-4 'markdown-header-face-4
1962 "Face name to use for level-4 headers.")
1964 (defvar markdown-header-face-5 'markdown-header-face-5
1965 "Face name to use for level-5 headers.")
1967 (defvar markdown-header-face-6 'markdown-header-face-6
1968 "Face name to use for level-6 headers.")
1970 (defvar markdown-inline-code-face 'markdown-inline-code-face
1971 "Face name to use for inline code.")
1973 (defvar markdown-list-face 'markdown-list-face
1974 "Face name to use for list markers.")
1976 (defvar markdown-blockquote-face 'markdown-blockquote-face
1977 "Face name to use for blockquote.")
1979 (defvar markdown-pre-face 'markdown-pre-face
1980 "Face name to use for preformatted text.")
1982 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
1983 "Face name to use for programming language identifiers.")
1985 (defvar markdown-language-info-face 'markdown-language-info-face
1986 "Face name to use for programming info strings.")
1988 (defvar markdown-link-face 'markdown-link-face
1989 "Face name to use for links.")
1991 (defvar markdown-missing-link-face 'markdown-missing-link-face
1992 "Face name to use for links where the linked file does not exist.")
1994 (defvar markdown-reference-face 'markdown-reference-face
1995 "Face name to use for reference.")
1997 (defvar markdown-footnote-face 'markdown-footnote-face
1998 "Face name to use for footnote identifiers.")
2000 (defvar markdown-url-face 'markdown-url-face
2001 "Face name to use for URLs.")
2003 (defvar markdown-link-title-face 'markdown-link-title-face
2004 "Face name to use for reference link titles.")
2006 (defvar markdown-line-break-face 'markdown-line-break-face
2007 "Face name to use for hard line breaks.")
2009 (defvar markdown-comment-face 'markdown-comment-face
2010 "Face name to use for HTML comments.")
2012 (defvar markdown-math-face 'markdown-math-face
2013 "Face name to use for LaTeX expressions.")
2015 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2016 "Face name to use for metadata keys.")
2018 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2019 "Face name to use for metadata values.")
2021 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2022 "Face name to use for GFM checkboxes.")
2024 (defvar markdown-highlight-face 'markdown-highlight-face
2025 "Face name to use for mouse highlighting.")
2027 (defvar markdown-markup-face 'markdown-markup-face
2028 "Face name to use for markup elements.")
2030 (defgroup markdown-faces nil
2031 "Faces used in Markdown Mode"
2032 :group 'markdown
2033 :group 'faces)
2035 (defface markdown-italic-face
2036 '((t (:inherit font-lock-variable-name-face :slant italic :weight normal)))
2037 "Face for italic text."
2038 :group 'markdown-faces)
2040 (defface markdown-bold-face
2041 '((t (:inherit font-lock-variable-name-face :weight bold :slant normal)))
2042 "Face for bold text."
2043 :group 'markdown-faces)
2045 (defface markdown-strike-through-face
2046 '((t (:inherit font-lock-variable-name-face :strike-through t)))
2047 "Face for strike-through text."
2048 :group 'markdown-faces)
2050 (defface markdown-markup-face
2051 '((t (:inherit shadow :slant normal :weight normal)))
2052 "Face for markup elements."
2053 :group 'markdown-faces)
2055 (defface markdown-header-rule-face
2056 '((t (:inherit markdown-markup-face)))
2057 "Base face for headers rules."
2058 :group 'markdown-faces)
2060 (defface markdown-header-delimiter-face
2061 '((t (:inherit markdown-markup-face)))
2062 "Base face for headers hash delimiter."
2063 :group 'markdown-faces)
2065 (defface markdown-inline-code-face
2066 '((t (:inherit font-lock-constant-face)))
2067 "Face for inline code."
2068 :group 'markdown-faces)
2070 (defface markdown-list-face
2071 '((t (:inherit markdown-markup-face)))
2072 "Face for list item markers."
2073 :group 'markdown-faces)
2075 (defface markdown-blockquote-face
2076 '((t (:inherit font-lock-doc-face)))
2077 "Face for blockquote sections."
2078 :group 'markdown-faces)
2080 (defface markdown-pre-face
2081 '((t (:inherit font-lock-constant-face)))
2082 "Face for preformatted text."
2083 :group 'markdown-faces)
2085 (defface markdown-language-keyword-face
2086 '((t (:inherit font-lock-type-face)))
2087 "Face for programming language identifiers."
2088 :group 'markdown-faces)
2090 (defface markdown-language-info-face
2091 '((t (:inherit font-lock-string-face)))
2092 "Face for programming language info strings."
2093 :group 'markdown-faces)
2095 (defface markdown-link-face
2096 '((t (:inherit font-lock-keyword-face)))
2097 "Face for links."
2098 :group 'markdown-faces)
2100 (defface markdown-missing-link-face
2101 '((t (:inherit font-lock-warning-face)))
2102 "Face for missing links."
2103 :group 'markdown-faces)
2105 (defface markdown-reference-face
2106 '((t (:inherit markdown-markup-face)))
2107 "Face for link references."
2108 :group 'markdown-faces)
2110 (defface markdown-footnote-face
2111 '((t (:inherit markdown-markup-face)))
2112 "Face for footnote markers."
2113 :group 'markdown-faces)
2115 (defface markdown-url-face
2116 '((t (:inherit font-lock-string-face)))
2117 "Face for URLs."
2118 :group 'markdown-faces)
2120 (defface markdown-link-title-face
2121 '((t (:inherit font-lock-comment-face)))
2122 "Face for reference link titles."
2123 :group 'markdown-faces)
2125 (defface markdown-line-break-face
2126 '((t (:inherit font-lock-constant-face :underline t)))
2127 "Face for hard line breaks."
2128 :group 'markdown-faces)
2130 (defface markdown-comment-face
2131 '((t (:inherit font-lock-comment-face)))
2132 "Face for HTML comments."
2133 :group 'markdown-faces)
2135 (defface markdown-math-face
2136 '((t (:inherit font-lock-string-face)))
2137 "Face for LaTeX expressions."
2138 :group 'markdown-faces)
2140 (defface markdown-metadata-key-face
2141 '((t (:inherit font-lock-variable-name-face)))
2142 "Face for metadata keys."
2143 :group 'markdown-faces)
2145 (defface markdown-metadata-value-face
2146 '((t (:inherit font-lock-string-face)))
2147 "Face for metadata values."
2148 :group 'markdown-faces)
2150 (defface markdown-gfm-checkbox-face
2151 '((t (:inherit font-lock-builtin-face)))
2152 "Face for GFM checkboxes."
2153 :group 'markdown-faces)
2155 (defface markdown-highlight-face
2156 '((t (:inherit highlight)))
2157 "Face for mouse highlighting."
2158 :group 'markdown-faces)
2160 (defcustom markdown-header-scaling nil
2161 "Whether to use variable-height faces for headers.
2162 When non-nil, `markdown-header-face' will inherit from
2163 `variable-pitch' and the scaling values in
2164 `markdown-header-scaling-values' will be applied to
2165 headers of levels one through six respectively."
2166 :type 'boolean
2167 :initialize 'custom-initialize-default
2168 :set (lambda (symbol value)
2169 (set-default symbol value)
2170 (markdown-update-header-faces value))
2171 :group 'markdown-faces)
2173 (defcustom markdown-header-scaling-values
2174 '(1.8 1.4 1.2 1.0 1.0 1.0)
2175 "List of scaling values for headers of level one through six.
2176 Used when `markdown-header-scaling' is non-nil."
2177 :type 'list
2178 :initialize 'custom-initialize-default
2179 :set (lambda (symbol value)
2180 (set-default symbol value)
2181 (markdown-update-header-faces markdown-header-scaling value))
2182 :group 'markdown-faces)
2184 (defun markdown-make-header-faces ()
2185 "Build the faces used for Markdown headers."
2186 (let ((inherit-faces '(font-lock-function-name-face)))
2187 (when markdown-header-scaling
2188 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2189 (defface markdown-header-face
2190 `((t (:inherit ,inherit-faces :weight bold)))
2191 "Base face for headers."
2192 :group 'markdown-faces))
2193 (dotimes (num 6)
2194 (let* ((num1 (1+ num))
2195 (face-name (intern (format "markdown-header-face-%s" num1)))
2196 (scale (if markdown-header-scaling
2197 (float (nth num markdown-header-scaling-values))
2198 1.0)))
2199 (eval
2200 `(defface ,face-name
2201 '((t (:inherit markdown-header-face :height ,scale)))
2202 (format "Face for level %s headers.
2204 You probably don't want to customize this face directly. Instead
2205 you can customize the base face `markdown-header-face' or the
2206 variable-height variable `markdown-header-scaling'." ,num1)
2207 :group 'markdown-faces)))))
2209 (markdown-make-header-faces)
2211 (defun markdown-update-header-faces (&optional scaling scaling-values)
2212 "Update header faces, depending on if header SCALING is desired.
2213 If so, use given list of SCALING-VALUES relative to the baseline
2214 size of `markdown-header-face'."
2215 (dotimes (num 6)
2216 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2217 (scale (cond ((not scaling) 1.0)
2218 (scaling-values (float (nth num scaling-values)))
2219 (t (float (nth num markdown-header-scaling-values))))))
2220 (unless (get face-name 'saved-face) ; Don't update customized faces
2221 (set-face-attribute face-name nil :height scale)))))
2223 (defun markdown-syntactic-face (state)
2224 "Return font-lock face for characters with given STATE.
2225 See `font-lock-syntactic-face-function' for details."
2226 (let ((in-comment (nth 4 state)))
2227 (cond
2228 (in-comment 'markdown-comment-face)
2229 (t nil))))
2231 (defvar markdown-mode-font-lock-keywords-basic
2232 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2233 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2234 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2235 (2 markdown-markup-face)
2236 (3 markdown-metadata-value-face)))
2237 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-face)
2238 (2 markdown-markup-face nil t)
2239 (3 markdown-language-keyword-face nil t)
2240 (4 markdown-language-info-face nil t)
2241 (5 markdown-markup-face nil t)))
2242 (markdown-match-gfm-close-code-blocks . ((1 markdown-markup-face)))
2243 (markdown-match-gfm-code-blocks . ((0 markdown-pre-face)))
2244 (markdown-match-fenced-start-code-block . ((1 markdown-markup-face)
2245 (2 markdown-markup-face nil t)
2246 (3 markdown-language-keyword-face nil t)
2247 (4 markdown-language-info-face nil t)
2248 (5 markdown-markup-face nil t)))
2249 (markdown-match-fenced-end-code-block . ((0 markdown-markup-face)))
2250 (markdown-match-fenced-code-blocks . ((0 markdown-pre-face)))
2251 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2252 (markdown-match-blockquotes . ((1 markdown-markup-face)
2253 (2 markdown-blockquote-face)))
2254 (markdown-match-heading-1-setext . ((1 markdown-header-face-1)
2255 (2 markdown-header-rule-face)))
2256 (markdown-match-heading-2-setext . ((1 markdown-header-face-2)
2257 (3 markdown-header-rule-face)))
2258 (markdown-match-heading-6-atx . ((4 markdown-header-delimiter-face)
2259 (5 markdown-header-face-6)
2260 (6 markdown-header-delimiter-face)))
2261 (markdown-match-heading-5-atx . ((4 markdown-header-delimiter-face)
2262 (5 markdown-header-face-5)
2263 (6 markdown-header-delimiter-face)))
2264 (markdown-match-heading-4-atx . ((4 markdown-header-delimiter-face)
2265 (5 markdown-header-face-4)
2266 (6 markdown-header-delimiter-face)))
2267 (markdown-match-heading-3-atx . ((4 markdown-header-delimiter-face)
2268 (5 markdown-header-face-3)
2269 (6 markdown-header-delimiter-face)))
2270 (markdown-match-heading-2-atx . ((4 markdown-header-delimiter-face)
2271 (5 markdown-header-face-2)
2272 (6 markdown-header-delimiter-face)))
2273 (markdown-match-heading-1-atx . ((4 markdown-header-delimiter-face)
2274 (5 markdown-header-face-1)
2275 (6 markdown-header-delimiter-face)))
2276 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2277 (2 markdown-markup-face)
2278 (3 markdown-metadata-value-face)))
2279 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2280 (2 markdown-markup-face)
2281 (3 markdown-metadata-value-face)))
2282 (markdown-match-hr . markdown-header-delimiter-face)
2283 (markdown-match-code . ((1 markdown-markup-face)
2284 (2 markdown-inline-code-face)
2285 (3 markdown-markup-face)))
2286 (,markdown-regex-kbd . ((1 markdown-markup-face)
2287 (2 markdown-inline-code-face)
2288 (3 markdown-markup-face)))
2289 (,markdown-regex-angle-uri . ((1 markdown-markup-face)
2290 (2 markdown-link-face)
2291 (3 markdown-markup-face)))
2292 (,markdown-regex-list . (2 markdown-list-face))
2293 (,markdown-regex-footnote . ((1 markdown-markup-face) ; [^
2294 (2 markdown-footnote-face) ; label
2295 (3 markdown-markup-face))) ; ]
2296 (,markdown-regex-link-inline . ((1 markdown-markup-face nil t) ; ! (optional)
2297 (2 markdown-markup-face) ; [
2298 (3 markdown-link-face) ; text
2299 (4 markdown-markup-face) ; ]
2300 (5 markdown-markup-face) ; (
2301 (6 markdown-url-face) ; url
2302 (7 markdown-link-title-face nil t) ; "title" (optional)
2303 (8 markdown-markup-face))) ; )
2304 (,markdown-regex-link-reference . ((1 markdown-markup-face nil t) ; ! (optional)
2305 (2 markdown-markup-face) ; [
2306 (3 markdown-link-face) ; text
2307 (4 markdown-markup-face) ; ]
2308 (5 markdown-markup-face) ; [
2309 (6 markdown-reference-face) ; label
2310 (7 markdown-markup-face))) ; ]
2311 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2312 (2 markdown-reference-face) ; label
2313 (3 markdown-markup-face) ; ]
2314 (4 markdown-markup-face) ; :
2315 (5 markdown-url-face) ; url
2316 (6 markdown-link-title-face))) ; "title" (optional)
2317 ;; Math mode $..$
2318 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2319 (2 markdown-math-face append)
2320 (3 markdown-markup-face prepend)))
2321 ;; Math mode $$..$$
2322 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2323 (2 markdown-math-face append)
2324 (3 markdown-markup-face prepend)))
2325 (markdown-match-bold . ((1 markdown-markup-face prepend)
2326 (2 markdown-bold-face append)
2327 (3 markdown-markup-face prepend)))
2328 (markdown-match-italic . ((1 markdown-markup-face prepend)
2329 (2 markdown-italic-face append)
2330 (3 markdown-markup-face prepend)))
2331 (,markdown-regex-uri . markdown-link-face)
2332 (,markdown-regex-email . markdown-link-face)
2333 (,markdown-regex-line-break . (1 markdown-line-break-face prepend)))
2335 "Syntax highlighting for Markdown files.")
2337 (defvar markdown-mode-font-lock-keywords nil
2338 "Default highlighting expressions for Markdown mode.
2339 This variable is defined as a buffer-local variable for dynamic
2340 extension support.")
2342 ;; Footnotes
2343 (defvar markdown-footnote-counter 0
2344 "Counter for footnote numbers.")
2345 (make-variable-buffer-local 'markdown-footnote-counter)
2347 (defconst markdown-footnote-chars
2348 "[[:alnum:]-]"
2349 "Regular expression matching any character that is allowed in a footnote identifier.")
2351 (defconst markdown-regex-footnote-definition
2352 (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2353 "Regular expression matching a footnote definition, capturing the label.")
2356 ;;; Compatibility =============================================================
2358 (defun markdown-replace-regexp-in-string (regexp rep string)
2359 "Replace ocurrences of REGEXP with REP in STRING.
2360 This is a compatibility wrapper to provide `replace-regexp-in-string'
2361 in XEmacs 21."
2362 (if (featurep 'xemacs)
2363 (replace-in-string string regexp rep)
2364 (replace-regexp-in-string regexp rep string)))
2366 ;; `markdown-use-region-p' is a compatibility function which checks
2367 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2368 (eval-and-compile
2369 (cond
2370 ;; Emacs 24 and newer
2371 ((fboundp 'use-region-p)
2372 (defalias 'markdown-use-region-p 'use-region-p))
2373 ;; XEmacs
2374 ((fboundp 'region-active-p)
2375 (defalias 'markdown-use-region-p 'region-active-p))))
2377 (defun markdown-use-buttons-p ()
2378 "Determine whether this Emacs supports buttons."
2379 (or (featurep 'button) (locate-library "button")))
2381 ;; Use new names for outline-mode functions in Emacs 25 and later.
2382 (eval-and-compile
2383 (defalias 'markdown-hide-sublevels
2384 (if (fboundp 'outline-hide-sublevels)
2385 'outline-hide-sublevels
2386 'hide-sublevels))
2387 (defalias 'markdown-show-all
2388 (if (fboundp 'outline-show-all)
2389 'outline-show-all
2390 'show-all))
2391 (defalias 'markdown-hide-body
2392 (if (fboundp 'outline-hide-body)
2393 'outline-hide-body
2394 'hide-body))
2395 (defalias 'markdown-show-children
2396 (if (fboundp 'outline-show-children)
2397 'outline-show-children
2398 'show-children))
2399 (defalias 'markdown-show-subtree
2400 (if (fboundp 'outline-show-subtree)
2401 'outline-show-subtree
2402 'show-subtree))
2403 (defalias 'markdown-hide-subtree
2404 (if (fboundp 'outline-hide-subtree)
2405 'outline-hide-subtree
2406 'hide-subtree)))
2408 ;; Provide directory-name-p to Emacs 24
2409 (defsubst markdown-directory-name-p (name)
2410 "Return non-nil if NAME ends with a directory separator character.
2411 Taken from `directory-name-p' from Emacs 25 and provided here for
2412 backwards compatibility."
2413 (let ((len (length name))
2414 (lastc ?.))
2415 (if (> len 0)
2416 (setq lastc (aref name (1- len))))
2417 (or (= lastc ?/)
2418 (and (memq system-type '(windows-nt ms-dos))
2419 (= lastc ?\\)))))
2421 ;; Provide a function to find files recursively in Emacs 24.
2422 (defalias 'markdown-directory-files-recursively
2423 (if (fboundp 'directory-files-recursively)
2424 'directory-files-recursively
2425 (lambda (dir regexp)
2426 "Return list of all files under DIR that have file names matching REGEXP.
2427 This function works recursively. Files are returned in \"depth first\"
2428 order, and files from each directory are sorted in alphabetical order.
2429 Each file name appears in the returned list in its absolute form.
2430 Based on `directory-files-recursively' from Emacs 25 and provided
2431 here for backwards compatibility."
2432 (let ((result nil)
2433 (files nil)
2434 ;; When DIR is "/", remote file names like "/method:" could
2435 ;; also be offered. We shall suppress them.
2436 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2437 (dolist (file (sort (file-name-all-completions "" dir)
2438 'string<))
2439 (unless (member file '("./" "../"))
2440 (if (markdown-directory-name-p file)
2441 (let* ((leaf (substring file 0 (1- (length file))))
2442 (full-file (expand-file-name leaf dir)))
2443 (setq result
2444 (nconc result (markdown-directory-files-recursively
2445 full-file regexp))))
2446 (when (string-match regexp file)
2447 (push (expand-file-name file dir) files)))))
2448 (nconc result (nreverse files))))))
2451 ;;; Markdown Parsing Functions ================================================
2453 (defun markdown-cur-line-blank-p ()
2454 "Return t if the current line is blank and nil otherwise."
2455 (save-excursion
2456 (beginning-of-line)
2457 (looking-at-p "^\\s *$")))
2459 (defun markdown-prev-line-blank-p ()
2460 "Return t if the previous line is blank and nil otherwise.
2461 If we are at the first line, then consider the previous line to be blank."
2462 (or (= (line-beginning-position) (point-min))
2463 (save-excursion
2464 (forward-line -1)
2465 (markdown-cur-line-blank-p))))
2467 (defun markdown-next-line-blank-p ()
2468 "Return t if the next line is blank and nil otherwise.
2469 If we are at the last line, then consider the next line to be blank."
2470 (or (= (line-end-position) (point-max))
2471 (save-excursion
2472 (forward-line 1)
2473 (markdown-cur-line-blank-p))))
2475 (defun markdown-prev-line-indent ()
2476 "Return the number of leading whitespace characters in the previous line.
2477 Return 0 if the current line is the first line in the buffer."
2478 (save-excursion
2479 (if (= (line-beginning-position) (point-min))
2481 (forward-line -1)
2482 (current-indentation))))
2484 (defun markdown-next-line-indent ()
2485 "Return the number of leading whitespace characters in the next line.
2486 Return 0 if line is the last line in the buffer."
2487 (save-excursion
2488 (if (= (line-end-position) (point-max))
2490 (forward-line 1)
2491 (current-indentation))))
2493 (defun markdown-cur-non-list-indent ()
2494 "Return beginning position of list item text (not including the list marker).
2495 Return nil if the current line is not the beginning of a list item."
2496 (save-match-data
2497 (save-excursion
2498 (beginning-of-line)
2499 (when (re-search-forward markdown-regex-list (line-end-position) t)
2500 (current-column)))))
2502 (defun markdown-prev-non-list-indent ()
2503 "Return position of the first non-list-marker on the previous line."
2504 (save-excursion
2505 (forward-line -1)
2506 (markdown-cur-non-list-indent)))
2508 (defun markdown-new-baseline-p ()
2509 "Determine if the current line begins a new baseline level."
2510 (save-excursion
2511 (beginning-of-line)
2512 (or (looking-at-p markdown-regex-header)
2513 (looking-at-p markdown-regex-hr)
2514 (and (null (markdown-cur-non-list-indent))
2515 (= (current-indentation) 0)
2516 (markdown-prev-line-blank-p)))))
2518 (defun markdown-search-backward-baseline ()
2519 "Search backward baseline point with no indentation and not a list item."
2520 (end-of-line)
2521 (let (stop)
2522 (while (not (or stop (bobp)))
2523 (re-search-backward markdown-regex-block-separator nil t)
2524 (when (match-end 2)
2525 (goto-char (match-end 2))
2526 (cond
2527 ((markdown-new-baseline-p)
2528 (setq stop t))
2529 ((looking-at-p markdown-regex-list)
2530 (setq stop nil))
2531 (t (setq stop t)))))))
2533 (defun markdown-update-list-levels (marker indent levels)
2534 "Update list levels given list MARKER, block INDENT, and current LEVELS.
2535 Here, MARKER is a string representing the type of list, INDENT is an integer
2536 giving the indentation, in spaces, of the current block, and LEVELS is a
2537 list of the indentation levels of parent list items. When LEVELS is nil,
2538 it means we are at baseline (not inside of a nested list)."
2539 (cond
2540 ;; New list item at baseline.
2541 ((and marker (null levels))
2542 (setq levels (list indent)))
2543 ;; List item with greater indentation (four or more spaces).
2544 ;; Increase list level.
2545 ((and marker (>= indent (+ (car levels) 4)))
2546 (setq levels (cons indent levels)))
2547 ;; List item with greater or equal indentation (less than four spaces).
2548 ;; Do not increase list level.
2549 ((and marker (>= indent (car levels)))
2550 levels)
2551 ;; Lesser indentation level.
2552 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
2553 ;; indentation could move back more than one list level). Note
2554 ;; that this block need not be the beginning of list item.
2555 ((< indent (car levels))
2556 (while (and (> (length levels) 1)
2557 (< indent (+ (cadr levels) 4)))
2558 (setq levels (cdr levels)))
2559 levels)
2560 ;; Otherwise, do nothing.
2561 (t levels)))
2563 (defun markdown-calculate-list-levels ()
2564 "Calculate list levels at point.
2565 Return a list of the form (n1 n2 n3 ...) where n1 is the
2566 indentation of the deepest nested list item in the branch of
2567 the list at the point, n2 is the indentation of the parent
2568 list item, and so on. The depth of the list item is therefore
2569 the length of the returned list. If the point is not at or
2570 immediately after a list item, return nil."
2571 (save-excursion
2572 (let ((first (point)) levels indent pre-regexp)
2573 ;; Find a baseline point with zero list indentation
2574 (markdown-search-backward-baseline)
2575 ;; Search for all list items between baseline and LOC
2576 (while (and (< (point) first)
2577 (re-search-forward markdown-regex-list first t))
2578 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
2579 (beginning-of-line)
2580 (cond
2581 ;; Make sure this is not a header or hr
2582 ((markdown-new-baseline-p) (setq levels nil))
2583 ;; Make sure this is not a line from a pre block
2584 ((looking-at-p pre-regexp))
2585 ;; If not, then update levels
2587 (setq indent (current-indentation))
2588 (setq levels (markdown-update-list-levels (match-string 2)
2589 indent levels))))
2590 (end-of-line))
2591 levels)))
2593 (defun markdown-prev-list-item (level)
2594 "Search backward from point for a list item with indentation LEVEL.
2595 Set point to the beginning of the item, and return point, or nil
2596 upon failure."
2597 (let (bounds indent prev)
2598 (setq prev (point))
2599 (forward-line -1)
2600 (setq indent (current-indentation))
2601 (while
2602 (cond
2603 ;; List item
2604 ((and (looking-at-p markdown-regex-list)
2605 (setq bounds (markdown-cur-list-item-bounds)))
2606 (cond
2607 ;; Stop and return point at item of lesser or equal indentation
2608 ((<= (nth 3 bounds) level)
2609 (setq prev (point))
2610 nil)
2611 ;; Stop at beginning of buffer
2612 ((bobp) (setq prev nil))
2613 ;; Continue at item with greater indentation
2614 ((> (nth 3 bounds) level) t)))
2615 ;; Stop at beginning of buffer
2616 ((bobp) (setq prev nil))
2617 ;; Continue if current line is blank
2618 ((markdown-cur-line-blank-p) t)
2619 ;; Continue while indentation is the same or greater
2620 ((>= indent level) t)
2621 ;; Stop if current indentation is less than list item
2622 ;; and the next is blank
2623 ((and (< indent level)
2624 (markdown-next-line-blank-p))
2625 (setq prev nil))
2626 ;; Stop at a header
2627 ((looking-at-p markdown-regex-header) (setq prev nil))
2628 ;; Stop at a horizontal rule
2629 ((looking-at-p markdown-regex-hr) (setq prev nil))
2630 ;; Otherwise, continue.
2631 (t t))
2632 (forward-line -1)
2633 (setq indent (current-indentation)))
2634 prev))
2636 (defun markdown-next-list-item (level)
2637 "Search forward from point for the next list item with indentation LEVEL.
2638 Set point to the beginning of the item, and return point, or nil
2639 upon failure."
2640 (let (bounds indent next)
2641 (setq next (point))
2642 (forward-line)
2643 (setq indent (current-indentation))
2644 (while
2645 (cond
2646 ;; Stop at end of the buffer.
2647 ((eobp) nil)
2648 ;; Continue if the current line is blank
2649 ((markdown-cur-line-blank-p) t)
2650 ;; List item
2651 ((and (looking-at-p markdown-regex-list)
2652 (setq bounds (markdown-cur-list-item-bounds)))
2653 (cond
2654 ;; Continue at item with greater indentation
2655 ((> (nth 3 bounds) level) t)
2656 ;; Stop and return point at item of equal indentation
2657 ((= (nth 3 bounds) level)
2658 (setq next (point))
2659 nil)
2660 ;; Stop and return nil at item with lesser indentation
2661 ((< (nth 3 bounds) level)
2662 (setq next nil)
2663 nil)))
2664 ;; Continue while indentation is the same or greater
2665 ((>= indent level) t)
2666 ;; Stop if current indentation is less than list item
2667 ;; and the previous line was blank.
2668 ((and (< indent level)
2669 (markdown-prev-line-blank-p))
2670 (setq next nil))
2671 ;; Stop at a header
2672 ((looking-at-p markdown-regex-header) (setq next nil))
2673 ;; Stop at a horizontal rule
2674 ((looking-at-p markdown-regex-hr) (setq next nil))
2675 ;; Otherwise, continue.
2676 (t t))
2677 (forward-line)
2678 (setq indent (current-indentation)))
2679 next))
2681 (defun markdown-cur-list-item-end (level)
2682 "Move to the end of the current list item with nonlist indentation LEVEL.
2683 If the point is not in a list item, do nothing."
2684 (let (indent)
2685 (forward-line)
2686 (setq indent (current-indentation))
2687 (while
2688 (cond
2689 ;; Stop at end of the buffer.
2690 ((eobp) nil)
2691 ;; Continue if the current line is blank
2692 ((markdown-cur-line-blank-p) t)
2693 ;; Continue while indentation is the same or greater
2694 ((>= indent level) t)
2695 ;; Stop if current indentation is less than list item
2696 ;; and the previous line was blank.
2697 ((and (< indent level)
2698 (markdown-prev-line-blank-p))
2699 nil)
2700 ;; Stop at a new list item of the same or lesser indentation
2701 ((looking-at-p markdown-regex-list) nil)
2702 ;; Stop at a header
2703 ((looking-at-p markdown-regex-header) nil)
2704 ;; Stop at a horizontal rule
2705 ((looking-at-p markdown-regex-hr) nil)
2706 ;; Otherwise, continue.
2707 (t t))
2708 (forward-line)
2709 (setq indent (current-indentation)))
2710 ;; Don't skip over whitespace for empty list items (marker and
2711 ;; whitespace only), just move to end of whitespace.
2712 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
2713 (goto-char (match-end 3))
2714 (skip-syntax-backward "-"))))
2716 (defun markdown-cur-list-item-bounds ()
2717 "Return bounds and indentation of the current list item.
2718 Return a list of the form (begin end indent nonlist-indent marker).
2719 If the point is not inside a list item, return nil.
2720 Leave match data intact for `markdown-regex-list'."
2721 (let (cur prev-begin prev-end indent nonlist-indent marker)
2722 ;; Store current location
2723 (setq cur (point))
2724 ;; Verify that cur is between beginning and end of item
2725 (save-excursion
2726 (end-of-line)
2727 (when (re-search-backward markdown-regex-list nil t)
2728 (setq prev-begin (match-beginning 0))
2729 (setq indent (length (match-string 1)))
2730 (setq nonlist-indent (length (match-string 0)))
2731 (setq marker (concat (match-string 2) (match-string 3)))
2732 (save-match-data
2733 (markdown-cur-list-item-end nonlist-indent)
2734 (setq prev-end (point)))
2735 (when (and (>= cur prev-begin)
2736 (<= cur prev-end)
2737 nonlist-indent)
2738 (list prev-begin prev-end indent nonlist-indent marker))))))
2740 (defun markdown-bounds-of-thing-at-point (thing)
2741 "Call `bounds-of-thing-at-point' for THING with slight modifications.
2742 Does not include trailing newlines when THING is 'line. Handles the
2743 end of buffer case by setting both endpoints equal to the value of
2744 `point-max', since an empty region will trigger empty markup insertion.
2745 Return bounds of form (beg . end) if THING is found, or nil otherwise."
2746 (let* ((bounds (bounds-of-thing-at-point thing))
2747 (a (car bounds))
2748 (b (cdr bounds)))
2749 (when bounds
2750 (when (eq thing 'line)
2751 (cond ((and (eobp) (markdown-cur-line-blank-p))
2752 (setq a b))
2753 ((char-equal (char-before b) ?\^J)
2754 (setq b (1- b)))))
2755 (cons a b))))
2757 (defun markdown-reference-definition (reference)
2758 "Find out whether Markdown REFERENCE is defined.
2759 REFERENCE should not include the square brackets.
2760 When REFERENCE is defined, return a list of the form (text start end)
2761 containing the definition text itself followed by the start and end
2762 locations of the text. Otherwise, return nil.
2763 Leave match data for `markdown-regex-reference-definition'
2764 intact additional processing."
2765 (let ((reference (downcase reference)))
2766 (save-excursion
2767 (goto-char (point-min))
2768 (catch 'found
2769 (while (re-search-forward markdown-regex-reference-definition nil t)
2770 (when (string= reference (downcase (match-string-no-properties 2)))
2771 (throw 'found
2772 (list (match-string-no-properties 5)
2773 (match-beginning 5) (match-end 5)))))))))
2775 (defun markdown-get-defined-references ()
2776 "Return a list of all defined reference labels (not including square brackets)."
2777 (save-excursion
2778 (goto-char (point-min))
2779 (let (refs)
2780 (while (re-search-forward markdown-regex-reference-definition nil t)
2781 (let ((target (match-string-no-properties 2)))
2782 (cl-pushnew target refs :test #'equal)))
2783 (reverse refs))))
2785 (defun markdown-inline-code-at-point ()
2786 "Return non-nil if the point is at an inline code fragment.
2787 Return nil otherwise. Set match data according to
2788 `markdown-match-code' upon success.
2789 This function searches the block for a code fragment that
2790 contains the point using `markdown-match-code'. We do this
2791 because `thing-at-point-looking-at' does not work reliably with
2792 `markdown-regex-code'.
2794 The match data is set as follows:
2795 Group 1 matches the opening backticks.
2796 Group 2 matches the code fragment itself, without backticks.
2797 Group 3 matches the closing backticks."
2798 (save-excursion
2799 (let ((old-point (point))
2800 (end-of-block (progn (markdown-end-of-block) (point)))
2801 found)
2802 (markdown-beginning-of-block)
2803 (while (and (markdown-match-code end-of-block)
2804 (setq found t)
2805 (< (match-end 0) old-point)))
2806 (and found ; matched something
2807 (<= (match-beginning 0) old-point) ; match contains old-point
2808 (>= (match-end 0) old-point)))))
2810 (defun markdown-inline-code-at-point-p ()
2811 "Return non-nil if there is inline code at the point.
2812 This is a predicate function counterpart to
2813 `markdown-inline-code-at-point' which does not modify the match
2814 data. See `markdown-code-block-at-point-p' for code blocks."
2815 (save-match-data (markdown-inline-code-at-point)))
2817 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "2017-05-10")
2819 (defun markdown-code-block-at-pos (pos)
2820 "Return match data list if there is a code block at POS.
2821 This includes pre blocks, tilde-fenced code blocks, and GFM
2822 quoted code blocks. Return nil otherwise."
2823 (or (get-text-property pos 'markdown-pre)
2824 (markdown-get-enclosing-fenced-block-construct pos)
2825 ;; polymode removes text properties set by markdown-mode, so
2826 ;; check if `poly-markdown-mode' is active and whether the
2827 ;; `chunkmode' property is non-nil at POS.
2828 (and (bound-and-true-p poly-markdown-mode)
2829 (get-text-property pos 'chunkmode))))
2831 (defun markdown-code-block-at-point ()
2832 "Return match data if the point is inside a code block.
2833 This includes pre blocks, tilde-fenced code blocks, and
2834 GFM quoted code blocks. Calls `markdown-code-block-at-pos'."
2835 (markdown-code-block-at-pos (point)))
2837 (defun markdown-code-block-at-point-p ()
2838 "Return non-nil if there is a code block at the point.
2839 This includes pre blocks, tilde-fenced code blocks, and GFM
2840 quoted code blocks. This is a predicate function counterpart to
2841 `markdown-code-block-at-point' which does not modify the match
2842 data. See `markdown-inline-code-at-point-p' for inline code."
2843 (save-match-data (markdown-code-block-at-point)))
2846 ;;; Markdown Font Lock Matching Functions =====================================
2848 (defun markdown-range-property-any (begin end prop prop-values)
2849 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
2850 Also returns t if PROP is a list containing one of the PROP-VALUES.
2851 Return nil otherwise."
2852 (let (props)
2853 (catch 'found
2854 (dolist (loc (number-sequence begin end))
2855 (when (setq props (get-char-property loc prop))
2856 (cond ((listp props)
2857 ;; props is a list, check for membership
2858 (dolist (val prop-values)
2859 (when (memq val props) (throw 'found loc))))
2861 ;; props is a scalar, check for equality
2862 (dolist (val prop-values)
2863 (when (eq val props) (throw 'found loc))))))))))
2865 (defun markdown-range-properties-exist (begin end props)
2866 (cl-loop
2867 for loc in (number-sequence begin end)
2868 with result = nil
2869 while (not
2870 (setq result
2871 (cl-some (lambda (prop) (get-char-property loc prop)) props)))
2872 finally return result))
2874 (defun markdown-match-inline-generic (regex last)
2875 "Match inline REGEX from the point to LAST."
2876 (when (re-search-forward regex last t)
2877 (let ((bounds (markdown-code-block-at-pos (match-beginning 1))))
2878 (if (null bounds)
2879 ;; Not in a code block: keep match data and return t when in bounds
2880 (<= (match-end 0) last)
2881 ;; In code block: move past it and recursively search again
2882 (when (< (goto-char (nth 1 bounds)) last)
2883 (markdown-match-inline-generic regex last))))))
2885 (defun markdown-match-code (last)
2886 "Match inline code fragments from point to LAST."
2887 (unless (bobp)
2888 (backward-char 1))
2889 (when (markdown-match-inline-generic markdown-regex-code last)
2890 (set-match-data (list (match-beginning 1) (match-end 1)
2891 (match-beginning 2) (match-end 2)
2892 (match-beginning 3) (match-end 3)
2893 (match-beginning 4) (match-end 4)))
2894 (goto-char (1+ (match-end 0)))))
2896 (defun markdown-match-bold (last)
2897 "Match inline bold from the point to LAST."
2898 (when (markdown-match-inline-generic markdown-regex-bold last)
2899 (let ((begin (match-beginning 2)) (end (match-end 2)))
2900 (cond
2901 ((markdown-range-property-any
2902 begin end 'face (list markdown-inline-code-face
2903 markdown-math-face))
2904 (goto-char (1+ (match-end 0)))
2905 (markdown-match-bold last))
2907 (set-match-data (list (match-beginning 2) (match-end 2)
2908 (match-beginning 3) (match-end 3)
2909 (match-beginning 4) (match-end 4)
2910 (match-beginning 5) (match-end 5)))
2911 (goto-char (1+ (match-end 0))))))))
2913 (defun markdown-match-italic (last)
2914 "Match inline italics from the point to LAST."
2915 (let ((regex (if (eq major-mode 'gfm-mode)
2916 markdown-regex-gfm-italic markdown-regex-italic)))
2917 (when (markdown-match-inline-generic regex last)
2918 (let ((begin (match-beginning 1)) (end (match-end 1)))
2919 (cond
2920 ((markdown-range-property-any
2921 begin begin 'face (list markdown-url-face))
2922 ;; Italics shouldn't begin inside a URL due to an underscore
2923 (goto-char (min (1+ (match-end 0)) last))
2924 (markdown-match-italic last))
2925 ((markdown-range-property-any
2926 begin end 'face (list markdown-inline-code-face
2927 markdown-bold-face
2928 markdown-list-face
2929 markdown-math-face))
2930 (goto-char (1+ (match-end 0)))
2931 (markdown-match-italic last))
2933 (set-match-data (list (match-beginning 1) (match-end 1)
2934 (match-beginning 2) (match-end 2)
2935 (match-beginning 3) (match-end 3)
2936 (match-beginning 4) (match-end 4)))
2937 (goto-char (1+ (match-end 0)))))))))
2939 (defun markdown-match-math-generic (regex last)
2940 "Match REGEX from point to LAST.
2941 REGEX is either `markdown-regex-math-inline-single' for matching
2942 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
2943 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
2944 (let ((begin (match-beginning 1)) (end (match-end 1)))
2945 (prog1
2946 (if (or (markdown-range-property-any
2947 begin end 'face (list markdown-inline-code-face
2948 markdown-bold-face))
2949 (markdown-range-properties-exist
2950 begin end
2951 (markdown-get-fenced-block-middle-properties)))
2952 (markdown-match-math-generic regex last)
2954 (goto-char (1+ (match-end 0)))))))
2956 (defun markdown-match-math-single (last)
2957 "Match single quoted $..$ math from point to LAST."
2958 (markdown-match-math-generic markdown-regex-math-inline-single last))
2960 (defun markdown-match-math-double (last)
2961 "Match double quoted $$..$$ math from point to LAST."
2962 (markdown-match-math-generic markdown-regex-math-inline-double last))
2964 (defun markdown-match-propertized-text (property last)
2965 "Match text with PROPERTY from point to LAST.
2966 Restore match data previously stored in PROPERTY."
2967 (let ((saved (get-text-property (point) property))
2968 pos)
2969 (unless saved
2970 (setq pos (next-single-char-property-change (point) property nil last))
2971 (setq saved (get-text-property pos property)))
2972 (when saved
2973 (set-match-data saved)
2974 ;; Step at least one character beyond point. Otherwise
2975 ;; `font-lock-fontify-keywords-region' infloops.
2976 (goto-char (min (1+ (max (match-end 0) (point)))
2977 (point-max)))
2978 saved)))
2980 (defun markdown-match-pre-blocks (last)
2981 "Match preformatted blocks from point to LAST.
2982 Use data stored in 'markdown-pre text property during syntax
2983 analysis."
2984 (markdown-match-propertized-text 'markdown-pre last))
2986 (defun markdown-match-gfm-code-blocks (last)
2987 "Match GFM quoted code blocks from point to LAST.
2988 Use data stored in 'markdown-gfm-code text property during syntax
2989 analysis."
2990 (markdown-match-propertized-text 'markdown-gfm-code last))
2992 (defun markdown-match-gfm-open-code-blocks (last)
2993 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
2995 (defun markdown-match-gfm-close-code-blocks (last)
2996 (markdown-match-propertized-text 'markdown-gfm-block-end last))
2998 (defun markdown-match-fenced-code-blocks (last)
2999 "Match fenced code blocks from the point to LAST."
3000 (markdown-match-propertized-text 'markdown-fenced-code last))
3002 (defun markdown-match-fenced-start-code-block (last)
3003 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3005 (defun markdown-match-fenced-end-code-block (last)
3006 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3008 (defun markdown-match-blockquotes (last)
3009 "Match blockquotes from point to LAST.
3010 Use data stored in 'markdown-blockquote text property during syntax
3011 analysis."
3012 (markdown-match-propertized-text 'markdown-blockquote last))
3014 (defun markdown-match-heading-1-setext (last)
3015 "Match level 1 setext headings from point to LAST."
3016 (markdown-match-propertized-text 'markdown-heading-1-setext last))
3018 (defun markdown-match-heading-2-setext (last)
3019 "Match level 2 setext headings from point to LAST."
3020 (markdown-match-propertized-text 'markdown-heading-2-setext last))
3022 (defun markdown-match-heading-1-atx (last)
3023 "Match level 1 ATX headings from point to LAST."
3024 (markdown-match-propertized-text 'markdown-heading-1-atx last))
3026 (defun markdown-match-heading-2-atx (last)
3027 "Match level 2 ATX headings from point to LAST."
3028 (markdown-match-propertized-text 'markdown-heading-2-atx last))
3030 (defun markdown-match-heading-3-atx (last)
3031 "Match level 3 ATX headings from point to LAST."
3032 (markdown-match-propertized-text 'markdown-heading-3-atx last))
3034 (defun markdown-match-heading-4-atx (last)
3035 "Match level 4 ATX headings from point to LAST."
3036 (markdown-match-propertized-text 'markdown-heading-4-atx last))
3038 (defun markdown-match-heading-5-atx (last)
3039 "Match level 5 ATX headings from point to LAST."
3040 (markdown-match-propertized-text 'markdown-heading-5-atx last))
3042 (defun markdown-match-heading-6-atx (last)
3043 "Match level 6 ATX headings from point to LAST."
3044 (markdown-match-propertized-text 'markdown-heading-6-atx last))
3046 (defun markdown-match-hr (last)
3047 "Match horizontal rules comments from the point to LAST."
3048 (while (and (re-search-forward markdown-regex-hr last t)
3049 (or (markdown-on-heading-p)
3050 (markdown-code-block-at-point))
3051 (< (match-end 0) last))
3052 (forward-line))
3053 (beginning-of-line)
3054 (cond ((looking-at-p markdown-regex-hr)
3055 (forward-line)
3057 (t nil)))
3059 (defun markdown-match-comments (last)
3060 "Match HTML comments from the point to LAST."
3061 (when (and (skip-syntax-forward "^<" last))
3062 (let ((beg (point)))
3063 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3064 (forward-char)
3065 (set-match-data (list beg (point)))
3066 t))))
3068 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3069 (save-excursion
3070 (goto-char (or pos (point-min)))
3071 (cl-loop
3072 with cur-result = nil
3073 and st-hdr = (or start-header "\\`")
3074 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3075 while (and (< (point) last)
3076 (re-search-forward st-hdr last t)
3077 (progn
3078 (setq cur-result (match-data))
3079 (re-search-forward end-hdr nil t)))
3080 collect (list cur-result (match-data)))))
3082 (defvar markdown-conditional-search-function #'re-search-forward
3083 "Conditional search function used in `markdown-search-until-condition'.
3084 Made into a variable to allow for dynamic let-binding.")
3086 (defun markdown-search-until-condition (condition &rest args)
3087 (let (ret)
3088 (while (and (not ret) (apply markdown-conditional-search-function args))
3089 (setq ret (funcall condition)))
3090 ret))
3092 (defun markdown-match-generic-metadata
3093 (regexp last &optional start-header end-header)
3094 "Match generic metadata specified by REGEXP from the point to LAST.
3095 If START-HEADER is nil, we assume metadata can only occur at the
3096 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3097 is \"\n\n\""
3098 (let* ((header-bounds
3099 (markdown-get-match-boundaries start-header end-header last))
3100 (enclosing-header
3101 (cl-find-if ; just take first if multiple
3102 (lambda (match-bounds)
3103 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3104 (and (< (point) begin)
3105 (save-excursion (re-search-forward regexp end t)))))
3106 header-bounds))
3107 (header-begin
3108 (when enclosing-header (cl-second (cl-first enclosing-header))))
3109 (header-end
3110 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3111 (cond ((null enclosing-header)
3112 ;; Don't match anything outside of a header.
3113 nil)
3114 ((markdown-search-until-condition
3115 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3116 ;; If a metadata item is found, it may span several lines.
3117 (let ((key-beginning (match-beginning 1))
3118 (key-end (match-end 1))
3119 (markup-begin (match-beginning 2))
3120 (markup-end (match-end 2))
3121 (value-beginning (match-beginning 3)))
3122 (set-match-data (list key-beginning (point) ; complete metadata
3123 key-beginning key-end ; key
3124 markup-begin markup-end ; markup
3125 value-beginning (point))) ; value
3127 (t nil))))
3129 (defun markdown-match-declarative-metadata (last)
3130 "Match declarative metadata from the point to LAST."
3131 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3133 (defun markdown-match-pandoc-metadata (last)
3134 "Match Pandoc metadata from the point to LAST."
3135 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3137 (defun markdown-match-yaml-metadata-begin (last)
3138 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3140 (defun markdown-match-yaml-metadata-end (last)
3141 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3143 (defun markdown-match-yaml-metadata-key (last)
3144 (markdown-match-propertized-text 'markdown-metadata-key last))
3147 ;;; Syntax Table ==============================================================
3149 (defvar markdown-mode-syntax-table
3150 (let ((tab (make-syntax-table text-mode-syntax-table)))
3151 (modify-syntax-entry ?\" "." tab)
3152 tab)
3153 "Syntax table for `markdown-mode'.")
3156 ;;; Element Insertion =========================================================
3158 (defun markdown-ensure-blank-line-before ()
3159 "If previous line is not already blank, insert a blank line before point."
3160 (unless (bolp) (insert "\n"))
3161 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
3163 (defun markdown-ensure-blank-line-after ()
3164 "If following line is not already blank, insert a blank line after point.
3165 Return the point where it was originally."
3166 (save-excursion
3167 (unless (eolp) (insert "\n"))
3168 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
3170 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
3171 "Insert the strings S1 and S2, wrapping around region or THING.
3172 If a region is specified by the optional BEG and END arguments,
3173 wrap the strings S1 and S2 around that region.
3174 If there is an active region, wrap the strings S1 and S2 around
3175 the region. If there is not an active region but the point is at
3176 THING, wrap that thing (which defaults to word). Otherwise, just
3177 insert S1 and S2 and place the cursor in between. Return the
3178 bounds of the entire wrapped string, or nil if nothing was wrapped
3179 and S1 and S2 were only inserted."
3180 (let (a b bounds new-point)
3181 (cond
3182 ;; Given region
3183 ((and beg end)
3184 (setq a beg
3185 b end
3186 new-point (+ (point) (length s1))))
3187 ;; Active region
3188 ((markdown-use-region-p)
3189 (setq a (region-beginning)
3190 b (region-end)
3191 new-point (+ (point) (length s1))))
3192 ;; Thing (word) at point
3193 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
3194 (setq a (car bounds)
3195 b (cdr bounds)
3196 new-point (+ (point) (length s1))))
3197 ;; No active region and no word
3199 (setq a (point)
3200 b (point))))
3201 (goto-char b)
3202 (insert s2)
3203 (goto-char a)
3204 (insert s1)
3205 (when new-point (goto-char new-point))
3206 (if (= a b)
3208 (setq b (+ b (length s1) (length s2)))
3209 (cons a b))))
3211 (defun markdown-point-after-unwrap (cur prefix suffix)
3212 "Return desired position of point after an unwrapping operation.
3213 CUR gives the position of the point before the operation.
3214 Additionally, two cons cells must be provided. PREFIX gives the
3215 bounds of the prefix string and SUFFIX gives the bounds of the
3216 suffix string."
3217 (cond ((< cur (cdr prefix)) (car prefix))
3218 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
3219 ((<= cur (cdr suffix))
3220 (- cur (+ (- (cdr prefix) (car prefix))
3221 (- cur (car suffix)))))
3222 (t cur)))
3224 (defun markdown-unwrap-thing-at-point (regexp all text)
3225 "Remove prefix and suffix of thing at point and reposition the point.
3226 When the thing at point matches REGEXP, replace the subexpression
3227 ALL with the string in subexpression TEXT. Reposition the point
3228 in an appropriate location accounting for the removal of prefix
3229 and suffix strings. Return new bounds of string from group TEXT.
3230 When REGEXP is nil, assumes match data is already set."
3231 (when (or (null regexp)
3232 (thing-at-point-looking-at regexp))
3233 (let ((cur (point))
3234 (prefix (cons (match-beginning all) (match-beginning text)))
3235 (suffix (cons (match-end text) (match-end all)))
3236 (bounds (cons (match-beginning text) (match-end text))))
3237 ;; Replace the thing at point
3238 (replace-match (match-string text) t t nil all)
3239 ;; Reposition the point
3240 (goto-char (markdown-point-after-unwrap cur prefix suffix))
3241 ;; Adjust bounds
3242 (setq bounds (cons (car prefix)
3243 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
3245 (defun markdown-unwrap-things-in-region (beg end regexp all text)
3246 "Remove prefix and suffix of all things in region from BEG to END.
3247 When a thing in the region matches REGEXP, replace the
3248 subexpression ALL with the string in subexpression TEXT.
3249 Return a cons cell containing updated bounds for the region."
3250 (save-excursion
3251 (goto-char beg)
3252 (let ((removed 0) len-all len-text)
3253 (while (re-search-forward regexp (- end removed) t)
3254 (setq len-all (length (match-string-no-properties all)))
3255 (setq len-text (length (match-string-no-properties text)))
3256 (setq removed (+ removed (- len-all len-text)))
3257 (replace-match (match-string text) t t nil all))
3258 (cons beg (- end removed)))))
3260 (defun markdown-insert-hr (arg)
3261 "Insert or replace a horizonal rule.
3262 By default, use the first element of `markdown-hr-strings'. When
3263 ARG is non-nil, as when given a prefix, select a different
3264 element as follows. When prefixed with \\[universal-argument],
3265 use the last element of `markdown-hr-strings' instead. When
3266 prefixed with an integer from 1 to the length of
3267 `markdown-hr-strings', use the element in that position instead."
3268 (interactive "*P")
3269 (when (thing-at-point-looking-at markdown-regex-hr)
3270 (delete-region (match-beginning 0) (match-end 0)))
3271 (markdown-ensure-blank-line-before)
3272 (cond ((equal arg '(4))
3273 (insert (car (reverse markdown-hr-strings))))
3274 ((and (integerp arg) (> arg 0)
3275 (<= arg (length markdown-hr-strings)))
3276 (insert (nth (1- arg) markdown-hr-strings)))
3278 (insert (car markdown-hr-strings))))
3279 (markdown-ensure-blank-line-after))
3281 (defun markdown-insert-bold ()
3282 "Insert markup to make a region or word bold.
3283 If there is an active region, make the region bold. If the point
3284 is at a non-bold word, make the word bold. If the point is at a
3285 bold word or phrase, remove the bold markup. Otherwise, simply
3286 insert bold delimiters and place the cursor in between them."
3287 (interactive)
3288 (let ((delim (if markdown-bold-underscore "__" "**")))
3289 (if (markdown-use-region-p)
3290 ;; Active region
3291 (let ((bounds (markdown-unwrap-things-in-region
3292 (region-beginning) (region-end)
3293 markdown-regex-bold 2 4)))
3294 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3295 ;; Bold markup removal, bold word at point, or empty markup insertion
3296 (if (thing-at-point-looking-at markdown-regex-bold)
3297 (markdown-unwrap-thing-at-point nil 2 4)
3298 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3300 (defun markdown-insert-italic ()
3301 "Insert markup to make a region or word italic.
3302 If there is an active region, make the region italic. If the point
3303 is at a non-italic word, make the word italic. If the point is at an
3304 italic word or phrase, remove the italic markup. Otherwise, simply
3305 insert italic delimiters and place the cursor in between them."
3306 (interactive)
3307 (let ((delim (if markdown-italic-underscore "_" "*")))
3308 (if (markdown-use-region-p)
3309 ;; Active region
3310 (let ((bounds (markdown-unwrap-things-in-region
3311 (region-beginning) (region-end)
3312 markdown-regex-italic 1 3)))
3313 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3314 ;; Italic markup removal, italic word at point, or empty markup insertion
3315 (if (thing-at-point-looking-at markdown-regex-italic)
3316 (markdown-unwrap-thing-at-point nil 1 3)
3317 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3319 (defun markdown-insert-strike-through ()
3320 "Insert markup to make a region or word strikethrough.
3321 If there is an active region, make the region strikethrough. If the point
3322 is at a non-bold word, make the word strikethrough. If the point is at a
3323 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
3324 simply insert bold delimiters and place the cursor in between them."
3325 (interactive)
3326 (let ((delim "~~"))
3327 (if (markdown-use-region-p)
3328 ;; Active region
3329 (let ((bounds (markdown-unwrap-things-in-region
3330 (region-beginning) (region-end)
3331 markdown-regex-strike-through 2 4)))
3332 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
3333 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
3334 (if (thing-at-point-looking-at markdown-regex-strike-through)
3335 (markdown-unwrap-thing-at-point nil 2 4)
3336 (markdown-wrap-or-insert delim delim 'word nil nil)))))
3338 (defun markdown-insert-code ()
3339 "Insert markup to make a region or word an inline code fragment.
3340 If there is an active region, make the region an inline code
3341 fragment. If the point is at a word, make the word an inline
3342 code fragment. Otherwise, simply insert code delimiters and
3343 place the cursor in between them."
3344 (interactive)
3345 (if (markdown-use-region-p)
3346 ;; Active region
3347 (let ((bounds (markdown-unwrap-things-in-region
3348 (region-beginning) (region-end)
3349 markdown-regex-code 1 3)))
3350 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
3351 ;; Code markup removal, code markup for word, or empty markup insertion
3352 (if (markdown-inline-code-at-point)
3353 (markdown-unwrap-thing-at-point nil 0 2)
3354 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
3356 (defun markdown-insert-kbd ()
3357 "Insert markup to wrap region or word in <kbd> tags.
3358 If there is an active region, use the region. If the point is at
3359 a word, use the word. Otherwise, simply insert <kbd> tags and
3360 place the cursor in between them."
3361 (interactive)
3362 (if (markdown-use-region-p)
3363 ;; Active region
3364 (let ((bounds (markdown-unwrap-things-in-region
3365 (region-beginning) (region-end)
3366 markdown-regex-kbd 0 2)))
3367 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
3368 ;; Markup removal, markup for word, or empty markup insertion
3369 (if (thing-at-point-looking-at markdown-regex-kbd)
3370 (markdown-unwrap-thing-at-point nil 0 2)
3371 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
3373 (defun markdown-insert-inline-link (text url &optional title)
3374 "Insert an inline link with TEXT pointing to URL.
3375 Optionally, the user can provide a TITLE."
3376 (let ((cur (point)))
3377 (setq title (and title (concat " \"" title "\"")))
3378 (insert (concat "[" text "](" url title ")"))
3379 (cond ((not text) (goto-char (+ 1 cur)))
3380 ((not url) (goto-char (+ 3 (length text) cur))))))
3382 (defun markdown-insert-inline-link-dwim ()
3383 "Insert an inline link of the form [link](url) at point.
3384 If there is an active region, the text in the region will be used
3385 as the URL, if it appears to be a URL, or else as the link text.
3386 If the point is at a URL, use it to create a new link. If the
3387 point is at a reference link, convert it to an inline link. If
3388 the point is at a word, use the word as the link text. In these
3389 cases, the point will be left at the position for inserting a
3390 URL. If there is no active region and the point is not at word,
3391 simply insert link markup and place the point in the position to
3392 enter link text."
3393 (interactive)
3394 (cond
3395 ;; If there is an active region, remove existing links in the
3396 ;; region and use resulting region as link text for a new link.
3397 ((markdown-use-region-p)
3398 (let* ((bounds (markdown-unwrap-things-in-region
3399 (region-beginning) (region-end)
3400 markdown-regex-link-inline 0 3))
3401 (text (buffer-substring (car bounds) (cdr bounds))))
3402 (delete-region (car bounds) (cdr bounds))
3403 (markdown-insert-inline-link text nil)))
3404 ;; If there is an inline link at the point, remove it and add the
3405 ;; link text to the kill ring.
3406 ((thing-at-point-looking-at markdown-regex-link-inline)
3407 (kill-new (match-string 3))
3408 (delete-region (match-beginning 0) (match-end 0)))
3409 ;; If there is an angle URL at the point, use it for a new link.
3410 ((thing-at-point-looking-at markdown-regex-angle-uri)
3411 (let ((url (match-string 2)))
3412 (delete-region (match-beginning 0) (match-end 0))
3413 (markdown-insert-inline-link nil url)))
3414 ;; If there is a plain URL at the point, use it for a new link.
3415 ((thing-at-point-looking-at markdown-regex-uri)
3416 (let ((url (match-string 0)))
3417 (delete-region (match-beginning 0) (match-end 0))
3418 (markdown-insert-inline-link nil url)))
3419 ;; If there is a reference link at point, convert to inline link.
3420 ((thing-at-point-looking-at markdown-regex-link-reference)
3421 (let ((beg (match-beginning 0))
3422 (end (match-end 0))
3423 (text (match-string 3))
3424 (url (markdown-link-link)))
3425 (delete-region beg end)
3426 (markdown-insert-inline-link text url)))
3427 ;; Otherwise, insert a link
3428 (t (let ((bounds (markdown-wrap-or-insert "[" "]()")))
3429 (when bounds
3430 (goto-char (- (cdr bounds) 1)))))))
3432 (defun markdown-insert-reference-link (text label &optional url title)
3433 "Insert a reference link and, optionally, a reference definition.
3434 The link TEXT will be inserted followed by the optional LABEL.
3435 If a URL is given, also insert a definition for the reference
3436 LABEL according to `markdown-reference-location'. If a TITLE is
3437 given, it will be added to the end of the reference definition
3438 and will be used to populate the title attribute when converted
3439 to XHTML. If URL is nil, insert only the link portion (for
3440 example, when a reference label is already defined)."
3441 (insert (concat "[" text "][" label "]"))
3442 (when url
3443 (markdown-insert-reference-definition
3444 (if (string-equal label "") text label)
3445 url title)))
3447 (defun markdown-insert-reference-definition (label &optional url title)
3448 "Add definition for reference LABEL with URL and TITLE.
3449 LABEL is a Markdown reference label without square brackets.
3450 URL and TITLE are optional. When given, the TITLE will
3451 be used to populate the title attribute when converted to XHTML."
3452 ;; END specifies where to leave the point upon return
3453 (let ((end (point)))
3454 (cl-case markdown-reference-location
3455 (end (goto-char (point-max)))
3456 (immediately (markdown-end-of-block))
3457 (header (markdown-end-of-defun)))
3458 (unless (markdown-cur-line-blank-p) (insert "\n"))
3459 (insert "\n[" label "]: ")
3460 (if url
3461 (insert url)
3462 ;; When no URL is given, leave cursor at END following the colon
3463 (setq end (point)))
3464 (when (> (length title) 0)
3465 (insert " \"" title "\""))
3466 (unless (looking-at-p "\n")
3467 (insert "\n"))
3468 (goto-char end)
3469 (when url
3470 (message
3471 (substitute-command-keys
3472 "Defined reference [%s], press \\[markdown-jump] to jump there")
3473 label))))
3475 (defun markdown-insert-reference-link-dwim ()
3476 "Insert a reference link of the form [text][label] at point.
3477 If there is an active region, the text in the region will be used
3478 as the link text. If the point is at an inline link, it will be
3479 converted to a reference link. If the point is at a word, it will
3480 be used as the link text. Otherwise, the link text will be read from
3481 the minibuffer. The link label will be read from the minibuffer in
3482 both cases, with completion from the set of currently defined
3483 references. To create an implicit reference link, press RET to
3484 accept the default, an empty label. If the entered referenced
3485 label is not defined, additionally prompt for the URL
3486 and (optional) title. The reference definition is placed at the
3487 location determined by `markdown-reference-location'."
3488 (interactive)
3489 (let* ((defined-labels (markdown-get-defined-references))
3490 (switch (thing-at-point-looking-at markdown-regex-link-inline))
3491 (bounds (cond ((markdown-use-region-p)
3492 (cons (region-beginning) (region-end)))
3493 (switch
3494 (cons (match-beginning 0) (match-end 0)))
3496 (markdown-bounds-of-thing-at-point 'word))))
3497 (text (cond (switch (match-string 3))
3498 (bounds (buffer-substring (car bounds) (cdr bounds)))
3499 (t (read-string "Link Text: "))))
3500 (label (completing-read
3501 "Link Label (default: none): " defined-labels
3502 nil nil nil 'markdown-reference-label-history nil))
3503 (ref (save-match-data
3504 (markdown-reference-definition
3505 (if (> (length label) 0) label text))))
3506 (url (cond (ref nil)
3507 (switch (match-string 6))
3508 (t (read-string "Link URL: "))))
3509 (title (cond
3510 ((= (length url) 0) nil)
3511 (switch (if (> (length (match-string 7)) 2)
3512 (substring (match-string 7) 1 -1)
3513 nil))
3514 (t (read-string "Link Title (optional): ")))))
3515 (when bounds (delete-region (car bounds) (cdr bounds)))
3516 (markdown-insert-reference-link text label url title)))
3518 (defun markdown-insert-uri ()
3519 "Insert markup for an inline URI.
3520 If there is an active region, use it as the URI. If the point is
3521 at a URI, wrap it with angle brackets. If the point is at an
3522 inline URI, remove the angle brackets. Otherwise, simply insert
3523 angle brackets place the point between them."
3524 (interactive)
3525 (if (markdown-use-region-p)
3526 ;; Active region
3527 (let ((bounds (markdown-unwrap-things-in-region
3528 (region-beginning) (region-end)
3529 markdown-regex-angle-uri 0 2)))
3530 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
3531 ;; Markup removal, URI at point, or empty markup insertion
3532 (if (thing-at-point-looking-at markdown-regex-angle-uri)
3533 (markdown-unwrap-thing-at-point nil 0 2)
3534 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
3536 (defun markdown-insert-wiki-link ()
3537 "Insert a wiki link of the form [[WikiLink]].
3538 If there is an active region, use the region as the link text.
3539 If the point is at a word, use the word as the link text. If
3540 there is no active region and the point is not at word, simply
3541 insert link markup."
3542 (interactive)
3543 (if (markdown-use-region-p)
3544 ;; Active region
3545 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
3546 ;; Markup removal, wiki link at at point, or empty markup insertion
3547 (if (thing-at-point-looking-at markdown-regex-wiki-link)
3548 (if (or markdown-wiki-link-alias-first
3549 (null (match-string 5)))
3550 (markdown-unwrap-thing-at-point nil 1 3)
3551 (markdown-unwrap-thing-at-point nil 1 5))
3552 (markdown-wrap-or-insert "[[" "]]"))))
3554 (defun markdown-insert-image (&optional arg)
3555 "Insert image markup using region or word as alt text if possible.
3556 If there is an active region, use the region as the alt text. If the
3557 point is at a word, use the word as the alt text. In these cases, the
3558 point will be left at the position for inserting a URL. If there is no
3559 active region and the point is not at word, simply insert image markup and
3560 place the point in the position to enter alt text. If ARG is nil, insert
3561 inline image markup. Otherwise, insert reference image markup."
3562 (interactive "*P")
3563 (let ((bounds (if arg
3564 (markdown-wrap-or-insert "![" "][]")
3565 (markdown-wrap-or-insert "![" "]()"))))
3566 (when bounds
3567 (goto-char (- (cdr bounds) 1)))))
3569 (defun markdown-insert-reference-image ()
3570 "Insert reference-style image markup using region or word as alt text.
3571 Calls `markdown-insert-image' with prefix argument."
3572 (interactive)
3573 (markdown-insert-image t))
3575 (defun markdown-remove-header ()
3576 "Remove header markup if point is at a header.
3577 Return bounds of remaining header text if a header was removed
3578 and nil otherwise."
3579 (interactive "*")
3580 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
3581 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
3583 (defun markdown-insert-header (&optional level text setext)
3584 "Insert or replace header markup.
3585 The level of the header is specified by LEVEL and header text is
3586 given by TEXT. LEVEL must be an integer from 1 and 6, and the
3587 default value is 1.
3588 When TEXT is nil, the header text is obtained as follows.
3589 If there is an active region, it is used as the header text.
3590 Otherwise, the current line will be used as the header text.
3591 If there is not an active region and the point is at a header,
3592 remove the header markup and replace with level N header.
3593 Otherwise, insert empty header markup and place the cursor in
3594 between.
3595 The style of the header will be atx (hash marks) unless
3596 SETEXT is non-nil, in which case a setext-style (underlined)
3597 header will be inserted."
3598 (interactive "p\nsHeader text: ")
3599 (setq level (min (max (or level 1) 1) (if setext 2 6)))
3600 ;; Determine header text if not given
3601 (when (null text)
3602 (if (markdown-use-region-p)
3603 ;; Active region
3604 (setq text (delete-and-extract-region (region-beginning) (region-end)))
3605 ;; No active region
3606 (markdown-remove-header)
3607 (setq text (delete-and-extract-region
3608 (line-beginning-position) (line-end-position)))
3609 (when (and setext (string-match-p "^[ \t]*$" text))
3610 (setq text (read-string "Header text: "))))
3611 (setq text (markdown-compress-whitespace-string text)))
3612 ;; Insertion with given text
3613 (markdown-ensure-blank-line-before)
3614 (let (hdr)
3615 (cond (setext
3616 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
3617 (insert text "\n" hdr))
3619 (setq hdr (make-string level ?#))
3620 (insert hdr " " text)
3621 (when (null markdown-asymmetric-header) (insert " " hdr)))))
3622 (markdown-ensure-blank-line-after)
3623 ;; Leave point at end of text
3624 (cond (setext
3625 (backward-char (1+ (string-width text))))
3626 ((null markdown-asymmetric-header)
3627 (backward-char (1+ level)))))
3629 (defun markdown-insert-header-dwim (&optional arg setext)
3630 "Insert or replace header markup.
3631 The level and type of the header are determined automatically by
3632 the type and level of the previous header, unless a prefix
3633 argument is given via ARG.
3634 With a numeric prefix valued 1 to 6, insert a header of the given
3635 level, with the type being determined automatically (note that
3636 only level 1 or 2 setext headers are possible).
3638 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
3639 promote the heading by one level.
3640 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
3641 demote the heading by one level.
3642 When SETEXT is non-nil, prefer setext-style headers when
3643 possible (levels one and two).
3645 When there is an active region, use it for the header text. When
3646 the point is at an existing header, change the type and level
3647 according to the rules above.
3648 Otherwise, if the line is not empty, create a header using the
3649 text on the current line as the header text.
3650 Finally, if the point is on a blank line, insert empty header
3651 markup (atx) or prompt for text (setext).
3652 See `markdown-insert-header' for more details about how the
3653 header text is determined."
3654 (interactive "*P")
3655 (let (level)
3656 (save-excursion
3657 (when (or (thing-at-point-looking-at markdown-regex-header)
3658 (re-search-backward markdown-regex-header nil t))
3659 ;; level of current or previous header
3660 (setq level (markdown-outline-level))
3661 ;; match group 1 indicates a setext header
3662 (setq setext (match-end 1))))
3663 ;; check prefix argument
3664 (cond
3665 ((and (equal arg '(4)) level (> level 1)) ;; C-u
3666 (cl-decf level))
3667 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
3668 (cl-incf level))
3669 (arg ;; numeric prefix
3670 (setq level (prefix-numeric-value arg))))
3671 ;; setext headers must be level one or two
3672 (and level (setq setext (and setext (<= level 2))))
3673 ;; insert the heading
3674 (markdown-insert-header level nil setext)))
3676 (defun markdown-insert-header-setext-dwim (&optional arg)
3677 "Insert or replace header markup, with preference for setext.
3678 See `markdown-insert-header-dwim' for details, including how ARG is handled."
3679 (interactive "*P")
3680 (markdown-insert-header-dwim arg t))
3682 (defun markdown-insert-header-atx-1 ()
3683 "Insert a first level atx-style (hash mark) header.
3684 See `markdown-insert-header'."
3685 (interactive "*")
3686 (markdown-insert-header 1 nil nil))
3688 (defun markdown-insert-header-atx-2 ()
3689 "Insert a level two atx-style (hash mark) header.
3690 See `markdown-insert-header'."
3691 (interactive "*")
3692 (markdown-insert-header 2 nil nil))
3694 (defun markdown-insert-header-atx-3 ()
3695 "Insert a level three atx-style (hash mark) header.
3696 See `markdown-insert-header'."
3697 (interactive "*")
3698 (markdown-insert-header 3 nil nil))
3700 (defun markdown-insert-header-atx-4 ()
3701 "Insert a level four atx-style (hash mark) header.
3702 See `markdown-insert-header'."
3703 (interactive "*")
3704 (markdown-insert-header 4 nil nil))
3706 (defun markdown-insert-header-atx-5 ()
3707 "Insert a level five atx-style (hash mark) header.
3708 See `markdown-insert-header'."
3709 (interactive "*")
3710 (markdown-insert-header 5 nil nil))
3712 (defun markdown-insert-header-atx-6 ()
3713 "Insert a sixth level atx-style (hash mark) header.
3714 See `markdown-insert-header'."
3715 (interactive "*")
3716 (markdown-insert-header 6 nil nil))
3718 (defun markdown-insert-header-setext-1 ()
3719 "Insert a setext-style (underlined) first-level header.
3720 See `markdown-insert-header'."
3721 (interactive "*")
3722 (markdown-insert-header 1 nil t))
3724 (defun markdown-insert-header-setext-2 ()
3725 "Insert a setext-style (underlined) second-level header.
3726 See `markdown-insert-header'."
3727 (interactive "*")
3728 (markdown-insert-header 2 nil t))
3730 (defun markdown-blockquote-indentation (loc)
3731 "Return string containing necessary indentation for a blockquote at LOC.
3732 Also see `markdown-pre-indentation'."
3733 (save-excursion
3734 (goto-char loc)
3735 (let* ((list-level (length (markdown-calculate-list-levels)))
3736 (indent ""))
3737 (dotimes (_ list-level indent)
3738 (setq indent (concat indent " "))))))
3740 (defun markdown-insert-blockquote ()
3741 "Start a blockquote section (or blockquote the region).
3742 If Transient Mark mode is on and a region is active, it is used as
3743 the blockquote text."
3744 (interactive)
3745 (if (markdown-use-region-p)
3746 (markdown-blockquote-region (region-beginning) (region-end))
3747 (markdown-ensure-blank-line-before)
3748 (insert (markdown-blockquote-indentation (point)) "> ")
3749 (markdown-ensure-blank-line-after)))
3751 (defun markdown-block-region (beg end prefix)
3752 "Format the region using a block prefix.
3753 Arguments BEG and END specify the beginning and end of the
3754 region. The characters PREFIX will appear at the beginning
3755 of each line."
3756 (save-excursion
3757 (let* ((end-marker (make-marker))
3758 (beg-marker (make-marker)))
3759 ;; Ensure blank line after and remove extra whitespace
3760 (goto-char end)
3761 (skip-syntax-backward "-")
3762 (set-marker end-marker (point))
3763 (delete-horizontal-space)
3764 (markdown-ensure-blank-line-after)
3765 ;; Ensure blank line before and remove extra whitespace
3766 (goto-char beg)
3767 (skip-syntax-forward "-")
3768 (delete-horizontal-space)
3769 (markdown-ensure-blank-line-before)
3770 (set-marker beg-marker (point))
3771 ;; Insert PREFIX before each line
3772 (goto-char beg-marker)
3773 (while (and (< (line-beginning-position) end-marker)
3774 (not (eobp)))
3775 (insert prefix)
3776 (forward-line)))))
3778 (defun markdown-blockquote-region (beg end)
3779 "Blockquote the region.
3780 Arguments BEG and END specify the beginning and end of the region."
3781 (interactive "*r")
3782 (markdown-block-region
3783 beg end (concat (markdown-blockquote-indentation
3784 (max (point-min) (1- beg))) "> ")))
3786 (defun markdown-pre-indentation (loc)
3787 "Return string containing necessary whitespace for a pre block at LOC.
3788 Also see `markdown-blockquote-indentation'."
3789 (save-excursion
3790 (goto-char loc)
3791 (let* ((list-level (length (markdown-calculate-list-levels)))
3792 indent)
3793 (dotimes (_ (1+ list-level) indent)
3794 (setq indent (concat indent " "))))))
3796 (defun markdown-insert-pre ()
3797 "Start a preformatted section (or apply to the region).
3798 If Transient Mark mode is on and a region is active, it is marked
3799 as preformatted text."
3800 (interactive)
3801 (if (markdown-use-region-p)
3802 (markdown-pre-region (region-beginning) (region-end))
3803 (markdown-ensure-blank-line-before)
3804 (insert (markdown-pre-indentation (point)))
3805 (markdown-ensure-blank-line-after)))
3807 (defun markdown-pre-region (beg end)
3808 "Format the region as preformatted text.
3809 Arguments BEG and END specify the beginning and end of the region."
3810 (interactive "*r")
3811 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
3812 (markdown-block-region beg end indent)))
3814 (defun markdown-electric-backquote (arg)
3815 "Insert a backquote.
3816 The numeric prefix argument ARG says how many times to repeat the insertion.
3817 Call `markdown-insert-gfm-code-block' interactively
3818 if three backquotes inserted at the beginning of line."
3819 (interactive "*P")
3820 (self-insert-command (prefix-numeric-value arg))
3821 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
3822 (replace-match "")
3823 (call-interactively #'markdown-insert-gfm-code-block)))
3825 (defconst markdown-gfm-recognized-languages
3826 ;; to reproduce/update, evaluate the let-form in
3827 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
3828 ;; but with appropriate use of a keyboard macro, indenting and filling it
3829 ;; properly is pretty fast.
3830 '("ABAP" "AGS-Script" "AMPL" "ANTLR" "API-Blueprint" "APL" "ASP" "ATS"
3831 "ActionScript" "Ada" "Agda" "Alloy" "Ant-Build-System" "ApacheConf" "Apex"
3832 "AppleScript" "Arc" "Arduino" "AsciiDoc" "AspectJ" "Assembly" "Augeas"
3833 "AutoHotkey" "AutoIt" "Awk" "Batchfile" "Befunge" "Bison" "BitBake"
3834 "BlitzBasic" "BlitzMax" "Bluespec" "Boo" "Brainfuck" "Brightscript" "Bro" "C#"
3835 "C++" "C-ObjDump" "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "CSS" "Cap'n-Proto"
3836 "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK" "Cirru" "Clarion" "Clean"
3837 "Click" "Clojure" "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
3838 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal" "Cucumber"
3839 "Cuda" "Cycript" "Cython" "D-ObjDump" "DIGITAL-Command-Language" "DM"
3840 "DNS-Zone" "DTrace" "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript"
3841 "Dylan" "ECL" "ECLiPSe" "Eagle" "Ecere-Projects" "Eiffel" "Elixir" "Elm"
3842 "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "FORTRAN" "Factor" "Fancy"
3843 "Fantom" "Filterscript" "Formatted" "Forth" "FreeMarker" "Frege" "G-code"
3844 "GAMS" "GAP" "GAS" "GDScript" "GLSL" "Game-Maker-Language" "Genshi"
3845 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Glyph" "Gnuplot" "Go"
3846 "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
3847 "Graph-Modeling-Language" "Graphviz-(DOT)" "Groff" "Groovy"
3848 "Groovy-Server-Pages" "HCL" "HTML" "HTML+Django" "HTML+EEX" "HTML+ERB"
3849 "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars" "Harbour" "Haskell" "Haxe" "Hy"
3850 "HyPhy" "IDL" "IGOR-Pro" "INI" "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io"
3851 "Ioke" "Isabelle" "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq"
3852 "JSX" "Jade" "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Julia"
3853 "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE" "LLVM" "LOLCODE" "LSL"
3854 "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex" "LilyPond" "Limbo"
3855 "Linker-Script" "Linux-Kernel-Module" "Liquid" "Literate-Agda"
3856 "Literate-CoffeeScript" "Literate-Haskell" "LiveScript" "Logos" "Logtalk"
3857 "LookML" "LoomScript" "Lua" "MAXScript" "MTML" "MUF" "Makefile" "Mako"
3858 "Markdown" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max" "MediaWiki"
3859 "Mercury" "Metal" "MiniD" "Mirah" "Modelica" "Modula-2"
3860 "Module-Management-System" "Monkey" "Moocode" "MoonScript" "Myghty" "NCL" "NL"
3861 "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo" "NewLisp" "Nginx" "Nimrod"
3862 "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml" "ObjDump" "Objective-C"
3863 "Objective-C++" "Objective-J" "Omgrofl" "Opa" "Opal" "OpenCL" "OpenEdge-ABL"
3864 "OpenSCAD" "Org" "Ox" "Oxygene" "Oz" "PAWN" "PHP" "PLSQL" "PLpgSQL" "Pan"
3865 "Papyrus" "Parrot" "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal"
3866 "Perl" "Perl6" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod" "PogoScript" "Pony"
3867 "PostScript" "PowerShell" "Processing" "Prolog" "Propeller-Spin"
3868 "Protocol-Buffer" "Public-Key" "Puppet" "Pure-Data" "PureBasic" "PureScript"
3869 "Python" "Python-traceback" "QML" "QMake" "RAML" "RDoc" "REALbasic" "RHTML"
3870 "RMarkdown" "Racket" "Ragel-in-Ruby-Host" "Raw-token-data" "Rebol" "Red"
3871 "Redcode" "Ren'Py" "RenderScript" "RobotFramework" "Rouge" "Ruby" "Rust" "SAS"
3872 "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL" "STON" "SVG" "Sage" "SaltStack"
3873 "Sass" "Scala" "Scaml" "Scheme" "Scilab" "Self" "Shell" "ShellSession" "Shen"
3874 "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn" "Squirrel" "Stan"
3875 "Standard-ML" "Stata" "Stylus" "SuperCollider" "Swift" "SystemVerilog" "TOML"
3876 "TXL" "Tcl" "Tcsh" "TeX" "Tea" "Text" "Textile" "Thrift" "Turing" "Turtle"
3877 "Twig" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset" "UnrealScript"
3878 "UrWeb" "VCL" "VHDL" "Vala" "Verilog" "VimL" "Visual-Basic" "Volt" "Vue"
3879 "Web-Ontology-Language" "WebIDL" "X10" "XC" "XML" "XPages" "XProc" "XQuery"
3880 "XS" "XSLT" "Xojo" "Xtend" "YAML" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn"
3881 "fish" "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
3882 "Language specifiers recognized by GitHub's syntax highlighting features.")
3884 (defvar markdown-gfm-used-languages nil
3885 "Language names used in GFM code blocks.")
3886 (make-variable-buffer-local 'markdown-gfm-used-languages)
3888 (defun markdown-trim-whitespace (str)
3889 (markdown-replace-regexp-in-string
3890 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
3892 (defun markdown-clean-language-string (str)
3893 (markdown-replace-regexp-in-string
3894 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
3896 (defun markdown-validate-language-string (widget)
3897 (let ((str (widget-value widget)))
3898 (unless (string= str (markdown-clean-language-string str))
3899 (widget-put widget :error (format "Invalid language spec: '%s'" str))
3900 widget)))
3902 (defun markdown-gfm-get-corpus ()
3903 "Create corpus of recognized GFM code block languages for the given buffer."
3904 (let ((given-corpus (append markdown-gfm-additional-languages
3905 markdown-gfm-recognized-languages)))
3906 (append
3907 markdown-gfm-used-languages
3908 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
3909 given-corpus))))
3911 (defun markdown-gfm-add-used-language (lang)
3912 "Clean LANG and add to list of used languages."
3913 (setq markdown-gfm-used-languages
3914 (cons lang (remove lang markdown-gfm-used-languages))))
3916 (defun markdown-insert-gfm-code-block (&optional lang)
3917 "Insert GFM code block for language LANG.
3918 If LANG is nil, the language will be queried from user. If a
3919 region is active, wrap this region with the markup instead. If
3920 the region boundaries are not on empty lines, these are added
3921 automatically in order to have the correct markup."
3922 (interactive
3923 (list (let ((completion-ignore-case nil))
3924 (condition-case nil
3925 (markdown-clean-language-string
3926 (completing-read
3927 "Programming language: "
3928 (markdown-gfm-get-corpus)
3929 nil 'confirm (car markdown-gfm-used-languages)
3930 'markdown-gfm-language-history))
3931 (quit "")))))
3932 (unless (string= lang "") (markdown-gfm-add-used-language lang))
3933 (when (> (length lang) 0) (setq lang (concat " " lang)))
3934 (if (markdown-use-region-p)
3935 (let ((b (region-beginning)) (e (region-end)))
3936 (goto-char e)
3937 ;; if we're on a blank line, don't newline, otherwise the ```
3938 ;; should go on its own line
3939 (unless (looking-back "\n" nil)
3940 (newline))
3941 (insert "```")
3942 (markdown-ensure-blank-line-after)
3943 (goto-char b)
3944 ;; if we're on a blank line, insert the quotes here, otherwise
3945 ;; add a new line first
3946 (unless (looking-at-p "\n")
3947 (newline)
3948 (forward-line -1))
3949 (markdown-ensure-blank-line-before)
3950 (insert "```" lang))
3951 (markdown-ensure-blank-line-before)
3952 (insert "```" lang "\n\n```")
3953 (markdown-ensure-blank-line-after)
3954 (forward-line -1)))
3956 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
3957 (with-current-buffer (or buffer (current-buffer))
3958 (save-excursion
3959 (goto-char (point-min))
3960 (cl-loop
3961 with prop = 'markdown-gfm-block-begin
3962 for pos-prop = (markdown-find-next-prop prop)
3963 while pos-prop
3964 for lang = (progn
3965 (goto-char (car pos-prop))
3966 (save-match-data
3967 (set-match-data (get-text-property (point) prop))
3968 ;; Note: Hard-coded group number assumes tilde
3969 ;; and GFM fenced code regexp groups agree.
3970 (when (and (match-beginning 3) (match-end 3))
3971 (buffer-substring-no-properties
3972 (match-beginning 3) (match-end 3)))))
3973 do (progn (when lang (markdown-gfm-add-used-language lang))
3974 (goto-char (next-single-property-change (point) prop)))))))
3977 ;;; Footnotes ==================================================================
3979 (defun markdown-footnote-counter-inc ()
3980 "Increment `markdown-footnote-counter' and return the new value."
3981 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
3982 (save-excursion
3983 (goto-char (point-min))
3984 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
3985 (point-max) t)
3986 (let ((fn (string-to-number (match-string 1))))
3987 (when (> fn markdown-footnote-counter)
3988 (setq markdown-footnote-counter fn))))))
3989 (cl-incf markdown-footnote-counter))
3991 (defun markdown-insert-footnote ()
3992 "Insert footnote with a new number and move point to footnote definition."
3993 (interactive)
3994 (let ((fn (markdown-footnote-counter-inc)))
3995 (insert (format "[^%d]" fn))
3996 (markdown-footnote-text-find-new-location)
3997 (markdown-ensure-blank-line-before)
3998 (unless (markdown-cur-line-blank-p)
3999 (insert "\n"))
4000 (insert (format "[^%d]: " fn))
4001 (markdown-ensure-blank-line-after)))
4003 (defun markdown-footnote-text-find-new-location ()
4004 "Position the cursor at the proper location for a new footnote text."
4005 (cond
4006 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
4007 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
4008 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
4010 (defun markdown-footnote-kill ()
4011 "Kill the footnote at point.
4012 The footnote text is killed (and added to the kill ring), the
4013 footnote marker is deleted. Point has to be either at the
4014 footnote marker or in the footnote text."
4015 (interactive)
4016 (let ((marker-pos nil)
4017 (skip-deleting-marker nil)
4018 (starting-footnote-text-positions
4019 (markdown-footnote-text-positions)))
4020 (when starting-footnote-text-positions
4021 ;; We're starting in footnote text, so mark our return position and jump
4022 ;; to the marker if possible.
4023 (let ((marker-pos (markdown-footnote-find-marker
4024 (cl-first starting-footnote-text-positions))))
4025 (if marker-pos
4026 (goto-char (1- marker-pos))
4027 ;; If there isn't a marker, we still want to kill the text.
4028 (setq skip-deleting-marker t))))
4029 ;; Either we didn't start in the text, or we started in the text and jumped
4030 ;; to the marker. We want to assume we're at the marker now and error if
4031 ;; we're not.
4032 (unless skip-deleting-marker
4033 (let ((marker (markdown-footnote-delete-marker)))
4034 (unless marker
4035 (error "Not at a footnote"))
4036 ;; Even if we knew the text position before, it changed when we deleted
4037 ;; the label.
4038 (setq marker-pos (cl-second marker))
4039 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
4040 (unless new-text-pos
4041 (error "No text for footnote `%s'" (cl-first marker)))
4042 (goto-char new-text-pos))))
4043 (let ((pos (markdown-footnote-kill-text)))
4044 (goto-char (if starting-footnote-text-positions
4046 marker-pos)))))
4048 (defun markdown-footnote-delete-marker ()
4049 "Delete a footnote marker at point.
4050 Returns a list (ID START) containing the footnote ID and the
4051 start position of the marker before deletion. If no footnote
4052 marker was deleted, this function returns NIL."
4053 (let ((marker (markdown-footnote-marker-positions)))
4054 (when marker
4055 (delete-region (cl-second marker) (cl-third marker))
4056 (butlast marker))))
4058 (defun markdown-footnote-kill-text ()
4059 "Kill footnote text at point.
4060 Returns the start position of the footnote text before deletion,
4061 or NIL if point was not inside a footnote text.
4063 The killed text is placed in the kill ring (without the footnote
4064 number)."
4065 (let ((fn (markdown-footnote-text-positions)))
4066 (when fn
4067 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
4068 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
4069 (kill-new (match-string 1 text))
4070 (when (and (markdown-cur-line-blank-p)
4071 (markdown-prev-line-blank-p)
4072 (not (bobp)))
4073 (delete-region (1- (point)) (point)))
4074 (cl-second fn)))))
4076 (defun markdown-footnote-goto-text ()
4077 "Jump to the text of the footnote at point."
4078 (interactive)
4079 (let ((fn (car (markdown-footnote-marker-positions))))
4080 (unless fn
4081 (error "Not at a footnote marker"))
4082 (let ((new-pos (markdown-footnote-find-text fn)))
4083 (unless new-pos
4084 (error "No definition found for footnote `%s'" fn))
4085 (goto-char new-pos))))
4087 (defun markdown-footnote-return ()
4088 "Return from a footnote to its footnote number in the main text."
4089 (interactive)
4090 (let ((fn (save-excursion
4091 (car (markdown-footnote-text-positions)))))
4092 (unless fn
4093 (error "Not in a footnote"))
4094 (let ((new-pos (markdown-footnote-find-marker fn)))
4095 (unless new-pos
4096 (error "Footnote marker `%s' not found" fn))
4097 (goto-char new-pos))))
4099 (defun markdown-footnote-find-marker (id)
4100 "Find the location of the footnote marker with ID.
4101 The actual buffer position returned is the position directly
4102 following the marker's closing bracket. If no marker is found,
4103 NIL is returned."
4104 (save-excursion
4105 (goto-char (point-min))
4106 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
4107 (skip-chars-backward "^]")
4108 (point))))
4110 (defun markdown-footnote-find-text (id)
4111 "Find the location of the text of footnote ID.
4112 The actual buffer position returned is the position of the first
4113 character of the text, after the footnote's identifier. If no
4114 footnote text is found, NIL is returned."
4115 (save-excursion
4116 (goto-char (point-min))
4117 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
4118 (skip-chars-forward "[ \t]")
4119 (point))))
4121 (defun markdown-footnote-marker-positions ()
4122 "Return the position and ID of the footnote marker point is on.
4123 The return value is a list (ID START END). If point is not on a
4124 footnote, NIL is returned."
4125 ;; first make sure we're at a footnote marker
4126 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
4127 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
4128 (save-excursion
4129 ;; move point between [ and ^:
4130 (if (looking-at-p "\\[")
4131 (forward-char 1)
4132 (skip-chars-backward "^["))
4133 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
4134 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
4136 (defun markdown-footnote-text-positions ()
4137 "Return the start and end positions of the footnote text point is in.
4138 The exact return value is a list of three elements: (ID START END).
4139 The start position is the position of the opening bracket
4140 of the footnote id. The end position is directly after the
4141 newline that ends the footnote. If point is not in a footnote,
4142 NIL is returned instead."
4143 (save-excursion
4144 (let (result)
4145 (move-beginning-of-line 1)
4146 ;; Try to find the label. If we haven't found the label and we're at a blank
4147 ;; or indented line, back up if possible.
4148 (while (and
4149 (not (and (looking-at markdown-regex-footnote-definition)
4150 (setq result (list (match-string 1) (point)))))
4151 (and (not (bobp))
4152 (or (markdown-cur-line-blank-p)
4153 (>= (current-indentation) 4))))
4154 (forward-line -1))
4155 (when result
4156 ;; Advance if there is a next line that is either blank or indented.
4157 ;; (Need to check if we're on the last line, because
4158 ;; markdown-next-line-blank-p returns true for last line in buffer.)
4159 (while (and (/= (line-end-position) (point-max))
4160 (or (markdown-next-line-blank-p)
4161 (>= (markdown-next-line-indent) 4)))
4162 (forward-line))
4163 ;; Move back while the current line is blank.
4164 (while (markdown-cur-line-blank-p)
4165 (forward-line -1))
4166 ;; Advance to capture this line and a single trailing newline (if there
4167 ;; is one).
4168 (forward-line)
4169 (append result (list (point)))))))
4172 ;;; Element Removal ===========================================================
4174 (defun markdown-kill-thing-at-point ()
4175 "Kill thing at point and add important text, without markup, to kill ring.
4176 Possible things to kill include (roughly in order of precedence):
4177 inline code, headers, horizonal rules, links (add link text to
4178 kill ring), images (add alt text to kill ring), angle uri, email
4179 addresses, bold, italics, reference definition (add URI to kill
4180 ring), footnote markers and text (kill both marker and text, add
4181 text to kill ring), and list items."
4182 (interactive "*")
4183 (let (val)
4184 (cond
4185 ;; Inline code
4186 ((markdown-inline-code-at-point)
4187 (kill-new (match-string 2))
4188 (delete-region (match-beginning 0) (match-end 0)))
4189 ;; ATX header
4190 ((thing-at-point-looking-at markdown-regex-header-atx)
4191 (kill-new (match-string 2))
4192 (delete-region (match-beginning 0) (match-end 0)))
4193 ;; Setext header
4194 ((thing-at-point-looking-at markdown-regex-header-setext)
4195 (kill-new (match-string 1))
4196 (delete-region (match-beginning 0) (match-end 0)))
4197 ;; Horizonal rule
4198 ((thing-at-point-looking-at markdown-regex-hr)
4199 (kill-new (match-string 0))
4200 (delete-region (match-beginning 0) (match-end 0)))
4201 ;; Inline link or image (add link or alt text to kill ring)
4202 ((thing-at-point-looking-at markdown-regex-link-inline)
4203 (kill-new (match-string 3))
4204 (delete-region (match-beginning 0) (match-end 0)))
4205 ;; Reference link or image (add link or alt text to kill ring)
4206 ((thing-at-point-looking-at markdown-regex-link-reference)
4207 (kill-new (match-string 3))
4208 (delete-region (match-beginning 0) (match-end 0)))
4209 ;; Angle URI (add URL to kill ring)
4210 ((thing-at-point-looking-at markdown-regex-angle-uri)
4211 (kill-new (match-string 2))
4212 (delete-region (match-beginning 0) (match-end 0)))
4213 ;; Email address in angle brackets (add email address to kill ring)
4214 ((thing-at-point-looking-at markdown-regex-email)
4215 (kill-new (match-string 1))
4216 (delete-region (match-beginning 0) (match-end 0)))
4217 ;; Wiki link (add alias text to kill ring)
4218 ((and markdown-enable-wiki-links
4219 (thing-at-point-looking-at markdown-regex-wiki-link))
4220 (kill-new (markdown-wiki-link-alias))
4221 (delete-region (match-beginning 1) (match-end 1)))
4222 ;; Bold
4223 ((thing-at-point-looking-at markdown-regex-bold)
4224 (kill-new (match-string 4))
4225 (delete-region (match-beginning 2) (match-end 2)))
4226 ;; Italics
4227 ((thing-at-point-looking-at markdown-regex-italic)
4228 (kill-new (match-string 3))
4229 (delete-region (match-beginning 1) (match-end 1)))
4230 ;; Strikethrough
4231 ((thing-at-point-looking-at markdown-regex-strike-through)
4232 (kill-new (match-string 4))
4233 (delete-region (match-beginning 2) (match-end 2)))
4234 ;; Footnote marker (add footnote text to kill ring)
4235 ((thing-at-point-looking-at markdown-regex-footnote)
4236 (markdown-footnote-kill))
4237 ;; Footnote text (add footnote text to kill ring)
4238 ((setq val (markdown-footnote-text-positions))
4239 (markdown-footnote-kill))
4240 ;; Reference definition (add URL to kill ring)
4241 ((thing-at-point-looking-at markdown-regex-reference-definition)
4242 (kill-new (match-string 5))
4243 (delete-region (match-beginning 0) (match-end 0)))
4244 ;; List item
4245 ((setq val (markdown-cur-list-item-bounds))
4246 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
4248 (error "Nothing found at point to kill")))))
4251 ;;; Indentation ====================================================================
4253 (defun markdown-indent-find-next-position (cur-pos positions)
4254 "Return the position after the index of CUR-POS in POSITIONS.
4255 Positions are calculated by `markdown-calc-indents'."
4256 (while (and positions
4257 (not (equal cur-pos (car positions))))
4258 (setq positions (cdr positions)))
4259 (or (cadr positions) 0))
4261 (defun markdown-exdent-find-next-position (cur-pos positions)
4262 "Return the maximal element that precedes CUR-POS from POSITIONS.
4263 Positions are calculated by `markdown-calc-indents'."
4264 (let ((result 0))
4265 (dolist (i positions)
4266 (when (< i cur-pos)
4267 (setq result (max result i))))
4268 result))
4270 (defun markdown-indent-line ()
4271 "Indent the current line using some heuristics.
4272 If the _previous_ command was either `markdown-enter-key' or
4273 `markdown-cycle', then we should cycle to the next
4274 reasonable indentation position. Otherwise, we could have been
4275 called directly by `markdown-enter-key', by an initial call of
4276 `markdown-cycle', or indirectly by `auto-fill-mode'. In
4277 these cases, indent to the default position.
4278 Positions are calculated by `markdown-calc-indents'."
4279 (interactive)
4280 (let ((positions (markdown-calc-indents))
4281 (cursor-pos (current-column))
4282 (_ (back-to-indentation))
4283 (cur-pos (current-column)))
4284 (if (not (equal this-command 'markdown-cycle))
4285 (indent-line-to (car positions))
4286 (setq positions (sort (delete-dups positions) '<))
4287 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
4288 (new-cursor-pos
4289 (if (< cur-pos next-pos)
4290 (+ cursor-pos (- next-pos cur-pos))
4291 (- cursor-pos cur-pos))))
4292 (indent-line-to next-pos)
4293 (move-to-column new-cursor-pos)))))
4295 (defun markdown-calc-indents ()
4296 "Return a list of indentation columns to cycle through.
4297 The first element in the returned list should be considered the
4298 default indentation level. This function does not worry about
4299 duplicate positions, which are handled up by calling functions."
4300 (let (pos prev-line-pos positions)
4302 ;; Indentation of previous line
4303 (setq prev-line-pos (markdown-prev-line-indent))
4304 (setq positions (cons prev-line-pos positions))
4306 ;; Indentation of previous non-list-marker text
4307 (when (setq pos (markdown-prev-non-list-indent))
4308 (setq positions (cons pos positions)))
4310 ;; Indentation required for a pre block in current context
4311 (setq pos (length (markdown-pre-indentation (point))))
4312 (setq positions (cons pos positions))
4314 ;; Indentation of the previous line + tab-width
4315 (if prev-line-pos
4316 (setq positions (cons (+ prev-line-pos tab-width) positions))
4317 (setq positions (cons tab-width positions)))
4319 ;; Indentation of the previous line - tab-width
4320 (if (and prev-line-pos (> prev-line-pos tab-width))
4321 (setq positions (cons (- prev-line-pos tab-width) positions)))
4323 ;; Indentation of all preceeding list markers (when in a list)
4324 (when (setq pos (markdown-calculate-list-levels))
4325 (setq positions (append pos positions)))
4327 ;; First column
4328 (setq positions (cons 0 positions))
4330 ;; Return reversed list
4331 (reverse positions)))
4333 (defun markdown-enter-key ()
4334 "Handle RET according to customized settings.
4335 When `markdown-indent-on-enter' is nil, this is equivalent to
4336 `newline'. Otherwise, indent following RET and when the point is
4337 in a list item, start a new item with the same indentation. If
4338 the point is in an empty list item, remove it."
4339 (interactive)
4340 (if (not markdown-indent-on-enter)
4341 (newline)
4342 (let ((bounds (markdown-cur-list-item-bounds)))
4343 (if bounds
4344 (let ((beg (cl-first bounds))
4345 (end (cl-second bounds))
4346 (length (cl-fourth bounds)))
4347 ;; Point is in a list item
4348 (if (= (- end beg) length)
4349 ;; Delete blank list
4350 (progn
4351 (delete-region beg end)
4352 (newline)
4353 (markdown-indent-line))
4354 (call-interactively #'markdown-insert-list-item)))
4355 ;; Point is not in a list
4356 (newline)
4357 (markdown-indent-line)))))
4359 (defun markdown-exdent-or-delete (arg)
4360 "Handle BACKSPACE by cycling through indentation points.
4361 When BACKSPACE is pressed, if there is only whitespace
4362 before the current point, then exdent the line one level.
4363 Otherwise, do normal delete by repeating
4364 `backward-delete-char-untabify' ARG times."
4365 (interactive "*p")
4366 (if (use-region-p)
4367 (backward-delete-char-untabify arg)
4368 (let ((cur-pos (current-column))
4369 (start-of-indention (save-excursion
4370 (back-to-indentation)
4371 (current-column)))
4372 (positions (markdown-calc-indents)))
4373 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
4374 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
4375 (backward-delete-char-untabify arg)))))
4377 (defun markdown-find-leftmost-column (beg end)
4378 "Find the leftmost column in the region from BEG to END."
4379 (let ((mincol 1000))
4380 (save-excursion
4381 (goto-char beg)
4382 (while (< (point) end)
4383 (back-to-indentation)
4384 (unless (looking-at-p "[ \t]*$")
4385 (setq mincol (min mincol (current-column))))
4386 (forward-line 1)
4388 mincol))
4390 (defun markdown-indent-region (beg end arg)
4391 "Indent the region from BEG to END using some heuristics.
4392 When ARG is non-nil, exdent the region instead.
4393 See `markdown-indent-line' and `markdown-indent-line'."
4394 (interactive "*r\nP")
4395 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
4396 (leftmostcol (markdown-find-leftmost-column beg end))
4397 (next-pos (if arg
4398 (markdown-exdent-find-next-position leftmostcol positions)
4399 (markdown-indent-find-next-position leftmostcol positions))))
4400 (indent-rigidly beg end (- next-pos leftmostcol))
4401 (setq deactivate-mark nil)))
4403 (defun markdown-exdent-region (beg end)
4404 "Call `markdown-indent-region' on region from BEG to END with prefix."
4405 (interactive "*r")
4406 (markdown-indent-region beg end t))
4409 ;;; Markup Completion =========================================================
4411 (defconst markdown-complete-alist
4412 '((markdown-regex-header-atx . markdown-complete-atx)
4413 (markdown-regex-header-setext . markdown-complete-setext)
4414 (markdown-regex-hr . markdown-complete-hr))
4415 "Association list of form (regexp . function) for markup completion.")
4417 (defun markdown-incomplete-atx-p ()
4418 "Return t if ATX header markup is incomplete and nil otherwise.
4419 Assumes match data is available for `markdown-regex-header-atx'.
4420 Checks that the number of trailing hash marks equals the number of leading
4421 hash marks, that there is only a single space before and after the text,
4422 and that there is no extraneous whitespace in the text."
4424 ;; Number of starting and ending hash marks differs
4425 (not (= (length (match-string 1)) (length (match-string 3))))
4426 ;; When the header text is not empty...
4427 (and (> (length (match-string 2)) 0)
4428 ;; ...if there are extra leading, trailing, or interior spaces
4429 (or (not (= (match-beginning 2) (1+ (match-end 1))))
4430 (not (= (match-beginning 3) (1+ (match-end 2))))
4431 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
4432 ;; When the header text is empty...
4433 (and (= (length (match-string 2)) 0)
4434 ;; ...if there are too many or too few spaces
4435 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
4437 (defun markdown-complete-atx ()
4438 "Complete and normalize ATX headers.
4439 Add or remove hash marks to the end of the header to match the
4440 beginning. Ensure that there is only a single space between hash
4441 marks and header text. Removes extraneous whitespace from header text.
4442 Assumes match data is available for `markdown-regex-header-atx'.
4443 Return nil if markup was complete and non-nil if markup was completed."
4444 (when (markdown-incomplete-atx-p)
4445 (let* ((new-marker (make-marker))
4446 (new-marker (set-marker new-marker (match-end 2))))
4447 ;; Hash marks and spacing at end
4448 (goto-char (match-end 2))
4449 (delete-region (match-end 2) (match-end 3))
4450 (insert " " (match-string 1))
4451 ;; Remove extraneous whitespace from title
4452 (replace-match (markdown-compress-whitespace-string (match-string 2))
4453 t t nil 2)
4454 ;; Spacing at beginning
4455 (goto-char (match-end 1))
4456 (delete-region (match-end 1) (match-beginning 2))
4457 (insert " ")
4458 ;; Leave point at end of text
4459 (goto-char new-marker))))
4461 (defun markdown-incomplete-setext-p ()
4462 "Return t if setext header markup is incomplete and nil otherwise.
4463 Assumes match data is available for `markdown-regex-header-setext'.
4464 Checks that length of underline matches text and that there is no
4465 extraneous whitespace in the text."
4466 (or (not (= (length (match-string 1)) (length (match-string 2))))
4467 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
4469 (defun markdown-complete-setext ()
4470 "Complete and normalize setext headers.
4471 Add or remove underline characters to match length of header
4472 text. Removes extraneous whitespace from header text. Assumes
4473 match data is available for `markdown-regex-header-setext'.
4474 Return nil if markup was complete and non-nil if markup was completed."
4475 (when (markdown-incomplete-setext-p)
4476 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
4477 (char (char-after (match-beginning 2)))
4478 (level (if (char-equal char ?-) 2 1)))
4479 (goto-char (match-beginning 0))
4480 (delete-region (match-beginning 0) (match-end 0))
4481 (markdown-insert-header level text t)
4482 t)))
4484 (defun markdown-incomplete-hr-p ()
4485 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
4486 Assumes match data is available for `markdown-regex-hr'."
4487 (not (member (match-string 0) markdown-hr-strings)))
4489 (defun markdown-complete-hr ()
4490 "Complete horizontal rules.
4491 If horizontal rule string is a member of `markdown-hr-strings',
4492 do nothing. Otherwise, replace with the car of
4493 `markdown-hr-strings'.
4494 Assumes match data is available for `markdown-regex-hr'.
4495 Return nil if markup was complete and non-nil if markup was completed."
4496 (when (markdown-incomplete-hr-p)
4497 (replace-match (car markdown-hr-strings))
4500 (defun markdown-complete ()
4501 "Complete markup of object near point or in region when active.
4502 Handle all objects in `markdown-complete-alist', in order.
4503 See `markdown-complete-at-point' and `markdown-complete-region'."
4504 (interactive "*")
4505 (if (markdown-use-region-p)
4506 (markdown-complete-region (region-beginning) (region-end))
4507 (markdown-complete-at-point)))
4509 (defun markdown-complete-at-point ()
4510 "Complete markup of object near point.
4511 Handle all elements of `markdown-complete-alist' in order."
4512 (interactive "*")
4513 (let ((list markdown-complete-alist) found changed)
4514 (while list
4515 (let ((regexp (eval (caar list)))
4516 (function (cdar list)))
4517 (setq list (cdr list))
4518 (when (thing-at-point-looking-at regexp)
4519 (setq found t)
4520 (setq changed (funcall function))
4521 (setq list nil))))
4522 (if found
4523 (or changed (error "Markup at point is complete"))
4524 (error "Nothing to complete at point"))))
4526 (defun markdown-complete-region (beg end)
4527 "Complete markup of objects in region from BEG to END.
4528 Handle all objects in `markdown-complete-alist', in order. Each
4529 match is checked to ensure that a previous regexp does not also
4530 match."
4531 (interactive "*r")
4532 (let ((end-marker (set-marker (make-marker) end))
4533 previous)
4534 (dolist (element markdown-complete-alist)
4535 (let ((regexp (eval (car element)))
4536 (function (cdr element)))
4537 (goto-char beg)
4538 (while (re-search-forward regexp end-marker 'limit)
4539 (when (match-string 0)
4540 ;; Make sure this is not a match for any of the preceding regexps.
4541 ;; This prevents mistaking an HR for a Setext subheading.
4542 (let (match)
4543 (save-match-data
4544 (dolist (prev-regexp previous)
4545 (or match (setq match (looking-back prev-regexp nil)))))
4546 (unless match
4547 (save-excursion (funcall function))))))
4548 (cl-pushnew regexp previous :test #'equal)))
4549 previous))
4551 (defun markdown-complete-buffer ()
4552 "Complete markup for all objects in the current buffer."
4553 (interactive "*")
4554 (markdown-complete-region (point-min) (point-max)))
4557 ;;; Markup Cycling ============================================================
4559 (defun markdown-cycle-atx (arg &optional remove)
4560 "Cycle ATX header markup.
4561 Promote header (decrease level) when ARG is 1 and demote
4562 header (increase level) if arg is -1. When REMOVE is non-nil,
4563 remove the header when the level reaches zero and stop cycling
4564 when it reaches six. Otherwise, perform a proper cycling through
4565 levels one through six. Assumes match data is available for
4566 `markdown-regex-header-atx'."
4567 (let* ((old-level (length (match-string 1)))
4568 (new-level (+ old-level arg))
4569 (text (match-string 2)))
4570 (when (not remove)
4571 (setq new-level (% new-level 6))
4572 (setq new-level (cond ((= new-level 0) 6)
4573 ((< new-level 0) (+ new-level 6))
4574 (t new-level))))
4575 (cond
4576 ((= new-level 0)
4577 (markdown-unwrap-thing-at-point nil 0 2))
4578 ((<= new-level 6)
4579 (goto-char (match-beginning 0))
4580 (delete-region (match-beginning 0) (match-end 0))
4581 (markdown-insert-header new-level text nil)))))
4583 (defun markdown-cycle-setext (arg &optional remove)
4584 "Cycle setext header markup.
4585 Promote header (increase level) when ARG is 1 and demote
4586 header (decrease level or remove) if arg is -1. When demoting a
4587 level-two setext header, replace with a level-three atx header.
4588 When REMOVE is non-nil, remove the header when the level reaches
4589 zero. Otherwise, cycle back to a level six atx header. Assumes
4590 match data is available for `markdown-regex-header-setext'."
4591 (let* ((char (char-after (match-beginning 2)))
4592 (old-level (if (char-equal char ?=) 1 2))
4593 (new-level (+ old-level arg)))
4594 (when (and (not remove) (= new-level 0))
4595 (setq new-level 6))
4596 (cond
4597 ((= new-level 0)
4598 (markdown-unwrap-thing-at-point nil 0 1))
4599 ((<= new-level 2)
4600 (markdown-insert-header new-level nil t))
4601 ((<= new-level 6)
4602 (markdown-insert-header new-level nil nil)))))
4604 (defun markdown-cycle-hr (arg &optional remove)
4605 "Cycle string used for horizontal rule from `markdown-hr-strings'.
4606 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
4607 backwards (promote). When REMOVE is non-nil, remove the hr instead
4608 of cycling when the end of the list is reached.
4609 Assumes match data is available for `markdown-regex-hr'."
4610 (let* ((strings (if (= arg -1)
4611 (reverse markdown-hr-strings)
4612 markdown-hr-strings))
4613 (tail (member (match-string 0) strings))
4614 (new (or (cadr tail)
4615 (if remove
4616 (if (= arg 1)
4618 (car tail))
4619 (car strings)))))
4620 (replace-match new)))
4622 (defun markdown-cycle-bold ()
4623 "Cycle bold markup between underscores and asterisks.
4624 Assumes match data is available for `markdown-regex-bold'."
4625 (save-excursion
4626 (let* ((old-delim (match-string 3))
4627 (new-delim (if (string-equal old-delim "**") "__" "**")))
4628 (replace-match new-delim t t nil 3)
4629 (replace-match new-delim t t nil 5))))
4631 (defun markdown-cycle-italic ()
4632 "Cycle italic markup between underscores and asterisks.
4633 Assumes match data is available for `markdown-regex-italic'."
4634 (save-excursion
4635 (let* ((old-delim (match-string 2))
4636 (new-delim (if (string-equal old-delim "*") "_" "*")))
4637 (replace-match new-delim t t nil 2)
4638 (replace-match new-delim t t nil 4))))
4641 ;;; Keymap ====================================================================
4643 (defvar markdown-mode-map
4644 (let ((map (make-keymap)))
4645 ;; Element insertion
4646 (define-key map "\C-c\C-al" 'markdown-insert-inline-link-dwim)
4647 (define-key map "\C-c\C-aL" 'markdown-insert-reference-link-dwim)
4648 (define-key map "\C-c\C-au" 'markdown-insert-uri)
4649 (define-key map "\C-c\C-af" 'markdown-insert-footnote)
4650 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
4651 (define-key map "\C-c\C-ii" 'markdown-insert-image)
4652 (define-key map "\C-c\C-iI" 'markdown-insert-reference-image)
4653 (define-key map "\C-c\C-i\C-t" 'markdown-toggle-inline-images)
4654 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
4655 (define-key map "\C-c\C-tH" 'markdown-insert-header-setext-dwim)
4656 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
4657 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
4658 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
4659 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
4660 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
4661 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
4662 (define-key map "\C-c\C-t!" 'markdown-insert-header-setext-1)
4663 (define-key map "\C-c\C-t@" 'markdown-insert-header-setext-2)
4664 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
4665 (define-key map "\C-c\C-se" 'markdown-insert-italic)
4666 (define-key map "\C-c\C-sc" 'markdown-insert-code)
4667 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
4668 (define-key map "\C-c\C-sk" 'markdown-insert-kbd)
4669 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
4670 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
4671 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
4672 (define-key map "\C-c\C-sP" 'markdown-insert-gfm-code-block)
4673 (define-key map "\C-c-" 'markdown-insert-hr)
4674 ;; Element insertion (deprecated)
4675 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
4676 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
4677 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
4678 ;; Element removal
4679 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
4680 ;; Promotion, Demotion, Completion, and Cycling
4681 (define-key map (kbd "C-c C--") 'markdown-promote)
4682 (define-key map (kbd "C-c C-=") 'markdown-demote)
4683 (define-key map (kbd "C-c C-]") 'markdown-complete)
4684 ;; Following and Jumping
4685 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
4686 (define-key map (kbd "C-c C-l") 'markdown-jump)
4687 ;; Indentation
4688 (define-key map (kbd "C-m") 'markdown-enter-key)
4689 (define-key map (kbd "DEL") 'markdown-exdent-or-delete)
4690 (define-key map (kbd "C-c >") 'markdown-indent-region)
4691 (define-key map (kbd "C-c <") 'markdown-exdent-region)
4692 ;; Visibility cycling
4693 (define-key map (kbd "TAB") 'markdown-cycle)
4694 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
4695 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
4696 (define-key map (kbd "<backtab>") 'markdown-shifttab)
4697 ;; Header navigation
4698 (define-key map (kbd "C-c C-n") 'markdown-next-visible-heading)
4699 (define-key map (kbd "C-c C-p") 'markdown-previous-visible-heading)
4700 (define-key map (kbd "C-c C-f") 'markdown-forward-same-level)
4701 (define-key map (kbd "C-c C-b") 'markdown-backward-same-level)
4702 (define-key map (kbd "C-c C-u") 'markdown-up-heading)
4703 ;; Buffer-wide commands
4704 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
4705 (define-key map (kbd "C-c C-c p") 'markdown-preview)
4706 (define-key map (kbd "C-c C-c e") 'markdown-export)
4707 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
4708 (define-key map (kbd "C-c C-c o") 'markdown-open)
4709 (define-key map (kbd "C-c C-c l") 'markdown-live-preview-mode)
4710 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
4711 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
4712 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
4713 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
4714 ;; List editing
4715 (define-key map (kbd "M-<up>") 'markdown-move-up)
4716 (define-key map (kbd "M-<down>") 'markdown-move-down)
4717 (define-key map (kbd "M-<left>") 'markdown-promote)
4718 (define-key map (kbd "M-<right>") 'markdown-demote)
4719 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
4720 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
4721 ;; Subtree editing
4722 (define-key map (kbd "M-S-<up>") 'markdown-move-subtree-up)
4723 (define-key map (kbd "M-S-<down>") 'markdown-move-subtree-down)
4724 (define-key map (kbd "M-S-<left>") 'markdown-promote-subtree)
4725 (define-key map (kbd "M-S-<right>") 'markdown-demote-subtree)
4726 ;; Movement
4727 (define-key map (kbd "M-{") 'markdown-backward-paragraph)
4728 (define-key map (kbd "M-}") 'markdown-forward-paragraph)
4729 (define-key map (kbd "M-n") 'markdown-next-link)
4730 (define-key map (kbd "M-p") 'markdown-previous-link)
4731 ;; Alternative keys (in case of problems with the arrow keys)
4732 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
4733 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
4734 (define-key map (kbd "C-c C-x l") 'markdown-promote)
4735 (define-key map (kbd "C-c C-x r") 'markdown-demote)
4736 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item)
4737 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox)
4738 map)
4739 "Keymap for Markdown major mode.")
4741 (defvar gfm-mode-map
4742 (let ((map (make-sparse-keymap)))
4743 (set-keymap-parent map markdown-mode-map)
4744 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
4745 (define-key map "`" 'markdown-electric-backquote)
4746 map)
4747 "Keymap for `gfm-mode'.
4748 See also `markdown-mode-map'.")
4751 ;;; Menu ==================================================================
4753 (easy-menu-define markdown-mode-menu markdown-mode-map
4754 "Menu for Markdown mode"
4755 '("Markdown"
4756 "---"
4757 ("Movement"
4758 ["Jump" markdown-jump]
4759 ["Follow Link" markdown-follow-thing-at-point]
4760 ["Next Link" markdown-next-link]
4761 ["Previous Link" markdown-previous-link]
4762 "---"
4763 ["Next Visible Heading" markdown-next-visible-heading]
4764 ["Previous Visible Heading" markdown-previous-visible-heading]
4765 ["Forward Same Level" markdown-forward-same-level]
4766 ["Backward Same Level" markdown-backward-same-level]
4767 ["Up to Parent Heading" markdown-up-heading]
4768 "---"
4769 ["Forward Paragraph" markdown-forward-paragraph]
4770 ["Backward Paragraph" markdown-backward-paragraph])
4771 ("Show/Hide"
4772 ["Cycle Visibility" markdown-cycle (markdown-on-heading-p)]
4773 ["Cycle Visibility Globally" markdown-shifttab])
4774 "---"
4775 ("Headings & Structure"
4776 ["Automatic Heading" markdown-insert-header-dwim]
4777 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim]
4778 ("Specific Heading (atx)"
4779 ["First Level Setext" markdown-insert-header-setext-1]
4780 ["Second Level Setext" markdown-insert-header-setext-2])
4781 ("Specific Heading (Setext)"
4782 ["First Level atx" markdown-insert-header-atx-1]
4783 ["Second Level atx" markdown-insert-header-atx-2]
4784 ["Third Level atx" markdown-insert-header-atx-3]
4785 ["Fourth Level atx" markdown-insert-header-atx-4]
4786 ["Fifth Level atx" markdown-insert-header-atx-5]
4787 ["Sixth Level atx" markdown-insert-header-atx-6])
4788 ["Horizontal Rule" markdown-insert-hr]
4789 "---"
4790 ["Promote Header" markdown-promote]
4791 ["Demote Header" markdown-demote]
4792 ["Promote Subtree" markdown-promote-subtree]
4793 ["Demote Subtree" markdown-demote-subtree]
4794 ["Move Subtree Up" markdown-move-subtree-up]
4795 ["Move Subtree Down" markdown-move-subtree-down])
4796 ("Region Editing"
4797 ["Indent Region" markdown-indent-region]
4798 ["Exdent Region" markdown-exdent-region])
4799 ("Lists"
4800 ["Insert List Item" markdown-insert-list-item]
4801 ["Indent List Item" markdown-demote]
4802 ["Exdent List Item" markdown-promote]
4803 ["Move List Item Up" markdown-move-up]
4804 ["Move List Item Down" markdown-move-down]
4805 ["Renumber List" markdown-cleanup-list-numbers]
4806 ["Toggle Task List Item" markdown-toggle-gfm-checkbox])
4807 ("Links & Images"
4808 ["Plain URL" markdown-insert-uri]
4809 ["Inline Link" markdown-insert-inline-link-dwim]
4810 ["Inline Image" markdown-insert-image]
4811 ["Reference Link" markdown-insert-reference-link-dwim]
4812 ["Reference Image" markdown-insert-reference-image]
4813 ["Footnote" markdown-insert-footnote]
4814 ["Wiki Link" markdown-insert-wiki-link]
4815 "---"
4816 ["Check References" markdown-check-refs]
4817 ["Toggle Inline Images" markdown-toggle-inline-images
4818 :style toggle :selected markdown-inline-image-overlays])
4819 ("Styles"
4820 ["Bold" markdown-insert-bold]
4821 ["Italic" markdown-insert-italic]
4822 ["Code" markdown-insert-code]
4823 ["Strikethrough" markdown-insert-strike-through]
4824 ["Keyboard" markdown-insert-kbd]
4825 "---"
4826 ["Blockquote" markdown-insert-blockquote]
4827 ["Preformatted" markdown-insert-pre]
4828 ["GFM Code Block" markdown-insert-gfm-code-block]
4829 "---"
4830 ["Blockquote Region" markdown-blockquote-region]
4831 ["Preformatted Region" markdown-pre-region])
4832 "---"
4833 ("Preview & Export"
4834 ["Compile" markdown-other-window]
4835 ["Preview" markdown-preview]
4836 ["Export" markdown-export]
4837 ["Export & View" markdown-export-and-preview]
4838 ["Open" markdown-open]
4839 ["Live Export" markdown-live-preview-mode
4840 :style toggle :selected markdown-live-preview-mode]
4841 ["Kill ring save" markdown-kill-ring-save])
4842 ("Markup Completion and Cycling"
4843 ["Complete Markup" markdown-complete]
4844 ["Promote Element" markdown-promote]
4845 ["Demote Element" markdown-demote])
4846 "---"
4847 ["Kill Element" markdown-kill-thing-at-point]
4848 "---"
4849 ("Documentation"
4850 ["Version" markdown-show-version]
4851 ["Homepage" markdown-mode-info]
4852 ["Describe Mode" (describe-function 'markdown-mode)])))
4855 ;;; imenu =====================================================================
4857 (defun markdown-imenu-create-nested-index ()
4858 "Create and return a nested imenu index alist for the current buffer.
4859 See `imenu-create-index-function' and `imenu--index-alist' for details."
4860 (let* ((root '(nil . nil))
4861 cur-alist
4862 (cur-level 0)
4863 (empty-heading "-")
4864 (self-heading ".")
4865 hashes pos level heading)
4866 (save-excursion
4867 (goto-char (point-min))
4868 (while (re-search-forward markdown-regex-header (point-max) t)
4869 (unless (markdown-code-block-at-point)
4870 (cond
4871 ((match-string-no-properties 2) ;; level 1 setext
4872 (setq heading (match-string-no-properties 1))
4873 (setq pos (match-beginning 1)
4874 level 1))
4875 ((match-string-no-properties 3) ;; level 2 setext
4876 (setq heading (match-string-no-properties 1))
4877 (setq pos (match-beginning 1)
4878 level 2))
4879 ((setq hashes (match-string-no-properties 4))
4880 (setq heading (match-string-no-properties 5)
4881 pos (match-beginning 4)
4882 level (length hashes))))
4883 (let ((alist (list (cons heading pos))))
4884 (cond
4885 ((= cur-level level) ; new sibling
4886 (setcdr cur-alist alist)
4887 (setq cur-alist alist))
4888 ((< cur-level level) ; first child
4889 (dotimes (_ (- level cur-level 1))
4890 (setq alist (list (cons empty-heading alist))))
4891 (if cur-alist
4892 (let* ((parent (car cur-alist))
4893 (self-pos (cdr parent)))
4894 (setcdr parent (cons (cons self-heading self-pos) alist)))
4895 (setcdr root alist)) ; primogenitor
4896 (setq cur-alist alist)
4897 (setq cur-level level))
4898 (t ; new sibling of an ancestor
4899 (let ((sibling-alist (last (cdr root))))
4900 (dotimes (_ (1- level))
4901 (setq sibling-alist (last (cdar sibling-alist))))
4902 (setcdr sibling-alist alist)
4903 (setq cur-alist alist))
4904 (setq cur-level level))))))
4905 (cdr root))))
4907 (defun markdown-imenu-create-flat-index ()
4908 "Create and return a flat imenu index alist for the current buffer.
4909 See `imenu-create-index-function' and `imenu--index-alist' for details."
4910 (let* ((empty-heading "-") index heading pos)
4911 (save-excursion
4912 (goto-char (point-min))
4913 (while (re-search-forward markdown-regex-header (point-max) t)
4914 (when (and (not (markdown-code-block-at-point))
4915 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
4916 (cond
4917 ((setq heading (match-string-no-properties 1))
4918 (setq pos (match-beginning 1)))
4919 ((setq heading (match-string-no-properties 5))
4920 (setq pos (match-beginning 4))))
4921 (or (> (length heading) 0)
4922 (setq heading empty-heading))
4923 (setq index (append index (list (cons heading pos))))))
4924 index)))
4927 ;;; References ================================================================
4929 (defun markdown-reference-goto-definition ()
4930 "Jump to the definition of the reference at point or create it."
4931 (interactive)
4932 (when (thing-at-point-looking-at markdown-regex-link-reference)
4933 (let* ((text (match-string-no-properties 3))
4934 (reference (match-string-no-properties 6))
4935 (target (downcase (if (string= reference "") text reference)))
4936 (loc (cadr (markdown-reference-definition target))))
4937 (if loc
4938 (goto-char loc)
4939 (goto-char (match-beginning 0))
4940 (markdown-insert-reference-definition target)))))
4942 (defun markdown-reference-find-links (reference)
4943 "Return a list of all links for REFERENCE.
4944 REFERENCE should not include the surrounding square brackets.
4945 Elements of the list have the form (text start line), where
4946 text is the link text, start is the location at the beginning of
4947 the link, and line is the line number on which the link appears."
4948 (let* ((ref-quote (regexp-quote reference))
4949 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
4950 ref-quote ref-quote))
4951 links)
4952 (save-excursion
4953 (goto-char (point-min))
4954 (while (re-search-forward regexp nil t)
4955 (let* ((text (or (match-string-no-properties 1)
4956 (match-string-no-properties 2)))
4957 (start (match-beginning 0))
4958 (line (markdown-line-number-at-pos)))
4959 (cl-pushnew (list text start line) links :test #'equal))))
4960 links))
4962 (defun markdown-get-undefined-refs ()
4963 "Return a list of undefined Markdown references.
4964 Result is an alist of pairs (reference . occurrences), where
4965 occurrences is itself another alist of pairs (label . line-number).
4966 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
4967 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
4968 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
4969 (let ((missing))
4970 (save-excursion
4971 (goto-char (point-min))
4972 (while
4973 (re-search-forward markdown-regex-link-reference nil t)
4974 (let* ((text (match-string-no-properties 3))
4975 (reference (match-string-no-properties 6))
4976 (target (downcase (if (string= reference "") text reference))))
4977 (unless (markdown-reference-definition target)
4978 (let ((entry (assoc target missing)))
4979 (if (not entry)
4980 (cl-pushnew
4981 (cons target (list (cons text (markdown-line-number-at-pos))))
4982 missing :test #'equal)
4983 (setcdr entry
4984 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
4985 (reverse missing))))
4987 (defconst markdown-reference-check-buffer
4988 "*Undefined references for %buffer%*"
4989 "Pattern for name of buffer for listing undefined references.
4990 The string %buffer% will be replaced by the corresponding
4991 `markdown-mode' buffer name.")
4993 (defun markdown-reference-check-buffer (&optional buffer-name)
4994 "Name and return buffer for reference checking.
4995 BUFFER-NAME is the name of the main buffer being visited."
4996 (or buffer-name (setq buffer-name (buffer-name)))
4997 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
4998 "%buffer%" buffer-name
4999 markdown-reference-check-buffer))))
5000 (with-current-buffer refbuf
5001 (when view-mode
5002 (View-exit-and-edit))
5003 (use-local-map button-buffer-map)
5004 (erase-buffer))
5005 refbuf))
5007 (defconst markdown-reference-links-buffer
5008 "*Reference links for %buffer%*"
5009 "Pattern for name of buffer for listing references.
5010 The string %buffer% will be replaced by the corresponding buffer name.")
5012 (defun markdown-reference-links-buffer (&optional buffer-name)
5013 "Name, setup, and return a buffer for listing links.
5014 BUFFER-NAME is the name of the main buffer being visited."
5015 (or buffer-name (setq buffer-name (buffer-name)))
5016 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
5017 "%buffer%" buffer-name
5018 markdown-reference-links-buffer))))
5019 (with-current-buffer linkbuf
5020 (when view-mode
5021 (View-exit-and-edit))
5022 (use-local-map button-buffer-map)
5023 (erase-buffer))
5024 linkbuf))
5026 (when (markdown-use-buttons-p)
5027 ;; Add an empty Markdown reference definition to buffer
5028 ;; specified in the 'target-buffer property. The reference name is
5029 ;; the button's label.
5030 (define-button-type 'markdown-undefined-reference-button
5031 'help-echo "mouse-1, RET: create definition for undefined reference"
5032 'follow-link t
5033 'face 'bold
5034 'action (lambda (b)
5035 (let ((buffer (button-get b 'target-buffer))
5036 (line (button-get b 'target-line))
5037 (label (button-label b)))
5038 (switch-to-buffer-other-window buffer)
5039 (goto-char (point-min))
5040 (forward-line line)
5041 (markdown-insert-reference-definition label)
5042 (markdown-check-refs t))))
5044 ;; Jump to line in buffer specified by 'target-buffer property.
5045 ;; Line number is button's 'line property.
5046 (define-button-type 'markdown-goto-line-button
5047 'help-echo "mouse-1, RET: go to line"
5048 'follow-link t
5049 'face 'italic
5050 'action (lambda (b)
5051 (message (button-get b 'buffer))
5052 (switch-to-buffer-other-window (button-get b 'target-buffer))
5053 ;; use call-interactively to silence compiler
5054 (let ((current-prefix-arg (button-get b 'target-line)))
5055 (call-interactively 'goto-line))))
5057 ;; Jumps to a particular link at location given by 'target-char
5058 ;; property in buffer given by 'target-buffer property.
5059 (define-button-type 'markdown-link-button
5060 'help-echo "mouse-1, RET: jump to location of link"
5061 'follow-link t
5062 'face 'bold
5063 'action (lambda (b)
5064 (let ((target (button-get b 'target-buffer))
5065 (loc (button-get b 'target-char)))
5066 (kill-buffer-and-window)
5067 (switch-to-buffer target)
5068 (goto-char loc)))))
5070 (defun markdown-insert-undefined-reference-button (reference oldbuf)
5071 "Insert a button for creating REFERENCE in buffer OLDBUF.
5072 REFERENCE should be a list of the form (reference . occurrences),
5073 as by `markdown-get-undefined-refs'."
5074 (let ((label (car reference)))
5075 (if (markdown-use-buttons-p)
5076 ;; Create a reference button in Emacs 22
5077 (insert-button label
5078 :type 'markdown-undefined-reference-button
5079 'target-buffer oldbuf
5080 'target-line (cdr (car (cdr reference))))
5081 ;; Insert reference as text in Emacs < 22
5082 (insert label))
5083 (insert " (")
5084 (dolist (occurrence (cdr reference))
5085 (let ((line (cdr occurrence)))
5086 (if (markdown-use-buttons-p)
5087 ;; Create a line number button in Emacs 22
5088 (insert-button (number-to-string line)
5089 :type 'markdown-goto-line-button
5090 'target-buffer oldbuf
5091 'target-line line)
5092 ;; Insert line number as text in Emacs < 22
5093 (insert (number-to-string line)))
5094 (insert " ")))
5095 (delete-char -1)
5096 (insert ")")
5097 (newline)))
5099 (defun markdown-insert-link-button (link oldbuf)
5100 "Insert a button for jumping to LINK in buffer OLDBUF.
5101 LINK should be a list of the form (text char line) containing
5102 the link text, location, and line number."
5103 (let ((label (cl-first link))
5104 (char (cl-second link))
5105 (line (cl-third link)))
5106 (if (markdown-use-buttons-p)
5107 ;; Create a reference button in Emacs 22
5108 (insert-button label
5109 :type 'markdown-link-button
5110 'target-buffer oldbuf
5111 'target-char char)
5112 ;; Insert reference as text in Emacs < 22
5113 (insert label))
5114 (insert (format " (line %d)\n" line))))
5116 (defun markdown-reference-goto-link (&optional reference)
5117 "Jump to the location of the first use of REFERENCE."
5118 (interactive)
5119 (unless reference
5120 (if (thing-at-point-looking-at markdown-regex-reference-definition)
5121 (setq reference (match-string-no-properties 2))
5122 (error "No reference definition at point")))
5123 (let ((links (markdown-reference-find-links reference)))
5124 (cond ((= (length links) 1)
5125 (goto-char (cadr (car links))))
5126 ((> (length links) 1)
5127 (let ((oldbuf (current-buffer))
5128 (linkbuf (markdown-reference-links-buffer)))
5129 (with-current-buffer linkbuf
5130 (insert "Links using reference " reference ":\n\n")
5131 (dolist (link (reverse links))
5132 (markdown-insert-link-button link oldbuf)))
5133 (view-buffer-other-window linkbuf)
5134 (goto-char (point-min))
5135 (forward-line 2)))
5137 (error "No links for reference %s" reference)))))
5139 (defun markdown-check-refs (&optional silent)
5140 "Show all undefined Markdown references in current `markdown-mode' buffer.
5141 If SILENT is non-nil, do not message anything when no undefined
5142 references found.
5143 Links which have empty reference definitions are considered to be
5144 defined."
5145 (interactive "P")
5146 (when (not (eq major-mode 'markdown-mode))
5147 (error "Not available in current mode"))
5148 (let ((oldbuf (current-buffer))
5149 (refs (markdown-get-undefined-refs))
5150 (refbuf (markdown-reference-check-buffer)))
5151 (if (null refs)
5152 (progn
5153 (when (not silent)
5154 (message "No undefined references found"))
5155 (kill-buffer refbuf))
5156 (with-current-buffer refbuf
5157 (insert "The following references are undefined:\n\n")
5158 (dolist (ref refs)
5159 (markdown-insert-undefined-reference-button ref oldbuf))
5160 (view-buffer-other-window refbuf)
5161 (goto-char (point-min))
5162 (forward-line 2)))))
5165 ;;; Lists =====================================================================
5167 (defun markdown-insert-list-item (&optional arg)
5168 "Insert a new list item.
5169 If the point is inside unordered list, insert a bullet mark. If
5170 the point is inside ordered list, insert the next number followed
5171 by a period. Use the previous list item to determine the amount
5172 of whitespace to place before and after list markers.
5174 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5175 decrease the indentation by one level.
5177 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5178 increase the indentation by one level."
5179 (interactive "p")
5180 (let (bounds cur-indent marker indent new-indent new-loc)
5181 (save-match-data
5182 ;; Look for a list item on current or previous non-blank line
5183 (save-excursion
5184 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
5185 (not (bobp))
5186 (markdown-cur-line-blank-p))
5187 (forward-line -1)))
5188 (when bounds
5189 (cond ((save-excursion
5190 (skip-chars-backward " \t")
5191 (looking-at-p markdown-regex-list))
5192 (beginning-of-line)
5193 (insert "\n")
5194 (forward-line -1))
5195 ((not (markdown-cur-line-blank-p))
5196 (newline)))
5197 (setq new-loc (point)))
5198 ;; Look ahead for a list item on next non-blank line
5199 (unless bounds
5200 (save-excursion
5201 (while (and (null bounds)
5202 (not (eobp))
5203 (markdown-cur-line-blank-p))
5204 (forward-line)
5205 (setq bounds (markdown-cur-list-item-bounds))))
5206 (when bounds
5207 (setq new-loc (point))
5208 (unless (markdown-cur-line-blank-p)
5209 (newline))))
5210 (if (not bounds)
5211 ;; When not in a list, start a new unordered one
5212 (progn
5213 (unless (markdown-cur-line-blank-p)
5214 (insert "\n"))
5215 (insert markdown-unordered-list-item-prefix))
5216 ;; Compute indentation and marker for new list item
5217 (setq cur-indent (nth 2 bounds))
5218 (setq marker (nth 4 bounds))
5219 (cond
5220 ;; Dedent: decrement indentation, find previous marker.
5221 ((= arg 4)
5222 (setq indent (max (- cur-indent 4) 0))
5223 (let ((prev-bounds
5224 (save-excursion
5225 (when (markdown-prev-list-item (- (nth 3 bounds) 1))
5226 (markdown-cur-list-item-bounds)))))
5227 (when prev-bounds
5228 (setq marker (nth 4 prev-bounds)))))
5229 ;; Indent: increment indentation by 4, use same marker.
5230 ((= arg 16) (setq indent (+ cur-indent 4)))
5231 ;; Same level: keep current indentation and marker.
5232 (t (setq indent cur-indent)))
5233 (setq new-indent (make-string indent 32))
5234 (goto-char new-loc)
5235 (cond
5236 ;; Ordered list
5237 ((string-match-p "[0-9]" marker)
5238 (if (= arg 16) ;; starting a new column indented one more level
5239 (insert (concat new-indent "1. "))
5240 ;; Don't use previous match-data
5241 (set-match-data nil)
5242 ;; travel up to the last item and pick the correct number. If
5243 ;; the argument was nil, "new-indent = cur-indent" is the same,
5244 ;; so we don't need special treatment. Neat.
5245 (save-excursion
5246 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
5247 (>= (forward-line -1) 0))))
5248 (let* ((old-prefix (match-string 1))
5249 (old-spacing (match-string 2))
5250 (new-prefix (if old-prefix
5251 (int-to-string (1+ (string-to-number old-prefix)))
5252 "1"))
5253 (space-adjust (- (length old-prefix) (length new-prefix)))
5254 (new-spacing (if (and (match-string 2)
5255 (not (string-match-p "\t" old-spacing))
5256 (< space-adjust 0)
5257 (> space-adjust (- 1 (length (match-string 2)))))
5258 (substring (match-string 2) 0 space-adjust)
5259 (or old-spacing ". "))))
5260 (insert (concat new-indent new-prefix new-spacing)))))
5261 ;; Unordered list, or ordered list with hash mark
5262 ((string-match-p "[\\*\\+-]\\|#\\." marker)
5263 (insert new-indent marker)))))))
5265 (defun markdown-move-list-item-up ()
5266 "Move the current list item up in the list when possible."
5267 (interactive)
5268 (let (cur prev old)
5269 (when (setq cur (markdown-cur-list-item-bounds))
5270 (setq old (point))
5271 (goto-char (nth 0 cur))
5272 (if (markdown-prev-list-item (nth 3 cur))
5273 (progn
5274 (setq prev (markdown-cur-list-item-bounds))
5275 (condition-case nil
5276 (progn
5277 (transpose-regions (nth 0 prev) (nth 1 prev)
5278 (nth 0 cur) (nth 1 cur) t)
5279 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
5280 ;; Catch error in case regions overlap.
5281 (error (goto-char old))))
5282 (goto-char old)))))
5284 (defun markdown-move-list-item-down ()
5285 "Move the current list item down in the list when possible."
5286 (interactive)
5287 (let (cur next old)
5288 (when (setq cur (markdown-cur-list-item-bounds))
5289 (setq old (point))
5290 (if (markdown-next-list-item (nth 3 cur))
5291 (progn
5292 (setq next (markdown-cur-list-item-bounds))
5293 (condition-case nil
5294 (progn
5295 (transpose-regions (nth 0 cur) (nth 1 cur)
5296 (nth 0 next) (nth 1 next) nil)
5297 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
5298 ;; Catch error in case regions overlap.
5299 (error (goto-char old))))
5300 (goto-char old)))))
5302 (defun markdown-demote-list-item (&optional bounds)
5303 "Indent (or demote) the current list item.
5304 Optionally, BOUNDS of the current list item may be provided if available."
5305 (interactive)
5306 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5307 (save-excursion
5308 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
5309 (goto-char (nth 0 bounds))
5310 (while (< (point) end-marker)
5311 (unless (markdown-cur-line-blank-p)
5312 (insert (make-string markdown-list-indent-width ? )))
5313 (forward-line))))))
5315 (defun markdown-promote-list-item (&optional bounds)
5316 "Unindent (or promote) the current list item.
5317 Optionally, BOUNDS of the current list item may be provided if available."
5318 (interactive)
5319 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
5320 (save-excursion
5321 (save-match-data
5322 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
5323 num regexp)
5324 (goto-char (nth 0 bounds))
5325 (when (looking-at (format "^[ ]\\{1,%d\\}"
5326 markdown-list-indent-width))
5327 (setq num (- (match-end 0) (match-beginning 0)))
5328 (setq regexp (format "^[ ]\\{1,%d\\}" num))
5329 (while (and (< (point) end-marker)
5330 (re-search-forward regexp end-marker t))
5331 (replace-match "" nil nil)
5332 (forward-line))))))))
5334 (defun markdown-cleanup-list-numbers-level (&optional pfx)
5335 "Update the numbering for level PFX (as a string of spaces).
5337 Assume that the previously found match was for a numbered item in
5338 a list."
5339 (let ((cpfx pfx)
5340 (idx 0)
5341 (continue t)
5342 (step t)
5343 (sep nil))
5344 (while (and continue (not (eobp)))
5345 (setq step t)
5346 (cond
5347 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
5348 (setq cpfx (match-string-no-properties 1))
5349 (cond
5350 ((string= cpfx pfx)
5351 (save-excursion
5352 (replace-match
5353 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
5354 (setq sep nil))
5355 ;; indented a level
5356 ((string< pfx cpfx)
5357 (setq sep (markdown-cleanup-list-numbers-level cpfx))
5358 (setq step nil))
5359 ;; exit the loop
5361 (setq step nil)
5362 (setq continue nil))))
5364 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
5365 (setq cpfx (match-string-no-properties 1))
5366 (cond
5367 ;; reset if separated before
5368 ((string= cpfx pfx) (when sep (setq idx 0)))
5369 ((string< cpfx pfx)
5370 (setq step nil)
5371 (setq continue nil))))
5372 (t (setq sep t)))
5374 (when step
5375 (beginning-of-line)
5376 (setq continue (= (forward-line) 0))))
5377 sep))
5379 (defun markdown-cleanup-list-numbers ()
5380 "Update the numbering of ordered lists."
5381 (interactive)
5382 (save-excursion
5383 (goto-char (point-min))
5384 (markdown-cleanup-list-numbers-level "")))
5387 ;;; Movement ==================================================================
5389 (defun markdown-beginning-of-defun (&optional arg)
5390 "`beginning-of-defun-function' for Markdown.
5391 Move backward to the beginning of the current or previous section.
5392 When ARG is non-nil, repeat that many times. When ARG is negative,
5393 move forward to the ARG-th following section."
5394 (interactive "P")
5395 (or arg (setq arg 1))
5396 (forward-char 1)
5397 (or (re-search-backward markdown-regex-header nil t arg)
5398 (goto-char (point-min))))
5400 (defun markdown-end-of-defun (&optional arg)
5401 "`end-of-defun-function' for Markdown.
5402 Move forward to the end of the current or following section.
5403 When ARG is non-nil, repeat that many times. When ARG is negative,
5404 move back to the ARG-th preceding section."
5405 (interactive "P")
5406 (or arg (setq arg 1))
5407 (when (looking-at markdown-regex-header)
5408 (goto-char (match-beginning 0))
5409 (forward-char 1))
5410 (if (re-search-forward markdown-regex-header nil t arg)
5411 (goto-char (match-beginning 0))
5412 (goto-char (point-max)))
5413 (skip-syntax-backward "-"))
5415 (defun markdown-beginning-of-block ()
5416 "Move the point to the start of the previous text block."
5417 (interactive)
5418 (if (re-search-backward markdown-regex-block-separator nil t)
5419 (goto-char (or (match-end 2) (match-end 0)))
5420 (goto-char (point-min))))
5422 (defun markdown-end-of-block ()
5423 "Move the point to the start of the next text block."
5424 (interactive)
5425 (beginning-of-line)
5426 (skip-syntax-forward "-")
5427 (when (= (point) (point-min))
5428 (forward-char))
5429 (if (re-search-forward markdown-regex-block-separator nil t)
5430 (goto-char (or (match-end 2) (match-end 0)))
5431 (goto-char (point-max)))
5432 (skip-syntax-backward "-")
5433 (forward-line))
5435 (defun markdown-forward-paragraph (arg)
5436 "Move forward one or more paragraphs or by one block.
5437 When ARG is nil or a numeric prefix, call `forward-paragraph'
5438 with ARG. When called with \\[universal-argument], call
5439 `markdown-end-of-block' instead."
5440 (interactive "P")
5441 (or arg (setq arg 1))
5442 (cond ((integerp arg)
5443 (forward-paragraph arg))
5444 ((equal arg '(4))
5445 (markdown-end-of-block))))
5447 (defun markdown-backward-paragraph (arg)
5448 "Move backward one or more paragraphs or by one block.
5449 When ARG is nil or a numeric prefix, call `backward-paragraph'
5450 with ARG. When called with \\[universal-argument], call
5451 `markdown-beginning-of-block' instead."
5452 (interactive "P")
5453 (or arg (setq arg 1))
5454 (cond ((integerp arg)
5455 (backward-paragraph arg))
5456 ((equal arg '(4))
5457 (markdown-beginning-of-block))))
5459 (defun markdown-end-of-block-element ()
5460 "Move the point to the start of the next block unit.
5461 Stops at blank lines, list items, headers, and horizontal rules."
5462 (interactive)
5463 (forward-line)
5464 (while (and (or (not (markdown-prev-line-blank-p))
5465 (markdown-cur-line-blank-p))
5466 (not (or (looking-at-p markdown-regex-list)
5467 (looking-at-p markdown-regex-header)
5468 (looking-at-p markdown-regex-hr)))
5469 (not (eobp)))
5470 (forward-line)))
5472 (defun markdown-next-link ()
5473 "Jump to next inline, reference, or wiki link.
5474 If successful, return point. Otherwise, return nil.
5475 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
5476 (interactive)
5477 (let ((opoint (point)))
5478 (when (or (markdown-link-p) (markdown-wiki-link-p))
5479 ;; At a link already, move past it.
5480 (goto-char (+ (match-end 0) 1)))
5481 ;; Search for the next wiki link and move to the beginning.
5482 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
5483 (markdown-code-block-at-point)
5484 (< (point) (point-max))))
5485 (if (and (not (eq (point) opoint))
5486 (or (markdown-link-p) (markdown-wiki-link-p)))
5487 ;; Group 1 will move past non-escape character in wiki link regexp.
5488 ;; Go to beginning of group zero for all other link types.
5489 (goto-char (or (match-beginning 1) (match-beginning 0)))
5490 (goto-char opoint)
5491 nil)))
5493 (defun markdown-previous-link ()
5494 "Jump to previous wiki link.
5495 If successful, return point. Otherwise, return nil.
5496 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
5497 (interactive)
5498 (let ((opoint (point)))
5499 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
5500 (markdown-code-block-at-point)
5501 (> (point) (point-min))))
5502 (if (and (not (eq (point) opoint))
5503 (or (markdown-link-p) (markdown-wiki-link-p)))
5504 (goto-char (or (match-beginning 1) (match-beginning 0)))
5505 (goto-char opoint)
5506 nil)))
5509 ;;; Outline ===================================================================
5511 (defun markdown-move-heading-common (move-fn &optional arg)
5512 "Wrapper for `outline-mode' functions to skip false positives.
5513 MOVE-FN is a function and ARG is its argument. For example,
5514 headings inside preformatted code blocks may match
5515 `outline-regexp' but should not be considered as headings."
5516 (let ((prev -1) (start (point)))
5517 (if arg (funcall move-fn arg) (funcall move-fn))
5518 (while (and (/= prev (point)) (markdown-code-block-at-point))
5519 (setq prev (point))
5520 (if arg (funcall move-fn arg) (funcall move-fn)))
5521 (if (= (point) start) nil (point))))
5523 (defun markdown-next-visible-heading (arg)
5524 "Move to the next visible heading line of any level.
5525 With argument, repeats or can move backward if negative. ARG is
5526 passed to `outline-next-visible-heading'."
5527 (interactive "p")
5528 (markdown-move-heading-common 'outline-next-visible-heading arg))
5530 (defun markdown-previous-visible-heading (arg)
5531 "Move to the previous visible heading line of any level.
5532 With argument, repeats or can move backward if negative. ARG is
5533 passed to `outline-previous-visible-heading'."
5534 (interactive "p")
5535 (markdown-move-heading-common 'outline-previous-visible-heading arg))
5537 (defun markdown-next-heading ()
5538 "Move to the next heading line of any level."
5539 (markdown-move-heading-common 'outline-next-heading))
5541 (defun markdown-previous-heading ()
5542 "Move to the previous heading line of any level."
5543 (markdown-move-heading-common 'outline-previous-heading))
5545 (defun markdown-forward-same-level (arg)
5546 "Move forward to the ARG'th heading at same level as this one.
5547 Stop at the first and last headings of a superior heading."
5548 (interactive "p")
5549 (markdown-move-heading-common 'outline-forward-same-level arg))
5551 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok)
5552 (beginning-of-line)
5553 (or (and (outline-on-heading-p invisible-ok)
5554 (not (markdown-code-block-at-point)))
5555 (let ((header-re (concat "^\\(?:" outline-regexp "\\)"))
5556 found)
5557 (save-excursion
5558 (while (not found)
5559 (let (finish)
5560 (while (and (not finish) (re-search-backward header-re nil t))
5561 (when (and (or invisible-ok (not (outline-invisible-p)))
5562 (not (markdown-code-block-at-point)))
5563 (setq finish t)))
5564 (if (not finish)
5565 (error "Before first heading")
5566 (setq found (point))))))
5567 (goto-char found)
5568 found)))
5570 (defun markdown-backward-same-level (arg)
5571 "Move backward to the ARG'th heading at same level as this one.
5572 Stop at the first and last headings of a superior heading."
5573 (interactive "p")
5574 (markdown-back-to-heading-over-code-block)
5575 (while (> arg 0)
5576 (let ((point-to-move-to (save-excursion
5577 (outline-get-last-sibling))))
5578 (if point-to-move-to
5579 (progn
5580 (goto-char point-to-move-to)
5581 (setq arg (1- arg)))
5582 (error "No previous same-level heading")))))
5584 (defun markdown-up-heading (arg)
5585 "Move to the visible heading line of which the present line is a subheading.
5586 With argument, move up ARG levels."
5587 (interactive "p")
5588 (and (called-interactively-p 'any)
5589 (not (eq last-command 'markdown-up-heading)) (push-mark))
5590 (markdown-move-heading-common 'outline-up-heading arg))
5592 (defun markdown-back-to-heading (&optional invisible-ok)
5593 "Move to previous heading line, or beg of this line if it's a heading.
5594 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
5595 (markdown-move-heading-common 'outline-back-to-heading invisible-ok))
5597 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
5599 (defun markdown-on-heading-p ()
5600 "Return t if point is on a (visible) heading line."
5601 (get-text-property (point) 'markdown-heading))
5603 (defun markdown-end-of-subtree (&optional invisible-OK)
5604 "Move to the end of the current subtree.
5605 Only visible heading lines are considered, unless INVISIBLE-OK is
5606 non-nil.
5607 Derived from `org-end-of-subtree'."
5608 (markdown-back-to-heading invisible-OK)
5609 (let ((first t)
5610 (level (markdown-outline-level)))
5611 (while (and (not (eobp))
5612 (or first (> (markdown-outline-level) level)))
5613 (setq first nil)
5614 (markdown-next-heading))
5615 (if (memq (preceding-char) '(?\n ?\^M))
5616 (progn
5617 ;; Go to end of line before heading
5618 (forward-char -1)
5619 (if (memq (preceding-char) '(?\n ?\^M))
5620 ;; leave blank line before heading
5621 (forward-char -1)))))
5622 (point))
5624 (defun markdown-outline-fix-visibility ()
5625 "Hide any false positive headings that should not be shown.
5626 For example, headings inside preformatted code blocks may match
5627 `outline-regexp' but should not be shown as headings when cycling.
5628 Also, the ending --- line in metadata blocks appears to be a
5629 setext header, but should not be folded."
5630 (save-excursion
5631 (goto-char (point-min))
5632 ;; Unhide any false positives in metadata blocks
5633 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
5634 (let ((body (progn (forward-line)
5635 (markdown-text-property-at-point
5636 'markdown-yaml-metadata-section))))
5637 (when body
5638 (let ((end (progn (goto-char (cl-second body))
5639 (markdown-text-property-at-point
5640 'markdown-yaml-metadata-end))))
5641 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
5642 ;; Hide any false positives in code blocks
5643 (unless (outline-on-heading-p)
5644 (outline-next-visible-heading 1))
5645 (while (< (point) (point-max))
5646 (when (markdown-code-block-at-point)
5647 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
5648 (outline-next-visible-heading 1))))
5650 (defvar markdown-cycle-global-status 1)
5651 (defvar markdown-cycle-subtree-status nil)
5653 (defun markdown-next-preface ()
5654 (let (finish)
5655 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
5656 nil 'move))
5657 (unless (markdown-code-block-at-point)
5658 (goto-char (match-beginning 0))
5659 (setq finish t))))
5660 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
5661 (forward-char -1)))
5663 (defun markdown-show-entry ()
5664 (save-excursion
5665 (outline-back-to-heading t)
5666 (outline-flag-region (1- (point))
5667 (progn
5668 (markdown-next-preface)
5669 (if (= 1 (- (point-max) (point)))
5670 (point-max)
5671 (point)))
5672 nil)))
5674 (defun markdown-cycle (&optional arg)
5675 "Visibility cycling for Markdown mode.
5676 If ARG is t, perform global visibility cycling. If the point is
5677 at an atx-style header, cycle visibility of the corresponding
5678 subtree. Otherwise, insert a tab using `indent-relative'.
5679 Derived from `org-cycle'."
5680 (interactive "P")
5681 (cond
5682 ((eq arg t) ;; Global cycling
5683 (cond
5684 ((and (eq last-command this-command)
5685 (eq markdown-cycle-global-status 2))
5686 ;; Move from overview to contents
5687 (markdown-hide-sublevels 1)
5688 (message "CONTENTS")
5689 (setq markdown-cycle-global-status 3)
5690 (markdown-outline-fix-visibility))
5692 ((and (eq last-command this-command)
5693 (eq markdown-cycle-global-status 3))
5694 ;; Move from contents to all
5695 (markdown-show-all)
5696 (message "SHOW ALL")
5697 (setq markdown-cycle-global-status 1))
5700 ;; Defaults to overview
5701 (markdown-hide-body)
5702 (message "OVERVIEW")
5703 (setq markdown-cycle-global-status 2)
5704 (markdown-outline-fix-visibility))))
5706 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
5707 ;; At a heading: rotate between three different views
5708 (markdown-back-to-heading)
5709 (let ((goal-column 0) eoh eol eos)
5710 ;; Determine boundaries
5711 (save-excursion
5712 (markdown-back-to-heading)
5713 (save-excursion
5714 (beginning-of-line 2)
5715 (while (and (not (eobp)) ;; this is like `next-line'
5716 (get-char-property (1- (point)) 'invisible))
5717 (beginning-of-line 2)) (setq eol (point)))
5718 (markdown-end-of-heading) (setq eoh (point))
5719 (markdown-end-of-subtree t)
5720 (skip-chars-forward " \t\n")
5721 (beginning-of-line 1) ; in case this is an item
5722 (setq eos (1- (point))))
5723 ;; Find out what to do next and set `this-command'
5724 (cond
5725 ((= eos eoh)
5726 ;; Nothing is hidden behind this heading
5727 (message "EMPTY ENTRY")
5728 (setq markdown-cycle-subtree-status nil))
5729 ((>= eol eos)
5730 ;; Entire subtree is hidden in one line: open it
5731 (markdown-show-entry)
5732 (markdown-show-children)
5733 (message "CHILDREN")
5734 (setq markdown-cycle-subtree-status 'children))
5735 ((and (eq last-command this-command)
5736 (eq markdown-cycle-subtree-status 'children))
5737 ;; We just showed the children, now show everything.
5738 (markdown-show-subtree)
5739 (message "SUBTREE")
5740 (setq markdown-cycle-subtree-status 'subtree))
5742 ;; Default action: hide the subtree.
5743 (markdown-hide-subtree)
5744 (message "FOLDED")
5745 (setq markdown-cycle-subtree-status 'folded)))))
5748 (indent-for-tab-command))))
5750 (defun markdown-shifttab ()
5751 "Global visibility cycling.
5752 Calls `markdown-cycle' with argument t."
5753 (interactive)
5754 (markdown-cycle t))
5756 (defun markdown-outline-level ()
5757 "Return the depth to which a statement is nested in the outline."
5758 (cond
5759 ((markdown-code-block-at-point-p) 7) ;; Only 6 header levels are defined.
5760 ((match-end 2) 1)
5761 ((match-end 3) 2)
5762 ((match-end 4) (- (match-end 4) (match-beginning 4)))))
5764 (defun markdown-promote-subtree (&optional arg)
5765 "Promote the current subtree of ATX headings.
5766 Note that Markdown does not support heading levels higher than
5767 six and therefore level-six headings will not be promoted
5768 further. If ARG is non-nil promote the heading, otherwise
5769 demote."
5770 (interactive "*P")
5771 (save-excursion
5772 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
5773 (re-search-backward markdown-regex-header-atx nil t))
5774 (not (markdown-code-block-at-point)))
5775 (let ((level (length (match-string 1)))
5776 (promote-or-demote (if arg 1 -1))
5777 (remove 't))
5778 (markdown-cycle-atx promote-or-demote remove)
5779 (catch 'end-of-subtree
5780 (while (markdown-next-heading)
5781 ;; Exit if this not a higher level heading; promote otherwise.
5782 (if (and (looking-at markdown-regex-header-atx)
5783 (<= (length (match-string-no-properties 1)) level))
5784 (throw 'end-of-subtree nil)
5785 (markdown-cycle-atx promote-or-demote remove))))))))
5787 (defun markdown-demote-subtree ()
5788 "Demote the current subtree of ATX headings."
5789 (interactive)
5790 (markdown-promote-subtree t))
5792 (defun markdown-move-subtree-up ()
5793 "Move the current subtree of ATX headings up."
5794 (interactive)
5795 (outline-move-subtree-up 1))
5797 (defun markdown-move-subtree-down ()
5798 "Move the current subtree of ATX headings down."
5799 (interactive)
5800 (outline-move-subtree-down 1))
5803 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
5805 (defun markdown-move-up ()
5806 "Move list item up.
5807 Calls `markdown-move-list-item-up'."
5808 (interactive)
5809 (markdown-move-list-item-up))
5811 (defun markdown-move-down ()
5812 "Move list item down.
5813 Calls `markdown-move-list-item-down'."
5814 (interactive)
5815 (markdown-move-list-item-down))
5817 (defun markdown-promote ()
5818 "Either promote header or list item at point or cycle markup.
5819 See `markdown-cycle-atx', `markdown-cycle-setext', and
5820 `markdown-promote-list-item'."
5821 (interactive)
5822 (let (bounds)
5823 (cond
5824 ;; Promote atx header
5825 ((thing-at-point-looking-at markdown-regex-header-atx)
5826 (markdown-cycle-atx -1))
5827 ;; Promote setext header
5828 ((thing-at-point-looking-at markdown-regex-header-setext)
5829 (markdown-cycle-setext -1))
5830 ;; Promote horizonal rule
5831 ((thing-at-point-looking-at markdown-regex-hr)
5832 (markdown-cycle-hr -1))
5833 ;; Promote list item
5834 ((setq bounds (markdown-cur-list-item-bounds))
5835 (markdown-promote-list-item bounds))
5836 ;; Promote bold
5837 ((thing-at-point-looking-at markdown-regex-bold)
5838 (markdown-cycle-bold))
5839 ;; Promote italic
5840 ((thing-at-point-looking-at markdown-regex-italic)
5841 (markdown-cycle-italic))
5843 (error "Nothing to promote at point")))))
5845 (defun markdown-demote ()
5846 "Either demote header or list item at point or cycle or remove markup.
5847 See `markdown-cycle-atx', `markdown-cycle-setext', and
5848 `markdown-demote-list-item'."
5849 (interactive)
5850 (let (bounds)
5851 (cond
5852 ;; Demote atx header
5853 ((thing-at-point-looking-at markdown-regex-header-atx)
5854 (markdown-cycle-atx 1))
5855 ;; Demote setext header
5856 ((thing-at-point-looking-at markdown-regex-header-setext)
5857 (markdown-cycle-setext 1))
5858 ;; Demote horizonal rule
5859 ((thing-at-point-looking-at markdown-regex-hr)
5860 (markdown-cycle-hr 1))
5861 ;; Demote list item
5862 ((setq bounds (markdown-cur-list-item-bounds))
5863 (markdown-demote-list-item bounds))
5864 ;; Demote bold
5865 ((thing-at-point-looking-at markdown-regex-bold)
5866 (markdown-cycle-bold))
5867 ;; Demote italic
5868 ((thing-at-point-looking-at markdown-regex-italic)
5869 (markdown-cycle-italic))
5871 (error "Nothing to demote at point")))))
5874 ;;; Commands ==================================================================
5876 (defun markdown (&optional output-buffer-name)
5877 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
5878 The output buffer name defaults to `markdown-output-buffer-name'.
5879 Return the name of the output buffer used."
5880 (interactive)
5881 (save-window-excursion
5882 (let ((begin-region)
5883 (end-region))
5884 (if (markdown-use-region-p)
5885 (setq begin-region (region-beginning)
5886 end-region (region-end))
5887 (setq begin-region (point-min)
5888 end-region (point-max)))
5890 (unless output-buffer-name
5891 (setq output-buffer-name markdown-output-buffer-name))
5892 (cond
5893 ;; Handle case when `markdown-command' does not read from stdin
5894 (markdown-command-needs-filename
5895 (if (not buffer-file-name)
5896 (error "Must be visiting a file")
5897 (shell-command (concat markdown-command " "
5898 (shell-quote-argument buffer-file-name))
5899 output-buffer-name)))
5900 ;; Pass region to `markdown-command' via stdin
5902 (let ((buf (get-buffer-create output-buffer-name)))
5903 (with-current-buffer buf
5904 (setq buffer-read-only nil)
5905 (erase-buffer))
5906 (call-process-region begin-region end-region
5907 shell-file-name nil buf nil
5908 shell-command-switch markdown-command)))))
5909 output-buffer-name))
5911 (defun markdown-standalone (&optional output-buffer-name)
5912 "Special function to provide standalone HTML output.
5913 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
5914 (interactive)
5915 (setq output-buffer-name (markdown output-buffer-name))
5916 (with-current-buffer output-buffer-name
5917 (set-buffer output-buffer-name)
5918 (unless (markdown-output-standalone-p)
5919 (markdown-add-xhtml-header-and-footer output-buffer-name))
5920 (goto-char (point-min))
5921 (html-mode))
5922 output-buffer-name)
5924 (defun markdown-other-window (&optional output-buffer-name)
5925 "Run `markdown-command' on current buffer and display in other window.
5926 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5927 that name."
5928 (interactive)
5929 (markdown-display-buffer-other-window
5930 (markdown-standalone output-buffer-name)))
5932 (defun markdown-output-standalone-p ()
5933 "Determine whether `markdown-command' output is standalone XHTML.
5934 Standalone XHTML output is identified by an occurrence of
5935 `markdown-xhtml-standalone-regexp' in the first five lines of output."
5936 (save-excursion
5937 (goto-char (point-min))
5938 (re-search-forward
5939 markdown-xhtml-standalone-regexp
5940 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
5941 t)))
5943 (defun markdown-stylesheet-link-string (stylesheet-path)
5944 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
5945 stylesheet-path
5946 "\" />"))
5948 (defun markdown-add-xhtml-header-and-footer (title)
5949 "Wrap XHTML header and footer with given TITLE around current buffer."
5950 (goto-char (point-min))
5951 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
5952 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
5953 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
5954 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
5955 "<head>\n<title>")
5956 (insert title)
5957 (insert "</title>\n")
5958 (when (> (length markdown-content-type) 0)
5959 (insert
5960 (format
5961 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
5962 markdown-content-type
5963 (or (and markdown-coding-system
5964 (fboundp 'coding-system-get)
5965 (coding-system-get markdown-coding-system
5966 'mime-charset))
5967 (and (fboundp 'coding-system-get)
5968 (coding-system-get buffer-file-coding-system
5969 'mime-charset))
5970 "iso-8859-1"))))
5971 (if (> (length markdown-css-paths) 0)
5972 (insert (mapconcat #'markdown-stylesheet-link-string
5973 markdown-css-paths "\n")))
5974 (when (> (length markdown-xhtml-header-content) 0)
5975 (insert markdown-xhtml-header-content))
5976 (insert "\n</head>\n\n"
5977 "<body>\n\n")
5978 (goto-char (point-max))
5979 (insert "\n"
5980 "</body>\n"
5981 "</html>\n"))
5983 (defun markdown-preview (&optional output-buffer-name)
5984 "Run `markdown-command' on the current buffer and view output in browser.
5985 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
5986 that name."
5987 (interactive)
5988 (browse-url-of-buffer
5989 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
5991 (defun markdown-export-file-name (&optional extension)
5992 "Attempt to generate a filename for Markdown output.
5993 The file extension will be EXTENSION if given, or .html by default.
5994 If the current buffer is visiting a file, we construct a new
5995 output filename based on that filename. Otherwise, return nil."
5996 (when (buffer-file-name)
5997 (unless extension
5998 (setq extension ".html"))
5999 (let ((candidate
6000 (concat
6001 (cond
6002 ((buffer-file-name)
6003 (file-name-sans-extension (buffer-file-name)))
6004 (t (buffer-name)))
6005 extension)))
6006 (cond
6007 ((equal candidate (buffer-file-name))
6008 (concat candidate extension))
6010 candidate)))))
6012 (defun markdown-export (&optional output-file)
6013 "Run Markdown on the current buffer, save to file, and return the filename.
6014 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
6015 generated by `markdown-export-file-name', which will be constructed using the
6016 current filename, but with the extension removed and replaced with .html."
6017 (interactive)
6018 (unless output-file
6019 (setq output-file (markdown-export-file-name ".html")))
6020 (when output-file
6021 (let* ((init-buf (current-buffer))
6022 (init-point (point))
6023 (init-buf-string (buffer-string))
6024 (output-buffer (find-file-noselect output-file))
6025 (output-buffer-name (buffer-name output-buffer)))
6026 (run-hooks 'markdown-before-export-hook)
6027 (markdown-standalone output-buffer-name)
6028 (with-current-buffer output-buffer
6029 (run-hooks 'markdown-after-export-hook)
6030 (save-buffer))
6031 ;; if modified, restore initial buffer
6032 (when (buffer-modified-p init-buf)
6033 (erase-buffer)
6034 (insert init-buf-string)
6035 (save-buffer)
6036 (goto-char init-point))
6037 output-file)))
6039 (defun markdown-export-and-preview ()
6040 "Export to XHTML using `markdown-export' and browse the resulting file."
6041 (interactive)
6042 (browse-url-of-file (markdown-export)))
6044 (defvar markdown-live-preview-buffer nil
6045 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
6046 (make-variable-buffer-local 'markdown-live-preview-buffer)
6048 (defvar markdown-live-preview-source-buffer nil
6049 "Source buffer from which current buffer was generated.
6050 This is the inverse of `markdown-live-preview-buffer'.")
6051 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
6053 (defvar markdown-live-preview-currently-exporting nil)
6055 (defun markdown-live-preview-get-filename ()
6056 "Standardize the filename exported by `markdown-live-preview-export'."
6057 (markdown-export-file-name ".html"))
6059 (defun markdown-live-preview-window-eww (file)
6060 "Preview FILE with eww.
6061 To be used with `markdown-live-preview-window-function'."
6062 (if (require 'eww nil t)
6063 (progn
6064 (eww-open-file file)
6065 (get-buffer "*eww*"))
6066 (error "EWW is not present or not loaded on this version of Emacs")))
6068 (defun markdown-visual-lines-between-points (beg end)
6069 (save-excursion
6070 (goto-char beg)
6071 (cl-loop with count = 0
6072 while (progn (end-of-visual-line)
6073 (and (< (point) end) (line-move-visual 1 t)))
6074 do (cl-incf count)
6075 finally return count)))
6077 (defun markdown-live-preview-window-serialize (buf)
6078 "Get window point and scroll data for all windows displaying BUF."
6079 (when (buffer-live-p buf)
6080 (with-current-buffer buf
6081 (mapcar
6082 (lambda (win)
6083 (with-selected-window win
6084 (let* ((start (window-start))
6085 (pt (window-point))
6086 (pt-or-sym (cond ((= pt (point-min)) 'min)
6087 ((= pt (point-max)) 'max)
6088 (t pt)))
6089 (diff (markdown-visual-lines-between-points
6090 start pt)))
6091 (list win pt-or-sym diff))))
6092 (get-buffer-window-list buf)))))
6094 (defun markdown-get-point-back-lines (pt num-lines)
6095 (save-excursion
6096 (goto-char pt)
6097 (line-move-visual (- num-lines) t)
6098 ;; in testing, can occasionally overshoot the number of lines to traverse
6099 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
6100 (when (> actual-num-lines num-lines)
6101 (line-move-visual (- actual-num-lines num-lines) t)))
6102 (point)))
6104 (defun markdown-live-preview-window-deserialize (window-posns)
6105 "Apply window point and scroll data from WINDOW-POSNS.
6106 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
6107 (cl-destructuring-bind (win pt-or-sym diff) window-posns
6108 (when (window-live-p win)
6109 (with-current-buffer markdown-live-preview-buffer
6110 (set-window-buffer win (current-buffer))
6111 (cl-destructuring-bind (actual-pt actual-diff)
6112 (cl-case pt-or-sym
6113 (min (list (point-min) 0))
6114 (max (list (point-max) diff))
6115 (t (list pt-or-sym diff)))
6116 (set-window-start
6117 win (markdown-get-point-back-lines actual-pt actual-diff))
6118 (set-window-point win actual-pt))))))
6120 (defun markdown-live-preview-export ()
6121 "Export to XHTML using `markdown-export'.
6122 Browse the resulting file within Emacs using
6123 `markdown-live-preview-window-function' Return the buffer
6124 displaying the rendered output."
6125 (interactive)
6126 (let* ((markdown-live-preview-currently-exporting t)
6127 (cur-buf (current-buffer))
6128 (export-file (markdown-export (markdown-live-preview-get-filename)))
6129 ;; get positions in all windows currently displaying output buffer
6130 (window-data
6131 (markdown-live-preview-window-serialize
6132 markdown-live-preview-buffer)))
6133 (save-window-excursion
6134 (let ((output-buffer
6135 (funcall markdown-live-preview-window-function export-file)))
6136 (with-current-buffer output-buffer
6137 (setq markdown-live-preview-source-buffer cur-buf)
6138 (add-hook 'kill-buffer-hook
6139 #'markdown-live-preview-remove-on-kill t t))
6140 (with-current-buffer cur-buf
6141 (setq markdown-live-preview-buffer output-buffer))))
6142 (with-current-buffer cur-buf
6143 ;; reset all windows displaying output buffer to where they were,
6144 ;; now with the new output
6145 (mapc #'markdown-live-preview-window-deserialize window-data)
6146 ;; delete html editing buffer
6147 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
6148 (when (and export-file (file-exists-p export-file)
6149 (eq markdown-live-preview-delete-export
6150 'delete-on-export))
6151 (delete-file export-file))
6152 markdown-live-preview-buffer)))
6154 (defun markdown-live-preview-remove ()
6155 (when (buffer-live-p markdown-live-preview-buffer)
6156 (kill-buffer markdown-live-preview-buffer))
6157 (setq markdown-live-preview-buffer nil)
6158 ;; if set to 'delete-on-export, the output has already been deleted
6159 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
6160 (let ((outfile-name (markdown-live-preview-get-filename)))
6161 (when (file-exists-p outfile-name)
6162 (delete-file outfile-name)))))
6164 (defun markdown-display-buffer-other-window (buf)
6165 (let ((cur-buf (current-buffer))
6166 split-width-threshold split-height-threshold)
6167 (cond ((memq markdown-split-window-direction '(vertical below))
6168 (setq split-width-threshold nil)
6169 (setq split-height-threshold 0))
6170 ((memq markdown-split-window-direction '(horizontal right))
6171 (setq split-width-threshold 0)
6172 (setq split-height-threshold nil)))
6173 (switch-to-buffer-other-window buf)
6174 (set-buffer cur-buf)))
6176 (defun markdown-live-preview-if-markdown ()
6177 (when (and (derived-mode-p 'markdown-mode)
6178 markdown-live-preview-mode)
6179 (unless markdown-live-preview-currently-exporting
6180 (if (buffer-live-p markdown-live-preview-buffer)
6181 (markdown-live-preview-export)
6182 (markdown-display-buffer-other-window
6183 (markdown-live-preview-export))))))
6185 (defun markdown-live-preview-remove-on-kill ()
6186 (cond ((and (derived-mode-p 'markdown-mode)
6187 markdown-live-preview-mode)
6188 (markdown-live-preview-remove))
6189 (markdown-live-preview-source-buffer
6190 (with-current-buffer markdown-live-preview-source-buffer
6191 (setq markdown-live-preview-buffer nil))
6192 (setq markdown-live-preview-source-buffer nil))))
6194 (defun markdown-live-preview-switch-to-output ()
6195 "Switch to output buffer."
6196 (interactive)
6197 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
6198 output buffer in another window."
6199 (if markdown-live-preview-mode
6200 (markdown-display-buffer-other-window (markdown-live-preview-export)))
6201 (markdown-live-preview-mode))
6203 (defun markdown-live-preview-re-export ()
6204 "Re export source buffer."
6205 (interactive)
6206 "If the current buffer is a buffer displaying the exported version of a
6207 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
6208 update this buffer's contents."
6209 (when markdown-live-preview-source-buffer
6210 (with-current-buffer markdown-live-preview-source-buffer
6211 (markdown-live-preview-export))))
6213 (defun markdown-open ()
6214 "Open file for the current buffer with `markdown-open-command'."
6215 (interactive)
6216 (if (not markdown-open-command)
6217 (error "Variable `markdown-open-command' must be set")
6218 (if (not buffer-file-name)
6219 (error "Must be visiting a file")
6220 (call-process markdown-open-command
6221 nil nil nil buffer-file-name))))
6223 (defun markdown-kill-ring-save ()
6224 "Run Markdown on file and store output in the kill ring."
6225 (interactive)
6226 (save-window-excursion
6227 (markdown)
6228 (with-current-buffer markdown-output-buffer-name
6229 (kill-ring-save (point-min) (point-max)))))
6232 ;;; Links =====================================================================
6234 (defun markdown-link-p ()
6235 "Return non-nil when `point' is at a non-wiki link.
6236 See `markdown-wiki-link-p' for more information."
6237 (let ((case-fold-search nil))
6238 (and (not (markdown-wiki-link-p))
6239 (not (markdown-code-block-at-point))
6240 (or (thing-at-point-looking-at markdown-regex-link-inline)
6241 (thing-at-point-looking-at markdown-regex-link-reference)
6242 (thing-at-point-looking-at markdown-regex-uri)
6243 (thing-at-point-looking-at markdown-regex-angle-uri)))))
6245 (defun markdown-link-link ()
6246 "Return the link part of the regular (non-wiki) link at point.
6247 Works with both inline and reference style links. If point is
6248 not at a link or the link reference is not defined returns nil."
6249 (cond
6250 ((thing-at-point-looking-at markdown-regex-link-inline)
6251 (match-string-no-properties 6))
6252 ((thing-at-point-looking-at markdown-regex-link-reference)
6253 (let* ((text (match-string-no-properties 3))
6254 (reference (match-string-no-properties 6))
6255 (target (downcase (if (string= reference "") text reference))))
6256 (car (markdown-reference-definition target))))
6257 ((thing-at-point-looking-at markdown-regex-uri)
6258 (match-string-no-properties 0))
6259 ((thing-at-point-looking-at markdown-regex-angle-uri)
6260 (match-string-no-properties 2))
6261 (t nil)))
6263 (defun markdown-follow-link-at-point ()
6264 "Open the current non-wiki link.
6265 If the link is a complete URL, open in browser with `browse-url'.
6266 Otherwise, open with `find-file' after stripping anchor and/or query string."
6267 (interactive)
6268 (if (markdown-link-p)
6269 (let* ((link (markdown-link-link))
6270 (struct (url-generic-parse-url link))
6271 (full (url-fullness struct))
6272 (file link))
6273 ;; Parse URL, determine fullness, strip query string
6274 (if (fboundp 'url-path-and-query)
6275 (setq file (car (url-path-and-query struct)))
6276 (when (and (setq file (url-filename struct))
6277 (string-match "\\?" file))
6278 (setq file (substring file 0 (match-beginning 0)))))
6279 ;; Open full URLs in browser, files in Emacs
6280 (if full
6281 (browse-url link)
6282 (when (and file (> (length file) 0)) (find-file file))))
6283 (error "Point is not at a Markdown link or URI")))
6286 ;;; WikiLink Following/Markup =================================================
6288 (defun markdown-wiki-link-p ()
6289 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
6290 A true wiki link name matches `markdown-regex-wiki-link' but does
6291 not match the current file name after conversion. This modifies
6292 the data returned by `match-data'. Note that the potential wiki
6293 link name must be available via `match-string'."
6294 (when markdown-enable-wiki-links
6295 (let ((case-fold-search nil))
6296 (and (thing-at-point-looking-at markdown-regex-wiki-link)
6297 (not (markdown-code-block-at-point))
6298 (or (not buffer-file-name)
6299 (not (string-equal (buffer-file-name)
6300 (markdown-convert-wiki-link-to-filename
6301 (markdown-wiki-link-link)))))))))
6303 (defun markdown-wiki-link-link ()
6304 "Return the link part of the wiki link using current match data.
6305 The location of the link component depends on the value of
6306 `markdown-wiki-link-alias-first'."
6307 (if markdown-wiki-link-alias-first
6308 (or (match-string-no-properties 5) (match-string-no-properties 3))
6309 (match-string-no-properties 3)))
6311 (defun markdown-wiki-link-alias ()
6312 "Return the alias or text part of the wiki link using current match data.
6313 The location of the alias component depends on the value of
6314 `markdown-wiki-link-alias-first'."
6315 (if markdown-wiki-link-alias-first
6316 (match-string-no-properties 3)
6317 (or (match-string-no-properties 5) (match-string-no-properties 3))))
6319 (defun markdown-convert-wiki-link-to-filename (name)
6320 "Generate a filename from the wiki link NAME.
6321 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
6322 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
6323 and [[test test]] both map to Test-test.ext. Look in the current
6324 directory first, then in subdirectories if
6325 `markdown-wiki-link-search-subdirectories' is non-nil, and then
6326 in parent directories if
6327 `markdown-wiki-link-search-parent-directories' is non-nil."
6328 (let* ((basename (markdown-replace-regexp-in-string
6329 "[[:space:]\n]" markdown-link-space-sub-char name))
6330 (basename (if (eq major-mode 'gfm-mode)
6331 (concat (upcase (substring basename 0 1))
6332 (downcase (substring basename 1 nil)))
6333 basename))
6334 directory extension default candidates dir)
6335 (when buffer-file-name
6336 (setq directory (file-name-directory buffer-file-name)
6337 extension (file-name-extension buffer-file-name)))
6338 (setq default (concat basename
6339 (when extension (concat "." extension))))
6340 (cond
6341 ;; Look in current directory first.
6342 ((or (null buffer-file-name)
6343 (file-exists-p default))
6344 default)
6345 ;; Possibly search in subdirectories, next.
6346 ((and markdown-wiki-link-search-subdirectories
6347 (setq candidates
6348 (markdown-directory-files-recursively
6349 directory (concat "^" default "$"))))
6350 (car candidates))
6351 ;; Possibly search in parent directories as a last resort.
6352 ((and markdown-wiki-link-search-parent-directories
6353 (setq dir (locate-dominating-file directory default)))
6354 (concat dir default))
6355 ;; If nothing is found, return default in current directory.
6356 (t default))))
6358 (defun markdown-follow-wiki-link (name &optional other)
6359 "Follow the wiki link NAME.
6360 Convert the name to a file name and call `find-file'. Ensure that
6361 the new buffer remains in `markdown-mode'. Open the link in another
6362 window when OTHER is non-nil."
6363 (let ((filename (markdown-convert-wiki-link-to-filename name))
6364 (wp (when buffer-file-name
6365 (file-name-directory buffer-file-name))))
6366 (if (not wp)
6367 (error "Must be visiting a file")
6368 (when other (other-window 1))
6369 (let ((default-directory wp))
6370 (find-file filename)))
6371 (when (not (eq major-mode 'markdown-mode))
6372 (markdown-mode))))
6374 (defun markdown-follow-wiki-link-at-point (&optional arg)
6375 "Find Wiki Link at point.
6376 With prefix argument ARG, open the file in other window.
6377 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
6378 (interactive "P")
6379 (if (markdown-wiki-link-p)
6380 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
6381 (error "Point is not at a Wiki Link")))
6383 (defun markdown-highlight-wiki-link (from to face)
6384 "Highlight the wiki link in the region between FROM and TO using FACE."
6385 (put-text-property from to 'font-lock-face face))
6387 (defun markdown-unfontify-region-wiki-links (from to)
6388 "Remove wiki link faces from the region specified by FROM and TO."
6389 (interactive "*r")
6390 (let ((modified (buffer-modified-p)))
6391 (remove-text-properties from to '(font-lock-face markdown-link-face))
6392 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
6393 ;; remove-text-properties marks the buffer modified in emacs 24.3,
6394 ;; undo that if it wasn't originally marked modified
6395 (set-buffer-modified-p modified)))
6397 (defun markdown-fontify-region-wiki-links (from to)
6398 "Search region given by FROM and TO for wiki links and fontify them.
6399 If a wiki link is found check to see if the backing file exists
6400 and highlight accordingly."
6401 (goto-char from)
6402 (save-match-data
6403 (while (re-search-forward markdown-regex-wiki-link to t)
6404 (when (not (markdown-code-block-at-point))
6405 (let ((highlight-beginning (match-beginning 1))
6406 (highlight-end (match-end 1))
6407 (file-name
6408 (markdown-convert-wiki-link-to-filename
6409 (markdown-wiki-link-link))))
6410 (if (condition-case nil (file-exists-p file-name) (error nil))
6411 (markdown-highlight-wiki-link
6412 highlight-beginning highlight-end markdown-link-face)
6413 (markdown-highlight-wiki-link
6414 highlight-beginning highlight-end markdown-missing-link-face)))))))
6416 (defun markdown-extend-changed-region (from to)
6417 "Extend region given by FROM and TO so that we can fontify all links.
6418 The region is extended to the first newline before and the first
6419 newline after."
6420 ;; start looking for the first new line before 'from
6421 (goto-char from)
6422 (re-search-backward "\n" nil t)
6423 (let ((new-from (point-min))
6424 (new-to (point-max)))
6425 (if (not (= (point) from))
6426 (setq new-from (point)))
6427 ;; do the same thing for the first new line after 'to
6428 (goto-char to)
6429 (re-search-forward "\n" nil t)
6430 (if (not (= (point) to))
6431 (setq new-to (point)))
6432 (cl-values new-from new-to)))
6434 (defun markdown-check-change-for-wiki-link (from to)
6435 "Check region between FROM and TO for wiki links and re-fontify as needed."
6436 (interactive "*r")
6437 (let* ((modified (buffer-modified-p))
6438 (buffer-undo-list t)
6439 (inhibit-read-only t)
6440 (inhibit-point-motion-hooks t)
6441 deactivate-mark
6442 buffer-file-truename)
6443 (unwind-protect
6444 (save-excursion
6445 (save-match-data
6446 (save-restriction
6447 ;; Extend the region to fontify so that it starts
6448 ;; and ends at safe places.
6449 (cl-multiple-value-bind (new-from new-to)
6450 (markdown-extend-changed-region from to)
6451 (goto-char new-from)
6452 ;; Only refontify when the range contains text with a
6453 ;; wiki link face or if the wiki link regexp matches.
6454 (when (or (markdown-range-property-any
6455 new-from new-to 'font-lock-face
6456 (list markdown-link-face
6457 markdown-missing-link-face))
6458 (re-search-forward
6459 markdown-regex-wiki-link new-to t))
6460 ;; Unfontify existing fontification (start from scratch)
6461 (markdown-unfontify-region-wiki-links new-from new-to)
6462 ;; Now do the fontification.
6463 (markdown-fontify-region-wiki-links new-from new-to))))))
6464 (and (not modified)
6465 (buffer-modified-p)
6466 (set-buffer-modified-p nil)))))
6468 (defun markdown-check-change-for-wiki-link-after-change (from to _)
6469 "Check region between FROM and TO for wiki links and re-fontify as needed.
6470 Designed to be used with the `after-change-functions' hook."
6471 (markdown-check-change-for-wiki-link from to))
6473 (defun markdown-fontify-buffer-wiki-links ()
6474 "Refontify all wiki links in the buffer."
6475 (interactive)
6476 (markdown-check-change-for-wiki-link (point-min) (point-max)))
6479 ;;; Following and Jumping =====================================================
6481 (defun markdown-follow-thing-at-point (arg)
6482 "Follow thing at point if possible, such as a reference link or wiki link.
6483 Opens inline and reference links in a browser. Opens wiki links
6484 to other files in the current window, or the another window if
6485 ARG is non-nil.
6486 See `markdown-follow-link-at-point' and
6487 `markdown-follow-wiki-link-at-point'."
6488 (interactive "P")
6489 (cond ((markdown-link-p)
6490 (markdown-follow-link-at-point))
6491 ((markdown-wiki-link-p)
6492 (markdown-follow-wiki-link-at-point arg))
6494 (error "Nothing to follow at point"))))
6496 (defun markdown-jump ()
6497 "Jump to another location based on context at point.
6498 Jumps between reference links and definitions; between footnote
6499 markers and footnote text."
6500 (interactive)
6501 (cond ((markdown-footnote-text-positions)
6502 (markdown-footnote-return))
6503 ((markdown-footnote-marker-positions)
6504 (markdown-footnote-goto-text))
6505 ((thing-at-point-looking-at markdown-regex-link-reference)
6506 (markdown-reference-goto-definition))
6507 ((thing-at-point-looking-at markdown-regex-reference-definition)
6508 (markdown-reference-goto-link (match-string-no-properties 2)))
6510 (error "Nothing to jump to from context at point"))))
6513 ;;; Miscellaneous =============================================================
6515 (defun markdown-compress-whitespace-string (str)
6516 "Compress whitespace in STR and return result.
6517 Leading and trailing whitespace is removed. Sequences of multiple
6518 spaces, tabs, and newlines are replaced with single spaces."
6519 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
6520 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
6522 (defun markdown-line-number-at-pos (&optional pos)
6523 "Return (narrowed) buffer line number at position POS.
6524 If POS is nil, use current buffer location.
6525 This is an exact copy of `line-number-at-pos' for use in emacs21."
6526 (let ((opoint (or pos (point))) start)
6527 (save-excursion
6528 (goto-char (point-min))
6529 (setq start (point))
6530 (goto-char opoint)
6531 (forward-line 0)
6532 (1+ (count-lines start (point))))))
6534 (defun markdown-inside-link-p ()
6535 "Return t if point is within a link."
6536 (save-match-data
6537 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
6539 (defun markdown-line-is-reference-definition-p ()
6540 "Return whether the current line is a (non-footnote) reference defition."
6541 (save-excursion
6542 (move-beginning-of-line 1)
6543 (and (looking-at-p markdown-regex-reference-definition)
6544 (not (looking-at-p "[ \t]*\\[^")))))
6546 (defun markdown-adaptive-fill-function ()
6547 "Return prefix for filling paragraph or nil if not determined."
6548 (cond
6549 ;; List item inside blockquote
6550 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
6551 (markdown-replace-regexp-in-string
6552 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
6553 ;; Blockquote
6554 ((looking-at "^[ \t]*>[ \t]*")
6555 (match-string-no-properties 0))
6556 ;; List items
6557 ((looking-at markdown-regex-list)
6558 (match-string-no-properties 0))
6559 ((looking-at-p markdown-regex-footnote-definition)
6560 " ") ; four spaces
6561 ;; No match
6562 (t nil)))
6564 (defun markdown-fill-paragraph (&optional justify)
6565 "Fill paragraph at or after point.
6566 This function is like \\[fill-paragraph], but it skips Markdown
6567 code blocks. If the point is in a code block, or just before one,
6568 do not fill. Otherwise, call `fill-paragraph' as usual. If
6569 JUSTIFY is non-nil, justify text as well. Since this function
6570 handles filling itself, it always returns t so that
6571 `fill-paragraph' doesn't run."
6572 (interactive "P")
6573 (unless (or (markdown-code-block-at-point-p)
6574 (save-excursion
6575 (back-to-indentation)
6576 (skip-syntax-forward "-")
6577 (markdown-code-block-at-point-p)))
6578 (fill-paragraph justify))
6581 (defun markdown-fill-forward-paragraph-function (&optional arg)
6582 "Function used by `fill-paragraph' to move over ARG paragraphs.
6583 This is a `fill-forward-paragraph-function' for `markdown-mode'.
6584 It is called with a single argument specifying the number of
6585 paragraphs to move. Just like `forward-paragraph', it should
6586 return the number of paragraphs left to move."
6587 (let* ((arg (or arg 1))
6588 (paragraphs-remaining (forward-paragraph arg))
6589 (start (point)))
6590 (when (< arg 0)
6591 (while (and (not (eobp))
6592 (progn (move-to-left-margin) (not (eobp)))
6593 (looking-at-p paragraph-separate))
6594 (forward-line 1))
6595 (if (looking-at markdown-regex-list)
6596 (forward-char (length (match-string 0)))
6597 (goto-char start)))
6598 paragraphs-remaining))
6601 ;;; Extension Framework =======================================================
6603 (defun markdown-reload-extensions ()
6604 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
6605 (interactive)
6606 (when (eq major-mode 'markdown-mode)
6607 ;; Update font lock keywords with extensions
6608 (setq markdown-mode-font-lock-keywords
6609 (append
6610 (markdown-mode-font-lock-keywords-math)
6611 markdown-mode-font-lock-keywords-basic
6612 (markdown-mode-font-lock-keywords-wiki-links)))
6613 ;; Update font lock defaults
6614 (setq font-lock-defaults
6615 '(markdown-mode-font-lock-keywords
6616 nil nil nil nil
6617 (font-lock-syntactic-face-function . markdown-syntactic-face)))
6618 ;; Refontify buffer
6619 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
6620 (font-lock-refresh-defaults))
6622 ;; Add or remove hooks related to extensions
6623 (markdown-setup-wiki-link-hooks)))
6625 (defun markdown-handle-local-variables ()
6626 "Run in `hack-local-variables-hook' to update font lock rules.
6627 Checks to see if there is actually a ‘markdown-mode’ file local variable
6628 before regenerating font-lock rules for extensions."
6629 (when (and (boundp 'file-local-variables-alist)
6630 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
6631 (assoc 'markdown-enable-math file-local-variables-alist))
6632 (markdown-reload-extensions)))
6635 ;;; Wiki Links ================================================================
6637 (defun markdown-toggle-wiki-links (&optional arg)
6638 "Toggle support for wiki links.
6639 With a prefix argument ARG, enable wiki link support if ARG is positive,
6640 and disable it otherwise."
6641 (interactive (list (or current-prefix-arg 'toggle)))
6642 (setq markdown-enable-wiki-links
6643 (if (eq arg 'toggle)
6644 (not markdown-enable-wiki-links)
6645 (> (prefix-numeric-value arg) 0)))
6646 (if markdown-enable-wiki-links
6647 (message "markdown-mode wiki link support enabled")
6648 (message "markdown-mode wiki link support disabled"))
6649 (markdown-reload-extensions))
6651 (defun markdown-setup-wiki-link-hooks ()
6652 "Add or remove hooks for fontifying wiki links.
6653 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
6654 ;; Anytime text changes make sure it gets fontified correctly
6655 (if (and markdown-enable-wiki-links
6656 markdown-wiki-link-fontify-missing)
6657 (add-hook 'after-change-functions
6658 'markdown-check-change-for-wiki-link-after-change t t)
6659 (remove-hook 'after-change-functions
6660 'markdown-check-change-for-wiki-link-after-change t))
6661 ;; If we left the buffer there is a really good chance we were
6662 ;; creating one of the wiki link documents. Make sure we get
6663 ;; refontified when we come back.
6664 (if (and markdown-enable-wiki-links
6665 markdown-wiki-link-fontify-missing)
6666 (progn
6667 (add-hook 'window-configuration-change-hook
6668 'markdown-fontify-buffer-wiki-links t t)
6669 (markdown-fontify-buffer-wiki-links))
6670 (remove-hook 'window-configuration-change-hook
6671 'markdown-fontify-buffer-wiki-links t)
6672 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
6674 (defun markdown-mode-font-lock-keywords-wiki-links ()
6675 "Return wiki-link lock keywords if support is enabled.
6676 If `markdown-wiki-link-fontify-missing' is also enabled, we use
6677 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
6678 (when (and markdown-enable-wiki-links
6679 (not markdown-wiki-link-fontify-missing))
6680 (list
6681 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
6684 ;;; Math Support ==============================================================
6686 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
6688 (defun markdown-toggle-math (&optional arg)
6689 "Toggle support for inline and display LaTeX math expressions.
6690 With a prefix argument ARG, enable math mode if ARG is positive,
6691 and disable it otherwise. If called from Lisp, enable the mode
6692 if ARG is omitted or nil."
6693 (interactive (list (or current-prefix-arg 'toggle)))
6694 (setq markdown-enable-math
6695 (if (eq arg 'toggle)
6696 (not markdown-enable-math)
6697 (> (prefix-numeric-value arg) 0)))
6698 (if markdown-enable-math
6699 (message "markdown-mode math support enabled")
6700 (message "markdown-mode math support disabled"))
6701 (markdown-reload-extensions))
6703 (defun markdown-mode-font-lock-keywords-math ()
6704 "Return math font lock keywords if support is enabled."
6705 (when markdown-enable-math
6706 (list
6707 ;; Display mode equations with brackets: \[ \]
6708 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
6709 (2 markdown-math-face append)
6710 (3 markdown-markup-face prepend)))
6711 ;; Equation reference (eq:foo)
6712 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
6713 (2 markdown-reference-face)
6714 (3 markdown-markup-face)))
6715 ;; Equation reference \eqref{foo}
6716 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
6717 (2 markdown-reference-face)
6718 (3 markdown-markup-face))))))
6721 ;;; GFM Checkboxes ============================================================
6723 (require 'button)
6725 (define-button-type 'markdown-gfm-checkbox-button
6726 'follow-link t
6727 'face 'markdown-gfm-checkbox-face
6728 'mouse-face 'markdown-highlight-face
6729 'action #'markdown-toggle-gfm-checkbox-button)
6731 (defun markdown-toggle-gfm-checkbox ()
6732 "Toggle GFM checkbox at point."
6733 (interactive)
6734 (save-match-data
6735 (save-excursion
6736 (let ((bounds (markdown-cur-list-item-bounds)))
6737 (when bounds
6738 ;; Move to beginning of task list item
6739 (goto-char (cl-first bounds))
6740 ;; Advance to column of first non-whitespace after marker
6741 (forward-char (cl-fourth bounds))
6742 (cond ((looking-at "\\[ \\]")
6743 (replace-match "[x]" nil t))
6744 ((looking-at "\\[[xX]\\]")
6745 (replace-match "[ ]" nil t))))))))
6747 (defun markdown-toggle-gfm-checkbox-button (button)
6748 "Toggle GFM checkbox BUTTON on click."
6749 (save-match-data
6750 (save-excursion
6751 (goto-char (button-start button))
6752 (markdown-toggle-gfm-checkbox))))
6754 (defun markdown-make-gfm-checkboxes-buttons (start end)
6755 "Make GFM checkboxes buttons in region between START and END."
6756 (save-excursion
6757 (goto-char start)
6758 (let ((case-fold-search t))
6759 (save-excursion
6760 (while (re-search-forward markdown-regex-gfm-checkbox end t)
6761 (make-button (match-beginning 1) (match-end 1)
6762 :type 'markdown-gfm-checkbox-button))))))
6764 ;; Called when any modification is made to buffer text.
6765 (defun markdown-gfm-checkbox-after-change-function (beg end _)
6766 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
6767 BEG and END are the limits of scanned region."
6768 (save-excursion
6769 (save-match-data
6770 ;; Rescan between start of line from `beg' and start of line after `end'.
6771 (markdown-make-gfm-checkboxes-buttons
6772 (progn (goto-char beg) (beginning-of-line) (point))
6773 (progn (goto-char end) (forward-line 1) (point))))))
6776 ;;; Display inline image =================================================
6778 (defvar markdown-inline-image-overlays nil)
6779 (make-variable-buffer-local 'markdown-inline-image-overlays)
6781 (defun markdown-remove-inline-images ()
6782 "Remove inline image overlays from image links in the buffer.
6783 This can be toggled with `markdown-toggle-inline-images'
6784 or \\[markdown-toggle-inline-images]."
6785 (interactive)
6786 (mapc #'delete-overlay markdown-inline-image-overlays)
6787 (setq markdown-inline-image-overlays nil))
6789 (defun markdown-display-inline-images ()
6790 "Add inline image overlays to image links in the buffer.
6791 This can be toggled with `markdown-toggle-inline-images'
6792 or \\[markdown-toggle-inline-images]."
6793 (interactive)
6794 (unless (display-graphic-p)
6795 (error "Cannot show images"))
6796 (save-excursion
6797 (save-restriction
6798 (widen)
6799 (goto-char (point-min))
6800 (while (re-search-forward markdown-regex-link-inline nil t)
6801 (let ((start (match-beginning 0))
6802 (end (match-end 0))
6803 (file (match-string-no-properties 6)))
6804 (when (file-exists-p file)
6805 (let* ((abspath (if (file-name-absolute-p file)
6806 file
6807 (concat default-directory file)))
6808 (image (create-image abspath)))
6809 (when image
6810 (let ((ov (make-overlay start end)))
6811 (overlay-put ov 'display image)
6812 (overlay-put ov 'face 'default)
6813 (push ov markdown-inline-image-overlays))))))))))
6815 (defun markdown-toggle-inline-images ()
6816 "Toggle inline image overlays in the buffer."
6817 (interactive)
6818 (if markdown-inline-image-overlays
6819 (markdown-remove-inline-images)
6820 (markdown-display-inline-images)))
6823 ;;; Mode Definition ==========================================================
6825 (defun markdown-show-version ()
6826 "Show the version number in the minibuffer."
6827 (interactive)
6828 (message "markdown-mode, version %s" markdown-mode-version))
6830 (defun markdown-mode-info ()
6831 "Open the `markdown-mode' homepage."
6832 (interactive)
6833 (browse-url "http://jblevins.org/projects/markdown-mode/"))
6835 ;;;###autoload
6836 (define-derived-mode markdown-mode text-mode "Markdown"
6837 "Major mode for editing Markdown files."
6838 ;; Natural Markdown tab width
6839 (setq tab-width 4)
6840 ;; Comments
6841 (make-local-variable 'comment-start)
6842 (setq comment-start "<!-- ")
6843 (make-local-variable 'comment-end)
6844 (setq comment-end " -->")
6845 (make-local-variable 'comment-start-skip)
6846 (setq comment-start-skip "<!--[ \t]*")
6847 (make-local-variable 'comment-column)
6848 (setq comment-column 0)
6849 (set (make-local-variable 'comment-auto-fill-only-comments) nil)
6850 ;; Syntax
6851 (add-hook 'syntax-propertize-extend-region-functions
6852 'markdown-syntax-propertize-extend-region)
6853 (add-hook 'jit-lock-after-change-extend-region-functions
6854 'markdown-font-lock-extend-region-function t t)
6855 (set (make-local-variable 'syntax-propertize-function)
6856 'markdown-syntax-propertize)
6857 ;; Font lock.
6858 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
6859 (set (make-local-variable 'font-lock-defaults) nil)
6860 (set (make-local-variable 'font-lock-multiline) t)
6861 ;; Extensions
6862 (make-local-variable 'markdown-enable-math)
6863 ;; Reload extensions
6864 (markdown-reload-extensions)
6865 ;; Add a buffer-local hook to reload after file-local variables are read
6866 (add-hook 'hack-local-variables-hook 'markdown-handle-local-variables nil t)
6867 ;; For imenu support
6868 (setq imenu-create-index-function
6869 (if markdown-nested-imenu-heading-index
6870 'markdown-imenu-create-nested-index
6871 'markdown-imenu-create-flat-index))
6872 ;; For menu support in XEmacs
6873 (easy-menu-add markdown-mode-menu markdown-mode-map)
6874 ;; Defun movement
6875 (set (make-local-variable 'beginning-of-defun-function)
6876 'markdown-beginning-of-defun)
6877 (set (make-local-variable 'end-of-defun-function)
6878 'markdown-end-of-defun)
6879 ;; Paragraph filling
6880 (set (make-local-variable 'fill-paragraph-function)
6881 'markdown-fill-paragraph)
6882 (set
6883 ;; Should match start of lines that start or separate paragraphs
6884 (make-local-variable 'paragraph-start)
6885 (mapconcat #'identity
6887 "\f" ; starts with a literal line-feed
6888 "[ \t\f]*$" ; space-only line
6889 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6890 "[ \t]*[*+-][ \t]+" ; unordered list item
6891 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
6892 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
6893 "[ \t]*:[ \t]+" ; definition
6895 "\\|"))
6896 (set
6897 ;; Should match lines that separate paragraphs without being
6898 ;; part of any paragraph:
6899 (make-local-variable 'paragraph-separate)
6900 (mapconcat #'identity
6901 '("[ \t\f]*$" ; space-only line
6902 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
6903 ;; The following is not ideal, but the Fill customization
6904 ;; options really only handle paragraph-starting prefixes,
6905 ;; not paragraph-ending suffixes:
6906 ".* $" ; line ending in two spaces
6907 "^#+"
6908 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
6909 "\\|"))
6910 (set (make-local-variable 'adaptive-fill-first-line-regexp)
6911 "\\`[ \t]*>[ \t]*?\\'")
6912 (set (make-local-variable 'adaptive-fill-regexp) "\\s-*")
6913 (set (make-local-variable 'adaptive-fill-function)
6914 'markdown-adaptive-fill-function)
6915 (set (make-local-variable 'fill-forward-paragraph-function)
6916 'markdown-fill-forward-paragraph-function)
6917 ;; Outline mode
6918 (make-local-variable 'outline-regexp)
6919 (setq outline-regexp markdown-regex-header)
6920 (make-local-variable 'outline-level)
6921 (setq outline-level 'markdown-outline-level)
6922 ;; Cause use of ellipses for invisible text.
6923 (add-to-invisibility-spec '(outline . t))
6925 ;; Inhibiting line-breaking:
6926 ;; Separating out each condition into a separate function so that users can
6927 ;; override if desired (with remove-hook)
6928 (add-hook 'fill-nobreak-predicate
6929 'markdown-inside-link-p nil t)
6930 (add-hook 'fill-nobreak-predicate
6931 'markdown-line-is-reference-definition-p nil t)
6933 ;; Indentation
6934 (setq indent-line-function markdown-indent-function)
6936 ;; Backwards compatibility with markdown-css-path
6937 (when (boundp 'markdown-css-path)
6938 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
6939 (add-to-list 'markdown-css-paths markdown-css-path))
6941 ;; Prepare hooks for XEmacs compatibility
6942 (when (featurep 'xemacs)
6943 (make-local-hook 'after-change-functions)
6944 (make-local-hook 'font-lock-extend-region-functions)
6945 (make-local-hook 'window-configuration-change-hook))
6947 ;; Make checkboxes buttons
6948 (when markdown-make-gfm-checkboxes-buttons
6949 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
6950 (add-hook 'after-change-functions 'markdown-gfm-checkbox-after-change-function t t))
6952 ;; add live preview export hook
6953 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
6954 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
6956 ;;;###autoload
6957 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
6958 ;;;###autoload
6959 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
6962 ;;; GitHub Flavored Markdown Mode ============================================
6964 (defvar gfm-mode-hook nil
6965 "Hook run when entering GFM mode.")
6967 (defvar gfm-font-lock-keywords
6968 (append
6969 ;; GFM features to match first
6970 (list
6971 (cons markdown-regex-strike-through '((3 markdown-markup-face)
6972 (4 markdown-strike-through-face)
6973 (5 markdown-markup-face))))
6974 ;; Basic Markdown features (excluding possibly overridden ones)
6975 markdown-mode-font-lock-keywords-basic)
6976 "Default highlighting expressions for GitHub Flavored Markdown mode.")
6978 ;;;###autoload
6979 (define-derived-mode gfm-mode markdown-mode "GFM"
6980 "Major mode for editing GitHub Flavored Markdown files."
6981 (setq markdown-link-space-sub-char "-")
6982 (setq markdown-wiki-link-search-subdirectories t)
6983 (set (make-local-variable 'font-lock-defaults)
6984 '(gfm-font-lock-keywords))
6985 ;; do the initial link fontification
6986 (markdown-gfm-parse-buffer-for-languages))
6989 ;;; Live Preview Mode ============================================
6990 (define-minor-mode markdown-live-preview-mode
6991 "Toggle native previewing on save for a specific markdown file."
6992 :lighter " MD-Preview"
6993 (if markdown-live-preview-mode
6994 (markdown-display-buffer-other-window (markdown-live-preview-export))
6995 (markdown-live-preview-remove)))
6998 (provide 'markdown-mode)
6999 ;; Local Variables:
7000 ;; indent-tabs-mode: nil
7001 ;; End:
7002 ;;; markdown-mode.el ends here