Use math mode toggle function when enabling via file variables
[markdown-mode.git] / markdown-mode.el
blob881013cc7f46ebcf7d29723eb71c2acf854bd2af
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 <jblevins@xbeta.org>
7 ;; Maintainer: Jason R. Blevins <jblevins@xbeta.org>
8 ;; Created: May 24, 2007
9 ;; Version: 2.4-dev
10 ;; Package-Requires: ((emacs "24") (cl-lib "0.5"))
11 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
12 ;; URL: https://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 3 of the License, or
19 ;; (at your option) 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, see <http://www.gnu.org/licenses/>.
29 ;;; Commentary:
31 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
32 ;; text. The latest stable version is markdown-mode 2.3, released on
33 ;; August 31, 2017. See the [release notes][] for details.
34 ;; markdown-mode is free software, licensed under the GNU GPL,
35 ;; version 3 or later.
37 ;; ![Markdown Mode Screenshot](https://jblevins.org/projects/markdown-mode/screenshots/20170818-001.png)
39 ;; [Markdown]: http://daringfireball.net/projects/markdown/
40 ;; [release notes]: https://jblevins.org/projects/markdown-mode/rev-2-3
42 ;;; Documentation:
44 ;; <a href="https://leanpub.com/markdown-mode">
45 ;; <img src="https://jblevins.org/projects/markdown-mode/guide-v2.3.png" align="right" height="350" width="231">
46 ;; </a>
48 ;; The primary documentation for Markdown Mode is available below, and
49 ;; is generated from comments in the source code. For a more in-depth
50 ;; treatment, the [_Guide to Markdown Mode for Emacs_][guide] covers
51 ;; Markdown syntax, advanced movement and editing in Emacs,
52 ;; extensions, configuration examples, tips and tricks, and a survey
53 ;; of other packages that work with Markdown Mode. Finally, Emacs is
54 ;; also a self-documenting editor. This means that the source code
55 ;; itself contains additional documentation: each function has its own
56 ;; docstring available via `C-h f` (`describe-function'), individual
57 ;; keybindings can be investigated with `C-h k` (`describe-key'), and
58 ;; a complete list of keybindings is available using `C-h m`
59 ;; (`describe-mode').
61 ;; [guide]: https://leanpub.com/markdown-mode
63 ;;; Installation:
65 ;; _Note:_ To use all of the features of `markdown-mode', you'll need
66 ;; to install the Emacs package itself and also have a local Markdown
67 ;; processor installed (e.g., Markdown.pl, MultiMarkdown, or Pandoc).
68 ;; The external processor is not required for editing, but will be
69 ;; used for rendering HTML for preview and export. After installing
70 ;; the Emacs package, be sure to configure `markdown-command' to point
71 ;; to the preferred Markdown executable on your system. See the
72 ;; Customization section below for more details.
74 ;; The recommended way to install `markdown-mode' is to install the package
75 ;; from [MELPA Stable](https://stable.melpa.org/#/markdown-mode)
76 ;; using `package.el'. First, configure `package.el' and the MELPA Stable
77 ;; repository by adding the following to your `.emacs', `init.el',
78 ;; or equivalent startup file:
80 ;; ``` Lisp
81 ;; (require 'package)
82 ;; (add-to-list 'package-archives
83 ;; '("melpa-stable" . "https://stable.melpa.org/packages/"))
84 ;; (package-initialize)
85 ;; ```
87 ;; Then, after restarting Emacs or evaluating the above statements, issue
88 ;; the following command: `M-x package-install RET markdown-mode RET`.
89 ;; When installed this way, the major modes `markdown-mode' and `gfm-mode'
90 ;; will be autoloaded and `markdown-mode' will be used for file names
91 ;; ending in either `.md` or `.markdown`.
93 ;; Alternatively, if you manage loading packages with [use-package][]
94 ;; then you can automatically install and configure `markdown-mode' by
95 ;; adding a declaration such as this one to your init file (as an
96 ;; example; adjust settings as desired):
98 ;; ``` Lisp
99 ;; (use-package markdown-mode
100 ;; :ensure t
101 ;; :commands (markdown-mode gfm-mode)
102 ;; :mode (("README\\.md\\'" . gfm-mode)
103 ;; ("\\.md\\'" . markdown-mode)
104 ;; ("\\.markdown\\'" . markdown-mode))
105 ;; :init (setq markdown-command "multimarkdown"))
106 ;; ```
108 ;; [MELPA Stable]: http://stable.melpa.org/
109 ;; [use-package]: https://github.com/jwiegley/use-package
111 ;; **Direct Download**
113 ;; Alternatively you can manually download and install markdown-mode.
114 ;; First, download the [latest stable version][markdown-mode.el] and
115 ;; save the file where Emacs can find it (i.e., a directory in your
116 ;; `load-path'). You can then configure `markdown-mode' and `gfm-mode'
117 ;; to load automatically by adding the following to your init file:
119 ;; ``` Lisp
120 ;; (autoload 'markdown-mode "markdown-mode"
121 ;; "Major mode for editing Markdown files" t)
122 ;; (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode))
123 ;; (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
125 ;; (autoload 'gfm-mode "markdown-mode"
126 ;; "Major mode for editing GitHub Flavored Markdown files" t)
127 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
128 ;; ```
130 ;; [markdown-mode.el]: https://jblevins.org/projects/markdown-mode/markdown-mode.el
132 ;; **Development Version**
134 ;; To follow or contribute to markdown-mode development, you can
135 ;; browse or clone the Git repository
136 ;; [on GitHub](https://github.com/jrblevin/markdown-mode):
138 ;; ```
139 ;; git clone https://github.com/jrblevin/markdown-mode.git
140 ;; ```
142 ;; If you prefer to install and use the development version, which may
143 ;; become unstable at some times, you can either clone the Git
144 ;; repository as above or install markdown-mode from
145 ;; [MELPA](https://melpa.org/#/markdown-mode).
147 ;; If you clone the repository directly, then make sure that Emacs can
148 ;; find it by adding the following line to your startup file:
150 ;; ``` Lisp
151 ;; (add-to-list 'load-path "/path/to/markdown-mode/repository")
152 ;; ```
154 ;; **Packaged Installation**
156 ;; markdown-mode is also available in several package managers. You
157 ;; may want to confirm that the package you install contains the
158 ;; latest stable version first (and please notify the package
159 ;; maintainer if not).
161 ;; * Debian Linux: [elpa-markdown-mode][] and [emacs-goodies-el][]
162 ;; * Ubuntu Linux: [elpa-markdown-mode][elpa-ubuntu] and [emacs-goodies-el][emacs-goodies-el-ubuntu]
163 ;; * RedHat and Fedora Linux: [emacs-goodies][]
164 ;; * NetBSD: [textproc/markdown-mode][]
165 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
166 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
168 ;; [elpa-markdown-mode]: https://packages.debian.org/sid/lisp/elpa-markdown-mode
169 ;; [elpa-ubuntu]: http://packages.ubuntu.com/search?keywords=elpa-markdown-mode
170 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
171 ;; [emacs-goodies-el-ubuntu]: http://packages.ubuntu.com/search?keywords=emacs-goodies-el
172 ;; [emacs-goodies]: https://apps.fedoraproject.org/packages/emacs-goodies
173 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
174 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
175 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
176 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
178 ;; **Dependencies**
180 ;; To enable editing of code blocks in indirect buffers using `C-c '`,
181 ;; you will need to install the [`edit-indirect'][ei] package.
183 ;; [ei]: https://github.com/Fanael/edit-indirect/
185 ;;; Usage:
187 ;; Keybindings are grouped by prefixes based on their function. For
188 ;; example, the commands for styling text are grouped under `C-c C-s`
189 ;; and toggle commands begin with `C-c C-x`. The primary commands in
190 ;; each group will are described below. You can obtain a list of all
191 ;; keybindings by pressing `C-c C-h`. Movement and shifting commands
192 ;; tend to be associated with paired delimiters such as `M-{` and
193 ;; `M-}` or `C-c <` and `C-c >`. Outline navigation keybindings the
194 ;; same as in `org-mode'. Finally, commands for running Markdown or
195 ;; doing maintenance on an open file are grouped under the `C-c C-c`
196 ;; prefix. The most commonly used commands are described below. You
197 ;; can obtain a list of all keybindings by pressing `C-c C-h`.
199 ;; * Links and Images: `C-c C-l` and `C-c C-i`
201 ;; `C-c C-l` (`markdown-insert-link`) is a general command for
202 ;; inserting new link markup or editing existing link markup. This
203 ;; is especially useful when markup or URL hiding is enabled, so
204 ;; that URLs can't easily be edited directly. This command can be
205 ;; used to insert links of any form: either inline links,
206 ;; reference links, or plain URLs in angle brackets. The URL or
207 ;; `[reference]` label, link text, and optional title are entered
208 ;; through a series of interactive prompts. The type of link is
209 ;; determined by which values are provided:
211 ;; * If both a URL and link text are given, insert an inline link:
212 ;; `[text](url)`.
213 ;; * If both a `[reference]` label and link text are given, insert
214 ;; a reference link: `[text][reference]`.
215 ;; * If only link text is given, insert an implicit reference link:
216 ;; `[text][]`.
217 ;; * If only a URL is given, insert a plain URL link:
218 ;; `<url>`.
220 ;; Similarly, `C-c C-i` (`markdown-insert-image`) is a general
221 ;; command for inserting or editing image markup. As with the link
222 ;; insertion command, through a series interactive prompts you can
223 ;; insert either an inline or reference image:
225 ;; * If both a URL and alt text are given, insert an inline
226 ;; image: `![alt text](url)`.
227 ;; * If both a `[reference]` label and alt text are given,
228 ;; insert a reference link: `![alt text][reference]`.
230 ;; If there is an existing link or image at the point, these
231 ;; command will edit the existing markup rather than inserting new
232 ;; markup. Otherwise, if there is an active region, these commands
233 ;; use the region as either the default URL (if it seems to be a
234 ;; URL) or link text value otherwise. In that case, the region
235 ;; will be deleted and replaced by the link.
237 ;; Note that these functions can be used to convert links and
238 ;; images from one type to another (inline, reference, or plain
239 ;; URL) by selectively adding or removing properties via the
240 ;; interactive prompts.
242 ;; If a reference label is given that is not yet defined, you
243 ;; will be prompted for the URL and optional title and the
244 ;; reference will be inserted according to the value of
245 ;; `markdown-reference-location'. If a title is given, it will be
246 ;; added to the end of the reference definition and will be used
247 ;; to populate the title attribute when converted to HTML.
249 ;; Local images associated with image links may be displayed
250 ;; inline in the buffer by pressing `C-c C-x C-i`
251 ;; (`markdown-toggle-inline-images'). This is a toggle command, so
252 ;; pressing this once again will remove inline images.
254 ;; * Text Styles: `C-c C-s`
256 ;; `C-c C-s i` inserts markup to make a region or word italic. If
257 ;; there is an active region, make the region italic. If the point
258 ;; is at a non-italic word, make the word italic. If the point is
259 ;; at an italic word or phrase, remove the italic markup.
260 ;; Otherwise, simply insert italic delimiters and place the cursor
261 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
262 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
264 ;; `C-c C-s q` inserts a blockquote using the active region, if
265 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
266 ;; which always operates on the region, regardless of whether it
267 ;; is active or not (i.e., when `transient-mark-mode` is off but
268 ;; the mark is set). The appropriate amount of indentation, if
269 ;; any, is calculated automatically given the surrounding context,
270 ;; but may be adjusted later using the region indentation
271 ;; commands.
273 ;; `C-c C-s p` behaves similarly for inserting preformatted code
274 ;; blocks (with `C-c C-s P` being the region-only counterpart)
275 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
277 ;; * Headings: `C-c C-s`
279 ;; To insert or replace headings, there are two options. You can
280 ;; insert a specific level heading directly or you can have
281 ;; `markdown-mode' determine the level for you based on the previous
282 ;; heading. As with the other markup commands, the heading
283 ;; insertion commands use the text in the active region, if any,
284 ;; as the heading text. Otherwise, if the current line is not
285 ;; blank, they use the text on the current line. Finally, the
286 ;; setext commands will prompt for heading text if there is no
287 ;; active region and the current line is blank.
289 ;; `C-c C-s h` inserts a heading with automatically chosen type and
290 ;; level (both determined by the previous heading). `C-c C-s H`
291 ;; behaves similarly, but uses setext (underlined) headings when
292 ;; possible, still calculating the level automatically.
293 ;; In cases where the automatically-determined level is not what
294 ;; you intended, the level can be quickly promoted or demoted
295 ;; (as described below). Alternatively, a `C-u` prefix can be
296 ;; given to insert a heading _promoted_ (lower number) by one
297 ;; level or a `C-u C-u` prefix can be given to insert a heading
298 ;; demoted (higher number) by one level.
300 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
301 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
302 ;; `C-c C-s @` for setext headings of level one or two, respectively.
303 ;; Note that `!` is `S-1` and `@` is `S-2`.
305 ;; If the point is at a heading, these commands will replace the
306 ;; existing markup in order to update the level and/or type of the
307 ;; heading. To remove the markup of the heading at the point,
308 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
309 ;; heading text back into the buffer.
311 ;; * Horizontal Rules: `C-c C-s -`
313 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
314 ;; first string in the list `markdown-hr-strings' (the most
315 ;; prominent rule). With a `C-u` prefix, insert the last string.
316 ;; With a numeric prefix `N`, insert the string in position `N`
317 ;; (counting from 1).
319 ;; * Footnotes: `C-c C-s f`
321 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
322 ;; footnote definition below, and positions the point for
323 ;; inserting the footnote text. Note that footnotes are an
324 ;; extension to Markdown and are not supported by all processors.
326 ;; * Wiki Links: `C-c C-s w`
328 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
329 ;; there is an active region, use the region as the link text. If the
330 ;; point is at a word, use the word as the link text. If there is
331 ;; no active region and the point is not at word, simply insert
332 ;; link markup. Note that wiki links are an extension to Markdown
333 ;; and are not supported by all processors.
335 ;; * Markdown and Maintenance Commands: `C-c C-c`
337 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
338 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
339 ;; runs Markdown on the current buffer and previews, stores the
340 ;; output in a temporary file, and displays the file in a browser.
341 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
342 ;; and save the result in the file `basename.html`, where
343 ;; `basename` is the name of the Markdown file with the extension
344 ;; removed. *Export and View:* press `C-c C-c v` to export the
345 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
346 ;; the Markdown source file directly using `markdown-open-command'.
347 ;; *Live Export*: Press `C-c C-c l` to turn on
348 ;; `markdown-live-preview-mode' to view the exported output
349 ;; side-by-side with the source Markdown. **For all export commands,
350 ;; the output file will be overwritten without notice.**
351 ;; `markdown-live-preview-window-function' can be customized to open
352 ;; in a browser other than `eww'. If you want to force the
353 ;; preview window to appear at the bottom or right, you can
354 ;; customize `markdown-split-window-direction'.
356 ;; To summarize:
358 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
359 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
360 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
361 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
362 ;; - `C-c C-c w`: `markdown-command' > kill ring.
363 ;; - `C-c C-c o`: `markdown-open-command'.
364 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
366 ;; `C-c C-c c` will check for undefined references. If there are
367 ;; any, a small buffer will open with a list of undefined
368 ;; references and the line numbers on which they appear. In Emacs
369 ;; 22 and greater, selecting a reference from this list and
370 ;; pressing `RET` will insert an empty reference definition at the
371 ;; end of the buffer. Similarly, selecting the line number will
372 ;; jump to the corresponding line.
374 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
375 ;; out of sequence.
377 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
378 ;; rules in the buffer.
380 ;; * Following Links: `C-c C-o`
382 ;; Press `C-c C-o` when the point is on an inline or reference
383 ;; link to open the URL in a browser. When the point is at a
384 ;; wiki link, open it in another buffer (in the current window,
385 ;; or in the other window with the `C-u` prefix). Use `M-p` and
386 ;; `M-n` to quickly jump to the previous or next link of any type.
388 ;; * Doing Things: `C-c C-d`
390 ;; Use `C-c C-d` to do something sensible with the object at the point:
392 ;; - Jumps between reference links and reference definitions.
393 ;; If more than one link uses the same reference label, a
394 ;; window will be shown containing clickable buttons for
395 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
396 ;; between buttons in this window.
397 ;; - Jumps between footnote markers and footnote text.
398 ;; - Toggles the completion status of GFM task list items
399 ;; (checkboxes).
400 ;; - Re-aligns table columns.
402 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
404 ;; Headings, horizontal rules, and list items can be promoted and
405 ;; demoted, as well as bold and italic text. For headings,
406 ;; "promotion" means *decreasing* the level (i.e., moving from
407 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
408 ;; level. For horizontal rules, promotion and demotion means
409 ;; moving backward or forward through the list of rule strings in
410 ;; `markdown-hr-strings'. For bold and italic text, promotion and
411 ;; demotion means changing the markup from underscores to asterisks.
412 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
413 ;; if possible.
415 ;; To remember these commands, note that `-` is for decreasing the
416 ;; level (promoting), and `=` (on the same key as `+`) is for
417 ;; increasing the level (demoting). Similarly, the left and right
418 ;; arrow keys indicate the direction that the atx heading markup
419 ;; is moving in when promoting or demoting.
421 ;; * Completion: `C-c C-]`
423 ;; Complete markup is in normalized form, which means, for
424 ;; example, that the underline portion of a setext header is the
425 ;; same length as the heading text, or that the number of leading
426 ;; and trailing hash marks of an atx header are equal and that
427 ;; there is no extra whitespace in the header text. `C-c C-]`
428 ;; completes the markup at the point, if it is determined to be
429 ;; incomplete.
431 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
433 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
434 ;; command determines the appropriate marker (one of the possible
435 ;; unordered list markers or the next number in sequence for an
436 ;; ordered list) and indentation level by examining nearby list
437 ;; items. If there is no list before or after the point, start a
438 ;; new list. As with heading insertion, you may prefix this
439 ;; command by `C-u` to decrease the indentation by one level.
440 ;; Prefix this command by `C-u C-u` to increase the indentation by
441 ;; one level.
443 ;; Existing list items (and their nested sub-items) can be moved
444 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
445 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
447 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
449 ;; Entire subtrees of ATX headings can be promoted and demoted
450 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
451 ;; used for promotion and demotion of list items. If the point is in
452 ;; a list item, the operate on the list item. Otherwise, they operate
453 ;; on the current heading subtree. Similarly, subtrees can be
454 ;; moved up and down with `C-c UP` and `C-c DOWN`.
456 ;; These commands currently do not work properly if there are
457 ;; Setext headings in the affected region.
459 ;; Please note the following "boundary" behavior for promotion and
460 ;; demotion. Any level-six headings will not be demoted further
461 ;; (i.e., they remain at level six, since Markdown and HTML define
462 ;; only six levels) and any level-one headings will promoted away
463 ;; entirely (i.e., heading markup will be removed, since a
464 ;; level-zero heading is not defined).
466 ;; * Shifting the Region: `C-c <` and `C-c >`
468 ;; Text in the region can be indented or outdented as a group using
469 ;; `C-c >` to indent to the next indentation point (calculated in
470 ;; the current context), and `C-c <` to outdent to the previous
471 ;; indentation point. These keybindings are the same as those for
472 ;; similar commands in `python-mode'.
474 ;; * Killing Elements: `C-c C-k`
476 ;; Press `C-c C-k` to kill the thing at point and add important
477 ;; text, without markup, to the kill ring. Possible things to
478 ;; kill include (roughly in order of precedece): inline code,
479 ;; headings, horizonal rules, links (add link text to kill ring),
480 ;; images (add alt text to kill ring), angle URIs, email
481 ;; addresses, bold, italics, reference definitions (add URI to
482 ;; kill ring), footnote markers and text (kill both marker and
483 ;; text, add text to kill ring), and list items.
485 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
487 ;; These keys are used for hierarchical navigation in lists and
488 ;; headings. When the point is in a list, they move between list
489 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
490 ;; `C-c C-p` to move between the next and previous visible
491 ;; headings or list items of any level. Similarly, `C-c C-f` and
492 ;; `C-c C-b` move to the next and previous visible headings or
493 ;; list items at the same level as the one at the point. Finally,
494 ;; `C-c C-u` will move up to the parent heading or list item.
496 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
498 ;; Paragraphs in `markdown-mode' are regular paragraphs,
499 ;; paragraphs inside blockquotes, individual list items, headings,
500 ;; etc. These keys are usually bound to `forward-paragraph' and
501 ;; `backward-paragraph', but the built-in Emacs functions are
502 ;; based on simple regular expressions that fail in Markdown
503 ;; files. Instead, they are bound to `markdown-forward-paragraph'
504 ;; and `markdown-backward-paragraph'. To mark a paragraph,
505 ;; you can use `M-h` (`markdown-mark-paragraph').
507 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
509 ;; Markdown blocks are regular paragraphs in many cases, but
510 ;; contain many paragraphs in other cases: blocks are considered
511 ;; to be entire lists, entire code blocks, and entire blockquotes.
512 ;; To move backward one block use `C-M-{`
513 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
514 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
515 ;; (`markdown-mark-block`).
517 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
519 ;; The usual Emacs commands can be used to move by defuns
520 ;; (top-level major definitions). In markdown-mode, a defun is a
521 ;; section. As usual, `C-M-a` will move the point to the
522 ;; beginning of the current or preceding defun, `C-M-e` will move
523 ;; to the end of the current or following defun, and `C-M-h` will
524 ;; put the region around the entire defun.
526 ;; * Table Editing:
528 ;; Markdown Mode includes support for editing tables, which
529 ;; have the following basic format:
531 ;; | Right | Left | Center | Default |
532 ;; |------:|:-----|:------:|---------|
533 ;; | 12 | 12 | 12 | 12 |
534 ;; | 123 | 123 | 123 | 123 |
535 ;; | 1 | 1 | 1 | 1 |
537 ;; The first line contains column headers. The second line
538 ;; contains a separator line between the headers and the content.
539 ;; Each following line is a row in the table. Columns are always
540 ;; separated by the pipe character. The colons indicate column
541 ;; alignment.
543 ;; A table is re-aligned automatically each time you press `TAB`
544 ;; or `RET` inside the table. `TAB` also moves to the next
545 ;; field (`RET` to the next row) and creates new table rows at
546 ;; the end of the table or before horizontal separator lines. The
547 ;; indentation of the table is set by the first line. Column
548 ;; centering inside Emacs is not supported.
550 ;; Beginning pipe characters are required for proper detection of
551 ;; table borders inside Emacs. Any line starting with `|-` or `|:`
552 ;; is considered as a horizontal separator line and will be
553 ;; expanded on the next re-align to span the whole table width. No
554 ;; padding is allowed between the beginning pipe character and
555 ;; header separator symbol. So, to create the above table, you
556 ;; would only type
558 ;; |Right|Left|Center|Default|
559 ;; |-
561 ;; and then press `TAB` to align the table and start filling in
562 ;; cells.
564 ;; Then you can jump with `TAB` from one cell to the next or with
565 ;; `S-TAB` to the previous one. `RET` will jump to the to the
566 ;; next cell in the same column, and create a new row if there is
567 ;; no such cell or if the next row is beyond a separator line.
569 ;; You can also convert selected region to a table. Basic editing
570 ;; capabilities include inserting, deleting, and moving of columns
571 ;; and rows, and table re-alignment, sorting, transposition:
573 ;; - `C-c UP` or `C-c DOWN` - Move the current row up or down.
574 ;; - `C-c LEFT` or `C-c RIGHT` - Move the current column left or right.
575 ;; - `C-c S-UP` - Kill the current row.
576 ;; - `C-c S-DOWN` - Insert a row above the current row. With a
577 ;; prefix argument, row line is created below the current one.
578 ;; - `C-c S-LEFT` - Kill the current column.
579 ;; - `C-c S-RIGHT` - Insert a new column to the left of the current one.
580 ;; - `C-c C-d` - Re-align the current table (`markdown-do`).
581 ;; - `C-c C-c ^` - Sort the rows of a table by a specified column.
582 ;; This command prompts you for the column number and a sort
583 ;; method (alphabetical or numerical, optionally in reverse).
584 ;; - `C-c C-c |` - Convert the region to a table. This function
585 ;; attempts to recognize comma, tab, and space separated data
586 ;; and then splits the data into cells accordingly.
587 ;; - `C-c C-c t` - Transpose table at point.
589 ;; The table editing functions try to handle markup hiding
590 ;; correctly when calculating column widths, however, columns
591 ;; containing hidden markup may not always be aligned properly.
593 ;; * Miscellaneous Commands:
595 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
596 ;; (`markdown-edit-code-block`) can be used to edit a code block
597 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
598 ;; to commit changes and return or `C-c C-k` to cancel.
600 ;; As noted, many of the commands above behave differently depending
601 ;; on whether Transient Mark mode is enabled or not. When it makes
602 ;; sense, if Transient Mark mode is on and the region is active, the
603 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
604 ;; region bold). For users who prefer to work outside of Transient
605 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
606 ;; `C-SPC C-SPC`. When this is not the case, many commands then
607 ;; proceed to look work with the word or line at the point.
609 ;; When applicable, commands that specifically act on the region even
610 ;; outside of Transient Mark mode have the same keybinding as their
611 ;; standard counterpart, but the letter is uppercase. For example,
612 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
613 ;; the region in Transient Mark mode while `markdown-blockquote-region'
614 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
616 ;; Note that these region-specific functions are useful in many
617 ;; cases where it may not be obvious. For example, yanking text from
618 ;; the kill ring sets the mark at the beginning of the yanked text
619 ;; and moves the point to the end. Therefore, the (inactive) region
620 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
621 ;; yank text and turn it into a blockquote.
623 ;; markdown-mode attempts to be flexible in how it handles
624 ;; indentation. When you press `TAB` repeatedly, the point will cycle
625 ;; through several possible indentation levels corresponding to things
626 ;; you might have in mind when you press `RET` at the end of a line or
627 ;; `TAB`. For example, you may want to start a new list item,
628 ;; continue a list item with hanging indentation, indent for a nested
629 ;; pre block, and so on. Outdenting is handled similarly when backspace
630 ;; is pressed at the beginning of the non-whitespace portion of a line.
632 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
633 ;; visibility cycling for atx- or hash-style headings. There are two
634 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
635 ;; the table of contents view (headings only), outline view (top-level
636 ;; headings only), and the full document view. Pressing `TAB` while the
637 ;; point is at a heading will cycle through levels of visibility for the
638 ;; subtree: completely folded, visible children, and fully visible.
639 ;; Note that mixing hash and underline style headings will give undesired
640 ;; results.
642 ;;; Customization:
644 ;; Although no configuration is *necessary* there are a few things
645 ;; that can be customized. The `M-x customize-mode` command
646 ;; provides an interface to all of the possible customizations:
648 ;; * `markdown-command' - the command used to run Markdown (default:
649 ;; `markdown`). This variable may be customized to pass
650 ;; command-line options to your Markdown processor of choice. It can
651 ;; also be a function; in this case `markdown' will call it with three
652 ;; arguments: the beginning and end of the region to process, and
653 ;; a buffer to write the output to.
655 ;; * `markdown-command-needs-filename' - set to `t' if
656 ;; `markdown-command' does not accept standard input (default:
657 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
658 ;; content to `markdown-command' using standard input (`stdin`).
659 ;; When set to `t', `markdown-mode' will pass the name of the file
660 ;; as the final command-line argument to `markdown-command'. Note
661 ;; that in the latter case, you will only be able to run
662 ;; `markdown-command' from buffers which are visiting a file. If
663 ;; `markdown-command' is a function, `markdown-command-needs-filename'
664 ;; is ignored.
666 ;; * `markdown-open-command' - the command used for calling a standalone
667 ;; Markdown previewer which is capable of opening Markdown source files
668 ;; directly (default: `nil'). This command will be called
669 ;; with a single argument, the filename of the current buffer.
670 ;; A representative program is the Mac app [Marked 2][], a
671 ;; live-updating Markdown previewer which can be [called from a
672 ;; simple shell script](https://jblevins.org/log/marked-2-command).
673 ;; This variable can also be a function; in this case `markdown-open'
674 ;; will call it without arguments to preview the current buffer.
676 ;; * `markdown-hr-strings' - list of strings to use when inserting
677 ;; horizontal rules. Different strings will not be distinguished
678 ;; when converted to HTML--they will all be converted to
679 ;; `<hr/>`--but they may add visual distinction and style to plain
680 ;; text documents. To maintain some notion of promotion and
681 ;; demotion, keep these sorted from largest to smallest.
683 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
684 ;; underscores when inserting bold text instead of two asterisks
685 ;; (default: `nil').
687 ;; * `markdown-italic-underscore' - set to a non-nil value to use
688 ;; underscores when inserting italic text instead of asterisks
689 ;; (default: `nil').
691 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
692 ;; asymmetric header styling, placing header characters only on
693 ;; the left of headers (default: `nil').
695 ;; * `markdown-header-scaling' - set to a non-nil value to use
696 ;; a variable-pitch font for headings where the size corresponds
697 ;; to the level of the heading (default: `nil').
699 ;; * `markdown-header-scaling-values' - list of scaling values,
700 ;; relative to baseline, for headers of levels one through six,
701 ;; used when `markdown-header-scaling' is non-nil
702 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
704 ;; * `markdown-marginalize-headers' - put opening atx header markup
705 ;; in the left margin when non-nil (default: `nil').
707 ;; * `markdown-marginalize-headers-margin-width' - width of margin
708 ;; used for marginalized headers (default: 6).
710 ;; * `markdown-list-indent-width' - depth of indentation for lists
711 ;; when inserting, promoting, and demoting list items (default: 4).
713 ;; * `markdown-indent-function' - the function to use for automatic
714 ;; indentation (default: `markdown-indent-line').
716 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
717 ;; automatically indent new lines when `RET` is pressed.
718 ;; Set to `indent-and-new-item' to additionally continue lists
719 ;; when `RET` is pressed (default: `t').
721 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
722 ;; links (default: `nil'). Set this to a non-nil value to turn on
723 ;; wiki link support by default. Wiki link support can be toggled
724 ;; later using the function `markdown-toggle-wiki-links'."
726 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
727 ;; treat aliased wiki links like `[[link text|PageName]]`
728 ;; (default: `t'). When set to nil, they will be treated as
729 ;; `[[PageName|link text]]'.
731 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
732 ;; for URIs that `markdown-mode' should highlight.
734 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
735 ;; math expressions (default: `nil'). Set this to `t' to turn on
736 ;; math support by default. Math support can be toggled
737 ;; interactively later using `C-c C-x C-e`
738 ;; (`markdown-toggle-math').
740 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
741 ;; (default: `nil`).
743 ;; * `markdown-content-type' - when set to a nonempty string, an
744 ;; `http-equiv` attribute will be included in the XHTML `<head>`
745 ;; block (default: `""`). If needed, the suggested values are
746 ;; `application/xhtml+xml` or `text/html`. See also:
747 ;; `markdown-coding-system'.
749 ;; * `markdown-coding-system' - used for specifying the character
750 ;; set identifier in the `http-equiv` attribute when included
751 ;; (default: `nil'). See `markdown-content-type', which must
752 ;; be set before this variable has any effect. When set to `nil',
753 ;; `buffer-file-coding-system' will be used to automatically
754 ;; determine the coding system string (falling back to
755 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
756 ;; and `iso-latin-1'.
758 ;; * `markdown-xhtml-header-content' - additional content to include
759 ;; in the XHTML `<head>` block (default: `""`).
761 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
762 ;; `markdown-mode' uses to determine whether the output of
763 ;; `markdown-command' is a standalone XHTML document or an XHTML
764 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
765 ;; this regular expression not matched in the first five lines of
766 ;; output, `markdown-mode' assumes the output is a fragment and
767 ;; adds a header and footer.
769 ;; * `markdown-link-space-sub-char' - a character to replace spaces
770 ;; when mapping wiki links to filenames (default: `"_"`).
771 ;; For example, use an underscore for compatibility with the
772 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
773 ;; set to `"-"` to conform with GitHub wiki links.
775 ;; * `markdown-reference-location' - where to insert reference
776 ;; definitions (default: `header`). The possible locations are
777 ;; the end of the document (`end`), after the current block
778 ;; (`immediately`), the end of the current subtree (`subtree'),
779 ;; or before the next header (`header`).
781 ;; * `markdown-footnote-location' - where to insert footnote text
782 ;; (default: `end`). The set of location options is the same as
783 ;; for `markdown-reference-location'.
785 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
786 ;; heading instead of a flat index (default: `t'). A nested
787 ;; index may provide more natural browsing from the menu, but a
788 ;; flat list may allow for faster keyboard navigation via tab
789 ;; completion.
791 ;; * `comment-auto-fill-only-comments' - variable is made
792 ;; buffer-local and set to `nil' by default. In programming
793 ;; language modes, when this variable is non-nil, only comments
794 ;; will be filled by auto-fill-mode. However, comments in
795 ;; Markdown documents are rare and the most users probably intend
796 ;; for the actual content of the document to be filled. Making
797 ;; this variable buffer-local allows `markdown-mode' to override
798 ;; the default behavior induced when the global variable is non-nil.
800 ;; * `markdown-gfm-additional-languages', - additional languages to
801 ;; make available, aside from those predefined in
802 ;; `markdown-gfm-recognized-languages', when inserting GFM code
803 ;; blocks (default: `nil`). Language strings must have be trimmed
804 ;; of whitespace and not contain any curly braces. They may be of
805 ;; arbitrary capitalization, though.
807 ;; * `markdown-gfm-use-electric-backquote' - use
808 ;; `markdown-electric-backquote' for interactive insertion of GFM
809 ;; code blocks when backquote is pressed three times (default: `t`).
811 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
812 ;; Flavored Markdown style task lists (checkboxes) should be
813 ;; turned into buttons that can be toggled with mouse-1 or RET. If
814 ;; non-nil (default), then buttons are enabled. This works in
815 ;; `markdown-mode' as well as `gfm-mode'.
817 ;; * `markdown-hide-urls' - Determines whether URL and reference
818 ;; labels are hidden for inline and reference links (default: `nil').
819 ;; When non-nil, inline links will appear in the buffer as
820 ;; `[link](∞)` instead of
821 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
822 ;; placeholder (composition) character used, set the variable
823 ;; `markdown-url-compose-char'. URL hiding can be toggled
824 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
825 ;; or from the Markdown | Links & Images menu.
827 ;; * `markdown-hide-markup' - Determines whether all possible markup
828 ;; is hidden or otherwise beautified (default: `nil'). The actual
829 ;; buffer text remains unchanged, but the display will be altered.
830 ;; Brackets and URLs for links will be hidden, asterisks and
831 ;; underscores for italic and bold text will be hidden, text
832 ;; bullets for unordered lists will be replaced by Unicode
833 ;; bullets, and so on. Since this includes URLs and reference
834 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
835 ;; Markup hiding can be toggled using `C-c C-x C-m`
836 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
837 ;; Hide menu.
839 ;; Unicode bullets are used to replace ASCII list item markers.
840 ;; The list of characters used, in order of list level, can be
841 ;; specified by setting the variable `markdown-list-item-bullets'.
842 ;; The placeholder characters used to replace other markup can
843 ;; be changed by customizing the corresponding variables:
844 ;; `markdown-blockquote-display-char',
845 ;; `markdown-hr-display-char', and
846 ;; `markdown-definition-display-char'.
848 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
849 ;; code in code blocks using the native major mode. This only
850 ;; works for fenced code blocks where the language is specified
851 ;; where we can automatically determine the appropriate mode to
852 ;; use. The language to mode mapping may be customized by setting
853 ;; the variable `markdown-code-lang-modes'. This can be toggled
854 ;; interactively by pressing `C-c C-x C-f`
855 ;; (`markdown-toggle-fontify-code-blocks-natively').
857 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
858 ;; task list items with `[X]` instead of `[x]` (default: `nil').
859 ;; This is useful for compatibility with `org-mode', which doesn't
860 ;; recognize the lowercase variant.
862 ;; * `markdown-translate-filename-function' - A function to be used to
863 ;; translate filenames in links.
865 ;; Additionally, the faces used for syntax highlighting can be modified to
866 ;; your liking by issuing `M-x customize-group RET markdown-faces`
867 ;; or by using the "Markdown Faces" link at the bottom of the mode
868 ;; customization screen.
870 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
872 ;;; Extensions:
874 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
875 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
876 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
877 ;; Wiki links may be followed by pressing `C-c C-o` when the point
878 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
879 ;; previous and next links (including links of other types).
880 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
881 ;; are also supported. Since some wikis reverse these components, set
882 ;; `markdown-wiki-link-alias-first' to nil to treat them as
883 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
884 ;; is also non-nil, Markdown Mode will highlight wiki links with
885 ;; missing target file in a different color. By default, Markdown
886 ;; Mode only searches for target files in the current directory.
887 ;; Search in subdirectories can be enabled by setting
888 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
889 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
890 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
891 ;; to a non-nil value.
893 ;; [Ikiwiki]: https://ikiwiki.info
895 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
896 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
897 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
898 ;; You can do this either by using `M-x customize-group markdown`
899 ;; or by placing the following in your `.emacs` file:
901 ;; ``` Lisp
902 ;; (setq markdown-command "markdown | smartypants")
903 ;; ```
905 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
907 ;; Syntax highlighting for mathematical expressions written
908 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
909 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
910 ;; either via customize or by placing `(setq markdown-enable-math t)`
911 ;; in `.emacs`, and then restarting Emacs or calling
912 ;; `markdown-reload-extensions'.
914 ;;; GitHub Flavored Markdown (GFM):
916 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
917 ;; available. The GitHub implementation differs slightly from
918 ;; standard Markdown in that it supports things like different
919 ;; behavior for underscores inside of words, automatic linking of
920 ;; URLs, strikethrough text, and fenced code blocks with an optional
921 ;; language keyword.
923 ;; The GFM-specific features above apply to `README.md` files, wiki
924 ;; pages, and other Markdown-formatted files in repositories on
925 ;; GitHub. GitHub also enables [additional features][GFM comments] for
926 ;; writing on the site (for issues, pull requests, messages, etc.)
927 ;; that are further extensions of GFM. These features include task
928 ;; lists (checkboxes), newlines corresponding to hard line breaks,
929 ;; auto-linked references to issues and commits, wiki links, and so
930 ;; on. To make matters more confusing, although task lists are not
931 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
932 ;; read-only fashion) in all Markdown documents in repositories on the
933 ;; site. These additional extensions are supported to varying degrees
934 ;; by `markdown-mode' and `gfm-mode' as described below.
936 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
937 ;; highlighting of URLs without angle brackets.
939 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
940 ;; toggle support for underscores inside of words. In this mode
941 ;; variable names such as `a_test_variable` will not trigger
942 ;; emphasis (italics).
944 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
945 ;; optional programming language keywords, are highlighted in
946 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
947 ;; `C-c C-s C`. If there is an active region, the text in the
948 ;; region will be placed inside the code block. You will be
949 ;; prompted for the name of the language, but may press enter to
950 ;; continue without naming a language.
952 ;; * **Strikethrough:** Strikethrough text is supported in both
953 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
954 ;; using `C-c C-s s`.
956 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
957 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
958 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
959 ;; (and it is set to t by default). These checkboxes can be
960 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
961 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
962 ;; in the task list item. A normal list item can be turned to a
963 ;; check list item by the same command, or more specifically
964 ;; `C-c C-s [` (`markdown-insert-gfm-checkbox`).
966 ;; * **Wiki links:** Generic wiki links are supported in
967 ;; `markdown-mode', but in `gfm-mode' specifically they will be
968 ;; treated as they are on GitHub: spaces will be replaced by hyphens
969 ;; in filenames and the first letter of the filename will be
970 ;; capitalized. For example, `[[wiki link]]' will map to a file
971 ;; named `Wiki-link` with the same extension as the current file.
972 ;; If a file with this name does not exist in the current directory,
973 ;; the first match in a subdirectory, if any, will be used instead.
975 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
976 ;; specifically with respect to newline behavior. If you use
977 ;; `gfm-mode' mostly to write text for comments or issues on the
978 ;; GitHub site--where newlines are significant and correspond to
979 ;; hard line breaks--then you may want to enable `visual-line-mode'
980 ;; for line wrapping in buffers. You can do this with a
981 ;; `gfm-mode-hook' as follows:
983 ;; ``` Lisp
984 ;; ;; Use visual-line-mode in gfm-mode
985 ;; (defun my-gfm-mode-hook ()
986 ;; (visual-line-mode 1))
987 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
988 ;; ```
990 ;; * **Preview:** GFM-specific preview can be powered by setting
991 ;; `markdown-command' to use [Docter][]. This may also be
992 ;; configured to work with [Marked 2][] for `markdown-open-command'.
994 ;; [GFM]: http://github.github.com/github-flavored-markdown/
995 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
996 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
997 ;; [Docter]: https://github.com/alampros/Docter
999 ;;; Acknowledgments:
1001 ;; markdown-mode has benefited greatly from the efforts of the many
1002 ;; volunteers who have sent patches, test cases, bug reports,
1003 ;; suggestions, helped with packaging, etc. Thank you for your
1004 ;; contributions! See the [contributors graph][contrib] for details.
1006 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
1008 ;;; Bugs:
1010 ;; markdown-mode is developed and tested primarily for compatibility
1011 ;; with GNU Emacs 24.3 and later. If you find any bugs in
1012 ;; markdown-mode, please construct a test case or a patch and open a
1013 ;; ticket on the [GitHub issue tracker][issues]. See the
1014 ;; contributing guidelines in `CONTRIBUTING.md` for details on
1015 ;; creating pull requests.
1017 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
1019 ;;; History:
1021 ;; markdown-mode was written and is maintained by Jason Blevins. The
1022 ;; first version was released on May 24, 2007.
1024 ;; * 2007-05-24: [Version 1.1][]
1025 ;; * 2007-05-25: [Version 1.2][]
1026 ;; * 2007-06-05: [Version 1.3][]
1027 ;; * 2007-06-29: [Version 1.4][]
1028 ;; * 2007-10-11: [Version 1.5][]
1029 ;; * 2008-06-04: [Version 1.6][]
1030 ;; * 2009-10-01: [Version 1.7][]
1031 ;; * 2011-08-12: [Version 1.8][]
1032 ;; * 2011-08-15: [Version 1.8.1][]
1033 ;; * 2013-01-25: [Version 1.9][]
1034 ;; * 2013-03-24: [Version 2.0][]
1035 ;; * 2016-01-09: [Version 2.1][]
1036 ;; * 2017-05-26: [Version 2.2][]
1037 ;; * 2017-08-31: [Version 2.3][]
1039 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
1040 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
1041 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
1042 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
1043 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
1044 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
1045 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
1046 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
1047 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
1048 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
1049 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
1050 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
1051 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
1052 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
1055 ;;; Code:
1057 (require 'easymenu)
1058 (require 'outline)
1059 (require 'thingatpt)
1060 (require 'cl-lib)
1061 (require 'url-parse)
1062 (require 'button)
1063 (require 'color)
1064 (require 'rx)
1066 (defvar jit-lock-start)
1067 (defvar jit-lock-end)
1068 (defvar flyspell-generic-check-word-predicate)
1070 (declare-function eww-open-file "eww")
1071 (declare-function url-path-and-query "url-parse")
1074 ;;; Constants =================================================================
1076 (defconst markdown-mode-version "2.4-dev"
1077 "Markdown mode version number.")
1079 (defconst markdown-output-buffer-name "*markdown-output*"
1080 "Name of temporary buffer for markdown command output.")
1082 (defconst markdown-sub-superscript-display
1083 '(((raise -0.3) (height 0.7)) ; subscript
1084 ((raise 0.3) (height 0.7))) ; superscript
1085 "Parameters for sub- and superscript formatting.")
1088 ;;; Global Variables ==========================================================
1090 (defvar markdown-reference-label-history nil
1091 "History of used reference labels.")
1093 (defvar markdown-live-preview-mode nil
1094 "Sentinel variable for command `markdown-live-preview-mode'.")
1096 (defvar markdown-gfm-language-history nil
1097 "History list of languages used in the current buffer in GFM code blocks.")
1100 ;;; Customizable Variables ====================================================
1102 (defvar markdown-mode-hook nil
1103 "Hook run when entering Markdown mode.")
1105 (defvar markdown-before-export-hook nil
1106 "Hook run before running Markdown to export XHTML output.
1107 The hook may modify the buffer, which will be restored to it's
1108 original state after exporting is complete.")
1110 (defvar markdown-after-export-hook nil
1111 "Hook run after XHTML output has been saved.
1112 Any changes to the output buffer made by this hook will be saved.")
1114 (defgroup markdown nil
1115 "Major mode for editing text files in Markdown format."
1116 :prefix "markdown-"
1117 :group 'wp
1118 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1120 (defcustom markdown-command "markdown"
1121 "Command to run markdown."
1122 :group 'markdown
1123 :type '(choice (string :tag "Shell command") function))
1125 (defcustom markdown-command-needs-filename nil
1126 "Set to non-nil if `markdown-command' does not accept input from stdin.
1127 Instead, it will be passed a filename as the final command line
1128 option. As a result, you will only be able to run Markdown from
1129 buffers which are visiting a file."
1130 :group 'markdown
1131 :type 'boolean)
1133 (defcustom markdown-open-command nil
1134 "Command used for opening Markdown files directly.
1135 For example, a standalone Markdown previewer. This command will
1136 be called with a single argument: the filename of the current
1137 buffer. It can also be a function, which will be called without
1138 arguments."
1139 :group 'markdown
1140 :type '(choice file function (const :tag "None" nil)))
1142 (defcustom markdown-hr-strings
1143 '("-------------------------------------------------------------------------------"
1144 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1145 "---------------------------------------"
1146 "* * * * * * * * * * * * * * * * * * * *"
1147 "---------"
1148 "* * * * *")
1149 "Strings to use when inserting horizontal rules.
1150 The first string in the list will be the default when inserting a
1151 horizontal rule. Strings should be listed in decreasing order of
1152 prominence (as in headings from level one to six) for use with
1153 promotion and demotion functions."
1154 :group 'markdown
1155 :type '(repeat string))
1157 (defcustom markdown-bold-underscore nil
1158 "Use two underscores when inserting bold text instead of two asterisks."
1159 :group 'markdown
1160 :type 'boolean)
1162 (defcustom markdown-italic-underscore nil
1163 "Use underscores when inserting italic text instead of asterisks."
1164 :group 'markdown
1165 :type 'boolean)
1167 (defcustom markdown-marginalize-headers nil
1168 "When non-nil, put opening atx header markup in a left margin.
1170 This setting goes well with `markdown-asymmetric-header'. But
1171 sadly it conflicts with `linum-mode' since they both use the
1172 same margin."
1173 :group 'markdown
1174 :type 'boolean
1175 :safe 'booleanp
1176 :package-version '(markdown-mode . "2.4"))
1178 (defcustom markdown-marginalize-headers-margin-width 6
1179 "Character width of margin used for marginalized headers.
1180 The default value is based on there being six heading levels
1181 defined by Markdown and HTML. Increasing this produces extra
1182 whitespace on the left. Decreasing it may be preferred when
1183 fewer than six nested heading levels are used."
1184 :group 'markdown
1185 :type 'natnump
1186 :safe 'natnump
1187 :package-version '(markdown-mode . "2.4"))
1189 (defcustom markdown-asymmetric-header nil
1190 "Determines if atx header style will be asymmetric.
1191 Set to a non-nil value to use asymmetric header styling, placing
1192 header markup only at the beginning of the line. By default,
1193 balanced markup will be inserted at the beginning and end of the
1194 line around the header title."
1195 :group 'markdown
1196 :type 'boolean)
1198 (defcustom markdown-indent-function 'markdown-indent-line
1199 "Function to use to indent."
1200 :group 'markdown
1201 :type 'function)
1203 (defcustom markdown-indent-on-enter t
1204 "Determines indentation behavior when pressing \\[newline].
1205 Possible settings are nil, t, and 'indent-and-new-item.
1207 When non-nil, pressing \\[newline] will call `newline-and-indent'
1208 to indent the following line according to the context using
1209 `markdown-indent-function'. In this case, note that
1210 \\[electric-newline-and-maybe-indent] can still be used to insert
1211 a newline without indentation.
1213 When set to 'indent-and-new-item and the point is in a list item
1214 when \\[newline] is pressed, the list will be continued on the next
1215 line, where a new item will be inserted.
1217 When set to nil, simply call `newline' as usual. In this case,
1218 you can still indent lines using \\[markdown-cycle] and continue
1219 lists with \\[markdown-insert-list-item].
1221 Note that this assumes the variable `electric-indent-mode' is
1222 non-nil (enabled). When it is *disabled*, the behavior of
1223 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1224 reversed."
1225 :group 'markdown
1226 :type '(choice (const :tag "Don't automatically indent" nil)
1227 (const :tag "Automatically indent" t)
1228 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1230 (defcustom markdown-enable-wiki-links nil
1231 "Syntax highlighting for wiki links.
1232 Set this to a non-nil value to turn on wiki link support by default.
1233 Support can be toggled later using the `markdown-toggle-wiki-links'
1234 function or \\[markdown-toggle-wiki-links]."
1235 :group 'markdown
1236 :type 'boolean
1237 :safe 'booleanp
1238 :package-version '(markdown-mode . "2.2"))
1240 (defcustom markdown-wiki-link-alias-first t
1241 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1242 Otherwise, they will be treated as [[PageName|alias text]]."
1243 :group 'markdown
1244 :type 'boolean
1245 :safe 'booleanp)
1247 (defcustom markdown-wiki-link-search-subdirectories nil
1248 "When non-nil, search for wiki link targets in subdirectories.
1249 This is the default search behavior for GitHub and is
1250 automatically set to t in `gfm-mode'."
1251 :group 'markdown
1252 :type 'boolean
1253 :safe 'booleanp
1254 :package-version '(markdown-mode . "2.2"))
1256 (defcustom markdown-wiki-link-search-parent-directories nil
1257 "When non-nil, search for wiki link targets in parent directories.
1258 This is the default search behavior of Ikiwiki."
1259 :group 'markdown
1260 :type 'boolean
1261 :safe 'booleanp
1262 :package-version '(markdown-mode . "2.2"))
1264 (defcustom markdown-wiki-link-fontify-missing nil
1265 "When non-nil, change wiki link face according to existence of target files.
1266 This is expensive because it requires checking for the file each time the buffer
1267 changes or the user switches windows. It is disabled by default because it may
1268 cause lag when typing on slower machines."
1269 :group 'markdown
1270 :type 'boolean
1271 :safe 'booleanp
1272 :package-version '(markdown-mode . "2.2"))
1274 (defcustom markdown-uri-types
1275 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1276 "gopher" "http" "https" "imap" "ldap" "mailto"
1277 "mid" "message" "modem" "news" "nfs" "nntp"
1278 "pop" "prospero" "rtsp" "service" "sip" "tel"
1279 "telnet" "tip" "urn" "vemmi" "wais")
1280 "Link types for syntax highlighting of URIs."
1281 :group 'markdown
1282 :type '(repeat (string :tag "URI scheme")))
1284 (defcustom markdown-url-compose-char
1285 (cond
1286 ((char-displayable-p ?∞) ?∞)
1287 ((char-displayable-p ?…) ?…)
1288 (t ?#))
1289 "Placeholder character for hidden URLs.
1290 Depending on your font, some good choices are …, ⋯, #, ∞, ★, and ⚓."
1291 :type 'character
1292 :safe 'characterp
1293 :package-version '(markdown-mode . "2.3"))
1295 (defcustom markdown-blockquote-display-char
1296 (cond
1297 ((char-displayable-p ?▌) "▌")
1298 ((char-displayable-p ?┃) "┃")
1299 ((char-displayable-p ?│) "│")
1300 ((char-displayable-p ?|) "|")
1301 (t ">"))
1302 "Character for hiding blockquote markup."
1303 :type 'string
1304 :safe 'stringp
1305 :package-version '(markdown-mode . "2.3"))
1307 (defcustom markdown-hr-display-char
1308 (cond ((char-displayable-p ?─) ?─)
1309 ((char-displayable-p ?━) ?━)
1310 (t ?-))
1311 "Character for hiding horizontal rule markup."
1312 :type 'character
1313 :safe 'characterp
1314 :package-version '(markdown-mode . "2.3"))
1316 (defcustom markdown-definition-display-char
1317 (cond ((char-displayable-p ?⁘) ?⁘)
1318 ((char-displayable-p ?⁙) ?⁙)
1319 ((char-displayable-p ?≡) ?≡)
1320 ((char-displayable-p ?⌑) ?⌑)
1321 ((char-displayable-p ?◊) ?◊)
1322 (t nil))
1323 "Character for replacing definition list markup."
1324 :type 'character
1325 :safe 'characterp
1326 :package-version '(markdown-mode . "2.3"))
1328 (defcustom markdown-enable-math nil
1329 "Syntax highlighting for inline LaTeX and itex expressions.
1330 Set this to a non-nil value to turn on math support by default.
1331 Math support can be enabled, disabled, or toggled later using
1332 `markdown-toggle-math' or \\[markdown-toggle-math]."
1333 :group 'markdown
1334 :type 'boolean
1335 :safe 'booleanp)
1336 (make-variable-buffer-local 'markdown-enable-math)
1338 (defcustom markdown-css-paths nil
1339 "URL of CSS file to link to in the output XHTML."
1340 :group 'markdown
1341 :type '(repeat (string :tag "CSS File Path")))
1343 (defcustom markdown-content-type ""
1344 "Content type string for the http-equiv header in XHTML output.
1345 When set to a non-empty string, insert the http-equiv attribute.
1346 Otherwise, this attribute is omitted."
1347 :group 'markdown
1348 :type 'string)
1350 (defcustom markdown-coding-system nil
1351 "Character set string for the http-equiv header in XHTML output.
1352 Defaults to `buffer-file-coding-system' (and falling back to
1353 `iso-8859-1' when not available). Common settings are `utf-8'
1354 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1355 :group 'markdown
1356 :type 'coding-system)
1358 (defcustom markdown-xhtml-header-content ""
1359 "Additional content to include in the XHTML <head> block."
1360 :group 'markdown
1361 :type 'string)
1363 (defcustom markdown-xhtml-standalone-regexp
1364 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1365 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1366 :group 'markdown
1367 :type 'regexp)
1369 (defcustom markdown-link-space-sub-char "_"
1370 "Character to use instead of spaces when mapping wiki links to filenames."
1371 :group 'markdown
1372 :type 'string)
1374 (defcustom markdown-reference-location 'header
1375 "Position where new reference definitions are inserted in the document."
1376 :group 'markdown
1377 :type '(choice (const :tag "At the end of the document" end)
1378 (const :tag "Immediately after the current block" immediately)
1379 (const :tag "At the end of the subtree" subtree)
1380 (const :tag "Before next header" header)))
1382 (defcustom markdown-footnote-location 'end
1383 "Position where new footnotes are inserted in the document."
1384 :group 'markdown
1385 :type '(choice (const :tag "At the end of the document" end)
1386 (const :tag "Immediately after the current block" immediately)
1387 (const :tag "At the end of the subtree" subtree)
1388 (const :tag "Before next header" header)))
1390 (defcustom markdown-unordered-list-item-prefix " * "
1391 "String inserted before unordered list items."
1392 :group 'markdown
1393 :type 'string)
1395 (defcustom markdown-nested-imenu-heading-index t
1396 "Use nested or flat imenu heading index.
1397 A nested index may provide more natural browsing from the menu,
1398 but a flat list may allow for faster keyboard navigation via tab
1399 completion."
1400 :group 'markdown
1401 :type 'boolean
1402 :safe 'booleanp
1403 :package-version '(markdown-mode . "2.2"))
1405 (defcustom markdown-make-gfm-checkboxes-buttons t
1406 "When non-nil, make GFM checkboxes into buttons."
1407 :group 'markdown
1408 :type 'boolean)
1410 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1411 "When non-nil, allow YAML metadata anywhere in the document."
1412 :group 'markdown
1413 :type 'boolean)
1415 (defcustom markdown-split-window-direction 'any
1416 "Preference for splitting windows for static and live preview.
1417 The default value is 'any, which instructs Emacs to use
1418 `split-window-sensibly' to automatically choose how to split
1419 windows based on the values of `split-width-threshold' and
1420 `split-height-threshold' and the available windows. To force
1421 vertically split (left and right) windows, set this to 'vertical
1422 or 'right. To force horizontally split (top and bottom) windows,
1423 set this to 'horizontal or 'below."
1424 :group 'markdown
1425 :type '(choice (const :tag "Automatic" any)
1426 (const :tag "Right (vertical)" right)
1427 (const :tag "Below (horizontal)" below))
1428 :package-version '(markdown-mode . "2.2"))
1430 (defcustom markdown-live-preview-window-function
1431 'markdown-live-preview-window-eww
1432 "Function to display preview of Markdown output within Emacs.
1433 Function must update the buffer containing the preview and return
1434 the buffer."
1435 :group 'markdown
1436 :type 'function)
1438 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1439 "Delete exported HTML file when using `markdown-live-preview-export'.
1440 If set to 'delete-on-export, delete on every export. When set to
1441 'delete-on-destroy delete when quitting from command
1442 `markdown-live-preview-mode'. Never delete if set to nil."
1443 :group 'markdown
1444 :type '(choice
1445 (const :tag "Delete on every export" delete-on-export)
1446 (const :tag "Delete when quitting live preview" delete-on-destroy)
1447 (const :tag "Never delete" nil)))
1449 (defcustom markdown-list-indent-width 4
1450 "Depth of indentation for markdown lists.
1451 Used in `markdown-demote-list-item' and
1452 `markdown-promote-list-item'."
1453 :group 'markdown
1454 :type 'integer)
1456 (defcustom markdown-enable-prefix-prompts t
1457 "Display prompts for certain prefix commands.
1458 Set to nil to disable these prompts."
1459 :group 'markdown
1460 :type 'boolean
1461 :safe 'booleanp
1462 :package-version '(markdown-mode . "2.3"))
1464 (defcustom markdown-gfm-additional-languages nil
1465 "Extra languages made available when inserting GFM code blocks.
1466 Language strings must have be trimmed of whitespace and not
1467 contain any curly braces. They may be of arbitrary
1468 capitalization, though."
1469 :group 'markdown
1470 :type '(repeat (string :validate markdown-validate-language-string)))
1472 (defcustom markdown-gfm-use-electric-backquote t
1473 "Use `markdown-electric-backquote' when backquote is hit three times."
1474 :group 'markdown
1475 :type 'boolean)
1477 (defcustom markdown-gfm-downcase-languages t
1478 "If non-nil, downcase suggested languages.
1479 This applies to insertions done with
1480 `markdown-electric-backquote'."
1481 :group 'markdown
1482 :type 'boolean)
1484 (defcustom markdown-gfm-uppercase-checkbox nil
1485 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1486 :group 'markdown
1487 :type 'boolean
1488 :safe 'booleanp)
1490 (defcustom markdown-hide-urls nil
1491 "Hide URLs of inline links and reference tags of reference links.
1492 Such URLs will be replaced by a single customizable
1493 character (∞), or `markdown-url-compose-char', but are still part
1494 of the buffer. Links can be edited interactively with
1495 \\[markdown-insert-link] or, for example, by deleting the final
1496 parenthesis to remove the invisibility property. You can also
1497 hover your mouse pointer over the link text to see the URL.
1498 Set this to a non-nil value to turn this feature on by default.
1499 You can interactively set the value of this variable by calling
1500 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1501 or from the menu Markdown > Links & Images menu."
1502 :group 'markdown
1503 :type 'boolean
1504 :safe 'booleanp
1505 :package-version '(markdown-mode . "2.3"))
1506 (make-variable-buffer-local 'markdown-hide-urls)
1508 (defcustom markdown-translate-filename-function #'identity
1509 "Function to use to translate filenames when following links.
1510 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1511 call this function with the filename as only argument whenever
1512 they encounter a filename (instead of a URL) to be visited and
1513 use its return value instead of the filename in the link. For
1514 example, if absolute filenames are actually relative to a server
1515 root directory, you can set
1516 `markdown-translate-filename-function' to a function that
1517 prepends the root directory to the given filename."
1518 :group 'markdown
1519 :type 'function
1520 :risky t
1521 :package-version '(markdown-mode . "2.4"))
1524 ;;; Regular Expressions =======================================================
1526 (defconst markdown-regex-comment-start
1527 "<!--"
1528 "Regular expression matches HTML comment opening.")
1530 (defconst markdown-regex-comment-end
1531 "--[ \t]*>"
1532 "Regular expression matches HTML comment closing.")
1534 (defconst markdown-regex-link-inline
1535 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1536 "Regular expression for a [text](file) or an image link ![text](file).
1537 Group 1 matches the leading exclamation point (optional).
1538 Group 2 matches the opening square bracket.
1539 Group 3 matches the text inside the square brackets.
1540 Group 4 matches the closing square bracket.
1541 Group 5 matches the opening parenthesis.
1542 Group 6 matches the URL.
1543 Group 7 matches the title (optional).
1544 Group 8 matches the closing parenthesis.")
1546 (defconst markdown-regex-link-reference
1547 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1548 "Regular expression for a reference link [text][id].
1549 Group 1 matches the leading exclamation point (optional).
1550 Group 2 matches the opening square bracket for the link text.
1551 Group 3 matches the text inside the square brackets.
1552 Group 4 matches the closing square bracket for the link text.
1553 Group 5 matches the opening square bracket for the reference label.
1554 Group 6 matches the reference label.
1555 Group 7 matches the closing square bracket for the reference label.")
1557 (defconst markdown-regex-reference-definition
1558 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1559 "Regular expression for a reference definition.
1560 Group 1 matches the opening square bracket.
1561 Group 2 matches the reference label.
1562 Group 3 matches the closing square bracket.
1563 Group 4 matches the colon.
1564 Group 5 matches the URL.
1565 Group 6 matches the title attribute (optional).")
1567 (defconst markdown-regex-footnote
1568 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1569 "Regular expression for a footnote marker [^fn].
1570 Group 1 matches the opening square bracket and carat.
1571 Group 2 matches only the label, without the surrounding markup.
1572 Group 3 matches the closing square bracket.")
1574 (defconst markdown-regex-header
1575 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1576 "Regexp identifying Markdown headings.
1577 Group 1 matches the text of a setext heading.
1578 Group 2 matches the underline of a level-1 setext heading.
1579 Group 3 matches the underline of a level-2 setext heading.
1580 Group 4 matches the opening hash marks of an atx heading and whitespace.
1581 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1582 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1584 (defconst markdown-regex-header-setext
1585 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1586 "Regular expression for generic setext-style (underline) headers.")
1588 (defconst markdown-regex-header-atx
1589 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1590 "Regular expression for generic atx-style (hash mark) headers.")
1592 (defconst markdown-regex-hr
1593 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1594 "Regular expression for matching Markdown horizontal rules.")
1596 (defconst markdown-regex-code
1597 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1598 "Regular expression for matching inline code fragments.
1600 Group 1 matches the entire code fragment including the backquotes.
1601 Group 2 matches the opening backquotes.
1602 Group 3 matches the code fragment itself, without backquotes.
1603 Group 4 matches the closing backquotes.
1605 The leading, unnumbered group ensures that the leading backquote
1606 character is not escaped.
1607 The last group, also unnumbered, requires that the character
1608 following the code fragment is not a backquote.
1609 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1610 but not two newlines in a row.")
1612 (defconst markdown-regex-kbd
1613 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1614 "Regular expression for matching <kbd> tags.
1615 Groups 1 and 3 match the opening and closing tags.
1616 Group 2 matches the key sequence.")
1618 (defconst markdown-regex-gfm-code-block-open
1619 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1620 "Regular expression matching opening of GFM code blocks.
1621 Group 1 matches the opening three backquotes and any following whitespace.
1622 Group 2 matches the opening brace (optional) and surrounding whitespace.
1623 Group 3 matches the language identifier (optional).
1624 Group 4 matches the info string (optional).
1625 Group 5 matches the closing brace (optional), whitespace, and newline.
1626 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1628 (defconst markdown-regex-gfm-code-block-close
1629 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1630 "Regular expression matching closing of GFM code blocks.
1631 Group 1 matches the closing three backquotes.
1632 Group 2 matches any whitespace and the final newline.")
1634 (defconst markdown-regex-pre
1635 "^\\( \\|\t\\).*$"
1636 "Regular expression for matching preformatted text sections.")
1638 (defconst markdown-regex-list
1639 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1640 "Regular expression for matching list items.")
1642 (defconst markdown-regex-bold
1643 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1644 "Regular expression for matching bold text.
1645 Group 1 matches the character before the opening asterisk or
1646 underscore, if any, ensuring that it is not a backslash escape.
1647 Group 2 matches the entire expression, including delimiters.
1648 Groups 3 and 5 matches the opening and closing delimiters.
1649 Group 4 matches the text inside the delimiters.")
1651 (defconst markdown-regex-italic
1652 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1653 "Regular expression for matching italic text.
1654 The leading unnumbered matches the character before the opening
1655 asterisk or underscore, if any, ensuring that it is not a
1656 backslash escape.
1657 Group 1 matches the entire expression, including delimiters.
1658 Groups 2 and 4 matches the opening and closing delimiters.
1659 Group 3 matches the text inside the delimiters.")
1661 (defconst markdown-regex-strike-through
1662 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1663 "Regular expression for matching strike-through text.
1664 Group 1 matches the character before the opening tilde, if any,
1665 ensuring that it is not a backslash escape.
1666 Group 2 matches the entire expression, including delimiters.
1667 Groups 3 and 5 matches the opening and closing delimiters.
1668 Group 4 matches the text inside the delimiters.")
1670 (defconst markdown-regex-gfm-italic
1671 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1672 "Regular expression for matching italic text in GitHub Flavored Markdown.
1673 Underscores in words are not treated as special.
1674 Group 1 matches the entire expression, including delimiters.
1675 Groups 2 and 4 matches the opening and closing delimiters.
1676 Group 3 matches the text inside the delimiters.")
1678 (defconst markdown-regex-blockquote
1679 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1680 "Regular expression for matching blockquote lines.
1681 Also accounts for a potential capital letter preceding the angle
1682 bracket, for use with Leanpub blocks (asides, warnings, info
1683 blocks, etc.).
1684 Group 1 matches the leading angle bracket.
1685 Group 2 matches the separating whitespace.
1686 Group 3 matches the text.")
1688 (defconst markdown-regex-line-break
1689 "[^ \n\t][ \t]*\\( \\)$"
1690 "Regular expression for matching line breaks.")
1692 (defconst markdown-regex-wiki-link
1693 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1694 "Regular expression for matching wiki links.
1695 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1696 wiki links of the form [[PageName|link text]].
1697 The meanings of the first and second components depend
1698 on the value of `markdown-wiki-link-alias-first'.
1700 Group 1 matches the entire link.
1701 Group 2 matches the opening square brackets.
1702 Group 3 matches the first component of the wiki link.
1703 Group 4 matches the pipe separator, when present.
1704 Group 5 matches the second component of the wiki link, when present.
1705 Group 6 matches the closing square brackets.")
1707 (defconst markdown-regex-uri
1708 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1709 "Regular expression for matching inline URIs.")
1711 (defconst markdown-regex-angle-uri
1712 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1713 "Regular expression for matching inline URIs in angle brackets.")
1715 (defconst markdown-regex-email
1716 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1717 "Regular expression for matching inline email addresses.")
1719 (defsubst markdown-make-regex-link-generic ()
1720 "Make regular expression for matching any recognized link."
1721 (concat "\\(?:" markdown-regex-link-inline
1722 (when markdown-enable-wiki-links
1723 (concat "\\|" markdown-regex-wiki-link))
1724 "\\|" markdown-regex-link-reference
1725 "\\|" markdown-regex-angle-uri "\\)"))
1727 (defconst markdown-regex-gfm-checkbox
1728 " \\(\\[[ xX]\\]\\) "
1729 "Regular expression for matching GFM checkboxes.
1730 Group 1 matches the text to become a button.")
1732 (defconst markdown-regex-block-separator
1733 "\n[\n\t\f ]*\n"
1734 "Regular expression for matching block boundaries.")
1736 (defconst markdown-regex-block-separator-noindent
1737 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1738 "Regexp for block separators before lines with no indentation.")
1740 (defconst markdown-regex-math-inline-single
1741 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1742 "Regular expression for itex $..$ math mode expressions.
1743 Groups 1 and 3 match the opening and closing dollar signs.
1744 Group 2 matches the mathematical expression contained within.")
1746 (defconst markdown-regex-math-inline-double
1747 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1748 "Regular expression for itex $$..$$ math mode expressions.
1749 Groups 1 and 3 match opening and closing dollar signs.
1750 Group 2 matches the mathematical expression contained within.")
1752 (defconst markdown-regex-math-display
1753 (rx line-start
1754 (group (group (repeat 1 2 "\\")) "[")
1755 (group (*? anything))
1756 (group (backref 2) "]")
1757 line-end)
1758 "Regular expression for \[..\] or \\[..\\] display math.
1759 Groups 1 and 4 match the opening and closing markup.
1760 Group 3 matches the mathematical expression contained within.
1761 Group 2 matches the opening slashes, and is used internally to
1762 match the closing slashes.")
1764 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1765 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1766 END-OF-LINE is the regexp construct to indicate end of line; $ if
1767 missing."
1768 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1769 (or end-of-line "$")))
1771 (defconst markdown-regex-tilde-fence-begin
1772 (markdown-make-tilde-fence-regex
1773 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1774 "Regular expression for matching tilde-fenced code blocks.
1775 Group 1 matches the opening tildes.
1776 Group 2 matches (optional) opening brace and surrounding whitespace.
1777 Group 3 matches the language identifier (optional).
1778 Group 4 matches the info string (optional).
1779 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1780 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1782 (defconst markdown-regex-declarative-metadata
1783 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1784 "Regular expression for matching declarative metadata statements.
1785 This matches MultiMarkdown metadata as well as YAML and TOML
1786 assignments such as the following:
1788 variable: value
1792 variable = value")
1794 (defconst markdown-regex-pandoc-metadata
1795 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1796 "Regular expression for matching Pandoc metadata.")
1798 (defconst markdown-regex-yaml-metadata-border
1799 "\\(-\\{3\\}\\)$"
1800 "Regular expression for matching YAML metadata.")
1802 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1803 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1804 "Regular expression for matching YAML metadata end borders.")
1806 (defsubst markdown-get-yaml-metadata-start-border ()
1807 "Return YAML metadata start border depending upon whether Pandoc is used."
1808 (concat
1809 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1810 markdown-regex-yaml-metadata-border))
1812 (defsubst markdown-get-yaml-metadata-end-border (_)
1813 "Return YAML metadata end border depending upon whether Pandoc is used."
1814 (if markdown-use-pandoc-style-yaml-metadata
1815 markdown-regex-yaml-pandoc-metadata-end-border
1816 markdown-regex-yaml-metadata-border))
1818 (defconst markdown-regex-inline-attributes
1819 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1820 "Regular expression for matching inline identifiers or attribute lists.
1821 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1823 (defconst markdown-regex-leanpub-sections
1824 (concat
1825 "^\\({\\)\\("
1826 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1827 "\\)\\(}\\)[ \t]*\n")
1828 "Regular expression for Leanpub section markers and related syntax.")
1830 (defconst markdown-regex-sub-superscript
1831 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1832 "The regular expression matching a sub- or superscript.
1833 The leading un-numbered group matches the character before the
1834 opening tilde or carat, if any, ensuring that it is not a
1835 backslash escape, carat, or tilde.
1836 Group 1 matches the entire expression, including markup.
1837 Group 2 matches the opening markup--a tilde or carat.
1838 Group 3 matches the text inside the delimiters.
1839 Group 4 matches the closing markup--a tilde or carat.")
1841 (defconst markdown-regex-include
1842 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1843 "Regular expression matching common forms of include syntax.
1844 Marked 2, Leanpub, and other processors support some of these forms:
1846 <<[sections/section1.md]
1847 <<(folder/filename)
1848 <<[Code title](folder/filename)
1849 <<{folder/raw_file.html}
1851 Group 1 matches the opening two angle brackets.
1852 Groups 2-4 match the opening square bracket, the text inside,
1853 and the closing square bracket, respectively.
1854 Groups 5-7 match the opening parenthesis, the text inside, and
1855 the closing parenthesis.
1856 Groups 8-10 match the opening brace, the text inside, and the brace.")
1858 (defconst markdown-regex-pandoc-inline-footnote
1859 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1860 "Regular expression for Pandoc inline footnote^[footnote text].
1861 Group 1 matches the opening caret.
1862 Group 2 matches the opening square bracket.
1863 Group 3 matches the footnote text, without the surrounding markup.
1864 Group 4 matches the closing square bracket.")
1867 ;;; Syntax ====================================================================
1869 (defsubst markdown-in-comment-p (&optional pos)
1870 "Return non-nil if POS is in a comment.
1871 If POS is not given, use point instead."
1872 (nth 4 (syntax-ppss pos)))
1874 (defun markdown-syntax-propertize-extend-region (start end)
1875 "Extend START to END region to include an entire block of text.
1876 This helps improve syntax analysis for block constructs.
1877 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1878 Function is called repeatedly until it returns nil. For details, see
1879 `syntax-propertize-extend-region-functions'."
1880 (save-match-data
1881 (save-excursion
1882 (let* ((new-start (progn (goto-char start)
1883 (skip-chars-forward "\n")
1884 (if (re-search-backward "\n\n" nil t)
1885 (min start (match-end 0))
1886 (point-min))))
1887 (new-end (progn (goto-char end)
1888 (skip-chars-backward "\n")
1889 (if (re-search-forward "\n\n" nil t)
1890 (max end (match-beginning 0))
1891 (point-max))))
1892 (code-match (markdown-code-block-at-pos new-start))
1893 (new-start (or (and code-match (cl-first code-match)) new-start))
1894 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1895 (new-end (or (and code-match (cl-second code-match)) new-end)))
1896 (unless (and (eq new-start start) (eq new-end end))
1897 (cons new-start (min new-end (point-max))))))))
1899 (defun markdown-font-lock-extend-region-function (start end _)
1900 "Used in `jit-lock-after-change-extend-region-functions'.
1901 Delegates to `markdown-syntax-propertize-extend-region'. START
1902 and END are the previous region to refontify."
1903 (let ((res (markdown-syntax-propertize-extend-region start end)))
1904 (when res
1905 ;; syntax-propertize-function is not called when character at
1906 ;; (point-max) is deleted, but font-lock-extend-region-functions
1907 ;; are called. Force a syntax property update in that case.
1908 (when (= end (point-max))
1909 ;; This function is called in a buffer modification hook.
1910 ;; `markdown-syntax-propertize' doesn't save the match data,
1911 ;; so we have to do it here.
1912 (save-match-data
1913 (markdown-syntax-propertize (car res) (cdr res))))
1914 (setq jit-lock-start (car res)
1915 jit-lock-end (cdr res)))))
1917 (defun markdown-syntax-propertize-pre-blocks (start end)
1918 "Match preformatted text blocks from START to END."
1919 (save-excursion
1920 (goto-char start)
1921 (let ((levels (markdown-calculate-list-levels))
1922 indent pre-regexp close-regexp open close)
1923 (while (and (< (point) end) (not close))
1924 ;; Search for a region with sufficient indentation
1925 (if (null levels)
1926 (setq indent 1)
1927 (setq indent (1+ (length levels))))
1928 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1929 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1931 (cond
1932 ;; If not at the beginning of a line, move forward
1933 ((not (bolp)) (forward-line))
1934 ;; Move past blank lines
1935 ((markdown-cur-line-blank) (forward-line))
1936 ;; At headers and horizontal rules, reset levels
1937 ((markdown-new-baseline) (forward-line) (setq levels nil))
1938 ;; If the current line has sufficient indentation, mark out pre block
1939 ;; The opening should be preceded by a blank line.
1940 ((and (looking-at pre-regexp)
1941 (markdown-prev-line-blank-p))
1942 (setq open (match-beginning 0))
1943 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1944 (not (eobp)))
1945 (forward-line))
1946 (skip-syntax-backward "-")
1947 (setq close (point)))
1948 ;; If current line has a list marker, update levels, move to end of block
1949 ((looking-at markdown-regex-list)
1950 (setq levels (markdown-update-list-levels
1951 (match-string 2) (current-indentation) levels))
1952 (markdown-end-of-text-block))
1953 ;; If this is the end of the indentation level, adjust levels accordingly.
1954 ;; Only match end of indentation level if levels is not the empty list.
1955 ((and (car levels) (looking-at-p close-regexp))
1956 (setq levels (markdown-update-list-levels
1957 nil (current-indentation) levels))
1958 (markdown-end-of-text-block))
1959 (t (markdown-end-of-text-block))))
1961 (when (and open close)
1962 ;; Set text property data
1963 (put-text-property open close 'markdown-pre (list open close))
1964 ;; Recursively search again
1965 (markdown-syntax-propertize-pre-blocks (point) end)))))
1967 (defconst markdown-fenced-block-pairs
1968 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1969 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1970 markdown-fenced-code)
1971 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1972 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1973 markdown-yaml-metadata-section)
1974 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1975 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1976 markdown-gfm-code))
1977 "Mapping of regular expressions to \"fenced-block\" constructs.
1978 These constructs are distinguished by having a distinctive start
1979 and end pattern, both of which take up an entire line of text,
1980 but no special pattern to identify text within the fenced
1981 blocks (unlike blockquotes and indented-code sections).
1983 Each element within this list takes the form:
1985 ((START-REGEX-OR-FUN START-PROPERTY)
1986 (END-REGEX-OR-FUN END-PROPERTY)
1987 MIDDLE-PROPERTY)
1989 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1990 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1991 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1992 which is the length of the first group of the START-REGEX-OR-FUN match, which
1993 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1994 evaluate these into \"real\" regexps.
1996 The *-PROPERTY elements are the text properties applied to each part of the
1997 block construct when it is matched using
1998 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1999 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2000 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2001 `match-data' when the regexp was matched to the text. In the case of
2002 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2003 begin and end set to the edges of the \"middle\" text. This makes fontification
2004 easier.")
2006 (defun markdown-text-property-at-point (prop)
2007 (get-text-property (point) prop))
2009 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2010 (cond ((functionp object)
2011 (if arg (funcall object arg) (funcall object)))
2012 ((stringp object) object)
2013 (t (error "Object cannot be turned into regex"))))
2015 (defsubst markdown-get-start-fence-regexp ()
2016 "Return regexp to find all \"start\" sections of fenced block constructs.
2017 Which construct is actually contained in the match must be found separately."
2018 (mapconcat
2019 #'identity
2020 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2021 markdown-fenced-block-pairs)
2022 "\\|"))
2024 (defun markdown-get-fenced-block-begin-properties ()
2025 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2027 (defun markdown-get-fenced-block-end-properties ()
2028 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2030 (defun markdown-get-fenced-block-middle-properties ()
2031 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2033 (defun markdown-find-previous-prop (prop &optional lim)
2034 "Find previous place where property PROP is non-nil, up to LIM.
2035 Return a cons of (pos . property). pos is point if point contains
2036 non-nil PROP."
2037 (let ((res
2038 (if (get-text-property (point) prop) (point)
2039 (previous-single-property-change
2040 (point) prop nil (or lim (point-min))))))
2041 (when (and (not (get-text-property res prop))
2042 (> res (point-min))
2043 (get-text-property (1- res) prop))
2044 (cl-decf res))
2045 (when (and res (get-text-property res prop)) (cons res prop))))
2047 (defun markdown-find-next-prop (prop &optional lim)
2048 "Find next place where property PROP is non-nil, up to LIM.
2049 Return a cons of (POS . PROPERTY) where POS is point if point
2050 contains non-nil PROP."
2051 (let ((res
2052 (if (get-text-property (point) prop) (point)
2053 (next-single-property-change
2054 (point) prop nil (or lim (point-max))))))
2055 (when (and res (get-text-property res prop)) (cons res prop))))
2057 (defun markdown-min-of-seq (map-fn seq)
2058 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2059 (cl-loop for el in seq
2060 with min = 1.0e+INF ; infinity
2061 with min-el = nil
2062 do (let ((res (funcall map-fn el)))
2063 (when (< res min)
2064 (setq min res)
2065 (setq min-el el)))
2066 finally return min-el))
2068 (defun markdown-max-of-seq (map-fn seq)
2069 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2070 (cl-loop for el in seq
2071 with max = -1.0e+INF ; negative infinity
2072 with max-el = nil
2073 do (let ((res (funcall map-fn el)))
2074 (when (and res (> res max))
2075 (setq max res)
2076 (setq max-el el)))
2077 finally return max-el))
2079 (defun markdown-find-previous-block ()
2080 "Find previous block.
2081 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2082 unable to propertize the entire block, but was able to propertize the beginning
2083 of the block. If so, return a cons of (pos . property) where the beginning of
2084 the block was propertized."
2085 (let ((start-pt (point))
2086 (closest-open
2087 (markdown-max-of-seq
2088 #'car
2089 (cl-remove-if
2090 #'null
2091 (cl-mapcar
2092 #'markdown-find-previous-prop
2093 (markdown-get-fenced-block-begin-properties))))))
2094 (when closest-open
2095 (let* ((length-of-open-match
2096 (let ((match-d
2097 (get-text-property (car closest-open) (cdr closest-open))))
2098 (- (cl-fourth match-d) (cl-third match-d))))
2099 (end-regexp
2100 (markdown-maybe-funcall-regexp
2101 (cl-caadr
2102 (cl-find-if
2103 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2104 markdown-fenced-block-pairs))
2105 length-of-open-match))
2106 (end-prop-loc
2107 (save-excursion
2108 (save-match-data
2109 (goto-char (car closest-open))
2110 (and (re-search-forward end-regexp start-pt t)
2111 (match-beginning 0))))))
2112 (and (not end-prop-loc) closest-open)))))
2114 (defun markdown-get-fenced-block-from-start (prop)
2115 "Return limits of an enclosing fenced block from its start, using PROP.
2116 Return value is a list usable as `match-data'."
2117 (catch 'no-rest-of-block
2118 (let* ((correct-entry
2119 (cl-find-if
2120 (lambda (entry) (eq (cl-cadar entry) prop))
2121 markdown-fenced-block-pairs))
2122 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2123 (middle-prop (cl-third correct-entry))
2124 (end-prop (cl-cadadr correct-entry))
2125 (end-of-end
2126 (save-excursion
2127 (goto-char (match-end 0)) ; end of begin
2128 (unless (eobp) (forward-char))
2129 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2130 (if (not mid-prop-v) ; no middle
2131 (progn
2132 ;; try to find end by advancing one
2133 (let ((end-prop-v
2134 (markdown-text-property-at-point end-prop)))
2135 (if end-prop-v (cl-second end-prop-v)
2136 (throw 'no-rest-of-block nil))))
2137 (set-match-data mid-prop-v)
2138 (goto-char (match-end 0)) ; end of middle
2139 (beginning-of-line) ; into end
2140 (cl-second (markdown-text-property-at-point end-prop)))))))
2141 (list begin-of-begin end-of-end))))
2143 (defun markdown-get-fenced-block-from-middle (prop)
2144 "Return limits of an enclosing fenced block from its middle, using PROP.
2145 Return value is a list usable as `match-data'."
2146 (let* ((correct-entry
2147 (cl-find-if
2148 (lambda (entry) (eq (cl-third entry) prop))
2149 markdown-fenced-block-pairs))
2150 (begin-prop (cl-cadar correct-entry))
2151 (begin-of-begin
2152 (save-excursion
2153 (goto-char (match-beginning 0))
2154 (unless (bobp) (forward-line -1))
2155 (beginning-of-line)
2156 (cl-first (markdown-text-property-at-point begin-prop))))
2157 (end-prop (cl-cadadr correct-entry))
2158 (end-of-end
2159 (save-excursion
2160 (goto-char (match-end 0))
2161 (beginning-of-line)
2162 (cl-second (markdown-text-property-at-point end-prop)))))
2163 (list begin-of-begin end-of-end)))
2165 (defun markdown-get-fenced-block-from-end (prop)
2166 "Return limits of an enclosing fenced block from its end, using PROP.
2167 Return value is a list usable as `match-data'."
2168 (let* ((correct-entry
2169 (cl-find-if
2170 (lambda (entry) (eq (cl-cadadr entry) prop))
2171 markdown-fenced-block-pairs))
2172 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2173 (middle-prop (cl-third correct-entry))
2174 (begin-prop (cl-cadar correct-entry))
2175 (begin-of-begin
2176 (save-excursion
2177 (goto-char (match-beginning 0)) ; beginning of end
2178 (unless (bobp) (backward-char)) ; into middle
2179 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2180 (if (not mid-prop-v)
2181 (progn
2182 (beginning-of-line)
2183 (cl-first (markdown-text-property-at-point begin-prop)))
2184 (set-match-data mid-prop-v)
2185 (goto-char (match-beginning 0)) ; beginning of middle
2186 (unless (bobp) (forward-line -1)) ; into beginning
2187 (beginning-of-line)
2188 (cl-first (markdown-text-property-at-point begin-prop)))))))
2189 (list begin-of-begin end-of-end)))
2191 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2192 "Get \"fake\" match data for block enclosing POS.
2193 Returns fake match data which encloses the start, middle, and end
2194 of the block construct enclosing POS, if it exists. Used in
2195 `markdown-code-block-at-pos'."
2196 (save-excursion
2197 (when pos (goto-char pos))
2198 (beginning-of-line)
2199 (car
2200 (cl-remove-if
2201 #'null
2202 (cl-mapcar
2203 (lambda (fun-and-prop)
2204 (cl-destructuring-bind (fun prop) fun-and-prop
2205 (when prop
2206 (save-match-data
2207 (set-match-data (markdown-text-property-at-point prop))
2208 (funcall fun prop)))))
2209 `((markdown-get-fenced-block-from-start
2210 ,(cl-find-if
2211 #'markdown-text-property-at-point
2212 (markdown-get-fenced-block-begin-properties)))
2213 (markdown-get-fenced-block-from-middle
2214 ,(cl-find-if
2215 #'markdown-text-property-at-point
2216 (markdown-get-fenced-block-middle-properties)))
2217 (markdown-get-fenced-block-from-end
2218 ,(cl-find-if
2219 #'markdown-text-property-at-point
2220 (markdown-get-fenced-block-end-properties)))))))))
2222 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2223 "Get match for REG up to END, if exists, and propertize appropriately.
2224 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2225 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2226 (when (re-search-forward reg end t)
2227 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2228 (close-end (match-end 0)) ; End of closing line.
2229 (close-data (match-data t))) ; Match data for closing line.
2230 ;; Propertize middle section of fenced block.
2231 (put-text-property middle-begin close-begin
2232 (cl-third fence-spec)
2233 (list middle-begin close-begin))
2234 ;; Propertize closing line of fenced block.
2235 (put-text-property close-begin close-end
2236 (cl-cadadr fence-spec) close-data))))
2238 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2239 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2240 If unable to propertize an entire block (if the start of a block is within START
2241 and END, but the end of the block is not), propertize the start section of a
2242 block, then in a subsequent call propertize both middle and end by finding the
2243 start which was previously propertized."
2244 (let ((start-reg (markdown-get-start-fence-regexp)))
2245 (save-excursion
2246 (goto-char start)
2247 ;; start from previous unclosed block, if exists
2248 (let ((prev-begin-block (markdown-find-previous-block)))
2249 (when prev-begin-block
2250 (let* ((correct-entry
2251 (cl-find-if (lambda (entry)
2252 (eq (cdr prev-begin-block) (cl-cadar entry)))
2253 markdown-fenced-block-pairs))
2254 (enclosed-text-start (1+ (car prev-begin-block)))
2255 (start-length
2256 (save-excursion
2257 (goto-char (car prev-begin-block))
2258 (string-match
2259 (markdown-maybe-funcall-regexp
2260 (caar correct-entry))
2261 (buffer-substring
2262 (point-at-bol) (point-at-eol)))
2263 (- (match-end 1) (match-beginning 1))))
2264 (end-reg (markdown-maybe-funcall-regexp
2265 (cl-caadr correct-entry) start-length)))
2266 (markdown-propertize-end-match
2267 end-reg end correct-entry enclosed-text-start))))
2268 ;; find all new blocks within region
2269 (while (re-search-forward start-reg end t)
2270 ;; we assume the opening constructs take up (only) an entire line,
2271 ;; so we re-check the current line
2272 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2273 ;; find entry in `markdown-fenced-block-pairs' corresponding
2274 ;; to regex which was matched
2275 (correct-entry
2276 (cl-find-if
2277 (lambda (fenced-pair)
2278 (string-match-p
2279 (markdown-maybe-funcall-regexp (caar fenced-pair))
2280 cur-line))
2281 markdown-fenced-block-pairs))
2282 (enclosed-text-start
2283 (save-excursion (1+ (point-at-eol))))
2284 (end-reg
2285 (markdown-maybe-funcall-regexp
2286 (cl-caadr correct-entry)
2287 (if (and (match-beginning 1) (match-end 1))
2288 (- (match-end 1) (match-beginning 1))
2289 0))))
2290 ;; get correct match data
2291 (save-excursion
2292 (beginning-of-line)
2293 (re-search-forward
2294 (markdown-maybe-funcall-regexp (caar correct-entry))
2295 (point-at-eol)))
2296 ;; mark starting, even if ending is outside of region
2297 (put-text-property (match-beginning 0) (match-end 0)
2298 (cl-cadar correct-entry) (match-data t))
2299 (markdown-propertize-end-match
2300 end-reg end correct-entry enclosed-text-start))))))
2302 (defun markdown-syntax-propertize-blockquotes (start end)
2303 "Match blockquotes from START to END."
2304 (save-excursion
2305 (goto-char start)
2306 (while (and (re-search-forward markdown-regex-blockquote end t)
2307 (not (markdown-code-block-at-pos (match-beginning 0))))
2308 (put-text-property (match-beginning 0) (match-end 0)
2309 'markdown-blockquote
2310 (match-data t)))))
2312 (defun markdown-syntax-propertize-hrs (start end)
2313 "Match horizontal rules from START to END."
2314 (save-excursion
2315 (goto-char start)
2316 (while (re-search-forward markdown-regex-hr end t)
2317 (unless (or (markdown-on-heading-p)
2318 (markdown-code-block-at-point-p))
2319 (put-text-property (match-beginning 0) (match-end 0)
2320 'markdown-hr
2321 (match-data t))))))
2323 (defun markdown-syntax-propertize-yaml-metadata (start end)
2324 (save-excursion
2325 (goto-char start)
2326 (cl-loop
2327 while (re-search-forward markdown-regex-declarative-metadata end t)
2328 do (when (get-text-property (match-beginning 0)
2329 'markdown-yaml-metadata-section)
2330 (put-text-property (match-beginning 1) (match-end 1)
2331 'markdown-metadata-key (match-data t))
2332 (put-text-property (match-beginning 2) (match-end 2)
2333 'markdown-metadata-markup (match-data t))
2334 (put-text-property (match-beginning 3) (match-end 3)
2335 'markdown-metadata-value (match-data t))))))
2337 (defun markdown-syntax-propertize-headings (start end)
2338 "Match headings of type SYMBOL with REGEX from START to END."
2339 (goto-char start)
2340 (while (re-search-forward markdown-regex-header end t)
2341 (unless (markdown-code-block-at-pos (match-beginning 0))
2342 (put-text-property
2343 (match-beginning 0) (match-end 0) 'markdown-heading
2344 (match-data t))
2345 (put-text-property
2346 (match-beginning 0) (match-end 0)
2347 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2348 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2349 (t (let ((atx-level (length (markdown-trim-whitespace
2350 (match-string-no-properties 4)))))
2351 (intern (format "markdown-heading-%d-atx" atx-level)))))
2352 (match-data t)))))
2354 (defun markdown-syntax-propertize-comments (start end)
2355 "Match HTML comments from the START to END."
2356 (let* ((in-comment (markdown-in-comment-p)))
2357 (goto-char start)
2358 (cond
2359 ;; Comment start
2360 ((and (not in-comment)
2361 (re-search-forward markdown-regex-comment-start end t)
2362 (not (markdown-inline-code-at-point-p))
2363 (not (markdown-code-block-at-point-p)))
2364 (let ((open-beg (match-beginning 0)))
2365 (put-text-property open-beg (1+ open-beg)
2366 'syntax-table (string-to-syntax "<"))
2367 (markdown-syntax-propertize-comments
2368 (min (1+ (match-end 0)) end (point-max)) end)))
2369 ;; Comment end
2370 ((and in-comment
2371 (re-search-forward markdown-regex-comment-end end t))
2372 (put-text-property (1- (match-end 0)) (match-end 0)
2373 'syntax-table (string-to-syntax ">"))
2374 (markdown-syntax-propertize-comments
2375 (min (1+ (match-end 0)) end (point-max)) end))
2376 ;; Nothing found
2377 (t nil))))
2379 (defvar markdown--syntax-properties
2380 (list 'markdown-tilde-fence-begin nil
2381 'markdown-tilde-fence-end nil
2382 'markdown-fenced-code nil
2383 'markdown-yaml-metadata-begin nil
2384 'markdown-yaml-metadata-end nil
2385 'markdown-yaml-metadata-section nil
2386 'markdown-gfm-block-begin nil
2387 'markdown-gfm-block-end nil
2388 'markdown-gfm-code nil
2389 'markdown-pre nil
2390 'markdown-blockquote nil
2391 'markdown-hr nil
2392 'markdown-heading nil
2393 'markdown-heading-1-setext nil
2394 'markdown-heading-2-setext nil
2395 'markdown-heading-1-atx nil
2396 'markdown-heading-2-atx nil
2397 'markdown-heading-3-atx nil
2398 'markdown-heading-4-atx nil
2399 'markdown-heading-5-atx nil
2400 'markdown-heading-6-atx nil
2401 'markdown-metadata-key nil
2402 'markdown-metadata-value nil
2403 'markdown-metadata-markup nil)
2404 "Property list of all Markdown syntactic properties.")
2406 (defun markdown-syntax-propertize (start end)
2407 "Function used as `syntax-propertize-function'.
2408 START and END delimit region to propertize."
2409 (with-silent-modifications
2410 (save-excursion
2411 (remove-text-properties start end markdown--syntax-properties)
2412 (markdown-syntax-propertize-fenced-block-constructs start end)
2413 (markdown-syntax-propertize-yaml-metadata start end)
2414 (markdown-syntax-propertize-pre-blocks start end)
2415 (markdown-syntax-propertize-blockquotes start end)
2416 (markdown-syntax-propertize-headings start end)
2417 (markdown-syntax-propertize-hrs start end)
2418 (markdown-syntax-propertize-comments start end))))
2421 ;;; Markup Hiding
2423 (defconst markdown-markup-properties
2424 '(face markdown-markup-face invisible markdown-markup)
2425 "List of properties and values to apply to markup.")
2427 (defconst markdown-language-keyword-properties
2428 '(face markdown-language-keyword-face invisible markdown-markup)
2429 "List of properties and values to apply to code block language names.")
2431 (defconst markdown-language-info-properties
2432 '(face markdown-language-info-face invisible markdown-markup)
2433 "List of properties and values to apply to code block language info strings.")
2435 (defconst markdown-include-title-properties
2436 '(face markdown-link-title-face invisible markdown-markup)
2437 "List of properties and values to apply to included code titles.")
2439 (defconst markdown-inline-footnote-properties
2440 '(face nil display ((raise 0.2) (height 0.8)))
2441 "Properties to apply to footnote markers and inline footnotes.")
2443 (defcustom markdown-hide-markup nil
2444 "Determines whether markup in the buffer will be hidden.
2445 When set to nil, all markup is displayed in the buffer as it
2446 appears in the file. An exception is when `markdown-hide-urls'
2447 is non-nil.
2448 Set this to a non-nil value to turn this feature on by default.
2449 You can interactively toggle the value of this variable with
2450 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2451 or from the Markdown > Show & Hide menu.
2453 Markup hiding works by adding text properties to positions in the
2454 buffer---either the `invisible' property or the `display' property
2455 in cases where alternative glyphs are used (e.g., list bullets).
2456 This does not, however, affect printing or other output.
2457 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2458 not honor these text properties. For printing, it would be better
2459 to first convert to HTML or PDF (e.g,. using Pandoc)."
2460 :group 'markdown
2461 :type 'boolean
2462 :safe 'booleanp
2463 :package-version '(markdown-mode . "2.3"))
2464 (make-variable-buffer-local 'markdown-hide-markup)
2466 (defun markdown-toggle-markup-hiding (&optional arg)
2467 "Toggle the display or hiding of markup.
2468 With a prefix argument ARG, enable markup hiding if ARG is positive,
2469 and disable it otherwise.
2470 See `markdown-hide-markup' for additional details."
2471 (interactive (list (or current-prefix-arg 'toggle)))
2472 (setq markdown-hide-markup
2473 (if (eq arg 'toggle)
2474 (not markdown-hide-markup)
2475 (> (prefix-numeric-value arg) 0)))
2476 (if markdown-hide-markup
2477 (progn (add-to-invisibility-spec 'markdown-markup)
2478 (message "markdown-mode markup hiding enabled"))
2479 (progn (remove-from-invisibility-spec 'markdown-markup)
2480 (message "markdown-mode markup hiding disabled")))
2481 (markdown-reload-extensions))
2484 ;;; Font Lock =================================================================
2486 (require 'font-lock)
2488 (defvar markdown-italic-face 'markdown-italic-face
2489 "Face name to use for italic text.")
2491 (defvar markdown-bold-face 'markdown-bold-face
2492 "Face name to use for bold text.")
2494 (defvar markdown-strike-through-face 'markdown-strike-through-face
2495 "Face name to use for strike-through text.")
2497 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2498 "Face name to use as a base for header delimiters.")
2500 (defvar markdown-header-rule-face 'markdown-header-rule-face
2501 "Face name to use as a base for header rules.")
2503 (defvar markdown-header-face 'markdown-header-face
2504 "Face name to use as a base for headers.")
2506 (defvar markdown-header-face-1 'markdown-header-face-1
2507 "Face name to use for level-1 headers.")
2509 (defvar markdown-header-face-2 'markdown-header-face-2
2510 "Face name to use for level-2 headers.")
2512 (defvar markdown-header-face-3 'markdown-header-face-3
2513 "Face name to use for level-3 headers.")
2515 (defvar markdown-header-face-4 'markdown-header-face-4
2516 "Face name to use for level-4 headers.")
2518 (defvar markdown-header-face-5 'markdown-header-face-5
2519 "Face name to use for level-5 headers.")
2521 (defvar markdown-header-face-6 'markdown-header-face-6
2522 "Face name to use for level-6 headers.")
2524 (defvar markdown-inline-code-face 'markdown-inline-code-face
2525 "Face name to use for inline code.")
2527 (defvar markdown-list-face 'markdown-list-face
2528 "Face name to use for list markers.")
2530 (defvar markdown-blockquote-face 'markdown-blockquote-face
2531 "Face name to use for blockquote.")
2533 (defvar markdown-pre-face 'markdown-pre-face
2534 "Face name to use for preformatted text.")
2536 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2537 "Face name to use for programming language identifiers.")
2539 (defvar markdown-language-info-face 'markdown-language-info-face
2540 "Face name to use for programming info strings.")
2542 (defvar markdown-link-face 'markdown-link-face
2543 "Face name to use for links.")
2545 (defvar markdown-missing-link-face 'markdown-missing-link-face
2546 "Face name to use for links where the linked file does not exist.")
2548 (defvar markdown-reference-face 'markdown-reference-face
2549 "Face name to use for reference.")
2551 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2552 "Face name to use for footnote markers.")
2554 (defvar markdown-url-face 'markdown-url-face
2555 "Face name to use for URLs.")
2557 (defvar markdown-link-title-face 'markdown-link-title-face
2558 "Face name to use for reference link titles.")
2560 (defvar markdown-line-break-face 'markdown-line-break-face
2561 "Face name to use for hard line breaks.")
2563 (defvar markdown-comment-face 'markdown-comment-face
2564 "Face name to use for HTML comments.")
2566 (defvar markdown-math-face 'markdown-math-face
2567 "Face name to use for LaTeX expressions.")
2569 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2570 "Face name to use for metadata keys.")
2572 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2573 "Face name to use for metadata values.")
2575 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2576 "Face name to use for GFM checkboxes.")
2578 (defvar markdown-highlight-face 'markdown-highlight-face
2579 "Face name to use for mouse highlighting.")
2581 (defvar markdown-markup-face 'markdown-markup-face
2582 "Face name to use for markup elements.")
2584 (defgroup markdown-faces nil
2585 "Faces used in Markdown Mode"
2586 :group 'markdown
2587 :group 'faces)
2589 (defface markdown-italic-face
2590 '((t (:inherit italic)))
2591 "Face for italic text."
2592 :group 'markdown-faces)
2594 (defface markdown-bold-face
2595 '((t (:inherit bold)))
2596 "Face for bold text."
2597 :group 'markdown-faces)
2599 (defface markdown-strike-through-face
2600 '((t (:strike-through t)))
2601 "Face for strike-through text."
2602 :group 'markdown-faces)
2604 (defface markdown-markup-face
2605 '((t (:inherit shadow :slant normal :weight normal)))
2606 "Face for markup elements."
2607 :group 'markdown-faces)
2609 (defface markdown-header-rule-face
2610 '((t (:inherit markdown-markup-face)))
2611 "Base face for headers rules."
2612 :group 'markdown-faces)
2614 (defface markdown-header-delimiter-face
2615 '((t (:inherit markdown-markup-face)))
2616 "Base face for headers hash delimiter."
2617 :group 'markdown-faces)
2619 (defface markdown-list-face
2620 '((t (:inherit markdown-markup-face)))
2621 "Face for list item markers."
2622 :group 'markdown-faces)
2624 (defface markdown-blockquote-face
2625 '((t (:inherit font-lock-doc-face)))
2626 "Face for blockquote sections."
2627 :group 'markdown-faces)
2629 (defface markdown-code-face
2630 '((t (:inherit fixed-pitch)))
2631 "Face for inline code, pre blocks, and fenced code blocks.
2632 This may be used, for example, to add a contrasting background to
2633 inline code fragments and code blocks."
2634 :group 'markdown-faces)
2636 (defface markdown-inline-code-face
2637 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2638 "Face for inline code."
2639 :group 'markdown-faces)
2641 (defface markdown-pre-face
2642 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2643 "Face for preformatted text."
2644 :group 'markdown-faces)
2646 (defface markdown-language-keyword-face
2647 '((t (:inherit font-lock-type-face)))
2648 "Face for programming language identifiers."
2649 :group 'markdown-faces)
2651 (defface markdown-language-info-face
2652 '((t (:inherit font-lock-string-face)))
2653 "Face for programming language info strings."
2654 :group 'markdown-faces)
2656 (defface markdown-link-face
2657 '((t (:inherit link)))
2658 "Face for links."
2659 :group 'markdown-faces)
2661 (defface markdown-missing-link-face
2662 '((t (:inherit font-lock-warning-face)))
2663 "Face for missing links."
2664 :group 'markdown-faces)
2666 (defface markdown-reference-face
2667 '((t (:inherit markdown-markup-face)))
2668 "Face for link references."
2669 :group 'markdown-faces)
2671 (define-obsolete-face-alias 'markdown-footnote-face
2672 'markdown-footnote-marker-face "v2.3")
2674 (defface markdown-footnote-marker-face
2675 '((t (:inherit markdown-markup-face)))
2676 "Face for footnote markers."
2677 :group 'markdown-faces)
2679 (defface markdown-footnote-text-face
2680 '((t (:inherit font-lock-comment-face)))
2681 "Face for footnote text."
2682 :group 'markdown-faces)
2684 (defface markdown-url-face
2685 '((t (:inherit font-lock-string-face)))
2686 "Face for URLs that are part of markup.
2687 For example, this applies to URLs in inline links:
2688 [link text](http://example.com/)."
2689 :group 'markdown-faces)
2691 (defface markdown-plain-url-face
2692 '((t (:inherit markdown-link-face)))
2693 "Face for URLs that are also links.
2694 For example, this applies to plain angle bracket URLs:
2695 <http://example.com/>."
2696 :group 'markdown-faces)
2698 (defface markdown-link-title-face
2699 '((t (:inherit font-lock-comment-face)))
2700 "Face for reference link titles."
2701 :group 'markdown-faces)
2703 (defface markdown-line-break-face
2704 '((t (:inherit font-lock-constant-face :underline t)))
2705 "Face for hard line breaks."
2706 :group 'markdown-faces)
2708 (defface markdown-comment-face
2709 '((t (:inherit font-lock-comment-face)))
2710 "Face for HTML comments."
2711 :group 'markdown-faces)
2713 (defface markdown-math-face
2714 '((t (:inherit font-lock-string-face)))
2715 "Face for LaTeX expressions."
2716 :group 'markdown-faces)
2718 (defface markdown-metadata-key-face
2719 '((t (:inherit font-lock-variable-name-face)))
2720 "Face for metadata keys."
2721 :group 'markdown-faces)
2723 (defface markdown-metadata-value-face
2724 '((t (:inherit font-lock-string-face)))
2725 "Face for metadata values."
2726 :group 'markdown-faces)
2728 (defface markdown-gfm-checkbox-face
2729 '((t (:inherit font-lock-builtin-face)))
2730 "Face for GFM checkboxes."
2731 :group 'markdown-faces)
2733 (defface markdown-highlight-face
2734 '((t (:inherit highlight)))
2735 "Face for mouse highlighting."
2736 :group 'markdown-faces)
2738 (defface markdown-hr-face
2739 '((t (:inherit markdown-markup-face)))
2740 "Face for horizontal rules."
2741 :group 'markdown-faces)
2743 (defcustom markdown-header-scaling nil
2744 "Whether to use variable-height faces for headers.
2745 When non-nil, `markdown-header-face' will inherit from
2746 `variable-pitch' and the scaling values in
2747 `markdown-header-scaling-values' will be applied to
2748 headers of levels one through six respectively."
2749 :type 'boolean
2750 :initialize 'custom-initialize-default
2751 :set (lambda (symbol value)
2752 (set-default symbol value)
2753 (markdown-update-header-faces value))
2754 :group 'markdown-faces
2755 :package-version '(markdown-mode . "2.2"))
2757 (defcustom markdown-header-scaling-values
2758 '(2.0 1.7 1.4 1.1 1.0 1.0)
2759 "List of scaling values for headers of level one through six.
2760 Used when `markdown-header-scaling' is non-nil."
2761 :type 'list
2762 :initialize 'custom-initialize-default
2763 :set (lambda (symbol value)
2764 (set-default symbol value)
2765 (markdown-update-header-faces markdown-header-scaling value))
2766 :group 'markdown-faces)
2768 (defun markdown-make-header-faces ()
2769 "Build the faces used for Markdown headers."
2770 (let ((inherit-faces '(font-lock-function-name-face)))
2771 (when markdown-header-scaling
2772 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2773 (defface markdown-header-face
2774 `((t (:inherit ,inherit-faces :weight bold)))
2775 "Base face for headers."
2776 :group 'markdown-faces))
2777 (dotimes (num 6)
2778 (let* ((num1 (1+ num))
2779 (face-name (intern (format "markdown-header-face-%s" num1)))
2780 (scale (if markdown-header-scaling
2781 (float (nth num markdown-header-scaling-values))
2782 1.0)))
2783 (eval
2784 `(defface ,face-name
2785 '((t (:inherit markdown-header-face :height ,scale)))
2786 (format "Face for level %s headers.
2787 You probably don't want to customize this face directly. Instead
2788 you can customize the base face `markdown-header-face' or the
2789 variable-height variable `markdown-header-scaling'." ,num1)
2790 :group 'markdown-faces)))))
2792 (markdown-make-header-faces)
2794 (defun markdown-update-header-faces (&optional scaling scaling-values)
2795 "Update header faces, depending on if header SCALING is desired.
2796 If so, use given list of SCALING-VALUES relative to the baseline
2797 size of `markdown-header-face'."
2798 (dotimes (num 6)
2799 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2800 (scale (cond ((not scaling) 1.0)
2801 (scaling-values (float (nth num scaling-values)))
2802 (t (float (nth num markdown-header-scaling-values))))))
2803 (unless (get face-name 'saved-face) ; Don't update customized faces
2804 (set-face-attribute face-name nil :height scale)))))
2806 (defun markdown-syntactic-face (state)
2807 "Return font-lock face for characters with given STATE.
2808 See `font-lock-syntactic-face-function' for details."
2809 (let ((in-comment (nth 4 state)))
2810 (cond
2811 (in-comment 'markdown-comment-face)
2812 (t nil))))
2814 (defcustom markdown-list-item-bullets
2815 '("●" "◎" "○" "◆" "◇" "►" "•")
2816 "List of bullets to use for unordered lists.
2817 It can contain any number of symbols, which will be repeated.
2818 Depending on your font, some reasonable choices are:
2819 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2820 :group 'markdown
2821 :type '(repeat (string :tag "Bullet character"))
2822 :package-version '(markdown-mode . "2.3"))
2824 (defvar markdown-mode-font-lock-keywords-basic
2825 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2826 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2827 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2828 (2 markdown-markup-face)
2829 (3 markdown-metadata-value-face)))
2830 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2831 (2 markdown-markup-properties nil t)
2832 (3 markdown-language-keyword-properties nil t)
2833 (4 markdown-language-info-properties nil t)
2834 (5 markdown-markup-properties nil t)))
2835 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2836 (markdown-fontify-gfm-code-blocks)
2837 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2838 (2 markdown-markup-properties nil t)
2839 (3 markdown-language-keyword-properties nil t)
2840 (4 markdown-language-info-properties nil t)
2841 (5 markdown-markup-properties nil t)))
2842 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2843 (markdown-fontify-fenced-code-blocks)
2844 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2845 (markdown-fontify-headings)
2846 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2847 (2 markdown-markup-face)
2848 (3 markdown-metadata-value-face)))
2849 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2850 (2 markdown-markup-face)
2851 (3 markdown-metadata-value-face)))
2852 (markdown-fontify-hrs)
2853 (markdown-match-code . ((1 markdown-markup-properties prepend)
2854 (2 markdown-inline-code-face prepend)
2855 (3 markdown-markup-properties prepend)))
2856 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2857 (2 markdown-inline-code-face)
2858 (3 markdown-markup-properties)))
2859 (markdown-fontify-angle-uris)
2860 (,markdown-regex-email . 'markdown-plain-url-face)
2861 (markdown-fontify-list-items)
2862 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2863 (1 markdown-markup-properties) ; [^
2864 (2 markdown-footnote-marker-face) ; label
2865 (3 markdown-markup-properties))) ; ]
2866 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2867 (1 markdown-markup-properties) ; ^
2868 (2 markdown-markup-properties) ; [
2869 (3 'markdown-footnote-text-face) ; text
2870 (4 markdown-markup-properties))) ; ]
2871 (markdown-match-includes . ((1 markdown-markup-properties)
2872 (2 markdown-markup-properties nil t)
2873 (3 markdown-include-title-properties nil t)
2874 (4 markdown-markup-properties nil t)
2875 (5 markdown-markup-properties)
2876 (6 'markdown-url-face)
2877 (7 markdown-markup-properties)))
2878 (markdown-fontify-inline-links)
2879 (markdown-fontify-reference-links)
2880 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2881 (2 markdown-reference-face) ; label
2882 (3 markdown-markup-face) ; ]
2883 (4 markdown-markup-face) ; :
2884 (5 markdown-url-face) ; url
2885 (6 markdown-link-title-face))) ; "title" (optional)
2886 (markdown-fontify-plain-uris)
2887 ;; Math mode $..$
2888 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2889 (2 markdown-math-face append)
2890 (3 markdown-markup-face prepend)))
2891 ;; Math mode $$..$$
2892 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2893 (2 markdown-math-face append)
2894 (3 markdown-markup-face prepend)))
2895 ;; Math mode \[..\] and \\[..\\]
2896 (markdown-match-math-display . ((1 markdown-markup-face prepend)
2897 (3 markdown-math-face append)
2898 (4 markdown-markup-face prepend)))
2899 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2900 (2 markdown-bold-face append)
2901 (3 markdown-markup-properties prepend)))
2902 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2903 (2 markdown-italic-face append)
2904 (3 markdown-markup-properties prepend)))
2905 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2906 (4 markdown-strike-through-face)
2907 (5 markdown-markup-properties)))
2908 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2909 (markdown-fontify-sub-superscripts)
2910 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2911 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2912 (markdown-fontify-blockquotes)
2913 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
2914 "Syntax highlighting for Markdown files.")
2916 (defvar markdown-mode-font-lock-keywords nil
2917 "Default highlighting expressions for Markdown mode.
2918 This variable is defined as a buffer-local variable for dynamic
2919 extension support.")
2921 ;; Footnotes
2922 (defvar markdown-footnote-counter 0
2923 "Counter for footnote numbers.")
2924 (make-variable-buffer-local 'markdown-footnote-counter)
2926 (defconst markdown-footnote-chars
2927 "[[:alnum:]-]"
2928 "Regular expression matching any character that is allowed in a footnote identifier.")
2930 (defconst markdown-regex-footnote-definition
2931 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2932 "Regular expression matching a footnote definition, capturing the label.")
2935 ;;; Compatibility =============================================================
2937 (defun markdown-replace-regexp-in-string (regexp rep string)
2938 "Replace ocurrences of REGEXP with REP in STRING.
2939 This is a compatibility wrapper to provide `replace-regexp-in-string'
2940 in XEmacs 21."
2941 (if (featurep 'xemacs)
2942 (replace-in-string string regexp rep)
2943 (replace-regexp-in-string regexp rep string)))
2945 ;; `markdown-use-region-p' is a compatibility function which checks
2946 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2947 (eval-and-compile
2948 (cond
2949 ;; Emacs 24 and newer
2950 ((fboundp 'use-region-p)
2951 (defalias 'markdown-use-region-p 'use-region-p))
2952 ;; XEmacs
2953 ((fboundp 'region-active-p)
2954 (defalias 'markdown-use-region-p 'region-active-p))))
2956 ;; Use new names for outline-mode functions in Emacs 25 and later.
2957 (eval-and-compile
2958 (defalias 'markdown-hide-sublevels
2959 (if (fboundp 'outline-hide-sublevels)
2960 'outline-hide-sublevels
2961 'hide-sublevels))
2962 (defalias 'markdown-show-all
2963 (if (fboundp 'outline-show-all)
2964 'outline-show-all
2965 'show-all))
2966 (defalias 'markdown-hide-body
2967 (if (fboundp 'outline-hide-body)
2968 'outline-hide-body
2969 'hide-body))
2970 (defalias 'markdown-show-children
2971 (if (fboundp 'outline-show-children)
2972 'outline-show-children
2973 'show-children))
2974 (defalias 'markdown-show-subtree
2975 (if (fboundp 'outline-show-subtree)
2976 'outline-show-subtree
2977 'show-subtree))
2978 (defalias 'markdown-hide-subtree
2979 (if (fboundp 'outline-hide-subtree)
2980 'outline-hide-subtree
2981 'hide-subtree)))
2983 ;; Provide directory-name-p to Emacs 24
2984 (defsubst markdown-directory-name-p (name)
2985 "Return non-nil if NAME ends with a directory separator character.
2986 Taken from `directory-name-p' from Emacs 25 and provided here for
2987 backwards compatibility."
2988 (let ((len (length name))
2989 (lastc ?.))
2990 (if (> len 0)
2991 (setq lastc (aref name (1- len))))
2992 (or (= lastc ?/)
2993 (and (memq system-type '(windows-nt ms-dos))
2994 (= lastc ?\\)))))
2996 ;; Provide a function to find files recursively in Emacs 24.
2997 (defalias 'markdown-directory-files-recursively
2998 (if (fboundp 'directory-files-recursively)
2999 'directory-files-recursively
3000 (lambda (dir regexp)
3001 "Return list of all files under DIR that have file names matching REGEXP.
3002 This function works recursively. Files are returned in \"depth first\"
3003 order, and files from each directory are sorted in alphabetical order.
3004 Each file name appears in the returned list in its absolute form.
3005 Based on `directory-files-recursively' from Emacs 25 and provided
3006 here for backwards compatibility."
3007 (let ((result nil)
3008 (files nil)
3009 ;; When DIR is "/", remote file names like "/method:" could
3010 ;; also be offered. We shall suppress them.
3011 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3012 (dolist (file (sort (file-name-all-completions "" dir)
3013 'string<))
3014 (unless (member file '("./" "../"))
3015 (if (markdown-directory-name-p file)
3016 (let* ((leaf (substring file 0 (1- (length file))))
3017 (full-file (expand-file-name leaf dir)))
3018 (setq result
3019 (nconc result (markdown-directory-files-recursively
3020 full-file regexp))))
3021 (when (string-match-p regexp file)
3022 (push (expand-file-name file dir) files)))))
3023 (nconc result (nreverse files))))))
3025 (defun markdown-flyspell-check-word-p ()
3026 "Return t if `flyspell' should check word just before point.
3027 Used for `flyspell-generic-check-word-predicate'."
3028 (save-excursion
3029 (goto-char (1- (point)))
3030 (not (or (markdown-code-block-at-point-p)
3031 (markdown-inline-code-at-point-p)
3032 (markdown-in-comment-p)
3033 (let ((faces (get-text-property (point) 'face)))
3034 (if (listp faces)
3035 (or (memq 'markdown-reference-face faces)
3036 (memq 'markdown-markup-face faces)
3037 (memq 'markdown-plain-url-face faces)
3038 (memq 'markdown-inline-code-face faces)
3039 (memq 'markdown-url-face faces))
3040 (memq faces '(markdown-reference-face
3041 markdown-markup-face
3042 markdown-plain-url-face
3043 markdown-inline-code-face
3044 markdown-url-face))))))))
3046 (defun markdown-font-lock-ensure ()
3047 "Provide `font-lock-ensure' in Emacs 24."
3048 (if (fboundp 'font-lock-ensure)
3049 (font-lock-ensure)
3050 (with-no-warnings
3051 ;; Suppress warning about non-interactive use of
3052 ;; `font-lock-fontify-buffer' in Emacs 25.
3053 (font-lock-fontify-buffer))))
3056 ;;; Markdown Parsing Functions ================================================
3058 (defun markdown-cur-line-blank (&optional predicate)
3059 "Return t if the current line is blank and nil otherwise.
3060 When PREDICATE is non-nil, don't modify the match data."
3061 (save-excursion
3062 (beginning-of-line)
3063 (let ((regexp "^\\s *$"))
3064 (if predicate
3065 (looking-at-p regexp)
3066 (looking-at regexp)))))
3068 (defun markdown-cur-line-blank-p ()
3069 "Same as `markdown-cur-line-blank', but does not change the match data."
3070 (markdown-cur-line-blank t))
3072 (defun markdown-prev-line-blank (&optional predicate)
3073 "Return t if the previous line is blank and nil otherwise.
3074 If we are at the first line, then consider the previous line to be blank.
3075 When PREDICATE is non-nil, don't modify the match data."
3076 (or (= (line-beginning-position) (point-min))
3077 (save-excursion
3078 (forward-line -1)
3079 (markdown-cur-line-blank predicate))))
3081 (defun markdown-prev-line-blank-p ()
3082 "Same as `markdown-prev-line-blank', but does not change the match data."
3083 (markdown-prev-line-blank t))
3085 (defun markdown-next-line-blank (&optional predicate)
3086 "Return t if the next line is blank and nil otherwise.
3087 If we are at the last line, then consider the next line to be blank.
3088 When PREDICATE is non-nil, don't modify the match data."
3089 (or (= (line-end-position) (point-max))
3090 (save-excursion
3091 (forward-line 1)
3092 (markdown-cur-line-blank predicate))))
3094 (defun markdown-next-line-blank-p ()
3095 "Same as `markdown-next-line-blank', but does not change the match data."
3096 (markdown-next-line-blank t))
3098 (defun markdown-prev-line-indent ()
3099 "Return the number of leading whitespace characters in the previous line.
3100 Return 0 if the current line is the first line in the buffer."
3101 (save-excursion
3102 (if (= (line-beginning-position) (point-min))
3104 (forward-line -1)
3105 (current-indentation))))
3107 (defun markdown-next-line-indent ()
3108 "Return the number of leading whitespace characters in the next line.
3109 Return 0 if line is the last line in the buffer."
3110 (save-excursion
3111 (if (= (line-end-position) (point-max))
3113 (forward-line 1)
3114 (current-indentation))))
3116 (defun markdown-cur-non-list-indent ()
3117 "Return beginning position of list item text (not including the list marker).
3118 Return nil if the current line is not the beginning of a list item."
3119 (save-match-data
3120 (save-excursion
3121 (beginning-of-line)
3122 (when (re-search-forward markdown-regex-list (line-end-position) t)
3123 (current-column)))))
3125 (defun markdown-prev-non-list-indent ()
3126 "Return position of the first non-list-marker on the previous line."
3127 (save-excursion
3128 (forward-line -1)
3129 (markdown-cur-non-list-indent)))
3131 (defun markdown-new-baseline ()
3132 "Determine if the current line begins a new baseline level."
3133 (save-excursion
3134 (beginning-of-line)
3135 (or (looking-at markdown-regex-header)
3136 (looking-at markdown-regex-hr)
3137 (and (null (markdown-cur-non-list-indent))
3138 (= (current-indentation) 0)
3139 (markdown-prev-line-blank)))))
3141 (defun markdown-search-backward-baseline ()
3142 "Search backward baseline point with no indentation and not a list item."
3143 (end-of-line)
3144 (let (stop)
3145 (while (not (or stop (bobp)))
3146 (re-search-backward markdown-regex-block-separator-noindent nil t)
3147 (when (match-end 2)
3148 (goto-char (match-end 2))
3149 (cond
3150 ((markdown-new-baseline)
3151 (setq stop t))
3152 ((looking-at-p markdown-regex-list)
3153 (setq stop nil))
3154 (t (setq stop t)))))))
3156 (defun markdown-update-list-levels (marker indent levels)
3157 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3158 Here, MARKER is a string representing the type of list, INDENT is an integer
3159 giving the indentation, in spaces, of the current block, and LEVELS is a
3160 list of the indentation levels of parent list items. When LEVELS is nil,
3161 it means we are at baseline (not inside of a nested list)."
3162 (cond
3163 ;; New list item at baseline.
3164 ((and marker (null levels))
3165 (setq levels (list indent)))
3166 ;; List item with greater indentation (four or more spaces).
3167 ;; Increase list level.
3168 ((and marker (>= indent (+ (car levels) 4)))
3169 (setq levels (cons indent levels)))
3170 ;; List item with greater or equal indentation (less than four spaces).
3171 ;; Do not increase list level.
3172 ((and marker (>= indent (car levels)))
3173 levels)
3174 ;; Lesser indentation level.
3175 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3176 ;; indentation could move back more than one list level). Note
3177 ;; that this block need not be the beginning of list item.
3178 ((< indent (car levels))
3179 (while (and (> (length levels) 1)
3180 (< indent (+ (cadr levels) 4)))
3181 (setq levels (cdr levels)))
3182 levels)
3183 ;; Otherwise, do nothing.
3184 (t levels)))
3186 (defun markdown-calculate-list-levels ()
3187 "Calculate list levels at point.
3188 Return a list of the form (n1 n2 n3 ...) where n1 is the
3189 indentation of the deepest nested list item in the branch of
3190 the list at the point, n2 is the indentation of the parent
3191 list item, and so on. The depth of the list item is therefore
3192 the length of the returned list. If the point is not at or
3193 immediately after a list item, return nil."
3194 (save-excursion
3195 (let ((first (point)) levels indent pre-regexp)
3196 ;; Find a baseline point with zero list indentation
3197 (markdown-search-backward-baseline)
3198 ;; Search for all list items between baseline and LOC
3199 (while (and (< (point) first)
3200 (re-search-forward markdown-regex-list first t))
3201 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3202 (beginning-of-line)
3203 (cond
3204 ;; Make sure this is not a header or hr
3205 ((markdown-new-baseline) (setq levels nil))
3206 ;; Make sure this is not a line from a pre block
3207 ((looking-at-p pre-regexp))
3208 ;; If not, then update levels
3210 (setq indent (current-indentation))
3211 (setq levels (markdown-update-list-levels (match-string 2)
3212 indent levels))))
3213 (end-of-line))
3214 levels)))
3216 (defun markdown-prev-list-item (level)
3217 "Search backward from point for a list item with indentation LEVEL.
3218 Set point to the beginning of the item, and return point, or nil
3219 upon failure."
3220 (let (bounds indent prev)
3221 (setq prev (point))
3222 (forward-line -1)
3223 (setq indent (current-indentation))
3224 (while
3225 (cond
3226 ;; List item
3227 ((and (looking-at-p markdown-regex-list)
3228 (setq bounds (markdown-cur-list-item-bounds)))
3229 (cond
3230 ;; Stop and return point at item of equal indentation
3231 ((= (nth 3 bounds) level)
3232 (setq prev (point))
3233 nil)
3234 ;; Stop and return nil at item with lesser indentation
3235 ((< (nth 3 bounds) level)
3236 (setq prev nil)
3237 nil)
3238 ;; Stop at beginning of buffer
3239 ((bobp) (setq prev nil))
3240 ;; Continue at item with greater indentation
3241 ((> (nth 3 bounds) level) t)))
3242 ;; Stop at beginning of buffer
3243 ((bobp) (setq prev nil))
3244 ;; Continue if current line is blank
3245 ((markdown-cur-line-blank-p) t)
3246 ;; Continue while indentation is the same or greater
3247 ((>= indent level) t)
3248 ;; Stop if current indentation is less than list item
3249 ;; and the next is blank
3250 ((and (< indent level)
3251 (markdown-next-line-blank-p))
3252 (setq prev nil))
3253 ;; Stop at a header
3254 ((looking-at-p markdown-regex-header) (setq prev nil))
3255 ;; Stop at a horizontal rule
3256 ((looking-at-p markdown-regex-hr) (setq prev nil))
3257 ;; Otherwise, continue.
3258 (t t))
3259 (forward-line -1)
3260 (setq indent (current-indentation)))
3261 prev))
3263 (defun markdown-next-list-item (level)
3264 "Search forward from point for the next list item with indentation LEVEL.
3265 Set point to the beginning of the item, and return point, or nil
3266 upon failure."
3267 (let (bounds indent next)
3268 (setq next (point))
3269 (if (looking-at markdown-regex-header-setext)
3270 (goto-char (match-end 0)))
3271 (forward-line)
3272 (setq indent (current-indentation))
3273 (while
3274 (cond
3275 ;; Stop at end of the buffer.
3276 ((eobp) nil)
3277 ;; Continue if the current line is blank
3278 ((markdown-cur-line-blank-p) t)
3279 ;; List item
3280 ((and (looking-at-p markdown-regex-list)
3281 (setq bounds (markdown-cur-list-item-bounds)))
3282 (cond
3283 ;; Continue at item with greater indentation
3284 ((> (nth 3 bounds) level) t)
3285 ;; Stop and return point at item of equal indentation
3286 ((= (nth 3 bounds) level)
3287 (setq next (point))
3288 nil)
3289 ;; Stop and return nil at item with lesser indentation
3290 ((< (nth 3 bounds) level)
3291 (setq next nil)
3292 nil)))
3293 ;; Continue while indentation is the same or greater
3294 ((>= indent level) t)
3295 ;; Stop if current indentation is less than list item
3296 ;; and the previous line was blank.
3297 ((and (< indent level)
3298 (markdown-prev-line-blank-p))
3299 (setq next nil))
3300 ;; Stop at a header
3301 ((looking-at-p markdown-regex-header) (setq next nil))
3302 ;; Stop at a horizontal rule
3303 ((looking-at-p markdown-regex-hr) (setq next nil))
3304 ;; Otherwise, continue.
3305 (t t))
3306 (forward-line)
3307 (setq indent (current-indentation)))
3308 next))
3310 (defun markdown-cur-list-item-end (level)
3311 "Move to the end of the current list item with nonlist indentation LEVEL.
3312 If the point is not in a list item, do nothing."
3313 (let (indent)
3314 (forward-line)
3315 (setq indent (current-indentation))
3316 (while
3317 (cond
3318 ;; Stop at end of the buffer.
3319 ((eobp) nil)
3320 ;; Continue if the current line is blank
3321 ((markdown-cur-line-blank-p) t)
3322 ;; Continue while indentation is the same or greater
3323 ((>= indent level) t)
3324 ;; Stop if current indentation is less than list item
3325 ;; and the previous line was blank.
3326 ((and (< indent level)
3327 (markdown-prev-line-blank-p))
3328 nil)
3329 ;; Stop at a new list item of the same or lesser indentation
3330 ((looking-at-p markdown-regex-list) nil)
3331 ;; Stop at a header
3332 ((looking-at-p markdown-regex-header) nil)
3333 ;; Stop at a horizontal rule
3334 ((looking-at-p markdown-regex-hr) nil)
3335 ;; Otherwise, continue.
3336 (t t))
3337 (forward-line)
3338 (setq indent (current-indentation)))
3339 ;; Don't skip over whitespace for empty list items (marker and
3340 ;; whitespace only), just move to end of whitespace.
3341 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3342 (goto-char (match-end 3))
3343 (skip-syntax-backward "-"))))
3345 (defun markdown-cur-list-item-bounds ()
3346 "Return bounds and indentation of the current list item.
3347 Return a list of the following form:
3349 (begin end indent nonlist-indent marker checkbox)
3351 The named components are:
3353 - begin: Position of beginning of list item, including leading indentation.
3354 - end: Position of the end of the list item, including list item text.
3355 - indent: Number of characters of indentation before list marker (an integer).
3356 - nonlist-indent: Number characters of indentation, list
3357 marker, and whitespace following list marker (an integer).
3358 - marker: String containing the list marker and following whitespace
3359 (e.g., \"- \" or \"* \").
3360 - checkbox: String containing the GFM checkbox portion, if any,
3361 including any trailing whitespace before the text
3362 begins (e.g., \"[x] \").
3364 As an example, for the following unordered list item
3366 - item
3368 the returned list would be
3370 (1 14 3 5 \"- \" nil)
3372 If the point is not inside a list item, return nil.
3373 Leave match data intact for `markdown-regex-list'."
3374 (save-excursion
3375 (let ((cur (point)))
3376 (end-of-line)
3377 (when (re-search-backward markdown-regex-list nil t)
3378 (let* ((begin (match-beginning 0))
3379 (indent (length (match-string-no-properties 1)))
3380 (nonlist-indent (length (match-string 0)))
3381 (marker (concat (match-string-no-properties 2)
3382 (match-string-no-properties 3)))
3383 (checkbox (progn (goto-char (match-end 0))
3384 (when (looking-at "\\[[xX ]\\]\\s-*")
3385 (match-string-no-properties 0))))
3386 (end (save-match-data
3387 (markdown-cur-list-item-end nonlist-indent)
3388 (point))))
3389 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3390 (list begin end indent nonlist-indent marker checkbox)))))))
3392 (defun markdown-list-item-at-point-p ()
3393 "Return t if there is a list item at the point and nil otherwise."
3394 (save-match-data (markdown-cur-list-item-bounds)))
3396 (defun markdown-prev-list-item-bounds ()
3397 "Return bounds of previous item in the same list of any level.
3398 The return value has the same form as that of
3399 `markdown-cur-list-item-bounds'."
3400 (save-excursion
3401 (let ((cur-bounds (markdown-cur-list-item-bounds))
3402 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3403 stop)
3404 (when cur-bounds
3405 (goto-char (nth 0 cur-bounds))
3406 (while (and (not stop) (not (bobp))
3407 (re-search-backward markdown-regex-list
3408 beginning-of-list t))
3409 (unless (or (looking-at markdown-regex-hr)
3410 (markdown-code-block-at-point-p))
3411 (setq stop (point))))
3412 (markdown-cur-list-item-bounds)))))
3414 (defun markdown-next-list-item-bounds ()
3415 "Return bounds of next item in the same list of any level.
3416 The return value has the same form as that of
3417 `markdown-cur-list-item-bounds'."
3418 (save-excursion
3419 (let ((cur-bounds (markdown-cur-list-item-bounds))
3420 (end-of-list (save-excursion (markdown-end-of-list)))
3421 stop)
3422 (when cur-bounds
3423 (goto-char (nth 0 cur-bounds))
3424 (end-of-line)
3425 (while (and (not stop) (not (eobp))
3426 (re-search-forward markdown-regex-list
3427 end-of-list t))
3428 (unless (or (looking-at markdown-regex-hr)
3429 (markdown-code-block-at-point-p))
3430 (setq stop (point))))
3431 (when stop
3432 (markdown-cur-list-item-bounds))))))
3434 (defun markdown-beginning-of-list ()
3435 "Move point to beginning of list at point, if any."
3436 (interactive)
3437 (let ((orig-point (point))
3438 (list-begin (save-excursion
3439 (markdown-search-backward-baseline)
3440 ;; Stop at next list item, regardless of the indentation.
3441 (markdown-next-list-item (point-max))
3442 (when (looking-at markdown-regex-list)
3443 (point)))))
3444 (when (and list-begin (<= list-begin orig-point))
3445 (goto-char list-begin))))
3447 (defun markdown-end-of-list ()
3448 "Move point to end of list at point, if any."
3449 (interactive)
3450 (let ((start (point))
3451 (end (save-excursion
3452 (when (markdown-beginning-of-list)
3453 ;; Items can't have nonlist-indent <= 1, so this
3454 ;; moves past all list items.
3455 (markdown-next-list-item 1)
3456 (skip-syntax-backward "-")
3457 (unless (eobp) (forward-char 1))
3458 (point)))))
3459 (when (and end (>= end start))
3460 (goto-char end))))
3462 (defun markdown-up-list ()
3463 "Move point to beginning of parent list item."
3464 (interactive)
3465 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3466 (when cur-bounds
3467 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3468 (let ((up-bounds (markdown-cur-list-item-bounds)))
3469 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3470 (point))))))
3472 (defun markdown-bounds-of-thing-at-point (thing)
3473 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3474 Does not include trailing newlines when THING is 'line. Handles the
3475 end of buffer case by setting both endpoints equal to the value of
3476 `point-max', since an empty region will trigger empty markup insertion.
3477 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3478 (let* ((bounds (bounds-of-thing-at-point thing))
3479 (a (car bounds))
3480 (b (cdr bounds)))
3481 (when bounds
3482 (when (eq thing 'line)
3483 (cond ((and (eobp) (markdown-cur-line-blank-p))
3484 (setq a b))
3485 ((char-equal (char-before b) ?\^J)
3486 (setq b (1- b)))))
3487 (cons a b))))
3489 (defun markdown-reference-definition (reference)
3490 "Find out whether Markdown REFERENCE is defined.
3491 REFERENCE should not include the square brackets.
3492 When REFERENCE is defined, return a list of the form (text start end)
3493 containing the definition text itself followed by the start and end
3494 locations of the text. Otherwise, return nil.
3495 Leave match data for `markdown-regex-reference-definition'
3496 intact additional processing."
3497 (let ((reference (downcase reference)))
3498 (save-excursion
3499 (goto-char (point-min))
3500 (catch 'found
3501 (while (re-search-forward markdown-regex-reference-definition nil t)
3502 (when (string= reference (downcase (match-string-no-properties 2)))
3503 (throw 'found
3504 (list (match-string-no-properties 5)
3505 (match-beginning 5) (match-end 5)))))))))
3507 (defun markdown-get-defined-references ()
3508 "Return a list of all defined reference labels (not including square brackets)."
3509 (save-excursion
3510 (goto-char (point-min))
3511 (let (refs)
3512 (while (re-search-forward markdown-regex-reference-definition nil t)
3513 (let ((target (match-string-no-properties 2)))
3514 (cl-pushnew target refs :test #'equal)))
3515 (reverse refs))))
3517 (defun markdown-get-used-uris ()
3518 "Return a list of all used URIs in the buffer."
3519 (save-excursion
3520 (goto-char (point-min))
3521 (let (uris)
3522 (while (re-search-forward
3523 (concat "\\(?:" markdown-regex-link-inline
3524 "\\|" markdown-regex-angle-uri
3525 "\\|" markdown-regex-uri
3526 "\\|" markdown-regex-email
3527 "\\)")
3528 nil t)
3529 (unless (or (markdown-inline-code-at-point-p)
3530 (markdown-code-block-at-point-p))
3531 (cl-pushnew (or (match-string-no-properties 6)
3532 (match-string-no-properties 10)
3533 (match-string-no-properties 12)
3534 (match-string-no-properties 13))
3535 uris :test #'equal)))
3536 (reverse uris))))
3538 (defun markdown-inline-code-at-pos (pos)
3539 "Return non-nil if there is an inline code fragment at POS.
3540 Return nil otherwise. Set match data according to
3541 `markdown-match-code' upon success.
3542 This function searches the block for a code fragment that
3543 contains the point using `markdown-match-code'. We do this
3544 because `thing-at-point-looking-at' does not work reliably with
3545 `markdown-regex-code'.
3547 The match data is set as follows:
3548 Group 1 matches the opening backquotes.
3549 Group 2 matches the code fragment itself, without backquotes.
3550 Group 3 matches the closing backquotes."
3551 (save-excursion
3552 (goto-char pos)
3553 (let ((old-point (point))
3554 (end-of-block (progn (markdown-end-of-text-block) (point)))
3555 found)
3556 (markdown-beginning-of-text-block)
3557 (while (and (markdown-match-code end-of-block)
3558 (setq found t)
3559 (< (match-end 0) old-point)))
3560 (and found ; matched something
3561 (<= (match-beginning 0) old-point) ; match contains old-point
3562 (>= (match-end 0) old-point)))))
3564 (defun markdown-inline-code-at-pos-p (pos)
3565 "Return non-nil if there is an inline code fragment at POS.
3566 Like `markdown-inline-code-at-pos`, but preserves match data."
3567 (save-match-data (markdown-inline-code-at-pos pos)))
3569 (defun markdown-inline-code-at-point ()
3570 "Return non-nil if the point is at an inline code fragment.
3571 See `markdown-inline-code-at-pos' for details."
3572 (markdown-inline-code-at-pos (point)))
3574 (defun markdown-inline-code-at-point-p ()
3575 "Return non-nil if there is inline code at the point.
3576 This is a predicate function counterpart to
3577 `markdown-inline-code-at-point' which does not modify the match
3578 data. See `markdown-code-block-at-point-p' for code blocks."
3579 (save-match-data (markdown-inline-code-at-pos (point))))
3581 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3583 (defun markdown-code-block-at-pos (pos)
3584 "Return match data list if there is a code block at POS.
3585 Uses text properties at the beginning of the line position.
3586 This includes pre blocks, tilde-fenced code blocks, and GFM
3587 quoted code blocks. Return nil otherwise."
3588 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3589 (or (get-text-property pos 'markdown-pre)
3590 (markdown-get-enclosing-fenced-block-construct pos)
3591 ;; polymode removes text properties set by markdown-mode, so
3592 ;; check if `poly-markdown-mode' is active and whether the
3593 ;; `chunkmode' property is non-nil at POS.
3594 (and (bound-and-true-p poly-markdown-mode)
3595 (get-text-property pos 'chunkmode))))
3597 ;; Function was renamed to emphasize that it does not modify match-data.
3598 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3600 (defun markdown-code-block-at-point-p ()
3601 "Return non-nil if there is a code block at the point.
3602 This includes pre blocks, tilde-fenced code blocks, and GFM
3603 quoted code blocks. This function does not modify the match
3604 data. See `markdown-inline-code-at-point-p' for inline code."
3605 (save-match-data (markdown-code-block-at-pos (point))))
3607 (defun markdown-heading-at-point ()
3608 "Return non-nil if there is a heading at the point.
3609 Set match data for `markdown-regex-header'."
3610 (let ((match-data (get-text-property (point) 'markdown-heading)))
3611 (when match-data
3612 (set-match-data match-data)
3613 t)))
3615 (defun markdown-pipe-at-bol-p ()
3616 "Return non-nil if the line begins with a pipe symbol.
3617 This may be useful for tables and Pandoc's line_blocks extension."
3618 (char-equal (char-after (point-at-bol)) ?|))
3621 ;;; Markdown Font Lock Matching Functions =====================================
3623 (defun markdown-range-property-any (begin end prop prop-values)
3624 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3625 Also returns t if PROP is a list containing one of the PROP-VALUES.
3626 Return nil otherwise."
3627 (let (props)
3628 (catch 'found
3629 (dolist (loc (number-sequence begin end))
3630 (when (setq props (get-text-property loc prop))
3631 (cond ((listp props)
3632 ;; props is a list, check for membership
3633 (dolist (val prop-values)
3634 (when (memq val props) (throw 'found loc))))
3636 ;; props is a scalar, check for equality
3637 (dolist (val prop-values)
3638 (when (eq val props) (throw 'found loc))))))))))
3640 (defun markdown-range-properties-exist (begin end props)
3641 (cl-loop
3642 for loc in (number-sequence begin end)
3643 with result = nil
3644 while (not
3645 (setq result
3646 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3647 finally return result))
3649 (defun markdown-match-inline-generic (regex last &optional faceless)
3650 "Match inline REGEX from the point to LAST.
3651 When FACELESS is non-nil, do not return matches where faces have been applied."
3652 (when (re-search-forward regex last t)
3653 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3654 (face (and faceless (text-property-not-all
3655 (match-beginning 0) (match-end 0) 'face nil))))
3656 (cond
3657 ;; In code block: move past it and recursively search again
3658 (bounds
3659 (when (< (goto-char (cl-second bounds)) last)
3660 (markdown-match-inline-generic regex last faceless)))
3661 ;; When faces are found in the match range, skip over the match and
3662 ;; recursively search again.
3663 (face
3664 (when (< (goto-char (match-end 0)) last)
3665 (markdown-match-inline-generic regex last faceless)))
3666 ;; Keep match data and return t when in bounds.
3668 (<= (match-end 0) last))))))
3670 (defun markdown-match-code (last)
3671 "Match inline code fragments from point to LAST."
3672 (unless (bobp)
3673 (backward-char 1))
3674 (when (markdown-match-inline-generic markdown-regex-code last)
3675 (let ((begin (match-beginning 1))
3676 (end (match-end 1))
3677 (open-begin (match-beginning 2))
3678 (open-end (match-end 2))
3679 (code-begin (match-beginning 3))
3680 (code-end (match-end 3))
3681 (close-begin (match-beginning 4))
3682 (close-end (match-end 4)))
3683 (if (or (markdown-in-comment-p begin)
3684 (markdown-in-comment-p end)
3685 (markdown-code-block-at-pos begin))
3686 (progn (goto-char (min (1+ begin) last))
3687 (when (< (point) last)
3688 (markdown-match-code last)))
3689 (set-match-data (list begin end
3690 open-begin open-end
3691 code-begin code-end
3692 close-begin close-end))
3693 t))))
3695 (defun markdown-match-bold (last)
3696 "Match inline bold from the point to LAST."
3697 (when (markdown-match-inline-generic markdown-regex-bold last)
3698 (let ((begin (match-beginning 2))
3699 (end (match-end 2)))
3700 (if (or (markdown-inline-code-at-pos-p begin)
3701 (markdown-inline-code-at-pos-p end)
3702 (markdown-in-comment-p)
3703 (markdown-range-property-any
3704 begin begin 'face '(markdown-url-face
3705 markdown-plain-url-face))
3706 (markdown-range-property-any
3707 begin end 'face '(markdown-inline-code-face
3708 markdown-math-face)))
3709 (progn (goto-char (min (1+ begin) last))
3710 (when (< (point) last)
3711 (markdown-match-italic last)))
3712 (set-match-data (list (match-beginning 2) (match-end 2)
3713 (match-beginning 3) (match-end 3)
3714 (match-beginning 4) (match-end 4)
3715 (match-beginning 5) (match-end 5)))
3716 t))))
3718 (defun markdown-match-italic (last)
3719 "Match inline italics from the point to LAST."
3720 (let ((regex (if (eq major-mode 'gfm-mode)
3721 markdown-regex-gfm-italic markdown-regex-italic)))
3722 (when (markdown-match-inline-generic regex last)
3723 (let ((begin (match-beginning 1))
3724 (end (match-end 1)))
3725 (if (or (markdown-inline-code-at-pos-p begin)
3726 (markdown-inline-code-at-pos-p end)
3727 (markdown-in-comment-p)
3728 (markdown-range-property-any
3729 begin begin 'face '(markdown-url-face
3730 markdown-plain-url-face))
3731 (markdown-range-property-any
3732 begin end 'face '(markdown-inline-code-face
3733 markdown-bold-face
3734 markdown-list-face
3735 markdown-math-face)))
3736 (progn (goto-char (min (1+ begin) last))
3737 (when (< (point) last)
3738 (markdown-match-italic last)))
3739 (set-match-data (list (match-beginning 1) (match-end 1)
3740 (match-beginning 2) (match-end 2)
3741 (match-beginning 3) (match-end 3)
3742 (match-beginning 4) (match-end 4)))
3743 t)))))
3745 (defun markdown-match-math-generic (regex last)
3746 "Match REGEX from point to LAST.
3747 REGEX is either `markdown-regex-math-inline-single' for matching
3748 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3749 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3750 (let ((begin (match-beginning 1)) (end (match-end 1)))
3751 (prog1
3752 (if (or (markdown-range-property-any
3753 begin end 'face (list markdown-inline-code-face
3754 markdown-bold-face))
3755 (markdown-range-properties-exist
3756 begin end
3757 (markdown-get-fenced-block-middle-properties)))
3758 (markdown-match-math-generic regex last)
3760 (goto-char (1+ (match-end 0)))))))
3762 (defun markdown-match-list-items (last)
3763 "Match list items from point to LAST."
3764 (when (markdown-match-inline-generic markdown-regex-list last)
3765 (let ((begin (match-beginning 2))
3766 (end (match-end 2)))
3767 (if (or (markdown-range-property-any
3768 begin end 'face (list markdown-inline-code-face
3769 markdown-bold-face
3770 markdown-math-face))
3771 (markdown-range-properties-exist begin end '(markdown-hr))
3772 (markdown-in-comment-p))
3773 (progn (goto-char (min (1+ (match-end 0)) last))
3774 (markdown-match-list-items last))
3775 (set-match-data (list (match-beginning 0) (match-end 0)
3776 (match-beginning 1) (match-end 1)
3777 (match-beginning 2) (match-end 2)))
3778 (goto-char (1+ (match-end 0)))))))
3780 (defun markdown-match-math-single (last)
3781 "Match single quoted $..$ math from point to LAST."
3782 (markdown-match-math-generic markdown-regex-math-inline-single last))
3784 (defun markdown-match-math-double (last)
3785 "Match double quoted $$..$$ math from point to LAST."
3786 (markdown-match-math-generic markdown-regex-math-inline-double last))
3788 (defun markdown-match-math-display (last)
3789 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3790 (markdown-match-math-generic markdown-regex-math-display last))
3792 (defun markdown-match-propertized-text (property last)
3793 "Match text with PROPERTY from point to LAST.
3794 Restore match data previously stored in PROPERTY."
3795 (let ((saved (get-text-property (point) property))
3796 pos)
3797 (unless saved
3798 (setq pos (next-single-char-property-change (point) property nil last))
3799 (setq saved (get-text-property pos property)))
3800 (when saved
3801 (set-match-data saved)
3802 ;; Step at least one character beyond point. Otherwise
3803 ;; `font-lock-fontify-keywords-region' infloops.
3804 (goto-char (min (1+ (max (match-end 0) (point)))
3805 (point-max)))
3806 saved)))
3808 (defun markdown-match-pre-blocks (last)
3809 "Match preformatted blocks from point to LAST.
3810 Use data stored in 'markdown-pre text property during syntax
3811 analysis."
3812 (markdown-match-propertized-text 'markdown-pre last))
3814 (defun markdown-match-gfm-code-blocks (last)
3815 "Match GFM quoted code blocks from point to LAST.
3816 Use data stored in 'markdown-gfm-code text property during syntax
3817 analysis."
3818 (markdown-match-propertized-text 'markdown-gfm-code last))
3820 (defun markdown-match-gfm-open-code-blocks (last)
3821 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3823 (defun markdown-match-gfm-close-code-blocks (last)
3824 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3826 (defun markdown-match-fenced-code-blocks (last)
3827 "Match fenced code blocks from the point to LAST."
3828 (markdown-match-propertized-text 'markdown-fenced-code last))
3830 (defun markdown-match-fenced-start-code-block (last)
3831 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3833 (defun markdown-match-fenced-end-code-block (last)
3834 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3836 (defun markdown-match-blockquotes (last)
3837 "Match blockquotes from point to LAST.
3838 Use data stored in 'markdown-blockquote text property during syntax
3839 analysis."
3840 (markdown-match-propertized-text 'markdown-blockquote last))
3842 (defun markdown-match-hr (last)
3843 "Match horizontal rules comments from the point to LAST."
3844 (markdown-match-propertized-text 'markdown-hr last))
3846 (defun markdown-match-comments (last)
3847 "Match HTML comments from the point to LAST."
3848 (when (and (skip-syntax-forward "^<" last))
3849 (let ((beg (point)))
3850 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3851 (forward-char)
3852 (set-match-data (list beg (point)))
3853 t))))
3855 (defun markdown-match-generic-links (last ref)
3856 "Match inline links from point to LAST.
3857 When REF is non-nil, match reference links instead of standard
3858 links with URLs."
3859 ;; Search for the next potential link (not in a code block).
3860 (while (and (progn
3861 ;; Clear match data to test for a match after functions returns.
3862 (set-match-data nil)
3863 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3864 ;; Keep searching if this is in a code block, inline
3865 ;; code, or a comment, or if it is include syntax.
3866 (or (markdown-code-block-at-point-p)
3867 (markdown-inline-code-at-pos-p (match-beginning 0))
3868 (markdown-inline-code-at-pos-p (match-end 0))
3869 (markdown-in-comment-p)
3870 (and (char-equal (char-after (point-at-bol)) ?<)
3871 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3872 (< (point) last)))
3873 ;; Match opening exclamation point (optional) and left bracket.
3874 (when (match-beginning 2)
3875 (let* ((bang (match-beginning 1))
3876 (first-begin (match-beginning 2))
3877 ;; Find end of block to prevent matching across blocks.
3878 (end-of-block (save-excursion
3879 (progn
3880 (goto-char (match-beginning 2))
3881 (markdown-end-of-text-block)
3882 (point))))
3883 ;; Move over balanced expressions to closing right bracket.
3884 ;; Catch unbalanced expression errors and return nil.
3885 (first-end (condition-case nil
3886 (and (goto-char first-begin)
3887 (scan-sexps (point) 1))
3888 (error nil)))
3889 ;; Continue with point at CONT-POINT upon failure.
3890 (cont-point (min (1+ first-begin) last))
3891 second-begin second-end url-begin url-end
3892 title-begin title-end)
3893 ;; When bracket found, in range, and followed by a left paren/bracket...
3894 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3895 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3896 ;; Scan across balanced expressions for closing parenthesis/bracket.
3897 (setq second-begin (point)
3898 second-end (condition-case nil
3899 (scan-sexps (point) 1)
3900 (error nil)))
3901 ;; Check that closing parenthesis/bracket is in range.
3902 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3903 (progn
3904 ;; Search for (optional) title inside closing parenthesis
3905 (when (and (not ref) (search-forward "\"" second-end t))
3906 (setq title-begin (1- (point))
3907 title-end (and (goto-char second-end)
3908 (search-backward "\"" (1+ title-begin) t))
3909 title-end (and title-end (1+ title-end))))
3910 ;; Store URL/reference range
3911 (setq url-begin (1+ second-begin)
3912 url-end (1- (or title-begin second-end)))
3913 ;; Set match data, move point beyond link, and return
3914 (set-match-data
3915 (list (or bang first-begin) second-end ; 0 - all
3916 bang (and bang (1+ bang)) ; 1 - bang
3917 first-begin (1+ first-begin) ; 2 - markup
3918 (1+ first-begin) (1- first-end) ; 3 - link text
3919 (1- first-end) first-end ; 4 - markup
3920 second-begin (1+ second-begin) ; 5 - markup
3921 url-begin url-end ; 6 - url/reference
3922 title-begin title-end ; 7 - title
3923 (1- second-end) second-end)) ; 8 - markup
3924 ;; Nullify cont-point and leave point at end and
3925 (setq cont-point nil)
3926 (goto-char second-end))
3927 ;; If no closing parenthesis in range, update continuation point
3928 (setq cont-point (min end-of-block second-begin))))
3929 (cond
3930 ;; On failure, continue searching at cont-point
3931 ((and cont-point (< cont-point last))
3932 (goto-char cont-point)
3933 (markdown-match-generic-links last ref))
3934 ;; No more text, return nil
3935 ((and cont-point (= cont-point last))
3936 nil)
3937 ;; Return t if a match occurred
3938 (t t)))))
3940 (defun markdown-match-inline-links (last)
3941 "Match standard inline links from point to LAST."
3942 (markdown-match-generic-links last nil))
3944 (defun markdown-match-reference-links (last)
3945 "Match inline reference links from point to LAST."
3946 (markdown-match-generic-links last t))
3948 (defun markdown-match-angle-uris (last)
3949 "Match angle bracket URIs from point to LAST."
3950 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3951 (goto-char (1+ (match-end 0)))))
3953 (defun markdown-match-plain-uris (last)
3954 "Match plain URIs from point to LAST."
3955 (when (markdown-match-inline-generic markdown-regex-uri last t)
3956 (goto-char (1+ (match-end 0)))))
3958 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3959 (save-excursion
3960 (goto-char (or pos (point-min)))
3961 (cl-loop
3962 with cur-result = nil
3963 and st-hdr = (or start-header "\\`")
3964 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3965 while (and (< (point) last)
3966 (re-search-forward st-hdr last t)
3967 (progn
3968 (setq cur-result (match-data))
3969 (re-search-forward end-hdr nil t)))
3970 collect (list cur-result (match-data)))))
3972 (defvar markdown-conditional-search-function #'re-search-forward
3973 "Conditional search function used in `markdown-search-until-condition'.
3974 Made into a variable to allow for dynamic let-binding.")
3976 (defun markdown-search-until-condition (condition &rest args)
3977 (let (ret)
3978 (while (and (not ret) (apply markdown-conditional-search-function args))
3979 (setq ret (funcall condition)))
3980 ret))
3982 (defun markdown-match-generic-metadata
3983 (regexp last &optional start-header end-header)
3984 "Match generic metadata specified by REGEXP from the point to LAST.
3985 If START-HEADER is nil, we assume metadata can only occur at the
3986 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3987 is \"\n\n\""
3988 (let* ((header-bounds
3989 (markdown-get-match-boundaries start-header end-header last))
3990 (enclosing-header
3991 (cl-find-if ; just take first if multiple
3992 (lambda (match-bounds)
3993 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3994 (and (< (point) begin)
3995 (save-excursion (re-search-forward regexp end t)))))
3996 header-bounds))
3997 (header-begin
3998 (when enclosing-header (cl-second (cl-first enclosing-header))))
3999 (header-end
4000 (when enclosing-header (cl-first (cl-second enclosing-header)))))
4001 (cond ((null enclosing-header)
4002 ;; Don't match anything outside of a header.
4003 nil)
4004 ((markdown-search-until-condition
4005 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
4006 ;; If a metadata item is found, it may span several lines.
4007 (let ((key-beginning (match-beginning 1))
4008 (key-end (match-end 1))
4009 (markup-begin (match-beginning 2))
4010 (markup-end (match-end 2))
4011 (value-beginning (match-beginning 3)))
4012 (set-match-data (list key-beginning (point) ; complete metadata
4013 key-beginning key-end ; key
4014 markup-begin markup-end ; markup
4015 value-beginning (point))) ; value
4017 (t nil))))
4019 (defun markdown-match-declarative-metadata (last)
4020 "Match declarative metadata from the point to LAST."
4021 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4023 (defun markdown-match-pandoc-metadata (last)
4024 "Match Pandoc metadata from the point to LAST."
4025 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4027 (defun markdown-match-yaml-metadata-begin (last)
4028 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4030 (defun markdown-match-yaml-metadata-end (last)
4031 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4033 (defun markdown-match-yaml-metadata-key (last)
4034 (markdown-match-propertized-text 'markdown-metadata-key last))
4036 (defun markdown-match-wiki-link (last)
4037 "Match wiki links from point to LAST."
4038 (when (and markdown-enable-wiki-links
4039 (not markdown-wiki-link-fontify-missing)
4040 (markdown-match-inline-generic markdown-regex-wiki-link last))
4041 (let ((begin (match-beginning 1)) (end (match-end 1)))
4042 (if (or (markdown-in-comment-p begin)
4043 (markdown-in-comment-p end)
4044 (markdown-inline-code-at-pos-p begin)
4045 (markdown-inline-code-at-pos-p end)
4046 (markdown-code-block-at-pos begin))
4047 (progn (goto-char (min (1+ begin) last))
4048 (when (< (point) last)
4049 (markdown-match-wiki-link last)))
4050 (set-match-data (list begin end))
4051 t))))
4053 (defun markdown-match-inline-attributes (last)
4054 "Match inline attributes from point to LAST."
4055 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4056 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4057 (markdown-inline-code-at-pos-p (match-end 0))
4058 (markdown-in-comment-p))
4059 t)))
4061 (defun markdown-match-leanpub-sections (last)
4062 "Match Leanpub section markers from point to LAST."
4063 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4064 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4065 (markdown-inline-code-at-pos-p (match-end 0))
4066 (markdown-in-comment-p))
4067 t)))
4069 (defun markdown-match-includes (last)
4070 "Match include statements from point to LAST.
4071 Sets match data for the following seven groups:
4072 Group 1: opening two angle brackets
4073 Group 2: opening title delimiter (optional)
4074 Group 3: title text (optional)
4075 Group 4: closing title delimiter (optional)
4076 Group 5: opening filename delimiter
4077 Group 6: filename
4078 Group 7: closing filename delimiter"
4079 (when (markdown-match-inline-generic markdown-regex-include last)
4080 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4081 (markdown-in-comment-p (match-end 0))
4082 (markdown-code-block-at-pos (match-beginning 0))))))
4083 (cond
4084 ;; Parentheses and maybe square brackets, but no curly braces:
4085 ;; match optional title in square brackets and file in parentheses.
4086 ((and valid (match-beginning 5)
4087 (not (match-beginning 8)))
4088 (set-match-data (list (match-beginning 1) (match-end 7)
4089 (match-beginning 1) (match-end 1)
4090 (match-beginning 2) (match-end 2)
4091 (match-beginning 3) (match-end 3)
4092 (match-beginning 4) (match-end 4)
4093 (match-beginning 5) (match-end 5)
4094 (match-beginning 6) (match-end 6)
4095 (match-beginning 7) (match-end 7))))
4096 ;; Only square brackets present: match file in square brackets.
4097 ((and valid (match-beginning 2)
4098 (not (match-beginning 5))
4099 (not (match-beginning 7)))
4100 (set-match-data (list (match-beginning 1) (match-end 4)
4101 (match-beginning 1) (match-end 1)
4102 nil nil
4103 nil nil
4104 nil nil
4105 (match-beginning 2) (match-end 2)
4106 (match-beginning 3) (match-end 3)
4107 (match-beginning 4) (match-end 4))))
4108 ;; Only curly braces present: match file in curly braces.
4109 ((and valid (match-beginning 8)
4110 (not (match-beginning 2))
4111 (not (match-beginning 5)))
4112 (set-match-data (list (match-beginning 1) (match-end 10)
4113 (match-beginning 1) (match-end 1)
4114 nil nil
4115 nil nil
4116 nil nil
4117 (match-beginning 8) (match-end 8)
4118 (match-beginning 9) (match-end 9)
4119 (match-beginning 10) (match-end 10))))
4121 ;; Not a valid match, move to next line and search again.
4122 (forward-line)
4123 (when (< (point) last)
4124 (setq valid (markdown-match-includes last)))))
4125 valid)))
4128 ;;; Markdown Font Fontification Functions =====================================
4130 (defun markdown--marginalize-string (level)
4131 "Generate atx markup string of given LEVEL for left margin."
4132 (let ((margin-left-space-count
4133 (- markdown-marginalize-headers-margin-width level)))
4134 (concat (make-string margin-left-space-count ? )
4135 (make-string level ?#))))
4137 (defun markdown-marginalize-update-current ()
4138 "Update the window configuration to create a left margin."
4139 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4140 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4141 (let* ((header-delimiter-font-width
4142 (window-font-width nil 'markdown-header-delimiter-face))
4143 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4144 header-delimiter-font-width))
4145 (margin-char-width (/ margin-pixel-width (default-font-width))))
4146 (set-window-margins nil margin-char-width))
4147 ;; As a fallback, simply set margin based on character count.
4148 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4150 (defun markdown-fontify-headings (last)
4151 "Add text properties to headings from point to LAST."
4152 (when (markdown-match-propertized-text 'markdown-heading last)
4153 (let* ((level (markdown-outline-level))
4154 (heading-face
4155 (intern (format "markdown-header-face-%d" level)))
4156 (heading-props `(face ,heading-face))
4157 (left-markup-props
4158 `(face markdown-header-delimiter-face
4159 ,@(cond
4160 (markdown-hide-markup
4161 `(display ""))
4162 (markdown-marginalize-headers
4163 `(display ((margin left-margin)
4164 ,(markdown--marginalize-string level)))))))
4165 (right-markup-props
4166 `(face markdown-header-delimiter-face
4167 ,@(when markdown-hide-markup `(display ""))))
4168 (rule-props `(face markdown-header-rule-face
4169 ,@(when markdown-hide-markup `(display "")))))
4170 (if (match-end 1)
4171 ;; Setext heading
4172 (progn (add-text-properties
4173 (match-beginning 1) (match-end 1) heading-props)
4174 (if (= level 1)
4175 (add-text-properties
4176 (match-beginning 2) (match-end 2) rule-props)
4177 (add-text-properties
4178 (match-beginning 3) (match-end 3) rule-props)))
4179 ;; atx heading
4180 (add-text-properties
4181 (match-beginning 4) (match-end 4) left-markup-props)
4182 (add-text-properties
4183 (match-beginning 5) (match-end 5) heading-props)
4184 (when (match-end 6)
4185 (add-text-properties
4186 (match-beginning 6) (match-end 6) right-markup-props))))
4189 (defun markdown-fontify-blockquotes (last)
4190 "Apply font-lock properties to blockquotes from point to LAST."
4191 (when (markdown-match-blockquotes last)
4192 (add-text-properties
4193 (match-beginning 1) (match-end 1)
4194 (if markdown-hide-markup
4195 `(face markdown-blockquote-face
4196 display ,markdown-blockquote-display-char)
4197 `(face markdown-markup-face
4198 ,@(when markdown-hide-markup
4199 `(display ,markdown-blockquote-display-char)))))
4200 (font-lock-append-text-property
4201 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4204 (defun markdown-fontify-list-items (last)
4205 "Apply font-lock properties to list markers from point to LAST."
4206 (when (markdown-match-list-items last)
4207 (let* ((indent (length (match-string-no-properties 1)))
4208 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4209 (bullet (nth (mod level (length markdown-list-item-bullets))
4210 markdown-list-item-bullets)))
4211 (add-text-properties
4212 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4213 (when markdown-hide-markup
4214 (cond
4215 ;; Unordered lists
4216 ((string-match-p "[\\*\\+-]" (match-string 2))
4217 (add-text-properties
4218 (match-beginning 2) (match-end 2) `(display ,bullet)))
4219 ;; Definition lists
4220 ((string-equal ":" (match-string 2))
4221 (add-text-properties
4222 (match-beginning 2) (match-end 2)
4223 `(display ,(char-to-string markdown-definition-display-char)))))))
4226 (defun markdown-fontify-hrs (last)
4227 "Add text properties to horizontal rules from point to LAST."
4228 (when (markdown-match-hr last)
4229 (add-text-properties
4230 (match-beginning 0) (match-end 0)
4231 `(face markdown-hr-face
4232 font-lock-multiline t
4233 ,@(when markdown-hide-markup
4234 `(display ,(make-string
4235 (window-body-width) markdown-hr-display-char)))))
4238 (defun markdown-fontify-sub-superscripts (last)
4239 "Apply text properties to sub- and superscripts from point to LAST."
4240 (when (markdown-search-until-condition
4241 (lambda () (and (not (markdown-code-block-at-point-p))
4242 (not (markdown-inline-code-at-point-p))
4243 (not (markdown-in-comment-p))))
4244 markdown-regex-sub-superscript last t)
4245 (let* ((subscript-p (string= (match-string 2) "~"))
4246 (index (if subscript-p 0 1))
4247 (mp (list 'face 'markdown-markup-face
4248 'invisible 'markdown-markup)))
4249 (when markdown-hide-markup
4250 (put-text-property (match-beginning 3) (match-end 3)
4251 'display
4252 (nth index markdown-sub-superscript-display)))
4253 (add-text-properties (match-beginning 2) (match-end 2) mp)
4254 (add-text-properties (match-beginning 4) (match-end 4) mp)
4255 t)))
4258 ;;; Syntax Table ==============================================================
4260 (defvar markdown-mode-syntax-table
4261 (let ((tab (make-syntax-table text-mode-syntax-table)))
4262 (modify-syntax-entry ?\" "." tab)
4263 tab)
4264 "Syntax table for `markdown-mode'.")
4267 ;;; Element Insertion =========================================================
4269 (defun markdown-ensure-blank-line-before ()
4270 "If previous line is not already blank, insert a blank line before point."
4271 (unless (bolp) (insert "\n"))
4272 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4274 (defun markdown-ensure-blank-line-after ()
4275 "If following line is not already blank, insert a blank line after point.
4276 Return the point where it was originally."
4277 (save-excursion
4278 (unless (eolp) (insert "\n"))
4279 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4281 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4282 "Insert the strings S1 and S2, wrapping around region or THING.
4283 If a region is specified by the optional BEG and END arguments,
4284 wrap the strings S1 and S2 around that region.
4285 If there is an active region, wrap the strings S1 and S2 around
4286 the region. If there is not an active region but the point is at
4287 THING, wrap that thing (which defaults to word). Otherwise, just
4288 insert S1 and S2 and place the cursor in between. Return the
4289 bounds of the entire wrapped string, or nil if nothing was wrapped
4290 and S1 and S2 were only inserted."
4291 (let (a b bounds new-point)
4292 (cond
4293 ;; Given region
4294 ((and beg end)
4295 (setq a beg
4296 b end
4297 new-point (+ (point) (length s1))))
4298 ;; Active region
4299 ((markdown-use-region-p)
4300 (setq a (region-beginning)
4301 b (region-end)
4302 new-point (+ (point) (length s1))))
4303 ;; Thing (word) at point
4304 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4305 (setq a (car bounds)
4306 b (cdr bounds)
4307 new-point (+ (point) (length s1))))
4308 ;; No active region and no word
4310 (setq a (point)
4311 b (point))))
4312 (goto-char b)
4313 (insert s2)
4314 (goto-char a)
4315 (insert s1)
4316 (when new-point (goto-char new-point))
4317 (if (= a b)
4319 (setq b (+ b (length s1) (length s2)))
4320 (cons a b))))
4322 (defun markdown-point-after-unwrap (cur prefix suffix)
4323 "Return desired position of point after an unwrapping operation.
4324 CUR gives the position of the point before the operation.
4325 Additionally, two cons cells must be provided. PREFIX gives the
4326 bounds of the prefix string and SUFFIX gives the bounds of the
4327 suffix string."
4328 (cond ((< cur (cdr prefix)) (car prefix))
4329 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4330 ((<= cur (cdr suffix))
4331 (- cur (+ (- (cdr prefix) (car prefix))
4332 (- cur (car suffix)))))
4333 (t cur)))
4335 (defun markdown-unwrap-thing-at-point (regexp all text)
4336 "Remove prefix and suffix of thing at point and reposition the point.
4337 When the thing at point matches REGEXP, replace the subexpression
4338 ALL with the string in subexpression TEXT. Reposition the point
4339 in an appropriate location accounting for the removal of prefix
4340 and suffix strings. Return new bounds of string from group TEXT.
4341 When REGEXP is nil, assumes match data is already set."
4342 (when (or (null regexp)
4343 (thing-at-point-looking-at regexp))
4344 (let ((cur (point))
4345 (prefix (cons (match-beginning all) (match-beginning text)))
4346 (suffix (cons (match-end text) (match-end all)))
4347 (bounds (cons (match-beginning text) (match-end text))))
4348 ;; Replace the thing at point
4349 (replace-match (match-string text) t t nil all)
4350 ;; Reposition the point
4351 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4352 ;; Adjust bounds
4353 (setq bounds (cons (car prefix)
4354 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4356 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4357 "Remove prefix and suffix of all things in region from BEG to END.
4358 When a thing in the region matches REGEXP, replace the
4359 subexpression ALL with the string in subexpression TEXT.
4360 Return a cons cell containing updated bounds for the region."
4361 (save-excursion
4362 (goto-char beg)
4363 (let ((removed 0) len-all len-text)
4364 (while (re-search-forward regexp (- end removed) t)
4365 (setq len-all (length (match-string-no-properties all)))
4366 (setq len-text (length (match-string-no-properties text)))
4367 (setq removed (+ removed (- len-all len-text)))
4368 (replace-match (match-string text) t t nil all))
4369 (cons beg (- end removed)))))
4371 (defun markdown-insert-hr (arg)
4372 "Insert or replace a horizonal rule.
4373 By default, use the first element of `markdown-hr-strings'. When
4374 ARG is non-nil, as when given a prefix, select a different
4375 element as follows. When prefixed with \\[universal-argument],
4376 use the last element of `markdown-hr-strings' instead. When
4377 prefixed with an integer from 1 to the length of
4378 `markdown-hr-strings', use the element in that position instead."
4379 (interactive "*P")
4380 (when (thing-at-point-looking-at markdown-regex-hr)
4381 (delete-region (match-beginning 0) (match-end 0)))
4382 (markdown-ensure-blank-line-before)
4383 (cond ((equal arg '(4))
4384 (insert (car (reverse markdown-hr-strings))))
4385 ((and (integerp arg) (> arg 0)
4386 (<= arg (length markdown-hr-strings)))
4387 (insert (nth (1- arg) markdown-hr-strings)))
4389 (insert (car markdown-hr-strings))))
4390 (markdown-ensure-blank-line-after))
4392 (defun markdown-insert-bold ()
4393 "Insert markup to make a region or word bold.
4394 If there is an active region, make the region bold. If the point
4395 is at a non-bold word, make the word bold. If the point is at a
4396 bold word or phrase, remove the bold markup. Otherwise, simply
4397 insert bold delimiters and place the cursor in between them."
4398 (interactive)
4399 (let ((delim (if markdown-bold-underscore "__" "**")))
4400 (if (markdown-use-region-p)
4401 ;; Active region
4402 (let ((bounds (markdown-unwrap-things-in-region
4403 (region-beginning) (region-end)
4404 markdown-regex-bold 2 4)))
4405 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4406 ;; Bold markup removal, bold word at point, or empty markup insertion
4407 (if (thing-at-point-looking-at markdown-regex-bold)
4408 (markdown-unwrap-thing-at-point nil 2 4)
4409 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4411 (defun markdown-insert-italic ()
4412 "Insert markup to make a region or word italic.
4413 If there is an active region, make the region italic. If the point
4414 is at a non-italic word, make the word italic. If the point is at an
4415 italic word or phrase, remove the italic markup. Otherwise, simply
4416 insert italic delimiters and place the cursor in between them."
4417 (interactive)
4418 (let ((delim (if markdown-italic-underscore "_" "*")))
4419 (if (markdown-use-region-p)
4420 ;; Active region
4421 (let ((bounds (markdown-unwrap-things-in-region
4422 (region-beginning) (region-end)
4423 markdown-regex-italic 1 3)))
4424 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4425 ;; Italic markup removal, italic word at point, or empty markup insertion
4426 (if (thing-at-point-looking-at markdown-regex-italic)
4427 (markdown-unwrap-thing-at-point nil 1 3)
4428 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4430 (defun markdown-insert-strike-through ()
4431 "Insert markup to make a region or word strikethrough.
4432 If there is an active region, make the region strikethrough. If the point
4433 is at a non-bold word, make the word strikethrough. If the point is at a
4434 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4435 simply insert bold delimiters and place the cursor in between them."
4436 (interactive)
4437 (let ((delim "~~"))
4438 (if (markdown-use-region-p)
4439 ;; Active region
4440 (let ((bounds (markdown-unwrap-things-in-region
4441 (region-beginning) (region-end)
4442 markdown-regex-strike-through 2 4)))
4443 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4444 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4445 (if (thing-at-point-looking-at markdown-regex-strike-through)
4446 (markdown-unwrap-thing-at-point nil 2 4)
4447 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4449 (defun markdown-insert-code ()
4450 "Insert markup to make a region or word an inline code fragment.
4451 If there is an active region, make the region an inline code
4452 fragment. If the point is at a word, make the word an inline
4453 code fragment. Otherwise, simply insert code delimiters and
4454 place the cursor in between them."
4455 (interactive)
4456 (if (markdown-use-region-p)
4457 ;; Active region
4458 (let ((bounds (markdown-unwrap-things-in-region
4459 (region-beginning) (region-end)
4460 markdown-regex-code 1 3)))
4461 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4462 ;; Code markup removal, code markup for word, or empty markup insertion
4463 (if (markdown-inline-code-at-point)
4464 (markdown-unwrap-thing-at-point nil 0 2)
4465 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4467 (defun markdown-insert-kbd ()
4468 "Insert markup to wrap region or word in <kbd> tags.
4469 If there is an active region, use the region. If the point is at
4470 a word, use the word. Otherwise, simply insert <kbd> tags and
4471 place the cursor in between them."
4472 (interactive)
4473 (if (markdown-use-region-p)
4474 ;; Active region
4475 (let ((bounds (markdown-unwrap-things-in-region
4476 (region-beginning) (region-end)
4477 markdown-regex-kbd 0 2)))
4478 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4479 ;; Markup removal, markup for word, or empty markup insertion
4480 (if (thing-at-point-looking-at markdown-regex-kbd)
4481 (markdown-unwrap-thing-at-point nil 0 2)
4482 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4484 (defun markdown-insert-inline-link (text url &optional title)
4485 "Insert an inline link with TEXT pointing to URL.
4486 Optionally, the user can provide a TITLE."
4487 (let ((cur (point)))
4488 (setq title (and title (concat " \"" title "\"")))
4489 (insert (concat "[" text "](" url title ")"))
4490 (cond ((not text) (goto-char (+ 1 cur)))
4491 ((not url) (goto-char (+ 3 (length text) cur))))))
4493 (defun markdown-insert-inline-image (text url &optional title)
4494 "Insert an inline link with alt TEXT pointing to URL.
4495 Optionally, also provide a TITLE."
4496 (let ((cur (point)))
4497 (setq title (and title (concat " \"" title "\"")))
4498 (insert (concat "![" text "](" url title ")"))
4499 (cond ((not text) (goto-char (+ 2 cur)))
4500 ((not url) (goto-char (+ 4 (length text) cur))))))
4502 (defun markdown-insert-reference-link (text label &optional url title)
4503 "Insert a reference link and, optionally, a reference definition.
4504 The link TEXT will be inserted followed by the optional LABEL.
4505 If a URL is given, also insert a definition for the reference
4506 LABEL according to `markdown-reference-location'. If a TITLE is
4507 given, it will be added to the end of the reference definition
4508 and will be used to populate the title attribute when converted
4509 to XHTML. If URL is nil, insert only the link portion (for
4510 example, when a reference label is already defined)."
4511 (insert (concat "[" text "][" label "]"))
4512 (when url
4513 (markdown-insert-reference-definition
4514 (if (string-equal label "") text label)
4515 url title)))
4517 (defun markdown-insert-reference-image (text label &optional url title)
4518 "Insert a reference image and, optionally, a reference definition.
4519 The alt TEXT will be inserted followed by the optional LABEL.
4520 If a URL is given, also insert a definition for the reference
4521 LABEL according to `markdown-reference-location'. If a TITLE is
4522 given, it will be added to the end of the reference definition
4523 and will be used to populate the title attribute when converted
4524 to XHTML. If URL is nil, insert only the link portion (for
4525 example, when a reference label is already defined)."
4526 (insert (concat "![" text "][" label "]"))
4527 (when url
4528 (markdown-insert-reference-definition
4529 (if (string-equal label "") text label)
4530 url title)))
4532 (defun markdown-insert-reference-definition (label &optional url title)
4533 "Add definition for reference LABEL with URL and TITLE.
4534 LABEL is a Markdown reference label without square brackets.
4535 URL and TITLE are optional. When given, the TITLE will
4536 be used to populate the title attribute when converted to XHTML."
4537 ;; END specifies where to leave the point upon return
4538 (let ((end (point)))
4539 (cl-case markdown-reference-location
4540 (end (goto-char (point-max)))
4541 (immediately (markdown-end-of-text-block))
4542 (subtree (markdown-end-of-subtree))
4543 (header (markdown-end-of-defun)))
4544 ;; Skip backwards over local variables. This logic is similar to the one
4545 ;; used in ‘hack-local-variables’.
4546 (when (and enable-local-variables (eobp))
4547 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4548 (when (let ((case-fold-search t))
4549 (search-forward "Local Variables:" nil :move))
4550 (beginning-of-line 0)
4551 (when (eq (char-before) ?\n) (backward-char))))
4552 (unless (or (markdown-cur-line-blank-p)
4553 (thing-at-point-looking-at markdown-regex-reference-definition))
4554 (insert "\n"))
4555 (insert "\n[" label "]: ")
4556 (if url
4557 (insert url)
4558 ;; When no URL is given, leave cursor at END following the colon
4559 (setq end (point)))
4560 (when (> (length title) 0)
4561 (insert " \"" title "\""))
4562 (unless (looking-at-p "\n")
4563 (insert "\n"))
4564 (goto-char end)
4565 (when url
4566 (message
4567 (markdown--substitute-command-keys
4568 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4569 label))))
4571 (define-obsolete-function-alias
4572 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4573 (define-obsolete-function-alias
4574 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4576 (defun markdown--insert-link-or-image (image)
4577 "Interactively insert new or update an existing link or image.
4578 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4579 This is an internal function called by
4580 `markdown-insert-link' and `markdown-insert-image'."
4581 (cl-multiple-value-bind (begin end text uri ref title)
4582 (if (markdown-use-region-p)
4583 ;; Use region as either link text or URL as appropriate.
4584 (let ((region (buffer-substring-no-properties
4585 (region-beginning) (region-end))))
4586 (if (string-match markdown-regex-uri region)
4587 ;; Region contains a URL; use it as such.
4588 (list (region-beginning) (region-end)
4589 nil (match-string 0 region) nil nil)
4590 ;; Region doesn't contain a URL, so use it as text.
4591 (list (region-beginning) (region-end)
4592 region nil nil nil)))
4593 ;; Extract and use properties of existing link, if any.
4594 (markdown-link-at-pos (point)))
4595 (let* ((ref (when ref (concat "[" ref "]")))
4596 (defined-refs (append
4597 (mapcar (lambda (ref) (concat "[" ref "]"))
4598 (markdown-get-defined-references))))
4599 (used-uris (markdown-get-used-uris))
4600 (uri-or-ref (completing-read
4601 "URL or [reference]: "
4602 (append defined-refs used-uris)
4603 nil nil (or uri ref)))
4604 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4605 (match-string 1 uri-or-ref))
4606 ((string-equal "" uri-or-ref)
4607 "")))
4608 (uri (unless ref uri-or-ref))
4609 (text-prompt (if image
4610 "Alt text: "
4611 (if ref
4612 "Link text: "
4613 "Link text (blank for plain URL): ")))
4614 (text (read-string text-prompt text))
4615 (text (if (= (length text) 0) nil text))
4616 (plainp (and uri (not text)))
4617 (implicitp (string-equal ref ""))
4618 (ref (if implicitp text ref))
4619 (definedp (and ref (markdown-reference-definition ref)))
4620 (ref-url (unless (or uri definedp)
4621 (completing-read "Reference URL: " used-uris)))
4622 (title (unless (or plainp definedp)
4623 (read-string "Title (tooltip text, optional): " title)))
4624 (title (if (= (length title) 0) nil title)))
4625 (when (and image implicitp)
4626 (user-error "Reference required: implicit image references are invalid"))
4627 (when (and begin end)
4628 (delete-region begin end))
4629 (cond
4630 ((and (not image) uri text)
4631 (markdown-insert-inline-link text uri title))
4632 ((and image uri text)
4633 (markdown-insert-inline-image text uri title))
4634 ((and ref text)
4635 (if image
4636 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4637 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4638 (unless definedp
4639 (markdown-insert-reference-definition ref ref-url title)))
4640 ((and (not image) uri)
4641 (markdown-insert-uri uri))))))
4643 (defun markdown-insert-link ()
4644 "Insert new or update an existing link, with interactive prompts.
4645 If the point is at an existing link or URL, update the link text,
4646 URL, reference label, and/or title. Otherwise, insert a new link.
4647 The type of link inserted (inline, reference, or plain URL)
4648 depends on which values are provided:
4650 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4651 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4652 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4653 * If only a URL is given, insert a plain link: <URL>.
4655 In other words, to create an implicit reference link, leave the
4656 URL prompt empty and to create a plain URL link, leave the link
4657 text empty.
4659 If there is an active region, use the text as the default URL, if
4660 it seems to be a URL, or link text value otherwise.
4662 If a given reference is not defined, this function will
4663 additionally prompt for the URL and optional title. In this case,
4664 the reference definition is placed at the location determined by
4665 `markdown-reference-location'.
4667 Through updating the link, this function can be used to convert a
4668 link of one type (inline, reference, or plain) to another type by
4669 selectively adding or removing information via the prompts."
4670 (interactive)
4671 (markdown--insert-link-or-image nil))
4673 (defun markdown-insert-image ()
4674 "Insert new or update an existing image, with interactive prompts.
4675 If the point is at an existing image, update the alt text, URL,
4676 reference label, and/or title. Otherwise, insert a new image.
4677 The type of image inserted (inline or reference) depends on which
4678 values are provided:
4680 * If a URL and ALT-TEXT are given, insert an inline image:
4681 ![ALT-TEXT](URL).
4682 * If [REF] and ALT-TEXT are given, insert a reference image:
4683 ![ALT-TEXT][REF].
4685 If there is an active region, use the text as the default URL, if
4686 it seems to be a URL, or alt text value otherwise.
4688 If a given reference is not defined, this function will
4689 additionally prompt for the URL and optional title. In this case,
4690 the reference definition is placed at the location determined by
4691 `markdown-reference-location'.
4693 Through updating the image, this function can be used to convert an
4694 image of one type (inline or reference) to another type by
4695 selectively adding or removing information via the prompts."
4696 (interactive)
4697 (markdown--insert-link-or-image t))
4699 (defun markdown-insert-uri (&optional uri)
4700 "Insert markup for an inline URI.
4701 If there is an active region, use it as the URI. If the point is
4702 at a URI, wrap it with angle brackets. If the point is at an
4703 inline URI, remove the angle brackets. Otherwise, simply insert
4704 angle brackets place the point between them."
4705 (interactive)
4706 (if (markdown-use-region-p)
4707 ;; Active region
4708 (let ((bounds (markdown-unwrap-things-in-region
4709 (region-beginning) (region-end)
4710 markdown-regex-angle-uri 0 2)))
4711 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4712 ;; Markup removal, URI at point, new URI, or empty markup insertion
4713 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4714 (markdown-unwrap-thing-at-point nil 0 2)
4715 (if uri
4716 (insert "<" uri ">")
4717 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4719 (defun markdown-insert-wiki-link ()
4720 "Insert a wiki link of the form [[WikiLink]].
4721 If there is an active region, use the region as the link text.
4722 If the point is at a word, use the word as the link text. If
4723 there is no active region and the point is not at word, simply
4724 insert link markup."
4725 (interactive)
4726 (if (markdown-use-region-p)
4727 ;; Active region
4728 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4729 ;; Markup removal, wiki link at at point, or empty markup insertion
4730 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4731 (if (or markdown-wiki-link-alias-first
4732 (null (match-string 5)))
4733 (markdown-unwrap-thing-at-point nil 1 3)
4734 (markdown-unwrap-thing-at-point nil 1 5))
4735 (markdown-wrap-or-insert "[[" "]]"))))
4737 (defun markdown-remove-header ()
4738 "Remove header markup if point is at a header.
4739 Return bounds of remaining header text if a header was removed
4740 and nil otherwise."
4741 (interactive "*")
4742 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4743 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4745 (defun markdown-insert-header (&optional level text setext)
4746 "Insert or replace header markup.
4747 The level of the header is specified by LEVEL and header text is
4748 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4749 default value is 1.
4750 When TEXT is nil, the header text is obtained as follows.
4751 If there is an active region, it is used as the header text.
4752 Otherwise, the current line will be used as the header text.
4753 If there is not an active region and the point is at a header,
4754 remove the header markup and replace with level N header.
4755 Otherwise, insert empty header markup and place the cursor in
4756 between.
4757 The style of the header will be atx (hash marks) unless
4758 SETEXT is non-nil, in which case a setext-style (underlined)
4759 header will be inserted."
4760 (interactive "p\nsHeader text: ")
4761 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4762 ;; Determine header text if not given
4763 (when (null text)
4764 (if (markdown-use-region-p)
4765 ;; Active region
4766 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4767 ;; No active region
4768 (markdown-remove-header)
4769 (setq text (delete-and-extract-region
4770 (line-beginning-position) (line-end-position)))
4771 (when (and setext (string-match-p "^[ \t]*$" text))
4772 (setq text (read-string "Header text: "))))
4773 (setq text (markdown-compress-whitespace-string text)))
4774 ;; Insertion with given text
4775 (markdown-ensure-blank-line-before)
4776 (let (hdr)
4777 (cond (setext
4778 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4779 (insert text "\n" hdr))
4781 (setq hdr (make-string level ?#))
4782 (insert hdr " " text)
4783 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4784 (markdown-ensure-blank-line-after)
4785 ;; Leave point at end of text
4786 (cond (setext
4787 (backward-char (1+ (string-width text))))
4788 ((null markdown-asymmetric-header)
4789 (backward-char (1+ level)))))
4791 (defun markdown-insert-header-dwim (&optional arg setext)
4792 "Insert or replace header markup.
4793 The level and type of the header are determined automatically by
4794 the type and level of the previous header, unless a prefix
4795 argument is given via ARG.
4796 With a numeric prefix valued 1 to 6, insert a header of the given
4797 level, with the type being determined automatically (note that
4798 only level 1 or 2 setext headers are possible).
4800 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4801 promote the heading by one level.
4802 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4803 demote the heading by one level.
4804 When SETEXT is non-nil, prefer setext-style headers when
4805 possible (levels one and two).
4807 When there is an active region, use it for the header text. When
4808 the point is at an existing header, change the type and level
4809 according to the rules above.
4810 Otherwise, if the line is not empty, create a header using the
4811 text on the current line as the header text.
4812 Finally, if the point is on a blank line, insert empty header
4813 markup (atx) or prompt for text (setext).
4814 See `markdown-insert-header' for more details about how the
4815 header text is determined."
4816 (interactive "*P")
4817 (let (level)
4818 (save-excursion
4819 (when (or (thing-at-point-looking-at markdown-regex-header)
4820 (re-search-backward markdown-regex-header nil t))
4821 ;; level of current or previous header
4822 (setq level (markdown-outline-level))
4823 ;; match group 1 indicates a setext header
4824 (setq setext (match-end 1))))
4825 ;; check prefix argument
4826 (cond
4827 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4828 (cl-decf level))
4829 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4830 (cl-incf level))
4831 (arg ;; numeric prefix
4832 (setq level (prefix-numeric-value arg))))
4833 ;; setext headers must be level one or two
4834 (and level (setq setext (and setext (<= level 2))))
4835 ;; insert the heading
4836 (markdown-insert-header level nil setext)))
4838 (defun markdown-insert-header-setext-dwim (&optional arg)
4839 "Insert or replace header markup, with preference for setext.
4840 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4841 (interactive "*P")
4842 (markdown-insert-header-dwim arg t))
4844 (defun markdown-insert-header-atx-1 ()
4845 "Insert a first level atx-style (hash mark) header.
4846 See `markdown-insert-header'."
4847 (interactive "*")
4848 (markdown-insert-header 1 nil nil))
4850 (defun markdown-insert-header-atx-2 ()
4851 "Insert a level two atx-style (hash mark) header.
4852 See `markdown-insert-header'."
4853 (interactive "*")
4854 (markdown-insert-header 2 nil nil))
4856 (defun markdown-insert-header-atx-3 ()
4857 "Insert a level three atx-style (hash mark) header.
4858 See `markdown-insert-header'."
4859 (interactive "*")
4860 (markdown-insert-header 3 nil nil))
4862 (defun markdown-insert-header-atx-4 ()
4863 "Insert a level four atx-style (hash mark) header.
4864 See `markdown-insert-header'."
4865 (interactive "*")
4866 (markdown-insert-header 4 nil nil))
4868 (defun markdown-insert-header-atx-5 ()
4869 "Insert a level five atx-style (hash mark) header.
4870 See `markdown-insert-header'."
4871 (interactive "*")
4872 (markdown-insert-header 5 nil nil))
4874 (defun markdown-insert-header-atx-6 ()
4875 "Insert a sixth level atx-style (hash mark) header.
4876 See `markdown-insert-header'."
4877 (interactive "*")
4878 (markdown-insert-header 6 nil nil))
4880 (defun markdown-insert-header-setext-1 ()
4881 "Insert a setext-style (underlined) first-level header.
4882 See `markdown-insert-header'."
4883 (interactive "*")
4884 (markdown-insert-header 1 nil t))
4886 (defun markdown-insert-header-setext-2 ()
4887 "Insert a setext-style (underlined) second-level header.
4888 See `markdown-insert-header'."
4889 (interactive "*")
4890 (markdown-insert-header 2 nil t))
4892 (defun markdown-blockquote-indentation (loc)
4893 "Return string containing necessary indentation for a blockquote at LOC.
4894 Also see `markdown-pre-indentation'."
4895 (save-excursion
4896 (goto-char loc)
4897 (let* ((list-level (length (markdown-calculate-list-levels)))
4898 (indent ""))
4899 (dotimes (_ list-level indent)
4900 (setq indent (concat indent " "))))))
4902 (defun markdown-insert-blockquote ()
4903 "Start a blockquote section (or blockquote the region).
4904 If Transient Mark mode is on and a region is active, it is used as
4905 the blockquote text."
4906 (interactive)
4907 (if (markdown-use-region-p)
4908 (markdown-blockquote-region (region-beginning) (region-end))
4909 (markdown-ensure-blank-line-before)
4910 (insert (markdown-blockquote-indentation (point)) "> ")
4911 (markdown-ensure-blank-line-after)))
4913 (defun markdown-block-region (beg end prefix)
4914 "Format the region using a block prefix.
4915 Arguments BEG and END specify the beginning and end of the
4916 region. The characters PREFIX will appear at the beginning
4917 of each line."
4918 (save-excursion
4919 (let* ((end-marker (make-marker))
4920 (beg-marker (make-marker))
4921 (prefix-without-trailing-whitespace
4922 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4923 ;; Ensure blank line after and remove extra whitespace
4924 (goto-char end)
4925 (skip-syntax-backward "-")
4926 (set-marker end-marker (point))
4927 (delete-horizontal-space)
4928 (markdown-ensure-blank-line-after)
4929 ;; Ensure blank line before and remove extra whitespace
4930 (goto-char beg)
4931 (skip-syntax-forward "-")
4932 (delete-horizontal-space)
4933 (markdown-ensure-blank-line-before)
4934 (set-marker beg-marker (point))
4935 ;; Insert PREFIX before each line
4936 (goto-char beg-marker)
4937 (while (and (< (line-beginning-position) end-marker)
4938 (not (eobp)))
4939 ;; Don’t insert trailing whitespace.
4940 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4941 (forward-line)))))
4943 (defun markdown-blockquote-region (beg end)
4944 "Blockquote the region.
4945 Arguments BEG and END specify the beginning and end of the region."
4946 (interactive "*r")
4947 (markdown-block-region
4948 beg end (concat (markdown-blockquote-indentation
4949 (max (point-min) (1- beg))) "> ")))
4951 (defun markdown-pre-indentation (loc)
4952 "Return string containing necessary whitespace for a pre block at LOC.
4953 Also see `markdown-blockquote-indentation'."
4954 (save-excursion
4955 (goto-char loc)
4956 (let* ((list-level (length (markdown-calculate-list-levels)))
4957 indent)
4958 (dotimes (_ (1+ list-level) indent)
4959 (setq indent (concat indent " "))))))
4961 (defun markdown-insert-pre ()
4962 "Start a preformatted section (or apply to the region).
4963 If Transient Mark mode is on and a region is active, it is marked
4964 as preformatted text."
4965 (interactive)
4966 (if (markdown-use-region-p)
4967 (markdown-pre-region (region-beginning) (region-end))
4968 (markdown-ensure-blank-line-before)
4969 (insert (markdown-pre-indentation (point)))
4970 (markdown-ensure-blank-line-after)))
4972 (defun markdown-pre-region (beg end)
4973 "Format the region as preformatted text.
4974 Arguments BEG and END specify the beginning and end of the region."
4975 (interactive "*r")
4976 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4977 (markdown-block-region beg end indent)))
4979 (defun markdown-electric-backquote (arg)
4980 "Insert a backquote.
4981 The numeric prefix argument ARG says how many times to repeat the insertion.
4982 Call `markdown-insert-gfm-code-block' interactively
4983 if three backquotes inserted at the beginning of line."
4984 (interactive "*P")
4985 (self-insert-command (prefix-numeric-value arg))
4986 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4987 (replace-match "")
4988 (call-interactively #'markdown-insert-gfm-code-block)))
4990 (defconst markdown-gfm-recognized-languages
4991 ;; To reproduce/update, evaluate the let-form in
4992 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4993 ;; but with appropriate use of a keyboard macro, indenting and filling it
4994 ;; properly is pretty fast.
4995 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4996 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4997 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4998 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4999 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5000 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5001 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5002 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5003 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5004 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5005 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5006 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5007 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5008 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5009 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5010 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5011 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5012 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5013 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5014 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5015 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5016 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5017 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5018 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5019 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5020 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5021 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5022 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5023 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5024 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5025 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5026 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5027 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5028 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5029 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5030 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5031 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5032 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5033 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5034 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5035 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5036 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5037 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5038 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5039 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5040 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5041 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5042 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5043 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5044 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5045 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5046 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5047 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5048 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5049 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5050 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5051 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5052 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5053 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5054 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5055 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5056 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5057 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5058 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5059 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5060 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5061 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5062 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5063 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5064 "Language specifiers recognized by GitHub's syntax highlighting features.")
5066 (defvar markdown-gfm-used-languages nil
5067 "Language names used in GFM code blocks.")
5068 (make-variable-buffer-local 'markdown-gfm-used-languages)
5070 (defun markdown-trim-whitespace (str)
5071 (markdown-replace-regexp-in-string
5072 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5074 (defun markdown-clean-language-string (str)
5075 (markdown-replace-regexp-in-string
5076 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5078 (defun markdown-validate-language-string (widget)
5079 (let ((str (widget-value widget)))
5080 (unless (string= str (markdown-clean-language-string str))
5081 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5082 widget)))
5084 (defun markdown-gfm-get-corpus ()
5085 "Create corpus of recognized GFM code block languages for the given buffer."
5086 (let ((given-corpus (append markdown-gfm-additional-languages
5087 markdown-gfm-recognized-languages)))
5088 (append
5089 markdown-gfm-used-languages
5090 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5091 given-corpus))))
5093 (defun markdown-gfm-add-used-language (lang)
5094 "Clean LANG and add to list of used languages."
5095 (setq markdown-gfm-used-languages
5096 (cons lang (remove lang markdown-gfm-used-languages))))
5098 (defcustom markdown-spaces-after-code-fence 1
5099 "Number of space characters to insert after a code fence.
5100 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5101 opening code fence and an info string."
5102 :group 'markdown
5103 :type 'integer
5104 :safe #'natnump
5105 :package-version '(markdown-mode . "2.3"))
5107 (defun markdown-insert-gfm-code-block (&optional lang)
5108 "Insert GFM code block for language LANG.
5109 If LANG is nil, the language will be queried from user. If a
5110 region is active, wrap this region with the markup instead. If
5111 the region boundaries are not on empty lines, these are added
5112 automatically in order to have the correct markup."
5113 (interactive
5114 (list (let ((completion-ignore-case nil))
5115 (condition-case nil
5116 (markdown-clean-language-string
5117 (completing-read
5118 "Programming language: "
5119 (markdown-gfm-get-corpus)
5120 nil 'confirm (car markdown-gfm-used-languages)
5121 'markdown-gfm-language-history))
5122 (quit "")))))
5123 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5124 (when (> (length lang) 0)
5125 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5126 lang)))
5127 (if (markdown-use-region-p)
5128 (let* ((b (region-beginning)) (e (region-end))
5129 (indent (progn (goto-char b) (current-indentation))))
5130 (goto-char e)
5131 ;; if we're on a blank line, don't newline, otherwise the ```
5132 ;; should go on its own line
5133 (unless (looking-back "\n" nil)
5134 (newline))
5135 (indent-to indent)
5136 (insert "```")
5137 (markdown-ensure-blank-line-after)
5138 (goto-char b)
5139 ;; if we're on a blank line, insert the quotes here, otherwise
5140 ;; add a new line first
5141 (unless (looking-at-p "\n")
5142 (newline)
5143 (forward-line -1))
5144 (markdown-ensure-blank-line-before)
5145 (indent-to indent)
5146 (insert "```" lang))
5147 (let ((indent (current-indentation)))
5148 (delete-horizontal-space :backward-only)
5149 (markdown-ensure-blank-line-before)
5150 (indent-to indent)
5151 (insert "```" lang "\n")
5152 (indent-to indent)
5153 (insert ?\n)
5154 (indent-to indent)
5155 (insert "```")
5156 (markdown-ensure-blank-line-after))
5157 (end-of-line 0)))
5159 (defun markdown-code-block-lang (&optional pos-prop)
5160 "Return the language name for a GFM or tilde fenced code block.
5161 The beginning of the block may be described by POS-PROP,
5162 a cons of (pos . prop) giving the position and property
5163 at the beginning of the block."
5164 (or pos-prop
5165 (setq pos-prop
5166 (markdown-max-of-seq
5167 #'car
5168 (cl-remove-if
5169 #'null
5170 (cl-mapcar
5171 #'markdown-find-previous-prop
5172 (markdown-get-fenced-block-begin-properties))))))
5173 (when pos-prop
5174 (goto-char (car pos-prop))
5175 (set-match-data (get-text-property (point) (cdr pos-prop)))
5176 ;; Note: Hard-coded group number assumes tilde
5177 ;; and GFM fenced code regexp groups agree.
5178 (let ((begin (match-beginning 3))
5179 (end (match-end 3)))
5180 (when (and begin end)
5181 ;; Fix language strings beginning with periods, like ".ruby".
5182 (when (eq (char-after begin) ?.)
5183 (setq begin (1+ begin)))
5184 (buffer-substring-no-properties begin end)))))
5186 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5187 (with-current-buffer (or buffer (current-buffer))
5188 (save-excursion
5189 (goto-char (point-min))
5190 (cl-loop
5191 with prop = 'markdown-gfm-block-begin
5192 for pos-prop = (markdown-find-next-prop prop)
5193 while pos-prop
5194 for lang = (markdown-code-block-lang pos-prop)
5195 do (progn (when lang (markdown-gfm-add-used-language lang))
5196 (goto-char (next-single-property-change (point) prop)))))))
5199 ;;; Footnotes ==================================================================
5201 (defun markdown-footnote-counter-inc ()
5202 "Increment `markdown-footnote-counter' and return the new value."
5203 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5204 (save-excursion
5205 (goto-char (point-min))
5206 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5207 (point-max) t)
5208 (let ((fn (string-to-number (match-string 1))))
5209 (when (> fn markdown-footnote-counter)
5210 (setq markdown-footnote-counter fn))))))
5211 (cl-incf markdown-footnote-counter))
5213 (defun markdown-insert-footnote ()
5214 "Insert footnote with a new number and move point to footnote definition."
5215 (interactive)
5216 (let ((fn (markdown-footnote-counter-inc)))
5217 (insert (format "[^%d]" fn))
5218 (markdown-footnote-text-find-new-location)
5219 (markdown-ensure-blank-line-before)
5220 (unless (markdown-cur-line-blank-p)
5221 (insert "\n"))
5222 (insert (format "[^%d]: " fn))
5223 (markdown-ensure-blank-line-after)))
5225 (defun markdown-footnote-text-find-new-location ()
5226 "Position the cursor at the proper location for a new footnote text."
5227 (cond
5228 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5229 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5230 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5231 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5233 (defun markdown-footnote-kill ()
5234 "Kill the footnote at point.
5235 The footnote text is killed (and added to the kill ring), the
5236 footnote marker is deleted. Point has to be either at the
5237 footnote marker or in the footnote text."
5238 (interactive)
5239 (let ((marker-pos nil)
5240 (skip-deleting-marker nil)
5241 (starting-footnote-text-positions
5242 (markdown-footnote-text-positions)))
5243 (when starting-footnote-text-positions
5244 ;; We're starting in footnote text, so mark our return position and jump
5245 ;; to the marker if possible.
5246 (let ((marker-pos (markdown-footnote-find-marker
5247 (cl-first starting-footnote-text-positions))))
5248 (if marker-pos
5249 (goto-char (1- marker-pos))
5250 ;; If there isn't a marker, we still want to kill the text.
5251 (setq skip-deleting-marker t))))
5252 ;; Either we didn't start in the text, or we started in the text and jumped
5253 ;; to the marker. We want to assume we're at the marker now and error if
5254 ;; we're not.
5255 (unless skip-deleting-marker
5256 (let ((marker (markdown-footnote-delete-marker)))
5257 (unless marker
5258 (error "Not at a footnote"))
5259 ;; Even if we knew the text position before, it changed when we deleted
5260 ;; the label.
5261 (setq marker-pos (cl-second marker))
5262 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5263 (unless new-text-pos
5264 (error "No text for footnote `%s'" (cl-first marker)))
5265 (goto-char new-text-pos))))
5266 (let ((pos (markdown-footnote-kill-text)))
5267 (goto-char (if starting-footnote-text-positions
5269 marker-pos)))))
5271 (defun markdown-footnote-delete-marker ()
5272 "Delete a footnote marker at point.
5273 Returns a list (ID START) containing the footnote ID and the
5274 start position of the marker before deletion. If no footnote
5275 marker was deleted, this function returns NIL."
5276 (let ((marker (markdown-footnote-marker-positions)))
5277 (when marker
5278 (delete-region (cl-second marker) (cl-third marker))
5279 (butlast marker))))
5281 (defun markdown-footnote-kill-text ()
5282 "Kill footnote text at point.
5283 Returns the start position of the footnote text before deletion,
5284 or NIL if point was not inside a footnote text.
5286 The killed text is placed in the kill ring (without the footnote
5287 number)."
5288 (let ((fn (markdown-footnote-text-positions)))
5289 (when fn
5290 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5291 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5292 (kill-new (match-string 1 text))
5293 (when (and (markdown-cur-line-blank-p)
5294 (markdown-prev-line-blank-p)
5295 (not (bobp)))
5296 (delete-region (1- (point)) (point)))
5297 (cl-second fn)))))
5299 (defun markdown-footnote-goto-text ()
5300 "Jump to the text of the footnote at point."
5301 (interactive)
5302 (let ((fn (car (markdown-footnote-marker-positions))))
5303 (unless fn
5304 (user-error "Not at a footnote marker"))
5305 (let ((new-pos (markdown-footnote-find-text fn)))
5306 (unless new-pos
5307 (error "No definition found for footnote `%s'" fn))
5308 (goto-char new-pos))))
5310 (defun markdown-footnote-return ()
5311 "Return from a footnote to its footnote number in the main text."
5312 (interactive)
5313 (let ((fn (save-excursion
5314 (car (markdown-footnote-text-positions)))))
5315 (unless fn
5316 (user-error "Not in a footnote"))
5317 (let ((new-pos (markdown-footnote-find-marker fn)))
5318 (unless new-pos
5319 (error "Footnote marker `%s' not found" fn))
5320 (goto-char new-pos))))
5322 (defun markdown-footnote-find-marker (id)
5323 "Find the location of the footnote marker with ID.
5324 The actual buffer position returned is the position directly
5325 following the marker's closing bracket. If no marker is found,
5326 NIL is returned."
5327 (save-excursion
5328 (goto-char (point-min))
5329 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5330 (skip-chars-backward "^]")
5331 (point))))
5333 (defun markdown-footnote-find-text (id)
5334 "Find the location of the text of footnote ID.
5335 The actual buffer position returned is the position of the first
5336 character of the text, after the footnote's identifier. If no
5337 footnote text is found, NIL is returned."
5338 (save-excursion
5339 (goto-char (point-min))
5340 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5341 (skip-chars-forward "[ \t]")
5342 (point))))
5344 (defun markdown-footnote-marker-positions ()
5345 "Return the position and ID of the footnote marker point is on.
5346 The return value is a list (ID START END). If point is not on a
5347 footnote, NIL is returned."
5348 ;; first make sure we're at a footnote marker
5349 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5350 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5351 (save-excursion
5352 ;; move point between [ and ^:
5353 (if (looking-at-p "\\[")
5354 (forward-char 1)
5355 (skip-chars-backward "^["))
5356 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5357 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5359 (defun markdown-footnote-text-positions ()
5360 "Return the start and end positions of the footnote text point is in.
5361 The exact return value is a list of three elements: (ID START END).
5362 The start position is the position of the opening bracket
5363 of the footnote id. The end position is directly after the
5364 newline that ends the footnote. If point is not in a footnote,
5365 NIL is returned instead."
5366 (save-excursion
5367 (let (result)
5368 (move-beginning-of-line 1)
5369 ;; Try to find the label. If we haven't found the label and we're at a blank
5370 ;; or indented line, back up if possible.
5371 (while (and
5372 (not (and (looking-at markdown-regex-footnote-definition)
5373 (setq result (list (match-string 1) (point)))))
5374 (and (not (bobp))
5375 (or (markdown-cur-line-blank-p)
5376 (>= (current-indentation) 4))))
5377 (forward-line -1))
5378 (when result
5379 ;; Advance if there is a next line that is either blank or indented.
5380 ;; (Need to check if we're on the last line, because
5381 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5382 (while (and (/= (line-end-position) (point-max))
5383 (or (markdown-next-line-blank-p)
5384 (>= (markdown-next-line-indent) 4)))
5385 (forward-line))
5386 ;; Move back while the current line is blank.
5387 (while (markdown-cur-line-blank-p)
5388 (forward-line -1))
5389 ;; Advance to capture this line and a single trailing newline (if there
5390 ;; is one).
5391 (forward-line)
5392 (append result (list (point)))))))
5395 ;;; Element Removal ===========================================================
5397 (defun markdown-kill-thing-at-point ()
5398 "Kill thing at point and add important text, without markup, to kill ring.
5399 Possible things to kill include (roughly in order of precedence):
5400 inline code, headers, horizonal rules, links (add link text to
5401 kill ring), images (add alt text to kill ring), angle uri, email
5402 addresses, bold, italics, reference definition (add URI to kill
5403 ring), footnote markers and text (kill both marker and text, add
5404 text to kill ring), and list items."
5405 (interactive "*")
5406 (let (val)
5407 (cond
5408 ;; Inline code
5409 ((markdown-inline-code-at-point)
5410 (kill-new (match-string 2))
5411 (delete-region (match-beginning 0) (match-end 0)))
5412 ;; ATX header
5413 ((thing-at-point-looking-at markdown-regex-header-atx)
5414 (kill-new (match-string 2))
5415 (delete-region (match-beginning 0) (match-end 0)))
5416 ;; Setext header
5417 ((thing-at-point-looking-at markdown-regex-header-setext)
5418 (kill-new (match-string 1))
5419 (delete-region (match-beginning 0) (match-end 0)))
5420 ;; Horizonal rule
5421 ((thing-at-point-looking-at markdown-regex-hr)
5422 (kill-new (match-string 0))
5423 (delete-region (match-beginning 0) (match-end 0)))
5424 ;; Inline link or image (add link or alt text to kill ring)
5425 ((thing-at-point-looking-at markdown-regex-link-inline)
5426 (kill-new (match-string 3))
5427 (delete-region (match-beginning 0) (match-end 0)))
5428 ;; Reference link or image (add link or alt text to kill ring)
5429 ((thing-at-point-looking-at markdown-regex-link-reference)
5430 (kill-new (match-string 3))
5431 (delete-region (match-beginning 0) (match-end 0)))
5432 ;; Angle URI (add URL to kill ring)
5433 ((thing-at-point-looking-at markdown-regex-angle-uri)
5434 (kill-new (match-string 2))
5435 (delete-region (match-beginning 0) (match-end 0)))
5436 ;; Email address in angle brackets (add email address to kill ring)
5437 ((thing-at-point-looking-at markdown-regex-email)
5438 (kill-new (match-string 1))
5439 (delete-region (match-beginning 0) (match-end 0)))
5440 ;; Wiki link (add alias text to kill ring)
5441 ((and markdown-enable-wiki-links
5442 (thing-at-point-looking-at markdown-regex-wiki-link))
5443 (kill-new (markdown-wiki-link-alias))
5444 (delete-region (match-beginning 1) (match-end 1)))
5445 ;; Bold
5446 ((thing-at-point-looking-at markdown-regex-bold)
5447 (kill-new (match-string 4))
5448 (delete-region (match-beginning 2) (match-end 2)))
5449 ;; Italics
5450 ((thing-at-point-looking-at markdown-regex-italic)
5451 (kill-new (match-string 3))
5452 (delete-region (match-beginning 1) (match-end 1)))
5453 ;; Strikethrough
5454 ((thing-at-point-looking-at markdown-regex-strike-through)
5455 (kill-new (match-string 4))
5456 (delete-region (match-beginning 2) (match-end 2)))
5457 ;; Footnote marker (add footnote text to kill ring)
5458 ((thing-at-point-looking-at markdown-regex-footnote)
5459 (markdown-footnote-kill))
5460 ;; Footnote text (add footnote text to kill ring)
5461 ((setq val (markdown-footnote-text-positions))
5462 (markdown-footnote-kill))
5463 ;; Reference definition (add URL to kill ring)
5464 ((thing-at-point-looking-at markdown-regex-reference-definition)
5465 (kill-new (match-string 5))
5466 (delete-region (match-beginning 0) (match-end 0)))
5467 ;; List item
5468 ((setq val (markdown-cur-list-item-bounds))
5469 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5471 (user-error "Nothing found at point to kill")))))
5474 ;;; Indentation ====================================================================
5476 (defun markdown-indent-find-next-position (cur-pos positions)
5477 "Return the position after the index of CUR-POS in POSITIONS.
5478 Positions are calculated by `markdown-calc-indents'."
5479 (while (and positions
5480 (not (equal cur-pos (car positions))))
5481 (setq positions (cdr positions)))
5482 (or (cadr positions) 0))
5484 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5485 'markdown-outdent-find-next-position "v2.3")
5487 (defun markdown-outdent-find-next-position (cur-pos positions)
5488 "Return the maximal element that precedes CUR-POS from POSITIONS.
5489 Positions are calculated by `markdown-calc-indents'."
5490 (let ((result 0))
5491 (dolist (i positions)
5492 (when (< i cur-pos)
5493 (setq result (max result i))))
5494 result))
5496 (defun markdown-indent-line ()
5497 "Indent the current line using some heuristics.
5498 If the _previous_ command was either `markdown-enter-key' or
5499 `markdown-cycle', then we should cycle to the next
5500 reasonable indentation position. Otherwise, we could have been
5501 called directly by `markdown-enter-key', by an initial call of
5502 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5503 these cases, indent to the default position.
5504 Positions are calculated by `markdown-calc-indents'."
5505 (interactive)
5506 (let ((positions (markdown-calc-indents))
5507 (cursor-pos (current-column))
5508 (_ (back-to-indentation))
5509 (cur-pos (current-column)))
5510 (if (not (equal this-command 'markdown-cycle))
5511 (indent-line-to (car positions))
5512 (setq positions (sort (delete-dups positions) '<))
5513 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5514 (new-cursor-pos
5515 (if (< cur-pos next-pos)
5516 (+ cursor-pos (- next-pos cur-pos))
5517 (- cursor-pos cur-pos))))
5518 (indent-line-to next-pos)
5519 (move-to-column new-cursor-pos)))))
5521 (defun markdown-calc-indents ()
5522 "Return a list of indentation columns to cycle through.
5523 The first element in the returned list should be considered the
5524 default indentation level. This function does not worry about
5525 duplicate positions, which are handled up by calling functions."
5526 (let (pos prev-line-pos positions)
5528 ;; Indentation of previous line
5529 (setq prev-line-pos (markdown-prev-line-indent))
5530 (setq positions (cons prev-line-pos positions))
5532 ;; Indentation of previous non-list-marker text
5533 (when (setq pos (markdown-prev-non-list-indent))
5534 (setq positions (cons pos positions)))
5536 ;; Indentation required for a pre block in current context
5537 (setq pos (length (markdown-pre-indentation (point))))
5538 (setq positions (cons pos positions))
5540 ;; Indentation of the previous line + tab-width
5541 (if prev-line-pos
5542 (setq positions (cons (+ prev-line-pos tab-width) positions))
5543 (setq positions (cons tab-width positions)))
5545 ;; Indentation of the previous line - tab-width
5546 (if (and prev-line-pos (> prev-line-pos tab-width))
5547 (setq positions (cons (- prev-line-pos tab-width) positions)))
5549 ;; Indentation of all preceeding list markers (when in a list)
5550 (when (setq pos (markdown-calculate-list-levels))
5551 (setq positions (append pos positions)))
5553 ;; First column
5554 (setq positions (cons 0 positions))
5556 ;; Return reversed list
5557 (reverse positions)))
5559 (defun markdown-enter-key ()
5560 "Handle RET depending on the context.
5561 If the point is at a table, move to the next row. Otherwise,
5562 indent according to value of `markdown-indent-on-enter'.
5563 When it is nil, simply call `newline'. Otherwise, indent the next line
5564 following RET using `markdown-indent-line'. Furthermore, when it
5565 is set to 'indent-and-new-item and the point is in a list item,
5566 start a new item with the same indentation. If the point is in an
5567 empty list item, remove it (so that pressing RET twice when in a
5568 list simply adds a blank line)."
5569 (interactive)
5570 (cond
5571 ;; Table
5572 ((markdown-table-at-point-p)
5573 (call-interactively #'markdown-table-next-row))
5574 ;; Indent non-table text
5575 (markdown-indent-on-enter
5576 (let (bounds)
5577 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5578 (setq bounds (markdown-cur-list-item-bounds)))
5579 (let ((beg (cl-first bounds))
5580 (end (cl-second bounds))
5581 (length (cl-fourth bounds)))
5582 ;; Point is in a list item
5583 (if (= (- end beg) length)
5584 ;; Delete blank list
5585 (progn
5586 (delete-region beg end)
5587 (newline)
5588 (markdown-indent-line))
5589 (call-interactively #'markdown-insert-list-item)))
5590 ;; Point is not in a list
5591 (newline)
5592 (markdown-indent-line))))
5593 ;; Insert a raw newline
5594 (t (newline))))
5596 (define-obsolete-function-alias 'markdown-exdent-or-delete
5597 'markdown-outdent-or-delete "v2.3")
5599 (defun markdown-outdent-or-delete (arg)
5600 "Handle BACKSPACE by cycling through indentation points.
5601 When BACKSPACE is pressed, if there is only whitespace
5602 before the current point, then outdent the line one level.
5603 Otherwise, do normal delete by repeating
5604 `backward-delete-char-untabify' ARG times."
5605 (interactive "*p")
5606 (if (use-region-p)
5607 (backward-delete-char-untabify arg)
5608 (let ((cur-pos (current-column))
5609 (start-of-indention (save-excursion
5610 (back-to-indentation)
5611 (current-column)))
5612 (positions (markdown-calc-indents)))
5613 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5614 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5615 (backward-delete-char-untabify arg)))))
5617 (defun markdown-find-leftmost-column (beg end)
5618 "Find the leftmost column in the region from BEG to END."
5619 (let ((mincol 1000))
5620 (save-excursion
5621 (goto-char beg)
5622 (while (< (point) end)
5623 (back-to-indentation)
5624 (unless (looking-at-p "[ \t]*$")
5625 (setq mincol (min mincol (current-column))))
5626 (forward-line 1)
5628 mincol))
5630 (defun markdown-indent-region (beg end arg)
5631 "Indent the region from BEG to END using some heuristics.
5632 When ARG is non-nil, outdent the region instead.
5633 See `markdown-indent-line' and `markdown-indent-line'."
5634 (interactive "*r\nP")
5635 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5636 (leftmostcol (markdown-find-leftmost-column beg end))
5637 (next-pos (if arg
5638 (markdown-outdent-find-next-position leftmostcol positions)
5639 (markdown-indent-find-next-position leftmostcol positions))))
5640 (indent-rigidly beg end (- next-pos leftmostcol))
5641 (setq deactivate-mark nil)))
5643 (define-obsolete-function-alias 'markdown-exdent-region
5644 'markdown-outdent-region "v2.3")
5646 (defun markdown-outdent-region (beg end)
5647 "Call `markdown-indent-region' on region from BEG to END with prefix."
5648 (interactive "*r")
5649 (markdown-indent-region beg end t))
5652 ;;; Markup Completion =========================================================
5654 (defconst markdown-complete-alist
5655 '((markdown-regex-header-atx . markdown-complete-atx)
5656 (markdown-regex-header-setext . markdown-complete-setext)
5657 (markdown-regex-hr . markdown-complete-hr))
5658 "Association list of form (regexp . function) for markup completion.")
5660 (defun markdown-incomplete-atx-p ()
5661 "Return t if ATX header markup is incomplete and nil otherwise.
5662 Assumes match data is available for `markdown-regex-header-atx'.
5663 Checks that the number of trailing hash marks equals the number of leading
5664 hash marks, that there is only a single space before and after the text,
5665 and that there is no extraneous whitespace in the text."
5667 ;; Number of starting and ending hash marks differs
5668 (not (= (length (match-string 1)) (length (match-string 3))))
5669 ;; When the header text is not empty...
5670 (and (> (length (match-string 2)) 0)
5671 ;; ...if there are extra leading, trailing, or interior spaces
5672 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5673 (not (= (match-beginning 3) (1+ (match-end 2))))
5674 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5675 ;; When the header text is empty...
5676 (and (= (length (match-string 2)) 0)
5677 ;; ...if there are too many or too few spaces
5678 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5680 (defun markdown-complete-atx ()
5681 "Complete and normalize ATX headers.
5682 Add or remove hash marks to the end of the header to match the
5683 beginning. Ensure that there is only a single space between hash
5684 marks and header text. Removes extraneous whitespace from header text.
5685 Assumes match data is available for `markdown-regex-header-atx'.
5686 Return nil if markup was complete and non-nil if markup was completed."
5687 (when (markdown-incomplete-atx-p)
5688 (let* ((new-marker (make-marker))
5689 (new-marker (set-marker new-marker (match-end 2))))
5690 ;; Hash marks and spacing at end
5691 (goto-char (match-end 2))
5692 (delete-region (match-end 2) (match-end 3))
5693 (insert " " (match-string 1))
5694 ;; Remove extraneous whitespace from title
5695 (replace-match (markdown-compress-whitespace-string (match-string 2))
5696 t t nil 2)
5697 ;; Spacing at beginning
5698 (goto-char (match-end 1))
5699 (delete-region (match-end 1) (match-beginning 2))
5700 (insert " ")
5701 ;; Leave point at end of text
5702 (goto-char new-marker))))
5704 (defun markdown-incomplete-setext-p ()
5705 "Return t if setext header markup is incomplete and nil otherwise.
5706 Assumes match data is available for `markdown-regex-header-setext'.
5707 Checks that length of underline matches text and that there is no
5708 extraneous whitespace in the text."
5709 (or (not (= (length (match-string 1)) (length (match-string 2))))
5710 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5712 (defun markdown-complete-setext ()
5713 "Complete and normalize setext headers.
5714 Add or remove underline characters to match length of header
5715 text. Removes extraneous whitespace from header text. Assumes
5716 match data is available for `markdown-regex-header-setext'.
5717 Return nil if markup was complete and non-nil if markup was completed."
5718 (when (markdown-incomplete-setext-p)
5719 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5720 (char (char-after (match-beginning 2)))
5721 (level (if (char-equal char ?-) 2 1)))
5722 (goto-char (match-beginning 0))
5723 (delete-region (match-beginning 0) (match-end 0))
5724 (markdown-insert-header level text t)
5725 t)))
5727 (defun markdown-incomplete-hr-p ()
5728 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5729 Assumes match data is available for `markdown-regex-hr'."
5730 (not (member (match-string 0) markdown-hr-strings)))
5732 (defun markdown-complete-hr ()
5733 "Complete horizontal rules.
5734 If horizontal rule string is a member of `markdown-hr-strings',
5735 do nothing. Otherwise, replace with the car of
5736 `markdown-hr-strings'.
5737 Assumes match data is available for `markdown-regex-hr'.
5738 Return nil if markup was complete and non-nil if markup was completed."
5739 (when (markdown-incomplete-hr-p)
5740 (replace-match (car markdown-hr-strings))
5743 (defun markdown-complete ()
5744 "Complete markup of object near point or in region when active.
5745 Handle all objects in `markdown-complete-alist', in order.
5746 See `markdown-complete-at-point' and `markdown-complete-region'."
5747 (interactive "*")
5748 (if (markdown-use-region-p)
5749 (markdown-complete-region (region-beginning) (region-end))
5750 (markdown-complete-at-point)))
5752 (defun markdown-complete-at-point ()
5753 "Complete markup of object near point.
5754 Handle all elements of `markdown-complete-alist' in order."
5755 (interactive "*")
5756 (let ((list markdown-complete-alist) found changed)
5757 (while list
5758 (let ((regexp (eval (caar list)))
5759 (function (cdar list)))
5760 (setq list (cdr list))
5761 (when (thing-at-point-looking-at regexp)
5762 (setq found t)
5763 (setq changed (funcall function))
5764 (setq list nil))))
5765 (if found
5766 (or changed (user-error "Markup at point is complete"))
5767 (user-error "Nothing to complete at point"))))
5769 (defun markdown-complete-region (beg end)
5770 "Complete markup of objects in region from BEG to END.
5771 Handle all objects in `markdown-complete-alist', in order. Each
5772 match is checked to ensure that a previous regexp does not also
5773 match."
5774 (interactive "*r")
5775 (let ((end-marker (set-marker (make-marker) end))
5776 previous)
5777 (dolist (element markdown-complete-alist)
5778 (let ((regexp (eval (car element)))
5779 (function (cdr element)))
5780 (goto-char beg)
5781 (while (re-search-forward regexp end-marker 'limit)
5782 (when (match-string 0)
5783 ;; Make sure this is not a match for any of the preceding regexps.
5784 ;; This prevents mistaking an HR for a Setext subheading.
5785 (let (match)
5786 (save-match-data
5787 (dolist (prev-regexp previous)
5788 (or match (setq match (looking-back prev-regexp nil)))))
5789 (unless match
5790 (save-excursion (funcall function))))))
5791 (cl-pushnew regexp previous :test #'equal)))
5792 previous))
5794 (defun markdown-complete-buffer ()
5795 "Complete markup for all objects in the current buffer."
5796 (interactive "*")
5797 (markdown-complete-region (point-min) (point-max)))
5800 ;;; Markup Cycling ============================================================
5802 (defun markdown-cycle-atx (arg &optional remove)
5803 "Cycle ATX header markup.
5804 Promote header (decrease level) when ARG is 1 and demote
5805 header (increase level) if arg is -1. When REMOVE is non-nil,
5806 remove the header when the level reaches zero and stop cycling
5807 when it reaches six. Otherwise, perform a proper cycling through
5808 levels one through six. Assumes match data is available for
5809 `markdown-regex-header-atx'."
5810 (let* ((old-level (length (match-string 1)))
5811 (new-level (+ old-level arg))
5812 (text (match-string 2)))
5813 (when (not remove)
5814 (setq new-level (% new-level 6))
5815 (setq new-level (cond ((= new-level 0) 6)
5816 ((< new-level 0) (+ new-level 6))
5817 (t new-level))))
5818 (cond
5819 ((= new-level 0)
5820 (markdown-unwrap-thing-at-point nil 0 2))
5821 ((<= new-level 6)
5822 (goto-char (match-beginning 0))
5823 (delete-region (match-beginning 0) (match-end 0))
5824 (markdown-insert-header new-level text nil)))))
5826 (defun markdown-cycle-setext (arg &optional remove)
5827 "Cycle setext header markup.
5828 Promote header (increase level) when ARG is 1 and demote
5829 header (decrease level or remove) if arg is -1. When demoting a
5830 level-two setext header, replace with a level-three atx header.
5831 When REMOVE is non-nil, remove the header when the level reaches
5832 zero. Otherwise, cycle back to a level six atx header. Assumes
5833 match data is available for `markdown-regex-header-setext'."
5834 (let* ((char (char-after (match-beginning 2)))
5835 (old-level (if (char-equal char ?=) 1 2))
5836 (new-level (+ old-level arg)))
5837 (when (and (not remove) (= new-level 0))
5838 (setq new-level 6))
5839 (cond
5840 ((= new-level 0)
5841 (markdown-unwrap-thing-at-point nil 0 1))
5842 ((<= new-level 2)
5843 (markdown-insert-header new-level nil t))
5844 ((<= new-level 6)
5845 (markdown-insert-header new-level nil nil)))))
5847 (defun markdown-cycle-hr (arg &optional remove)
5848 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5849 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5850 backwards (promote). When REMOVE is non-nil, remove the hr instead
5851 of cycling when the end of the list is reached.
5852 Assumes match data is available for `markdown-regex-hr'."
5853 (let* ((strings (if (= arg -1)
5854 (reverse markdown-hr-strings)
5855 markdown-hr-strings))
5856 (tail (member (match-string 0) strings))
5857 (new (or (cadr tail)
5858 (if remove
5859 (if (= arg 1)
5861 (car tail))
5862 (car strings)))))
5863 (replace-match new)))
5865 (defun markdown-cycle-bold ()
5866 "Cycle bold markup between underscores and asterisks.
5867 Assumes match data is available for `markdown-regex-bold'."
5868 (save-excursion
5869 (let* ((old-delim (match-string 3))
5870 (new-delim (if (string-equal old-delim "**") "__" "**")))
5871 (replace-match new-delim t t nil 3)
5872 (replace-match new-delim t t nil 5))))
5874 (defun markdown-cycle-italic ()
5875 "Cycle italic markup between underscores and asterisks.
5876 Assumes match data is available for `markdown-regex-italic'."
5877 (save-excursion
5878 (let* ((old-delim (match-string 2))
5879 (new-delim (if (string-equal old-delim "*") "_" "*")))
5880 (replace-match new-delim t t nil 2)
5881 (replace-match new-delim t t nil 4))))
5884 ;;; Keymap ====================================================================
5886 (defun markdown--style-map-prompt ()
5887 "Return a formatted prompt for Markdown markup insertion."
5888 (when markdown-enable-prefix-prompts
5889 (concat
5890 "Markdown: "
5891 (propertize "bold" 'face 'markdown-bold-face) ", "
5892 (propertize "italic" 'face 'markdown-italic-face) ", "
5893 (propertize "code" 'face 'markdown-inline-code-face) ", "
5894 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5895 (propertize "pre" 'face 'markdown-pre-face) ", "
5896 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5897 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5898 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5899 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5900 "C-h = more")))
5902 (defun markdown--command-map-prompt ()
5903 "Return prompt for Markdown buffer-wide commands."
5904 (when markdown-enable-prefix-prompts
5905 (concat
5906 "Command: "
5907 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5908 (propertize "p" 'face 'markdown-bold-face) "review, "
5909 (propertize "o" 'face 'markdown-bold-face) "pen, "
5910 (propertize "e" 'face 'markdown-bold-face) "xport, "
5911 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5912 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5913 "C-h = more")))
5915 (defvar markdown-mode-style-map
5916 (let ((map (make-keymap (markdown--style-map-prompt))))
5917 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5918 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5919 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5920 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5921 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5922 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5923 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5924 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5925 (define-key map (kbd "b") 'markdown-insert-bold)
5926 (define-key map (kbd "c") 'markdown-insert-code)
5927 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5928 (define-key map (kbd "f") 'markdown-insert-footnote)
5929 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5930 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5931 (define-key map (kbd "i") 'markdown-insert-italic)
5932 (define-key map (kbd "k") 'markdown-insert-kbd)
5933 (define-key map (kbd "l") 'markdown-insert-link)
5934 (define-key map (kbd "p") 'markdown-insert-pre)
5935 (define-key map (kbd "P") 'markdown-pre-region)
5936 (define-key map (kbd "q") 'markdown-insert-blockquote)
5937 (define-key map (kbd "s") 'markdown-insert-strike-through)
5938 (define-key map (kbd "Q") 'markdown-blockquote-region)
5939 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5940 (define-key map (kbd "-") 'markdown-insert-hr)
5941 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
5942 ;; Deprecated keys that may be removed in a future version
5943 (define-key map (kbd "e") 'markdown-insert-italic)
5944 map)
5945 "Keymap for Markdown text styling commands.")
5947 (defvar markdown-mode-command-map
5948 (let ((map (make-keymap (markdown--command-map-prompt))))
5949 (define-key map (kbd "m") 'markdown-other-window)
5950 (define-key map (kbd "p") 'markdown-preview)
5951 (define-key map (kbd "e") 'markdown-export)
5952 (define-key map (kbd "v") 'markdown-export-and-preview)
5953 (define-key map (kbd "o") 'markdown-open)
5954 (define-key map (kbd "l") 'markdown-live-preview-mode)
5955 (define-key map (kbd "w") 'markdown-kill-ring-save)
5956 (define-key map (kbd "c") 'markdown-check-refs)
5957 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5958 (define-key map (kbd "]") 'markdown-complete-buffer)
5959 (define-key map (kbd "^") 'markdown-table-sort-lines)
5960 (define-key map (kbd "|") 'markdown-table-convert-region)
5961 (define-key map (kbd "t") 'markdown-table-transpose)
5962 map)
5963 "Keymap for Markdown buffer-wide commands.")
5965 (defvar markdown-mode-map
5966 (let ((map (make-keymap)))
5967 ;; Markup insertion & removal
5968 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5969 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5970 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5971 ;; Promotion, demotion, and cycling
5972 (define-key map (kbd "C-c C--") 'markdown-promote)
5973 (define-key map (kbd "C-c C-=") 'markdown-demote)
5974 (define-key map (kbd "C-c C-]") 'markdown-complete)
5975 ;; Following and doing things
5976 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5977 (define-key map (kbd "C-c C-d") 'markdown-do)
5978 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5979 ;; Indentation
5980 (define-key map (kbd "C-m") 'markdown-enter-key)
5981 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5982 (define-key map (kbd "C-c >") 'markdown-indent-region)
5983 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5984 ;; Visibility cycling
5985 (define-key map (kbd "TAB") 'markdown-tab)
5986 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5987 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5988 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5989 ;; Heading and list navigation
5990 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5991 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5992 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5993 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5994 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5995 ;; Buffer-wide commands
5996 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5997 ;; Subtree, list, and table editing
5998 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5999 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6000 (define-key map (kbd "C-c <left>") 'markdown-promote)
6001 (define-key map (kbd "C-c <right>") 'markdown-demote)
6002 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6003 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6004 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6005 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6006 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6007 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6008 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6009 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6010 ;; Paragraphs (Markdown context aware)
6011 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6012 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6013 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6014 ;; Blocks (one or more paragraphs)
6015 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6016 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6017 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6018 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6019 ;; Pages (top-level sections)
6020 (define-key map [remap backward-page] 'markdown-backward-page)
6021 (define-key map [remap forward-page] 'markdown-forward-page)
6022 (define-key map [remap mark-page] 'markdown-mark-page)
6023 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6024 ;; Link Movement
6025 (define-key map (kbd "M-n") 'markdown-next-link)
6026 (define-key map (kbd "M-p") 'markdown-previous-link)
6027 ;; Toggling functionality
6028 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6029 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6030 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6031 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6032 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6033 ;; Alternative keys (in case of problems with the arrow keys)
6034 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6035 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6036 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6037 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6038 ;; Deprecated keys that may be removed in a future version
6039 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6040 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6041 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6042 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6043 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6044 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6045 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6046 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6047 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6048 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6049 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6050 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6051 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6052 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6053 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6054 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6055 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6056 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6057 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6058 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6059 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6060 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6061 map)
6062 "Keymap for Markdown major mode.")
6064 (defvar markdown-mode-mouse-map
6065 (let ((map (make-sparse-keymap)))
6066 (define-key map [follow-link] 'mouse-face)
6067 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6068 map)
6069 "Keymap for following links with mouse.")
6071 (defvar gfm-mode-map
6072 (let ((map (make-sparse-keymap)))
6073 (set-keymap-parent map markdown-mode-map)
6074 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6075 (define-key map "`" 'markdown-electric-backquote)
6076 map)
6077 "Keymap for `gfm-mode'.
6078 See also `markdown-mode-map'.")
6080 (defun markdown-tab ()
6081 "Handle TAB key based on context."
6082 (interactive)
6083 (cond
6084 ((markdown-table-at-point-p)
6085 (call-interactively #'markdown-table-forward-cell))
6086 (t (call-interactively #'markdown-cycle))))
6089 ;;; Menu ==================================================================
6091 (easy-menu-define markdown-mode-menu markdown-mode-map
6092 "Menu for Markdown mode"
6093 '("Markdown"
6094 "---"
6095 ("Movement"
6096 ["Jump" markdown-do]
6097 ["Follow Link" markdown-follow-thing-at-point]
6098 ["Next Link" markdown-next-link]
6099 ["Previous Link" markdown-previous-link]
6100 "---"
6101 ["Next Heading or List Item" markdown-outline-next]
6102 ["Previous Heading or List Item" markdown-outline-previous]
6103 ["Next at Same Level" markdown-outline-next-same-level]
6104 ["Previous at Same Level" markdown-outline-previous-same-level]
6105 ["Up to Parent" markdown-outline-up]
6106 "---"
6107 ["Forward Paragraph" markdown-forward-paragraph]
6108 ["Backward Paragraph" markdown-backward-paragraph]
6109 ["Forward Block" markdown-forward-block]
6110 ["Backward Block" markdown-backward-block])
6111 ("Show & Hide"
6112 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6113 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6114 "---"
6115 ["Narrow to Region" narrow-to-region]
6116 ["Narrow to Block" markdown-narrow-to-block]
6117 ["Narrow to Section" narrow-to-defun]
6118 ["Narrow to Subtree" markdown-narrow-to-subtree]
6119 ["Widen" widen (buffer-narrowed-p)]
6120 "---"
6121 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6122 :keys "C-c C-x C-m"
6123 :style radio
6124 :selected markdown-hide-markup])
6125 "---"
6126 ("Headings & Structure"
6127 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6128 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6129 ("Specific Heading (atx)"
6130 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6131 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6132 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6133 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6134 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6135 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6136 ("Specific Heading (Setext)"
6137 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6138 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6139 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6140 "---"
6141 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6142 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6143 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6144 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6145 ("Region & Mark"
6146 ["Indent Region" markdown-indent-region]
6147 ["Outdent Region" markdown-outdent-region]
6148 "--"
6149 ["Mark Paragraph" mark-paragraph]
6150 ["Mark Block" markdown-mark-block]
6151 ["Mark Section" mark-defun]
6152 ["Mark Subtree" markdown-mark-subtree])
6153 ("Lists"
6154 ["Insert List Item" markdown-insert-list-item]
6155 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6156 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6157 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6158 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6159 ["Renumber List" markdown-cleanup-list-numbers]
6160 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6161 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6162 ("Links & Images"
6163 ["Insert Link" markdown-insert-link]
6164 ["Insert Image" markdown-insert-image]
6165 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6166 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6167 "---"
6168 ["Check References" markdown-check-refs]
6169 ["Toggle URL Hiding" markdown-toggle-url-hiding
6170 :style radio
6171 :selected markdown-hide-urls]
6172 ["Toggle Inline Images" markdown-toggle-inline-images
6173 :keys "C-c C-x C-i"
6174 :style radio
6175 :selected markdown-inline-image-overlays]
6176 ["Toggle Wiki Links" markdown-toggle-wiki-links
6177 :style radio
6178 :selected markdown-enable-wiki-links])
6179 ("Styles"
6180 ["Bold" markdown-insert-bold]
6181 ["Italic" markdown-insert-italic]
6182 ["Code" markdown-insert-code]
6183 ["Strikethrough" markdown-insert-strike-through]
6184 ["Keyboard" markdown-insert-kbd]
6185 "---"
6186 ["Blockquote" markdown-insert-blockquote]
6187 ["Preformatted" markdown-insert-pre]
6188 ["GFM Code Block" markdown-insert-gfm-code-block]
6189 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6190 "---"
6191 ["Blockquote Region" markdown-blockquote-region]
6192 ["Preformatted Region" markdown-pre-region]
6193 "---"
6194 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6195 :style radio
6196 :selected markdown-fontify-code-blocks-natively]
6197 ["LaTeX Math Support" markdown-toggle-math
6198 :style radio
6199 :selected markdown-enable-math])
6200 "---"
6201 ("Preview & Export"
6202 ["Compile" markdown-other-window]
6203 ["Preview" markdown-preview]
6204 ["Export" markdown-export]
6205 ["Export & View" markdown-export-and-preview]
6206 ["Open" markdown-open]
6207 ["Live Export" markdown-live-preview-mode
6208 :style radio
6209 :selected markdown-live-preview-mode]
6210 ["Kill ring save" markdown-kill-ring-save])
6211 ("Markup Completion and Cycling"
6212 ["Complete Markup" markdown-complete]
6213 ["Promote Element" markdown-promote :keys "C-c C--"]
6214 ["Demote Element" markdown-demote :keys "C-c C-="])
6215 "---"
6216 ["Kill Element" markdown-kill-thing-at-point]
6217 "---"
6218 ("Documentation"
6219 ["Version" markdown-show-version]
6220 ["Homepage" markdown-mode-info]
6221 ["Describe Mode" (describe-function 'markdown-mode)]
6222 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6225 ;;; imenu =====================================================================
6227 (defun markdown-imenu-create-nested-index ()
6228 "Create and return a nested imenu index alist for the current buffer.
6229 See `imenu-create-index-function' and `imenu--index-alist' for details."
6230 (let* ((root '(nil . nil))
6231 cur-alist
6232 (cur-level 0)
6233 (empty-heading "-")
6234 (self-heading ".")
6235 hashes pos level heading)
6236 (save-excursion
6237 (goto-char (point-min))
6238 (while (re-search-forward markdown-regex-header (point-max) t)
6239 (unless (markdown-code-block-at-point-p)
6240 (cond
6241 ((match-string-no-properties 2) ;; level 1 setext
6242 (setq heading (match-string-no-properties 1))
6243 (setq pos (match-beginning 1)
6244 level 1))
6245 ((match-string-no-properties 3) ;; level 2 setext
6246 (setq heading (match-string-no-properties 1))
6247 (setq pos (match-beginning 1)
6248 level 2))
6249 ((setq hashes (markdown-trim-whitespace
6250 (match-string-no-properties 4)))
6251 (setq heading (match-string-no-properties 5)
6252 pos (match-beginning 4)
6253 level (length hashes))))
6254 (let ((alist (list (cons heading pos))))
6255 (cond
6256 ((= cur-level level) ; new sibling
6257 (setcdr cur-alist alist)
6258 (setq cur-alist alist))
6259 ((< cur-level level) ; first child
6260 (dotimes (_ (- level cur-level 1))
6261 (setq alist (list (cons empty-heading alist))))
6262 (if cur-alist
6263 (let* ((parent (car cur-alist))
6264 (self-pos (cdr parent)))
6265 (setcdr parent (cons (cons self-heading self-pos) alist)))
6266 (setcdr root alist)) ; primogenitor
6267 (setq cur-alist alist)
6268 (setq cur-level level))
6269 (t ; new sibling of an ancestor
6270 (let ((sibling-alist (last (cdr root))))
6271 (dotimes (_ (1- level))
6272 (setq sibling-alist (last (cdar sibling-alist))))
6273 (setcdr sibling-alist alist)
6274 (setq cur-alist alist))
6275 (setq cur-level level))))))
6276 (cdr root))))
6278 (defun markdown-imenu-create-flat-index ()
6279 "Create and return a flat imenu index alist for the current buffer.
6280 See `imenu-create-index-function' and `imenu--index-alist' for details."
6281 (let* ((empty-heading "-") index heading pos)
6282 (save-excursion
6283 (goto-char (point-min))
6284 (while (re-search-forward markdown-regex-header (point-max) t)
6285 (when (and (not (markdown-code-block-at-point-p))
6286 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6287 (cond
6288 ((setq heading (match-string-no-properties 1))
6289 (setq pos (match-beginning 1)))
6290 ((setq heading (match-string-no-properties 5))
6291 (setq pos (match-beginning 4))))
6292 (or (> (length heading) 0)
6293 (setq heading empty-heading))
6294 (setq index (append index (list (cons heading pos))))))
6295 index)))
6298 ;;; References ================================================================
6300 (defun markdown-reference-goto-definition ()
6301 "Jump to the definition of the reference at point or create it."
6302 (interactive)
6303 (when (thing-at-point-looking-at markdown-regex-link-reference)
6304 (let* ((text (match-string-no-properties 3))
6305 (reference (match-string-no-properties 6))
6306 (target (downcase (if (string= reference "") text reference)))
6307 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6308 (if loc
6309 (goto-char loc)
6310 (goto-char (match-beginning 0))
6311 (markdown-insert-reference-definition target)))))
6313 (defun markdown-reference-find-links (reference)
6314 "Return a list of all links for REFERENCE.
6315 REFERENCE should not include the surrounding square brackets.
6316 Elements of the list have the form (text start line), where
6317 text is the link text, start is the location at the beginning of
6318 the link, and line is the line number on which the link appears."
6319 (let* ((ref-quote (regexp-quote reference))
6320 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6321 ref-quote ref-quote))
6322 links)
6323 (save-excursion
6324 (goto-char (point-min))
6325 (while (re-search-forward regexp nil t)
6326 (let* ((text (or (match-string-no-properties 1)
6327 (match-string-no-properties 2)))
6328 (start (match-beginning 0))
6329 (line (markdown-line-number-at-pos)))
6330 (cl-pushnew (list text start line) links :test #'equal))))
6331 links))
6333 (defun markdown-get-undefined-refs ()
6334 "Return a list of undefined Markdown references.
6335 Result is an alist of pairs (reference . occurrences), where
6336 occurrences is itself another alist of pairs (label . line-number).
6337 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6338 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6339 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6340 (let ((missing))
6341 (save-excursion
6342 (goto-char (point-min))
6343 (while
6344 (re-search-forward markdown-regex-link-reference nil t)
6345 (let* ((text (match-string-no-properties 3))
6346 (reference (match-string-no-properties 6))
6347 (target (downcase (if (string= reference "") text reference))))
6348 (unless (markdown-reference-definition target)
6349 (let ((entry (assoc target missing)))
6350 (if (not entry)
6351 (cl-pushnew
6352 (cons target (list (cons text (markdown-line-number-at-pos))))
6353 missing :test #'equal)
6354 (setcdr entry
6355 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6356 (reverse missing))))
6358 (defconst markdown-reference-check-buffer
6359 "*Undefined references for %buffer%*"
6360 "Pattern for name of buffer for listing undefined references.
6361 The string %buffer% will be replaced by the corresponding
6362 `markdown-mode' buffer name.")
6364 (defun markdown-reference-check-buffer (&optional buffer-name)
6365 "Name and return buffer for reference checking.
6366 BUFFER-NAME is the name of the main buffer being visited."
6367 (or buffer-name (setq buffer-name (buffer-name)))
6368 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6369 "%buffer%" buffer-name
6370 markdown-reference-check-buffer))))
6371 (with-current-buffer refbuf
6372 (when view-mode
6373 (View-exit-and-edit))
6374 (use-local-map button-buffer-map)
6375 (erase-buffer))
6376 refbuf))
6378 (defconst markdown-reference-links-buffer
6379 "*Reference links for %buffer%*"
6380 "Pattern for name of buffer for listing references.
6381 The string %buffer% will be replaced by the corresponding buffer name.")
6383 (defun markdown-reference-links-buffer (&optional buffer-name)
6384 "Name, setup, and return a buffer for listing links.
6385 BUFFER-NAME is the name of the main buffer being visited."
6386 (or buffer-name (setq buffer-name (buffer-name)))
6387 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6388 "%buffer%" buffer-name
6389 markdown-reference-links-buffer))))
6390 (with-current-buffer linkbuf
6391 (when view-mode
6392 (View-exit-and-edit))
6393 (use-local-map button-buffer-map)
6394 (erase-buffer))
6395 linkbuf))
6397 ;; Add an empty Markdown reference definition to buffer
6398 ;; specified in the 'target-buffer property. The reference name is
6399 ;; the button's label.
6400 (define-button-type 'markdown-undefined-reference-button
6401 'help-echo "mouse-1, RET: create definition for undefined reference"
6402 'follow-link t
6403 'face 'bold
6404 'action (lambda (b)
6405 (let ((buffer (button-get b 'target-buffer))
6406 (line (button-get b 'target-line))
6407 (label (button-label b)))
6408 (switch-to-buffer-other-window buffer)
6409 (goto-char (point-min))
6410 (forward-line line)
6411 (markdown-insert-reference-definition label)
6412 (markdown-check-refs t))))
6414 ;; Jump to line in buffer specified by 'target-buffer property.
6415 ;; Line number is button's 'line property.
6416 (define-button-type 'markdown-goto-line-button
6417 'help-echo "mouse-1, RET: go to line"
6418 'follow-link t
6419 'face 'italic
6420 'action (lambda (b)
6421 (message (button-get b 'buffer))
6422 (switch-to-buffer-other-window (button-get b 'target-buffer))
6423 ;; use call-interactively to silence compiler
6424 (let ((current-prefix-arg (button-get b 'target-line)))
6425 (call-interactively 'goto-line))))
6427 ;; Jumps to a particular link at location given by 'target-char
6428 ;; property in buffer given by 'target-buffer property.
6429 (define-button-type 'markdown-location-button
6430 'help-echo "mouse-1, RET: jump to location of link"
6431 'follow-link t
6432 'face 'bold
6433 'action (lambda (b)
6434 (let ((target (button-get b 'target-buffer))
6435 (loc (button-get b 'target-char)))
6436 (kill-buffer-and-window)
6437 (switch-to-buffer target)
6438 (goto-char loc))))
6440 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6441 "Insert a button for creating REFERENCE in buffer OLDBUF.
6442 REFERENCE should be a list of the form (reference . occurrences),
6443 as by `markdown-get-undefined-refs'."
6444 (let ((label (car reference)))
6445 ;; Create a reference button
6446 (insert-button label
6447 :type 'markdown-undefined-reference-button
6448 'target-buffer oldbuf
6449 'target-line (cdr (car (cdr reference))))
6450 (insert " (")
6451 (dolist (occurrence (cdr reference))
6452 (let ((line (cdr occurrence)))
6453 ;; Create a line number button
6454 (insert-button (number-to-string line)
6455 :type 'markdown-goto-line-button
6456 'target-buffer oldbuf
6457 'target-line line)
6458 (insert " ")))
6459 (delete-char -1)
6460 (insert ")")
6461 (newline)))
6463 (defun markdown-insert-link-button (link oldbuf)
6464 "Insert a button for jumping to LINK in buffer OLDBUF.
6465 LINK should be a list of the form (text char line) containing
6466 the link text, location, and line number."
6467 (let ((label (cl-first link))
6468 (char (cl-second link))
6469 (line (cl-third link)))
6470 ;; Create a reference button
6471 (insert-button label
6472 :type 'markdown-location-button
6473 'target-buffer oldbuf
6474 'target-char char)
6475 (insert (format " (line %d)\n" line))))
6477 (defun markdown-reference-goto-link (&optional reference)
6478 "Jump to the location of the first use of REFERENCE."
6479 (interactive)
6480 (unless reference
6481 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6482 (setq reference (match-string-no-properties 2))
6483 (user-error "No reference definition at point")))
6484 (let ((links (markdown-reference-find-links reference)))
6485 (cond ((= (length links) 1)
6486 (goto-char (cadr (car links))))
6487 ((> (length links) 1)
6488 (let ((oldbuf (current-buffer))
6489 (linkbuf (markdown-reference-links-buffer)))
6490 (with-current-buffer linkbuf
6491 (insert "Links using reference " reference ":\n\n")
6492 (dolist (link (reverse links))
6493 (markdown-insert-link-button link oldbuf)))
6494 (view-buffer-other-window linkbuf)
6495 (goto-char (point-min))
6496 (forward-line 2)))
6498 (error "No links for reference %s" reference)))))
6500 (defun markdown-check-refs (&optional silent)
6501 "Show all undefined Markdown references in current `markdown-mode' buffer.
6502 If SILENT is non-nil, do not message anything when no undefined
6503 references found.
6504 Links which have empty reference definitions are considered to be
6505 defined."
6506 (interactive "P")
6507 (when (not (eq major-mode 'markdown-mode))
6508 (user-error "Not available in current mode"))
6509 (let ((oldbuf (current-buffer))
6510 (refs (markdown-get-undefined-refs))
6511 (refbuf (markdown-reference-check-buffer)))
6512 (if (null refs)
6513 (progn
6514 (when (not silent)
6515 (message "No undefined references found"))
6516 (kill-buffer refbuf))
6517 (with-current-buffer refbuf
6518 (insert "The following references are undefined:\n\n")
6519 (dolist (ref refs)
6520 (markdown-insert-undefined-reference-button ref oldbuf))
6521 (view-buffer-other-window refbuf)
6522 (goto-char (point-min))
6523 (forward-line 2)))))
6526 ;;; Lists =====================================================================
6528 (defun markdown-insert-list-item (&optional arg)
6529 "Insert a new list item.
6530 If the point is inside unordered list, insert a bullet mark. If
6531 the point is inside ordered list, insert the next number followed
6532 by a period. Use the previous list item to determine the amount
6533 of whitespace to place before and after list markers.
6535 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6536 decrease the indentation by one level.
6538 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6539 increase the indentation by one level."
6540 (interactive "p")
6541 (let (bounds cur-indent marker indent new-indent new-loc)
6542 (save-match-data
6543 ;; Look for a list item on current or previous non-blank line
6544 (save-excursion
6545 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6546 (not (bobp))
6547 (markdown-cur-line-blank-p))
6548 (forward-line -1)))
6549 (when bounds
6550 (cond ((save-excursion
6551 (skip-chars-backward " \t")
6552 (looking-at-p markdown-regex-list))
6553 (beginning-of-line)
6554 (insert "\n")
6555 (forward-line -1))
6556 ((not (markdown-cur-line-blank-p))
6557 (newline)))
6558 (setq new-loc (point)))
6559 ;; Look ahead for a list item on next non-blank line
6560 (unless bounds
6561 (save-excursion
6562 (while (and (null bounds)
6563 (not (eobp))
6564 (markdown-cur-line-blank-p))
6565 (forward-line)
6566 (setq bounds (markdown-cur-list-item-bounds))))
6567 (when bounds
6568 (setq new-loc (point))
6569 (unless (markdown-cur-line-blank-p)
6570 (newline))))
6571 (if (not bounds)
6572 ;; When not in a list, start a new unordered one
6573 (progn
6574 (unless (markdown-cur-line-blank-p)
6575 (insert "\n"))
6576 (insert markdown-unordered-list-item-prefix))
6577 ;; Compute indentation and marker for new list item
6578 (setq cur-indent (nth 2 bounds))
6579 (setq marker (nth 4 bounds))
6580 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6581 (when (nth 5 bounds)
6582 (setq marker
6583 (concat marker
6584 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6585 (cond
6586 ;; Dedent: decrement indentation, find previous marker.
6587 ((= arg 4)
6588 (setq indent (max (- cur-indent 4) 0))
6589 (let ((prev-bounds
6590 (save-excursion
6591 (goto-char (nth 0 bounds))
6592 (when (markdown-up-list)
6593 (markdown-cur-list-item-bounds)))))
6594 (when prev-bounds
6595 (setq marker (nth 4 prev-bounds)))))
6596 ;; Indent: increment indentation by 4, use same marker.
6597 ((= arg 16) (setq indent (+ cur-indent 4)))
6598 ;; Same level: keep current indentation and marker.
6599 (t (setq indent cur-indent)))
6600 (setq new-indent (make-string indent 32))
6601 (goto-char new-loc)
6602 (cond
6603 ;; Ordered list
6604 ((string-match-p "[0-9]" marker)
6605 (if (= arg 16) ;; starting a new column indented one more level
6606 (insert (concat new-indent "1. "))
6607 ;; Don't use previous match-data
6608 (set-match-data nil)
6609 ;; travel up to the last item and pick the correct number. If
6610 ;; the argument was nil, "new-indent = cur-indent" is the same,
6611 ;; so we don't need special treatment. Neat.
6612 (save-excursion
6613 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6614 (>= (forward-line -1) 0))))
6615 (let* ((old-prefix (match-string 1))
6616 (old-spacing (match-string 2))
6617 (new-prefix (if old-prefix
6618 (int-to-string (1+ (string-to-number old-prefix)))
6619 "1"))
6620 (space-adjust (- (length old-prefix) (length new-prefix)))
6621 (new-spacing (if (and (match-string 2)
6622 (not (string-match-p "\t" old-spacing))
6623 (< space-adjust 0)
6624 (> space-adjust (- 1 (length (match-string 2)))))
6625 (substring (match-string 2) 0 space-adjust)
6626 (or old-spacing ". "))))
6627 (insert (concat new-indent new-prefix new-spacing)))))
6628 ;; Unordered list, GFM task list, or ordered list with hash mark
6629 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6630 (insert new-indent marker)))))))
6632 (defun markdown-move-list-item-up ()
6633 "Move the current list item up in the list when possible.
6634 In nested lists, move child items with the parent item."
6635 (interactive)
6636 (let (cur prev old)
6637 (when (setq cur (markdown-cur-list-item-bounds))
6638 (setq old (point))
6639 (goto-char (nth 0 cur))
6640 (if (markdown-prev-list-item (nth 3 cur))
6641 (progn
6642 (setq prev (markdown-cur-list-item-bounds))
6643 (condition-case nil
6644 (progn
6645 (transpose-regions (nth 0 prev) (nth 1 prev)
6646 (nth 0 cur) (nth 1 cur) t)
6647 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6648 ;; Catch error in case regions overlap.
6649 (error (goto-char old))))
6650 (goto-char old)))))
6652 (defun markdown-move-list-item-down ()
6653 "Move the current list item down in the list when possible.
6654 In nested lists, move child items with the parent item."
6655 (interactive)
6656 (let (cur next old)
6657 (when (setq cur (markdown-cur-list-item-bounds))
6658 (setq old (point))
6659 (if (markdown-next-list-item (nth 3 cur))
6660 (progn
6661 (setq next (markdown-cur-list-item-bounds))
6662 (condition-case nil
6663 (progn
6664 (transpose-regions (nth 0 cur) (nth 1 cur)
6665 (nth 0 next) (nth 1 next) nil)
6666 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6667 ;; Catch error in case regions overlap.
6668 (error (goto-char old))))
6669 (goto-char old)))))
6671 (defun markdown-demote-list-item (&optional bounds)
6672 "Indent (or demote) the current list item.
6673 Optionally, BOUNDS of the current list item may be provided if available.
6674 In nested lists, demote child items as well."
6675 (interactive)
6676 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6677 (save-excursion
6678 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6679 (goto-char (nth 0 bounds))
6680 (while (< (point) end-marker)
6681 (unless (markdown-cur-line-blank-p)
6682 (insert (make-string markdown-list-indent-width ? )))
6683 (forward-line))))))
6685 (defun markdown-promote-list-item (&optional bounds)
6686 "Unindent (or promote) the current list item.
6687 Optionally, BOUNDS of the current list item may be provided if available.
6688 In nested lists, demote child items as well."
6689 (interactive)
6690 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6691 (save-excursion
6692 (save-match-data
6693 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6694 num regexp)
6695 (goto-char (nth 0 bounds))
6696 (when (looking-at (format "^[ ]\\{1,%d\\}"
6697 markdown-list-indent-width))
6698 (setq num (- (match-end 0) (match-beginning 0)))
6699 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6700 (while (and (< (point) end-marker)
6701 (re-search-forward regexp end-marker t))
6702 (replace-match "" nil nil)
6703 (forward-line))))))))
6705 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6706 "Update the numbering for level PFX (as a string of spaces).
6708 Assume that the previously found match was for a numbered item in
6709 a list."
6710 (let ((cpfx pfx)
6711 (idx 0)
6712 (continue t)
6713 (step t)
6714 (sep nil))
6715 (while (and continue (not (eobp)))
6716 (setq step t)
6717 (cond
6718 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6719 (setq cpfx (match-string-no-properties 1))
6720 (cond
6721 ((string= cpfx pfx)
6722 (save-excursion
6723 (replace-match
6724 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6725 (setq sep nil))
6726 ;; indented a level
6727 ((string< pfx cpfx)
6728 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6729 (setq step nil))
6730 ;; exit the loop
6732 (setq step nil)
6733 (setq continue nil))))
6735 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6736 (setq cpfx (match-string-no-properties 1))
6737 (cond
6738 ;; reset if separated before
6739 ((string= cpfx pfx) (when sep (setq idx 0)))
6740 ((string< cpfx pfx)
6741 (setq step nil)
6742 (setq continue nil))))
6743 (t (setq sep t)))
6745 (when step
6746 (beginning-of-line)
6747 (setq continue (= (forward-line) 0))))
6748 sep))
6750 (defun markdown-cleanup-list-numbers ()
6751 "Update the numbering of ordered lists."
6752 (interactive)
6753 (save-excursion
6754 (goto-char (point-min))
6755 (markdown-cleanup-list-numbers-level "")))
6758 ;;; Movement ==================================================================
6760 (defun markdown-beginning-of-defun (&optional arg)
6761 "`beginning-of-defun-function' for Markdown.
6762 This is used to find the beginning of the defun and should behave
6763 like ‘beginning-of-defun’, returning non-nil if it found the
6764 beginning of a defun. It moves the point backward, right before a
6765 heading which defines a defun. When ARG is non-nil, repeat that
6766 many times. When ARG is negative, move forward to the ARG-th
6767 following section."
6768 (or arg (setq arg 1))
6769 (when (< arg 0) (end-of-line))
6770 ;; Adjust position for setext headings.
6771 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6772 (not (= (point) (match-beginning 0)))
6773 (not (markdown-code-block-at-point-p)))
6774 (goto-char (match-end 0)))
6775 (let (found)
6776 ;; Move backward with positive argument.
6777 (while (and (not (bobp)) (> arg 0))
6778 (setq found nil)
6779 (while (and (not found)
6780 (not (bobp))
6781 (re-search-backward markdown-regex-header nil 'move))
6782 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6783 (setq found (match-beginning 0)))
6784 (setq arg (1- arg)))
6785 ;; Move forward with negative argument.
6786 (while (and (not (eobp)) (< arg 0))
6787 (setq found nil)
6788 (while (and (not found)
6789 (not (eobp))
6790 (re-search-forward markdown-regex-header nil 'move))
6791 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6792 (setq found (match-beginning 0)))
6793 (setq arg (1+ arg)))
6794 (when found
6795 (beginning-of-line)
6796 t)))
6798 (defun markdown-end-of-defun ()
6799 "`end-of-defun-function’ for Markdown.
6800 This is used to find the end of the defun at point.
6801 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6802 so it can assume that point is at the beginning of the defun body.
6803 It should move point to the first position after the defun."
6804 (or (eobp) (forward-char 1))
6805 (let (found)
6806 (while (and (not found)
6807 (not (eobp))
6808 (re-search-forward markdown-regex-header nil 'move))
6809 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6810 (setq found (match-beginning 0))))
6811 (when found
6812 (goto-char found)
6813 (skip-syntax-backward "-"))))
6815 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6817 (defun markdown-beginning-of-text-block ()
6818 "Move backward to previous beginning of a plain text block.
6819 This function simply looks for blank lines without considering
6820 the surrounding context in light of Markdown syntax. For that, see
6821 `markdown-backward-block'."
6822 (interactive)
6823 (let ((start (point)))
6824 (if (re-search-backward markdown-regex-block-separator nil t)
6825 (goto-char (match-end 0))
6826 (goto-char (point-min)))
6827 (when (and (= start (point)) (not (bobp)))
6828 (forward-line -1)
6829 (if (re-search-backward markdown-regex-block-separator nil t)
6830 (goto-char (match-end 0))
6831 (goto-char (point-min))))))
6833 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6835 (defun markdown-end-of-text-block ()
6836 "Move forward to next beginning of a plain text block.
6837 This function simply looks for blank lines without considering
6838 the surrounding context in light of Markdown syntax. For that, see
6839 `markdown-forward-block'."
6840 (interactive)
6841 (beginning-of-line)
6842 (skip-syntax-forward "-")
6843 (when (= (point) (point-min))
6844 (forward-char))
6845 (if (re-search-forward markdown-regex-block-separator nil t)
6846 (goto-char (match-end 0))
6847 (goto-char (point-max)))
6848 (skip-syntax-backward "-")
6849 (forward-line))
6851 (defun markdown-backward-paragraph (&optional arg)
6852 "Move the point to the start of the current paragraph.
6853 With argument ARG, do it ARG times; a negative argument ARG = -N
6854 means move forward N blocks."
6855 (interactive "^p")
6856 (or arg (setq arg 1))
6857 (if (< arg 0)
6858 (markdown-forward-paragraph (- arg))
6859 (dotimes (_ arg)
6860 ;; Skip over whitespace in between paragraphs when moving backward.
6861 (skip-syntax-backward "-")
6862 (beginning-of-line)
6863 ;; Skip over code block endings.
6864 (when (markdown-range-properties-exist
6865 (point-at-bol) (point-at-eol)
6866 '(markdown-gfm-block-end
6867 markdown-tilde-fence-end))
6868 (forward-line -1))
6869 ;; Skip over blank lines inside blockquotes.
6870 (while (and (not (eobp))
6871 (looking-at markdown-regex-blockquote)
6872 (= (length (match-string 3)) 0))
6873 (forward-line -1))
6874 ;; Proceed forward based on the type of block of paragraph.
6875 (let (bounds skip)
6876 (cond
6877 ;; Blockquotes
6878 ((looking-at markdown-regex-blockquote)
6879 (while (and (not (bobp))
6880 (looking-at markdown-regex-blockquote)
6881 (> (length (match-string 3)) 0)) ;; not blank
6882 (forward-line -1))
6883 (forward-line))
6884 ;; List items
6885 ((setq bounds (markdown-cur-list-item-bounds))
6886 (goto-char (nth 0 bounds)))
6887 ;; Other
6889 (while (and (not (bobp))
6890 (not skip)
6891 (not (markdown-cur-line-blank-p))
6892 (not (looking-at markdown-regex-blockquote))
6893 (not (markdown-range-properties-exist
6894 (point-at-bol) (point-at-eol)
6895 '(markdown-gfm-block-end
6896 markdown-tilde-fence-end))))
6897 (setq skip (markdown-range-properties-exist
6898 (point-at-bol) (point-at-eol)
6899 '(markdown-gfm-block-begin
6900 markdown-tilde-fence-begin)))
6901 (forward-line -1))
6902 (unless (bobp)
6903 (forward-line 1))))))))
6905 (defun markdown-forward-paragraph (&optional arg)
6906 "Move forward to the next end of a paragraph.
6907 With argument ARG, do it ARG times; a negative argument ARG = -N
6908 means move backward N blocks."
6909 (interactive "^p")
6910 (or arg (setq arg 1))
6911 (if (< arg 0)
6912 (markdown-backward-paragraph (- arg))
6913 (dotimes (_ arg)
6914 ;; Skip whitespace in between paragraphs.
6915 (when (markdown-cur-line-blank-p)
6916 (skip-syntax-forward "-")
6917 (beginning-of-line))
6918 ;; Proceed forward based on the type of block.
6919 (let (bounds skip)
6920 (cond
6921 ;; Blockquotes
6922 ((looking-at markdown-regex-blockquote)
6923 ;; Skip over blank lines inside blockquotes.
6924 (while (and (not (eobp))
6925 (looking-at markdown-regex-blockquote)
6926 (= (length (match-string 3)) 0))
6927 (forward-line))
6928 ;; Move to end of quoted text block
6929 (while (and (not (eobp))
6930 (looking-at markdown-regex-blockquote)
6931 (> (length (match-string 3)) 0)) ;; not blank
6932 (forward-line)))
6933 ;; List items
6934 ((and (markdown-cur-list-item-bounds)
6935 (setq bounds (markdown-next-list-item-bounds)))
6936 (goto-char (nth 0 bounds)))
6937 ;; Other
6939 (forward-line)
6940 (while (and (not (eobp))
6941 (not skip)
6942 (not (markdown-cur-line-blank-p))
6943 (not (looking-at markdown-regex-blockquote))
6944 (not (markdown-range-properties-exist
6945 (point-at-bol) (point-at-eol)
6946 '(markdown-gfm-block-begin
6947 markdown-tilde-fence-begin))))
6948 (setq skip (markdown-range-properties-exist
6949 (point-at-bol) (point-at-eol)
6950 '(markdown-gfm-block-end
6951 markdown-tilde-fence-end)))
6952 (forward-line))))))))
6954 (defun markdown-backward-block (&optional arg)
6955 "Move the point to the start of the current Markdown block.
6956 Moves across complete code blocks, list items, and blockquotes,
6957 but otherwise stops at blank lines, headers, and horizontal
6958 rules. With argument ARG, do it ARG times; a negative argument
6959 ARG = -N means move forward N blocks."
6960 (interactive "^p")
6961 (or arg (setq arg 1))
6962 (if (< arg 0)
6963 (markdown-forward-block (- arg))
6964 (dotimes (_ arg)
6965 ;; Skip over whitespace in between blocks when moving backward,
6966 ;; unless at a block boundary with no whitespace.
6967 (skip-syntax-backward "-")
6968 (beginning-of-line)
6969 ;; Proceed forward based on the type of block.
6970 (cond
6971 ;; Code blocks
6972 ((and (markdown-code-block-at-pos (point)) ;; this line
6973 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6974 (forward-line -1)
6975 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6976 (forward-line -1))
6977 (forward-line))
6978 ;; Headings
6979 ((markdown-heading-at-point)
6980 (goto-char (match-beginning 0)))
6981 ;; Horizontal rules
6982 ((looking-at markdown-regex-hr))
6983 ;; Blockquotes
6984 ((looking-at markdown-regex-blockquote)
6985 (forward-line -1)
6986 (while (and (looking-at markdown-regex-blockquote)
6987 (not (bobp)))
6988 (forward-line -1))
6989 (forward-line))
6990 ;; List items
6991 ((markdown-cur-list-item-bounds)
6992 (markdown-beginning-of-list))
6993 ;; Other
6995 ;; Move forward in case it is a one line regular paragraph.
6996 (unless (markdown-next-line-blank-p)
6997 (forward-line))
6998 (unless (markdown-prev-line-blank-p)
6999 (markdown-backward-paragraph)))))))
7001 (defun markdown-forward-block (&optional arg)
7002 "Move forward to the next end of a Markdown block.
7003 Moves across complete code blocks, list items, and blockquotes,
7004 but otherwise stops at blank lines, headers, and horizontal
7005 rules. With argument ARG, do it ARG times; a negative argument
7006 ARG = -N means move backward N blocks."
7007 (interactive "^p")
7008 (or arg (setq arg 1))
7009 (if (< arg 0)
7010 (markdown-backward-block (- arg))
7011 (dotimes (_ arg)
7012 ;; Skip over whitespace in between blocks when moving forward.
7013 (if (markdown-cur-line-blank-p)
7014 (skip-syntax-forward "-")
7015 (beginning-of-line))
7016 ;; Proceed forward based on the type of block.
7017 (cond
7018 ;; Code blocks
7019 ((markdown-code-block-at-point-p)
7020 (forward-line)
7021 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7022 (forward-line)))
7023 ;; Headings
7024 ((looking-at markdown-regex-header)
7025 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7026 (forward-line))
7027 ;; Horizontal rules
7028 ((looking-at markdown-regex-hr)
7029 (forward-line))
7030 ;; Blockquotes
7031 ((looking-at markdown-regex-blockquote)
7032 (forward-line)
7033 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7034 (forward-line)))
7035 ;; List items
7036 ((markdown-cur-list-item-bounds)
7037 (markdown-end-of-list)
7038 (forward-line))
7039 ;; Other
7040 (t (markdown-forward-paragraph))))
7041 (skip-syntax-backward "-")
7042 (unless (eobp)
7043 (forward-char 1))))
7045 (defun markdown-backward-page (&optional count)
7046 "Move backward to boundary of the current toplevel section.
7047 With COUNT, repeat, or go forward if negative."
7048 (interactive "p")
7049 (or count (setq count 1))
7050 (if (< count 0)
7051 (markdown-forward-page (- count))
7052 (skip-syntax-backward "-")
7053 (or (markdown-back-to-heading-over-code-block t t)
7054 (goto-char (point-min)))
7055 (when (looking-at markdown-regex-header)
7056 (let ((level (markdown-outline-level)))
7057 (when (> level 1) (markdown-up-heading level))
7058 (when (> count 1)
7059 (condition-case nil
7060 (markdown-backward-same-level (1- count))
7061 (error (goto-char (point-min)))))))))
7063 (defun markdown-forward-page (&optional count)
7064 "Move forward to boundary of the current toplevel section.
7065 With COUNT, repeat, or go backward if negative."
7066 (interactive "p")
7067 (or count (setq count 1))
7068 (if (< count 0)
7069 (markdown-backward-page (- count))
7070 (if (markdown-back-to-heading-over-code-block t t)
7071 (let ((level (markdown-outline-level)))
7072 (when (> level 1) (markdown-up-heading level))
7073 (condition-case nil
7074 (markdown-forward-same-level count)
7075 (error (goto-char (point-max)))))
7076 (markdown-next-visible-heading 1))))
7078 (defun markdown-next-link ()
7079 "Jump to next inline, reference, or wiki link.
7080 If successful, return point. Otherwise, return nil.
7081 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7082 (interactive)
7083 (let ((opoint (point)))
7084 (when (or (markdown-link-p) (markdown-wiki-link-p))
7085 ;; At a link already, move past it.
7086 (goto-char (+ (match-end 0) 1)))
7087 ;; Search for the next wiki link and move to the beginning.
7088 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7089 (markdown-code-block-at-point-p)
7090 (< (point) (point-max))))
7091 (if (and (not (eq (point) opoint))
7092 (or (markdown-link-p) (markdown-wiki-link-p)))
7093 ;; Group 1 will move past non-escape character in wiki link regexp.
7094 ;; Go to beginning of group zero for all other link types.
7095 (goto-char (or (match-beginning 1) (match-beginning 0)))
7096 (goto-char opoint)
7097 nil)))
7099 (defun markdown-previous-link ()
7100 "Jump to previous wiki link.
7101 If successful, return point. Otherwise, return nil.
7102 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7103 (interactive)
7104 (let ((opoint (point)))
7105 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7106 (markdown-code-block-at-point-p)
7107 (> (point) (point-min))))
7108 (if (and (not (eq (point) opoint))
7109 (or (markdown-link-p) (markdown-wiki-link-p)))
7110 (goto-char (or (match-beginning 1) (match-beginning 0)))
7111 (goto-char opoint)
7112 nil)))
7115 ;;; Outline ===================================================================
7117 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7118 "Wrapper for `outline-mode' functions to skip false positives.
7119 MOVE-FN is a function and ARG is its argument. For example,
7120 headings inside preformatted code blocks may match
7121 `outline-regexp' but should not be considered as headings.
7122 When ADJUST is non-nil, adjust the point for interactive calls
7123 to avoid leaving the point at invisible markup. This adjustment
7124 generally should only be done for interactive calls, since other
7125 functions may expect the point to be at the beginning of the
7126 regular expression."
7127 (let ((prev -1) (start (point)))
7128 (if arg (funcall move-fn arg) (funcall move-fn))
7129 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7130 (setq prev (point))
7131 (if arg (funcall move-fn arg) (funcall move-fn)))
7132 ;; Adjust point for setext headings and invisible text.
7133 (save-match-data
7134 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7135 (if markdown-hide-markup
7136 ;; Move to beginning of heading text if markup is hidden.
7137 (goto-char (or (match-beginning 1) (match-beginning 5)))
7138 ;; Move to beginning of markup otherwise.
7139 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7140 (if (= (point) start) nil (point))))
7142 (defun markdown-next-visible-heading (arg)
7143 "Move to the next visible heading line of any level.
7144 With argument, repeats or can move backward if negative. ARG is
7145 passed to `outline-next-visible-heading'."
7146 (interactive "p")
7147 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7149 (defun markdown-previous-visible-heading (arg)
7150 "Move to the previous visible heading line of any level.
7151 With argument, repeats or can move backward if negative. ARG is
7152 passed to `outline-previous-visible-heading'."
7153 (interactive "p")
7154 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7156 (defun markdown-next-heading ()
7157 "Move to the next heading line of any level."
7158 (markdown-move-heading-common #'outline-next-heading))
7160 (defun markdown-previous-heading ()
7161 "Move to the previous heading line of any level."
7162 (markdown-move-heading-common #'outline-previous-heading))
7164 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7165 "Move back to the beginning of the previous heading.
7166 Returns t if the point is at a heading, the location if a heading
7167 was found, and nil otherwise.
7168 Only visible heading lines are considered, unless INVISIBLE-OK is
7169 non-nil. Throw an error if there is no previous heading unless
7170 NO-ERROR is non-nil.
7171 Leaves match data intact for `markdown-regex-header'."
7172 (beginning-of-line)
7173 (or (and (markdown-heading-at-point)
7174 (not (markdown-code-block-at-point-p)))
7175 (let (found)
7176 (save-excursion
7177 (while (and (not found)
7178 (re-search-backward markdown-regex-header nil t))
7179 (when (and (or invisible-ok (not (outline-invisible-p)))
7180 (not (markdown-code-block-at-point-p)))
7181 (setq found (point))))
7182 (if (not found)
7183 (unless no-error (user-error "Before first heading"))
7184 (setq found (point))))
7185 (when found (goto-char found)))))
7187 (defun markdown-forward-same-level (arg)
7188 "Move forward to the ARG'th heading at same level as this one.
7189 Stop at the first and last headings of a superior heading."
7190 (interactive "p")
7191 (markdown-back-to-heading-over-code-block)
7192 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7194 (defun markdown-backward-same-level (arg)
7195 "Move backward to the ARG'th heading at same level as this one.
7196 Stop at the first and last headings of a superior heading."
7197 (interactive "p")
7198 (markdown-back-to-heading-over-code-block)
7199 (while (> arg 0)
7200 (let ((point-to-move-to
7201 (save-excursion
7202 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7203 (if point-to-move-to
7204 (progn
7205 (goto-char point-to-move-to)
7206 (setq arg (1- arg)))
7207 (user-error "No previous same-level heading")))))
7209 (defun markdown-up-heading (arg)
7210 "Move to the visible heading line of which the present line is a subheading.
7211 With argument, move up ARG levels."
7212 (interactive "p")
7213 (and (called-interactively-p 'any)
7214 (not (eq last-command 'markdown-up-heading)) (push-mark))
7215 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7217 (defun markdown-back-to-heading (&optional invisible-ok)
7218 "Move to previous heading line, or beg of this line if it's a heading.
7219 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7220 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7222 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7224 (defun markdown-on-heading-p ()
7225 "Return non-nil if point is on a heading line."
7226 (get-text-property (point-at-bol) 'markdown-heading))
7228 (defun markdown-end-of-subtree (&optional invisible-OK)
7229 "Move to the end of the current subtree.
7230 Only visible heading lines are considered, unless INVISIBLE-OK is
7231 non-nil.
7232 Derived from `org-end-of-subtree'."
7233 (markdown-back-to-heading invisible-OK)
7234 (let ((first t)
7235 (level (markdown-outline-level)))
7236 (while (and (not (eobp))
7237 (or first (> (markdown-outline-level) level)))
7238 (setq first nil)
7239 (markdown-next-heading))
7240 (if (memq (preceding-char) '(?\n ?\^M))
7241 (progn
7242 ;; Go to end of line before heading
7243 (forward-char -1)
7244 (if (memq (preceding-char) '(?\n ?\^M))
7245 ;; leave blank line before heading
7246 (forward-char -1)))))
7247 (point))
7249 (defun markdown-outline-fix-visibility ()
7250 "Hide any false positive headings that should not be shown.
7251 For example, headings inside preformatted code blocks may match
7252 `outline-regexp' but should not be shown as headings when cycling.
7253 Also, the ending --- line in metadata blocks appears to be a
7254 setext header, but should not be folded."
7255 (save-excursion
7256 (goto-char (point-min))
7257 ;; Unhide any false positives in metadata blocks
7258 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7259 (let ((body (progn (forward-line)
7260 (markdown-text-property-at-point
7261 'markdown-yaml-metadata-section))))
7262 (when body
7263 (let ((end (progn (goto-char (cl-second body))
7264 (markdown-text-property-at-point
7265 'markdown-yaml-metadata-end))))
7266 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7267 ;; Hide any false positives in code blocks
7268 (unless (outline-on-heading-p)
7269 (outline-next-visible-heading 1))
7270 (while (< (point) (point-max))
7271 (when (markdown-code-block-at-point-p)
7272 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7273 (outline-next-visible-heading 1))))
7275 (defvar markdown-cycle-global-status 1)
7276 (defvar markdown-cycle-subtree-status nil)
7278 (defun markdown-next-preface ()
7279 (let (finish)
7280 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7281 nil 'move))
7282 (unless (markdown-code-block-at-point-p)
7283 (goto-char (match-beginning 0))
7284 (setq finish t))))
7285 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7286 (forward-char -1)))
7288 (defun markdown-show-entry ()
7289 (save-excursion
7290 (outline-back-to-heading t)
7291 (outline-flag-region (1- (point))
7292 (progn
7293 (markdown-next-preface)
7294 (if (= 1 (- (point-max) (point)))
7295 (point-max)
7296 (point)))
7297 nil)))
7299 ;; This function was originally derived from `org-cycle' from org.el.
7300 (defun markdown-cycle (&optional arg)
7301 "Visibility cycling for Markdown mode.
7302 If ARG is t, perform global visibility cycling. If the point is
7303 at an atx-style header, cycle visibility of the corresponding
7304 subtree. Otherwise, indent the current line or insert a tab,
7305 as appropriate, by calling `indent-for-tab-command'."
7306 (interactive "P")
7307 (cond
7308 ((eq arg t) ;; Global cycling
7309 (cond
7310 ((and (eq last-command this-command)
7311 (eq markdown-cycle-global-status 2))
7312 ;; Move from overview to contents
7313 (markdown-hide-sublevels 1)
7314 (message "CONTENTS")
7315 (setq markdown-cycle-global-status 3)
7316 (markdown-outline-fix-visibility))
7318 ((and (eq last-command this-command)
7319 (eq markdown-cycle-global-status 3))
7320 ;; Move from contents to all
7321 (markdown-show-all)
7322 (message "SHOW ALL")
7323 (setq markdown-cycle-global-status 1))
7326 ;; Defaults to overview
7327 (markdown-hide-body)
7328 (message "OVERVIEW")
7329 (setq markdown-cycle-global-status 2)
7330 (markdown-outline-fix-visibility))))
7332 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7333 ;; At a heading: rotate between three different views
7334 (markdown-back-to-heading)
7335 (let ((goal-column 0) eoh eol eos)
7336 ;; Determine boundaries
7337 (save-excursion
7338 (markdown-back-to-heading)
7339 (save-excursion
7340 (beginning-of-line 2)
7341 (while (and (not (eobp)) ;; this is like `next-line'
7342 (get-char-property (1- (point)) 'invisible))
7343 (beginning-of-line 2)) (setq eol (point)))
7344 (markdown-end-of-heading) (setq eoh (point))
7345 (markdown-end-of-subtree t)
7346 (skip-chars-forward " \t\n")
7347 (beginning-of-line 1) ; in case this is an item
7348 (setq eos (1- (point))))
7349 ;; Find out what to do next and set `this-command'
7350 (cond
7351 ((= eos eoh)
7352 ;; Nothing is hidden behind this heading
7353 (message "EMPTY ENTRY")
7354 (setq markdown-cycle-subtree-status nil))
7355 ((>= eol eos)
7356 ;; Entire subtree is hidden in one line: open it
7357 (markdown-show-entry)
7358 (markdown-show-children)
7359 (message "CHILDREN")
7360 (setq markdown-cycle-subtree-status 'children))
7361 ((and (eq last-command this-command)
7362 (eq markdown-cycle-subtree-status 'children))
7363 ;; We just showed the children, now show everything.
7364 (markdown-show-subtree)
7365 (message "SUBTREE")
7366 (setq markdown-cycle-subtree-status 'subtree))
7368 ;; Default action: hide the subtree.
7369 (markdown-hide-subtree)
7370 (message "FOLDED")
7371 (setq markdown-cycle-subtree-status 'folded)))))
7374 (indent-for-tab-command))))
7376 (defun markdown-shifttab ()
7377 "Handle S-TAB keybinding based on context.
7378 When in a table, move backward one cell.
7379 Otherwise, cycle global heading visibility by calling
7380 `markdown-cycle' with argument t."
7381 (interactive)
7382 (cond ((markdown-table-at-point-p)
7383 (call-interactively #'markdown-table-backward-cell))
7384 (t (markdown-cycle t))))
7386 (defun markdown-outline-level ()
7387 "Return the depth to which a statement is nested in the outline."
7388 (cond
7389 ((and (match-beginning 0)
7390 (markdown-code-block-at-pos (match-beginning 0)))
7391 7) ;; Only 6 header levels are defined.
7392 ((match-end 2) 1)
7393 ((match-end 3) 2)
7394 ((match-end 4)
7395 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7397 (defun markdown-promote-subtree (&optional arg)
7398 "Promote the current subtree of ATX headings.
7399 Note that Markdown does not support heading levels higher than
7400 six and therefore level-six headings will not be promoted
7401 further. If ARG is non-nil promote the heading, otherwise
7402 demote."
7403 (interactive "*P")
7404 (save-excursion
7405 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7406 (re-search-backward markdown-regex-header-atx nil t))
7407 (not (markdown-code-block-at-point-p)))
7408 (let ((level (length (match-string 1)))
7409 (promote-or-demote (if arg 1 -1))
7410 (remove 't))
7411 (markdown-cycle-atx promote-or-demote remove)
7412 (catch 'end-of-subtree
7413 (while (and (markdown-next-heading)
7414 (looking-at markdown-regex-header-atx))
7415 ;; Exit if this not a higher level heading; promote otherwise.
7416 (if (and (looking-at markdown-regex-header-atx)
7417 (<= (length (match-string-no-properties 1)) level))
7418 (throw 'end-of-subtree nil)
7419 (markdown-cycle-atx promote-or-demote remove))))))))
7421 (defun markdown-demote-subtree ()
7422 "Demote the current subtree of ATX headings."
7423 (interactive)
7424 (markdown-promote-subtree t))
7426 (defun markdown-move-subtree-up ()
7427 "Move the current subtree of ATX headings up."
7428 (interactive)
7429 (outline-move-subtree-up 1))
7431 (defun markdown-move-subtree-down ()
7432 "Move the current subtree of ATX headings down."
7433 (interactive)
7434 (outline-move-subtree-down 1))
7436 (defun markdown-outline-next ()
7437 "Move to next list item, when in a list, or next visible heading."
7438 (interactive)
7439 (let ((bounds (markdown-next-list-item-bounds)))
7440 (if bounds
7441 (goto-char (nth 0 bounds))
7442 (markdown-next-visible-heading 1))))
7444 (defun markdown-outline-previous ()
7445 "Move to previous list item, when in a list, or previous visible heading."
7446 (interactive)
7447 (let ((bounds (markdown-prev-list-item-bounds)))
7448 (if bounds
7449 (goto-char (nth 0 bounds))
7450 (markdown-previous-visible-heading 1))))
7452 (defun markdown-outline-next-same-level ()
7453 "Move to next list item or heading of same level."
7454 (interactive)
7455 (let ((bounds (markdown-cur-list-item-bounds)))
7456 (if bounds
7457 (markdown-next-list-item (nth 3 bounds))
7458 (markdown-forward-same-level 1))))
7460 (defun markdown-outline-previous-same-level ()
7461 "Move to previous list item or heading of same level."
7462 (interactive)
7463 (let ((bounds (markdown-cur-list-item-bounds)))
7464 (if bounds
7465 (markdown-prev-list-item (nth 3 bounds))
7466 (markdown-backward-same-level 1))))
7468 (defun markdown-outline-up ()
7469 "Move to previous list item, when in a list, or next heading."
7470 (interactive)
7471 (unless (markdown-up-list)
7472 (markdown-up-heading 1)))
7475 ;;; Marking and Narrowing =====================================================
7477 (defun markdown-mark-paragraph ()
7478 "Put mark at end of this block, point at beginning.
7479 The block marked is the one that contains point or follows point.
7481 Interactively, if this command is repeated or (in Transient Mark
7482 mode) if the mark is active, it marks the next block after the
7483 ones already marked."
7484 (interactive)
7485 (if (or (and (eq last-command this-command) (mark t))
7486 (and transient-mark-mode mark-active))
7487 (set-mark
7488 (save-excursion
7489 (goto-char (mark))
7490 (markdown-forward-paragraph)
7491 (point)))
7492 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7493 (end-of-defun-function 'markdown-forward-paragraph))
7494 (mark-defun))))
7496 (defun markdown-mark-block ()
7497 "Put mark at end of this block, point at beginning.
7498 The block marked is the one that contains point or follows point.
7500 Interactively, if this command is repeated or (in Transient Mark
7501 mode) if the mark is active, it marks the next block after the
7502 ones already marked."
7503 (interactive)
7504 (if (or (and (eq last-command this-command) (mark t))
7505 (and transient-mark-mode mark-active))
7506 (set-mark
7507 (save-excursion
7508 (goto-char (mark))
7509 (markdown-forward-block)
7510 (point)))
7511 (let ((beginning-of-defun-function 'markdown-backward-block)
7512 (end-of-defun-function 'markdown-forward-block))
7513 (mark-defun))))
7515 (defun markdown-narrow-to-block ()
7516 "Make text outside current block invisible.
7517 The current block is the one that contains point or follows point."
7518 (interactive)
7519 (let ((beginning-of-defun-function 'markdown-backward-block)
7520 (end-of-defun-function 'markdown-forward-block))
7521 (narrow-to-defun)))
7523 (defun markdown-mark-text-block ()
7524 "Put mark at end of this plain text block, point at beginning.
7525 The block marked is the one that contains point or follows point.
7527 Interactively, if this command is repeated or (in Transient Mark
7528 mode) if the mark is active, it marks the next block after the
7529 ones already marked."
7530 (interactive)
7531 (if (or (and (eq last-command this-command) (mark t))
7532 (and transient-mark-mode mark-active))
7533 (set-mark
7534 (save-excursion
7535 (goto-char (mark))
7536 (markdown-end-of-text-block)
7537 (point)))
7538 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7539 (end-of-defun-function 'markdown-end-of-text-block))
7540 (mark-defun))))
7542 (defun markdown-mark-page ()
7543 "Put mark at end of this top level section, point at beginning.
7544 The top level section marked is the one that contains point or
7545 follows point.
7547 Interactively, if this command is repeated or (in Transient Mark
7548 mode) if the mark is active, it marks the next page after the
7549 ones already marked."
7550 (interactive)
7551 (if (or (and (eq last-command this-command) (mark t))
7552 (and transient-mark-mode mark-active))
7553 (set-mark
7554 (save-excursion
7555 (goto-char (mark))
7556 (markdown-forward-page)
7557 (point)))
7558 (let ((beginning-of-defun-function 'markdown-backward-page)
7559 (end-of-defun-function 'markdown-forward-page))
7560 (mark-defun))))
7562 (defun markdown-narrow-to-page ()
7563 "Make text outside current top level section invisible.
7564 The current section is the one that contains point or follows point."
7565 (interactive)
7566 (let ((beginning-of-defun-function 'markdown-backward-page)
7567 (end-of-defun-function 'markdown-forward-page))
7568 (narrow-to-defun)))
7570 (defun markdown-mark-subtree ()
7571 "Mark the current subtree.
7572 This puts point at the start of the current subtree, and mark at the end."
7573 (interactive)
7574 (let ((beg))
7575 (if (markdown-heading-at-point)
7576 (beginning-of-line)
7577 (markdown-previous-visible-heading 1))
7578 (setq beg (point))
7579 (markdown-end-of-subtree)
7580 (push-mark (point) nil t)
7581 (goto-char beg)))
7583 (defun markdown-narrow-to-subtree ()
7584 "Narrow buffer to the current subtree."
7585 (interactive)
7586 (save-excursion
7587 (save-match-data
7588 (narrow-to-region
7589 (progn (markdown-back-to-heading-over-code-block t) (point))
7590 (progn (markdown-end-of-subtree)
7591 (if (and (markdown-heading-at-point) (not (eobp)))
7592 (backward-char 1))
7593 (point))))))
7596 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7598 (defun markdown-move-up ()
7599 "Move thing at point up.
7600 When in a list item, call `markdown-move-list-item-up'.
7601 When in a table, call `markdown-table-move-row-up'.
7602 Otherwise, move the current heading subtree up with
7603 `markdown-move-subtree-up'."
7604 (interactive)
7605 (cond
7606 ((markdown-list-item-at-point-p)
7607 (call-interactively #'markdown-move-list-item-up))
7608 ((markdown-table-at-point-p)
7609 (call-interactively #'markdown-table-move-row-up))
7611 (call-interactively #'markdown-move-subtree-up))))
7613 (defun markdown-move-down ()
7614 "Move thing at point down.
7615 When in a list item, call `markdown-move-list-item-down'.
7616 Otherwise, move the current heading subtree up with
7617 `markdown-move-subtree-down'."
7618 (interactive)
7619 (cond
7620 ((markdown-list-item-at-point-p)
7621 (call-interactively #'markdown-move-list-item-down))
7622 ((markdown-table-at-point-p)
7623 (call-interactively #'markdown-table-move-row-down))
7625 (call-interactively #'markdown-move-subtree-down))))
7627 (defun markdown-promote ()
7628 "Promote or move element at point to the left.
7629 Depending on the context, this function will promote a heading or
7630 list item at the point, move a table column to the left, or cycle
7631 markup."
7632 (interactive)
7633 (let (bounds)
7634 (cond
7635 ;; Promote atx heading subtree
7636 ((thing-at-point-looking-at markdown-regex-header-atx)
7637 (markdown-promote-subtree))
7638 ;; Promote setext heading
7639 ((thing-at-point-looking-at markdown-regex-header-setext)
7640 (markdown-cycle-setext -1))
7641 ;; Promote horizonal rule
7642 ((thing-at-point-looking-at markdown-regex-hr)
7643 (markdown-cycle-hr -1))
7644 ;; Promote list item
7645 ((setq bounds (markdown-cur-list-item-bounds))
7646 (markdown-promote-list-item bounds))
7647 ;; Move table column to the left
7648 ((markdown-table-at-point-p)
7649 (call-interactively #'markdown-table-move-column-left))
7650 ;; Promote bold
7651 ((thing-at-point-looking-at markdown-regex-bold)
7652 (markdown-cycle-bold))
7653 ;; Promote italic
7654 ((thing-at-point-looking-at markdown-regex-italic)
7655 (markdown-cycle-italic))
7657 (user-error "Nothing to promote at point")))))
7659 (defun markdown-demote ()
7660 "Demote or move element at point to the right.
7661 Depending on the context, this function will demote a heading or
7662 list item at the point, move a table column to the right, or cycle
7663 or remove markup."
7664 (interactive)
7665 (let (bounds)
7666 (cond
7667 ;; Demote atx heading subtree
7668 ((thing-at-point-looking-at markdown-regex-header-atx)
7669 (markdown-demote-subtree))
7670 ;; Demote setext heading
7671 ((thing-at-point-looking-at markdown-regex-header-setext)
7672 (markdown-cycle-setext 1))
7673 ;; Demote horizonal rule
7674 ((thing-at-point-looking-at markdown-regex-hr)
7675 (markdown-cycle-hr 1))
7676 ;; Demote list item
7677 ((setq bounds (markdown-cur-list-item-bounds))
7678 (markdown-demote-list-item bounds))
7679 ;; Move table column to the right
7680 ((markdown-table-at-point-p)
7681 (call-interactively #'markdown-table-move-column-right))
7682 ;; Demote bold
7683 ((thing-at-point-looking-at markdown-regex-bold)
7684 (markdown-cycle-bold))
7685 ;; Demote italic
7686 ((thing-at-point-looking-at markdown-regex-italic)
7687 (markdown-cycle-italic))
7689 (user-error "Nothing to demote at point")))))
7692 ;;; Commands ==================================================================
7694 (defun markdown (&optional output-buffer-name)
7695 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7696 The output buffer name defaults to `markdown-output-buffer-name'.
7697 Return the name of the output buffer used."
7698 (interactive)
7699 (save-window-excursion
7700 (let ((begin-region)
7701 (end-region))
7702 (if (markdown-use-region-p)
7703 (setq begin-region (region-beginning)
7704 end-region (region-end))
7705 (setq begin-region (point-min)
7706 end-region (point-max)))
7708 (unless output-buffer-name
7709 (setq output-buffer-name markdown-output-buffer-name))
7710 (cond
7711 ;; Handle case when `markdown-command' does not read from stdin
7712 ((and (stringp markdown-command) markdown-command-needs-filename)
7713 (if (not buffer-file-name)
7714 (user-error "Must be visiting a file")
7715 (shell-command (concat markdown-command " "
7716 (shell-quote-argument buffer-file-name))
7717 output-buffer-name)))
7718 ;; Pass region to `markdown-command' via stdin
7720 (let ((buf (get-buffer-create output-buffer-name)))
7721 (with-current-buffer buf
7722 (setq buffer-read-only nil)
7723 (erase-buffer))
7724 (if (stringp markdown-command)
7725 (call-process-region begin-region end-region
7726 shell-file-name nil buf nil
7727 shell-command-switch markdown-command)
7728 (funcall markdown-command begin-region end-region buf))))))
7729 output-buffer-name))
7731 (defun markdown-standalone (&optional output-buffer-name)
7732 "Special function to provide standalone HTML output.
7733 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7734 (interactive)
7735 (setq output-buffer-name (markdown output-buffer-name))
7736 (with-current-buffer output-buffer-name
7737 (set-buffer output-buffer-name)
7738 (unless (markdown-output-standalone-p)
7739 (markdown-add-xhtml-header-and-footer output-buffer-name))
7740 (goto-char (point-min))
7741 (html-mode))
7742 output-buffer-name)
7744 (defun markdown-other-window (&optional output-buffer-name)
7745 "Run `markdown-command' on current buffer and display in other window.
7746 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7747 that name."
7748 (interactive)
7749 (markdown-display-buffer-other-window
7750 (markdown-standalone output-buffer-name)))
7752 (defun markdown-output-standalone-p ()
7753 "Determine whether `markdown-command' output is standalone XHTML.
7754 Standalone XHTML output is identified by an occurrence of
7755 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7756 (save-excursion
7757 (goto-char (point-min))
7758 (save-match-data
7759 (re-search-forward
7760 markdown-xhtml-standalone-regexp
7761 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7762 t))))
7764 (defun markdown-stylesheet-link-string (stylesheet-path)
7765 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7766 stylesheet-path
7767 "\" />"))
7769 (defun markdown-add-xhtml-header-and-footer (title)
7770 "Wrap XHTML header and footer with given TITLE around current buffer."
7771 (goto-char (point-min))
7772 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7773 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7774 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7775 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7776 "<head>\n<title>")
7777 (insert title)
7778 (insert "</title>\n")
7779 (when (> (length markdown-content-type) 0)
7780 (insert
7781 (format
7782 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7783 markdown-content-type
7784 (or (and markdown-coding-system
7785 (fboundp 'coding-system-get)
7786 (coding-system-get markdown-coding-system
7787 'mime-charset))
7788 (and (fboundp 'coding-system-get)
7789 (coding-system-get buffer-file-coding-system
7790 'mime-charset))
7791 "iso-8859-1"))))
7792 (if (> (length markdown-css-paths) 0)
7793 (insert (mapconcat #'markdown-stylesheet-link-string
7794 markdown-css-paths "\n")))
7795 (when (> (length markdown-xhtml-header-content) 0)
7796 (insert markdown-xhtml-header-content))
7797 (insert "\n</head>\n\n"
7798 "<body>\n\n")
7799 (goto-char (point-max))
7800 (insert "\n"
7801 "</body>\n"
7802 "</html>\n"))
7804 (defun markdown-preview (&optional output-buffer-name)
7805 "Run `markdown-command' on the current buffer and view output in browser.
7806 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7807 that name."
7808 (interactive)
7809 (browse-url-of-buffer
7810 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7812 (defun markdown-export-file-name (&optional extension)
7813 "Attempt to generate a filename for Markdown output.
7814 The file extension will be EXTENSION if given, or .html by default.
7815 If the current buffer is visiting a file, we construct a new
7816 output filename based on that filename. Otherwise, return nil."
7817 (when (buffer-file-name)
7818 (unless extension
7819 (setq extension ".html"))
7820 (let ((candidate
7821 (concat
7822 (cond
7823 ((buffer-file-name)
7824 (file-name-sans-extension (buffer-file-name)))
7825 (t (buffer-name)))
7826 extension)))
7827 (cond
7828 ((equal candidate (buffer-file-name))
7829 (concat candidate extension))
7831 candidate)))))
7833 (defun markdown-export (&optional output-file)
7834 "Run Markdown on the current buffer, save to file, and return the filename.
7835 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7836 generated by `markdown-export-file-name', which will be constructed using the
7837 current filename, but with the extension removed and replaced with .html."
7838 (interactive)
7839 (unless output-file
7840 (setq output-file (markdown-export-file-name ".html")))
7841 (when output-file
7842 (let* ((init-buf (current-buffer))
7843 (init-point (point))
7844 (init-buf-string (buffer-string))
7845 (output-buffer (find-file-noselect output-file))
7846 (output-buffer-name (buffer-name output-buffer)))
7847 (run-hooks 'markdown-before-export-hook)
7848 (markdown-standalone output-buffer-name)
7849 (with-current-buffer output-buffer
7850 (run-hooks 'markdown-after-export-hook)
7851 (save-buffer))
7852 ;; if modified, restore initial buffer
7853 (when (buffer-modified-p init-buf)
7854 (erase-buffer)
7855 (insert init-buf-string)
7856 (save-buffer)
7857 (goto-char init-point))
7858 output-file)))
7860 (defun markdown-export-and-preview ()
7861 "Export to XHTML using `markdown-export' and browse the resulting file."
7862 (interactive)
7863 (browse-url-of-file (markdown-export)))
7865 (defvar markdown-live-preview-buffer nil
7866 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7867 (make-variable-buffer-local 'markdown-live-preview-buffer)
7869 (defvar markdown-live-preview-source-buffer nil
7870 "Source buffer from which current buffer was generated.
7871 This is the inverse of `markdown-live-preview-buffer'.")
7872 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7874 (defvar markdown-live-preview-currently-exporting nil)
7876 (defun markdown-live-preview-get-filename ()
7877 "Standardize the filename exported by `markdown-live-preview-export'."
7878 (markdown-export-file-name ".html"))
7880 (defun markdown-live-preview-window-eww (file)
7881 "Preview FILE with eww.
7882 To be used with `markdown-live-preview-window-function'."
7883 (if (require 'eww nil t)
7884 (progn
7885 (eww-open-file file)
7886 (get-buffer "*eww*"))
7887 (error "EWW is not present or not loaded on this version of Emacs")))
7889 (defun markdown-visual-lines-between-points (beg end)
7890 (save-excursion
7891 (goto-char beg)
7892 (cl-loop with count = 0
7893 while (progn (end-of-visual-line)
7894 (and (< (point) end) (line-move-visual 1 t)))
7895 do (cl-incf count)
7896 finally return count)))
7898 (defun markdown-live-preview-window-serialize (buf)
7899 "Get window point and scroll data for all windows displaying BUF."
7900 (when (buffer-live-p buf)
7901 (with-current-buffer buf
7902 (mapcar
7903 (lambda (win)
7904 (with-selected-window win
7905 (let* ((start (window-start))
7906 (pt (window-point))
7907 (pt-or-sym (cond ((= pt (point-min)) 'min)
7908 ((= pt (point-max)) 'max)
7909 (t pt)))
7910 (diff (markdown-visual-lines-between-points
7911 start pt)))
7912 (list win pt-or-sym diff))))
7913 (get-buffer-window-list buf)))))
7915 (defun markdown-get-point-back-lines (pt num-lines)
7916 (save-excursion
7917 (goto-char pt)
7918 (line-move-visual (- num-lines) t)
7919 ;; in testing, can occasionally overshoot the number of lines to traverse
7920 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7921 (when (> actual-num-lines num-lines)
7922 (line-move-visual (- actual-num-lines num-lines) t)))
7923 (point)))
7925 (defun markdown-live-preview-window-deserialize (window-posns)
7926 "Apply window point and scroll data from WINDOW-POSNS.
7927 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7928 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7929 (when (window-live-p win)
7930 (with-current-buffer markdown-live-preview-buffer
7931 (set-window-buffer win (current-buffer))
7932 (cl-destructuring-bind (actual-pt actual-diff)
7933 (cl-case pt-or-sym
7934 (min (list (point-min) 0))
7935 (max (list (point-max) diff))
7936 (t (list pt-or-sym diff)))
7937 (set-window-start
7938 win (markdown-get-point-back-lines actual-pt actual-diff))
7939 (set-window-point win actual-pt))))))
7941 (defun markdown-live-preview-export ()
7942 "Export to XHTML using `markdown-export'.
7943 Browse the resulting file within Emacs using
7944 `markdown-live-preview-window-function' Return the buffer
7945 displaying the rendered output."
7946 (interactive)
7947 (let ((filename (markdown-live-preview-get-filename)))
7948 (when filename
7949 (let* ((markdown-live-preview-currently-exporting t)
7950 (cur-buf (current-buffer))
7951 (export-file (markdown-export filename))
7952 ;; get positions in all windows currently displaying output buffer
7953 (window-data
7954 (markdown-live-preview-window-serialize
7955 markdown-live-preview-buffer)))
7956 (save-window-excursion
7957 (let ((output-buffer
7958 (funcall markdown-live-preview-window-function export-file)))
7959 (with-current-buffer output-buffer
7960 (setq markdown-live-preview-source-buffer cur-buf)
7961 (add-hook 'kill-buffer-hook
7962 #'markdown-live-preview-remove-on-kill t t))
7963 (with-current-buffer cur-buf
7964 (setq markdown-live-preview-buffer output-buffer))))
7965 (with-current-buffer cur-buf
7966 ;; reset all windows displaying output buffer to where they were,
7967 ;; now with the new output
7968 (mapc #'markdown-live-preview-window-deserialize window-data)
7969 ;; delete html editing buffer
7970 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7971 (when (and export-file (file-exists-p export-file)
7972 (eq markdown-live-preview-delete-export
7973 'delete-on-export))
7974 (delete-file export-file))
7975 markdown-live-preview-buffer)))))
7977 (defun markdown-live-preview-remove ()
7978 (when (buffer-live-p markdown-live-preview-buffer)
7979 (kill-buffer markdown-live-preview-buffer))
7980 (setq markdown-live-preview-buffer nil)
7981 ;; if set to 'delete-on-export, the output has already been deleted
7982 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7983 (let ((outfile-name (markdown-live-preview-get-filename)))
7984 (when (and outfile-name (file-exists-p outfile-name))
7985 (delete-file outfile-name)))))
7987 (defun markdown-get-other-window ()
7988 "Find another window to display preview or output content."
7989 (cond
7990 ((memq markdown-split-window-direction '(vertical below))
7991 (or (window-in-direction 'below) (split-window-vertically)))
7992 ((memq markdown-split-window-direction '(horizontal right))
7993 (or (window-in-direction 'right) (split-window-horizontally)))
7994 (t (split-window-sensibly (get-buffer-window)))))
7996 (defun markdown-display-buffer-other-window (buf)
7997 "Display preview or output buffer BUF in another window."
7998 (let ((cur-buf (current-buffer))
7999 (window (markdown-get-other-window)))
8000 (set-window-buffer window buf)
8001 (set-buffer cur-buf)))
8003 (defun markdown-live-preview-if-markdown ()
8004 (when (and (derived-mode-p 'markdown-mode)
8005 markdown-live-preview-mode)
8006 (unless markdown-live-preview-currently-exporting
8007 (if (buffer-live-p markdown-live-preview-buffer)
8008 (markdown-live-preview-export)
8009 (markdown-display-buffer-other-window
8010 (markdown-live-preview-export))))))
8012 (defun markdown-live-preview-remove-on-kill ()
8013 (cond ((and (derived-mode-p 'markdown-mode)
8014 markdown-live-preview-mode)
8015 (markdown-live-preview-remove))
8016 (markdown-live-preview-source-buffer
8017 (with-current-buffer markdown-live-preview-source-buffer
8018 (setq markdown-live-preview-buffer nil))
8019 (setq markdown-live-preview-source-buffer nil))))
8021 (defun markdown-live-preview-switch-to-output ()
8022 "Switch to output buffer."
8023 (interactive)
8024 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8025 output buffer in another window."
8026 (if markdown-live-preview-mode
8027 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8028 (markdown-live-preview-mode))
8030 (defun markdown-live-preview-re-export ()
8031 "Re export source buffer."
8032 (interactive)
8033 "If the current buffer is a buffer displaying the exported version of a
8034 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8035 update this buffer's contents."
8036 (when markdown-live-preview-source-buffer
8037 (with-current-buffer markdown-live-preview-source-buffer
8038 (markdown-live-preview-export))))
8040 (defun markdown-open ()
8041 "Open file for the current buffer with `markdown-open-command'."
8042 (interactive)
8043 (unless markdown-open-command
8044 (user-error "Variable `markdown-open-command' must be set"))
8045 (if (stringp markdown-open-command)
8046 (if (not buffer-file-name)
8047 (user-error "Must be visiting a file")
8048 (save-buffer)
8049 (call-process markdown-open-command nil 0 nil buffer-file-name))
8050 (funcall markdown-open-command))
8051 nil)
8053 (defun markdown-kill-ring-save ()
8054 "Run Markdown on file and store output in the kill ring."
8055 (interactive)
8056 (save-window-excursion
8057 (markdown)
8058 (with-current-buffer markdown-output-buffer-name
8059 (kill-ring-save (point-min) (point-max)))))
8062 ;;; Links =====================================================================
8064 (defun markdown-link-p ()
8065 "Return non-nil when `point' is at a non-wiki link.
8066 See `markdown-wiki-link-p' for more information."
8067 (let ((case-fold-search nil))
8068 (and (not (markdown-wiki-link-p))
8069 (not (markdown-code-block-at-point-p))
8070 (or (thing-at-point-looking-at markdown-regex-link-inline)
8071 (thing-at-point-looking-at markdown-regex-link-reference)
8072 (thing-at-point-looking-at markdown-regex-uri)
8073 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8075 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8077 (defun markdown-link-at-pos (pos)
8078 "Return properties of link or image at position POS.
8079 Value is a list of elements describing the link:
8080 0. beginning position
8081 1. end position
8082 2. link text
8083 3. URL
8084 4. reference label
8085 5. title text
8086 6. bang (nil or \"!\")"
8087 (save-excursion
8088 (goto-char pos)
8089 (let (begin end text url reference title bang)
8090 (cond
8091 ;; Inline or reference image or link at point.
8092 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8093 (thing-at-point-looking-at markdown-regex-link-reference))
8094 (setq bang (match-string-no-properties 1)
8095 begin (match-beginning 0)
8096 end (match-end 0)
8097 text (match-string-no-properties 3))
8098 (if (char-equal (char-after (match-beginning 5)) ?\[)
8099 ;; Reference link
8100 (setq reference (match-string-no-properties 6))
8101 ;; Inline link
8102 (setq url (match-string-no-properties 6))
8103 (when (match-end 7)
8104 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8105 ;; Angle bracket URI at point.
8106 ((thing-at-point-looking-at markdown-regex-angle-uri)
8107 (setq begin (match-beginning 0)
8108 end (match-end 0)
8109 url (match-string-no-properties 2)))
8110 ;; Plain URI at point.
8111 ((thing-at-point-looking-at markdown-regex-uri)
8112 (setq begin (match-beginning 0)
8113 end (match-end 0)
8114 url (match-string-no-properties 1))))
8115 (list begin end text url reference title bang))))
8117 (defun markdown-link-url ()
8118 "Return the URL part of the regular (non-wiki) link at point.
8119 Works with both inline and reference style links, and with images.
8120 If point is not at a link or the link reference is not defined
8121 returns nil."
8122 (let* ((values (markdown-link-at-pos (point)))
8123 (text (nth 2 values))
8124 (url (nth 3 values))
8125 (ref (nth 4 values)))
8126 (or url (and ref (car (markdown-reference-definition
8127 (downcase (if (string= ref "") text ref))))))))
8129 (defun markdown-follow-link-at-point ()
8130 "Open the current non-wiki link.
8131 If the link is a complete URL, open in browser with `browse-url'.
8132 Otherwise, open with `find-file' after stripping anchor and/or query string.
8133 Translate filenames using `markdown-filename-translate-function'."
8134 (interactive)
8135 (if (markdown-link-p)
8136 (let* ((url (markdown-link-url))
8137 (struct (url-generic-parse-url url))
8138 (full (url-fullness struct))
8139 (file url))
8140 ;; Parse URL, determine fullness, strip query string
8141 (if (fboundp 'url-path-and-query)
8142 (setq file (car (url-path-and-query struct)))
8143 (when (and (setq file (url-filename struct))
8144 (string-match "\\?" file))
8145 (setq file (substring file 0 (match-beginning 0)))))
8146 ;; Open full URLs in browser, files in Emacs
8147 (if full
8148 (browse-url url)
8149 (when (and file (> (length file) 0))
8150 (find-file (funcall markdown-translate-filename-function file)))))
8151 (user-error "Point is not at a Markdown link or URL")))
8153 (defun markdown-fontify-inline-links (last)
8154 "Add text properties to next inline link from point to LAST."
8155 (when (markdown-match-generic-links last nil)
8156 (let* ((link-start (match-beginning 3))
8157 (link-end (match-end 3))
8158 (url-start (match-beginning 6))
8159 (url-end (match-end 6))
8160 (url (match-string-no-properties 6))
8161 (title-start (match-beginning 7))
8162 (title-end (match-end 7))
8163 (title (match-string-no-properties 7))
8164 ;; Markup part
8165 (mp (list 'face 'markdown-markup-face
8166 'invisible 'markdown-markup
8167 'rear-nonsticky t
8168 'font-lock-multiline t))
8169 ;; Link part
8170 (lp (list 'keymap markdown-mode-mouse-map
8171 'face markdown-link-face
8172 'mouse-face 'markdown-highlight-face
8173 'font-lock-multiline t
8174 'help-echo (if title (concat title "\n" url) url)))
8175 ;; URL part
8176 (up (list 'keymap markdown-mode-mouse-map
8177 'face 'markdown-url-face
8178 'invisible 'markdown-markup
8179 'mouse-face 'markdown-highlight-face
8180 'font-lock-multiline t))
8181 ;; Title part
8182 (tp (list 'face 'markdown-link-title-face
8183 'invisible 'markdown-markup
8184 'font-lock-multiline t)))
8185 (dolist (g '(1 2 4 5 8))
8186 (when (match-end g)
8187 (add-text-properties (match-beginning g) (match-end g) mp)))
8188 (when link-start (add-text-properties link-start link-end lp))
8189 (when url-start (add-text-properties url-start url-end up))
8190 (when title-start (add-text-properties url-end title-end tp))
8191 (when (and markdown-hide-urls url-start)
8192 (compose-region url-start (or title-end url-end)
8193 markdown-url-compose-char))
8194 t)))
8196 (defun markdown-fontify-reference-links (last)
8197 "Add text properties to next reference link from point to LAST."
8198 (when (markdown-match-generic-links last t)
8199 (let* ((link-start (match-beginning 3))
8200 (link-end (match-end 3))
8201 (ref-start (match-beginning 6))
8202 (ref-end (match-end 6))
8203 ;; Markup part
8204 (mp (list 'face 'markdown-markup-face
8205 'invisible 'markdown-markup
8206 'rear-nonsticky t
8207 'font-lock-multiline t))
8208 ;; Link part
8209 (lp (list 'keymap markdown-mode-mouse-map
8210 'face markdown-link-face
8211 'mouse-face 'markdown-highlight-face
8212 'font-lock-multiline t
8213 'help-echo (lambda (_ __ pos)
8214 (save-match-data
8215 (save-excursion
8216 (goto-char pos)
8217 (or (markdown-link-url)
8218 "Undefined reference"))))))
8219 ;; Reference part
8220 (rp (list 'face 'markdown-reference-face
8221 'invisible 'markdown-markup
8222 'font-lock-multiline t)))
8223 (dolist (g '(1 2 4 5 8))
8224 (when (match-end g)
8225 (add-text-properties (match-beginning g) (match-end g) mp)))
8226 (when link-start (add-text-properties link-start link-end lp))
8227 (when ref-start (add-text-properties ref-start ref-end rp)
8228 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8229 (compose-region ref-start ref-end markdown-url-compose-char)))
8230 t)))
8232 (defun markdown-fontify-angle-uris (last)
8233 "Add text properties to angle URIs from point to LAST."
8234 (when (markdown-match-angle-uris last)
8235 (let* ((url-start (match-beginning 2))
8236 (url-end (match-end 2))
8237 ;; Markup part
8238 (mp (list 'face 'markdown-markup-face
8239 'invisible 'markdown-markup
8240 'rear-nonsticky t
8241 'font-lock-multiline t))
8242 ;; URI part
8243 (up (list 'keymap markdown-mode-mouse-map
8244 'face 'markdown-plain-url-face
8245 'mouse-face 'markdown-highlight-face
8246 'font-lock-multiline t)))
8247 (dolist (g '(1 3))
8248 (add-text-properties (match-beginning g) (match-end g) mp))
8249 (add-text-properties url-start url-end up)
8250 t)))
8252 (defun markdown-fontify-plain-uris (last)
8253 "Add text properties to plain URLs from point to LAST."
8254 (when (markdown-match-plain-uris last)
8255 (let* ((start (match-beginning 0))
8256 (end (match-end 0))
8257 (props (list 'keymap markdown-mode-mouse-map
8258 'face 'markdown-plain-url-face
8259 'mouse-face 'markdown-highlight-face
8260 'rear-nonsticky t
8261 'font-lock-multiline t)))
8262 (add-text-properties start end props)
8263 t)))
8265 (defun markdown-toggle-url-hiding (&optional arg)
8266 "Toggle the display or hiding of URLs.
8267 With a prefix argument ARG, enable URL hiding if ARG is positive,
8268 and disable it otherwise."
8269 (interactive (list (or current-prefix-arg 'toggle)))
8270 (setq markdown-hide-urls
8271 (if (eq arg 'toggle)
8272 (not markdown-hide-urls)
8273 (> (prefix-numeric-value arg) 0)))
8274 (if markdown-hide-urls
8275 (message "markdown-mode URL hiding enabled")
8276 (message "markdown-mode URL hiding disabled"))
8277 (markdown-reload-extensions))
8280 ;;; WikiLink Following/Markup =================================================
8282 (defun markdown-wiki-link-p ()
8283 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8284 A true wiki link name matches `markdown-regex-wiki-link' but does
8285 not match the current file name after conversion. This modifies
8286 the data returned by `match-data'. Note that the potential wiki
8287 link name must be available via `match-string'."
8288 (when markdown-enable-wiki-links
8289 (let ((case-fold-search nil))
8290 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8291 (not (markdown-code-block-at-point-p))
8292 (or (not buffer-file-name)
8293 (not (string-equal (buffer-file-name)
8294 (markdown-convert-wiki-link-to-filename
8295 (markdown-wiki-link-link)))))))))
8297 (defun markdown-wiki-link-link ()
8298 "Return the link part of the wiki link using current match data.
8299 The location of the link component depends on the value of
8300 `markdown-wiki-link-alias-first'."
8301 (if markdown-wiki-link-alias-first
8302 (or (match-string-no-properties 5) (match-string-no-properties 3))
8303 (match-string-no-properties 3)))
8305 (defun markdown-wiki-link-alias ()
8306 "Return the alias or text part of the wiki link using current match data.
8307 The location of the alias component depends on the value of
8308 `markdown-wiki-link-alias-first'."
8309 (if markdown-wiki-link-alias-first
8310 (match-string-no-properties 3)
8311 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8313 (defun markdown-convert-wiki-link-to-filename (name)
8314 "Generate a filename from the wiki link NAME.
8315 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8316 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8317 and [[test test]] both map to Test-test.ext. Look in the current
8318 directory first, then in subdirectories if
8319 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8320 in parent directories if
8321 `markdown-wiki-link-search-parent-directories' is non-nil."
8322 (let* ((basename (markdown-replace-regexp-in-string
8323 "[[:space:]\n]" markdown-link-space-sub-char name))
8324 (basename (if (eq major-mode 'gfm-mode)
8325 (concat (upcase (substring basename 0 1))
8326 (downcase (substring basename 1 nil)))
8327 basename))
8328 directory extension default candidates dir)
8329 (when buffer-file-name
8330 (setq directory (file-name-directory buffer-file-name)
8331 extension (file-name-extension buffer-file-name)))
8332 (setq default (concat basename
8333 (when extension (concat "." extension))))
8334 (cond
8335 ;; Look in current directory first.
8336 ((or (null buffer-file-name)
8337 (file-exists-p default))
8338 default)
8339 ;; Possibly search in subdirectories, next.
8340 ((and markdown-wiki-link-search-subdirectories
8341 (setq candidates
8342 (markdown-directory-files-recursively
8343 directory (concat "^" default "$"))))
8344 (car candidates))
8345 ;; Possibly search in parent directories as a last resort.
8346 ((and markdown-wiki-link-search-parent-directories
8347 (setq dir (locate-dominating-file directory default)))
8348 (concat dir default))
8349 ;; If nothing is found, return default in current directory.
8350 (t default))))
8352 (defun markdown-follow-wiki-link (name &optional other)
8353 "Follow the wiki link NAME.
8354 Convert the name to a file name and call `find-file'. Ensure that
8355 the new buffer remains in `markdown-mode'. Open the link in another
8356 window when OTHER is non-nil."
8357 (let ((filename (markdown-convert-wiki-link-to-filename name))
8358 (wp (when buffer-file-name
8359 (file-name-directory buffer-file-name))))
8360 (if (not wp)
8361 (user-error "Must be visiting a file")
8362 (when other (other-window 1))
8363 (let ((default-directory wp))
8364 (find-file filename)))
8365 (when (not (eq major-mode 'markdown-mode))
8366 (markdown-mode))))
8368 (defun markdown-follow-wiki-link-at-point (&optional arg)
8369 "Find Wiki Link at point.
8370 With prefix argument ARG, open the file in other window.
8371 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8372 (interactive "P")
8373 (if (markdown-wiki-link-p)
8374 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8375 (user-error "Point is not at a Wiki Link")))
8377 (defun markdown-highlight-wiki-link (from to face)
8378 "Highlight the wiki link in the region between FROM and TO using FACE."
8379 (put-text-property from to 'font-lock-face face))
8381 (defun markdown-unfontify-region-wiki-links (from to)
8382 "Remove wiki link faces from the region specified by FROM and TO."
8383 (interactive "*r")
8384 (let ((modified (buffer-modified-p)))
8385 (remove-text-properties from to '(font-lock-face markdown-link-face))
8386 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8387 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8388 ;; undo that if it wasn't originally marked modified
8389 (set-buffer-modified-p modified)))
8391 (defun markdown-fontify-region-wiki-links (from to)
8392 "Search region given by FROM and TO for wiki links and fontify them.
8393 If a wiki link is found check to see if the backing file exists
8394 and highlight accordingly."
8395 (goto-char from)
8396 (save-match-data
8397 (while (re-search-forward markdown-regex-wiki-link to t)
8398 (when (not (markdown-code-block-at-point-p))
8399 (let ((highlight-beginning (match-beginning 1))
8400 (highlight-end (match-end 1))
8401 (file-name
8402 (markdown-convert-wiki-link-to-filename
8403 (markdown-wiki-link-link))))
8404 (if (condition-case nil (file-exists-p file-name) (error nil))
8405 (markdown-highlight-wiki-link
8406 highlight-beginning highlight-end markdown-link-face)
8407 (markdown-highlight-wiki-link
8408 highlight-beginning highlight-end markdown-missing-link-face)))))))
8410 (defun markdown-extend-changed-region (from to)
8411 "Extend region given by FROM and TO so that we can fontify all links.
8412 The region is extended to the first newline before and the first
8413 newline after."
8414 ;; start looking for the first new line before 'from
8415 (goto-char from)
8416 (re-search-backward "\n" nil t)
8417 (let ((new-from (point-min))
8418 (new-to (point-max)))
8419 (if (not (= (point) from))
8420 (setq new-from (point)))
8421 ;; do the same thing for the first new line after 'to
8422 (goto-char to)
8423 (re-search-forward "\n" nil t)
8424 (if (not (= (point) to))
8425 (setq new-to (point)))
8426 (cl-values new-from new-to)))
8428 (defun markdown-check-change-for-wiki-link (from to)
8429 "Check region between FROM and TO for wiki links and re-fontify as needed."
8430 (interactive "*r")
8431 (let* ((modified (buffer-modified-p))
8432 (buffer-undo-list t)
8433 (inhibit-read-only t)
8434 (inhibit-point-motion-hooks t)
8435 deactivate-mark
8436 buffer-file-truename)
8437 (unwind-protect
8438 (save-excursion
8439 (save-match-data
8440 (save-restriction
8441 ;; Extend the region to fontify so that it starts
8442 ;; and ends at safe places.
8443 (cl-multiple-value-bind (new-from new-to)
8444 (markdown-extend-changed-region from to)
8445 (goto-char new-from)
8446 ;; Only refontify when the range contains text with a
8447 ;; wiki link face or if the wiki link regexp matches.
8448 (when (or (markdown-range-property-any
8449 new-from new-to 'font-lock-face
8450 (list markdown-link-face
8451 markdown-missing-link-face))
8452 (re-search-forward
8453 markdown-regex-wiki-link new-to t))
8454 ;; Unfontify existing fontification (start from scratch)
8455 (markdown-unfontify-region-wiki-links new-from new-to)
8456 ;; Now do the fontification.
8457 (markdown-fontify-region-wiki-links new-from new-to))))))
8458 (and (not modified)
8459 (buffer-modified-p)
8460 (set-buffer-modified-p nil)))))
8462 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8463 "Check region between FROM and TO for wiki links and re-fontify as needed.
8464 Designed to be used with the `after-change-functions' hook."
8465 (markdown-check-change-for-wiki-link from to))
8467 (defun markdown-fontify-buffer-wiki-links ()
8468 "Refontify all wiki links in the buffer."
8469 (interactive)
8470 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8473 ;;; Following & Doing =========================================================
8475 (defun markdown-follow-thing-at-point (arg)
8476 "Follow thing at point if possible, such as a reference link or wiki link.
8477 Opens inline and reference links in a browser. Opens wiki links
8478 to other files in the current window, or the another window if
8479 ARG is non-nil.
8480 See `markdown-follow-link-at-point' and
8481 `markdown-follow-wiki-link-at-point'."
8482 (interactive "P")
8483 (cond ((markdown-link-p)
8484 (markdown-follow-link-at-point))
8485 ((markdown-wiki-link-p)
8486 (markdown-follow-wiki-link-at-point arg))
8488 (user-error "Nothing to follow at point"))))
8490 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8492 (defun markdown-do ()
8493 "Do something sensible based on context at point.
8494 Jumps between reference links and definitions; between footnote
8495 markers and footnote text."
8496 (interactive)
8497 (cond
8498 ;; Footnote definition
8499 ((markdown-footnote-text-positions)
8500 (markdown-footnote-return))
8501 ;; Footnote marker
8502 ((markdown-footnote-marker-positions)
8503 (markdown-footnote-goto-text))
8504 ;; Reference link
8505 ((thing-at-point-looking-at markdown-regex-link-reference)
8506 (markdown-reference-goto-definition))
8507 ;; Reference definition
8508 ((thing-at-point-looking-at markdown-regex-reference-definition)
8509 (markdown-reference-goto-link (match-string-no-properties 2)))
8510 ;; GFM task list item
8511 ((markdown-gfm-task-list-item-at-point)
8512 (markdown-toggle-gfm-checkbox))
8513 ;; Align table
8514 ((markdown-table-at-point-p)
8515 (call-interactively #'markdown-table-align))
8516 ;; Otherwise
8518 (markdown-insert-gfm-checkbox))))
8521 ;;; Miscellaneous =============================================================
8523 (defun markdown-compress-whitespace-string (str)
8524 "Compress whitespace in STR and return result.
8525 Leading and trailing whitespace is removed. Sequences of multiple
8526 spaces, tabs, and newlines are replaced with single spaces."
8527 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8528 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8530 (defun markdown--substitute-command-keys (string)
8531 "Like `substitute-command-keys' but, but prefers control characters.
8532 First pass STRING to `substitute-command-keys' and then
8533 substitute `C-i` for `TAB` and `C-m` for `RET`."
8534 (replace-regexp-in-string
8535 "\\<TAB\\>" "C-i"
8536 (replace-regexp-in-string
8537 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8539 (defun markdown-line-number-at-pos (&optional pos)
8540 "Return (narrowed) buffer line number at position POS.
8541 If POS is nil, use current buffer location.
8542 This is an exact copy of `line-number-at-pos' for use in emacs21."
8543 (let ((opoint (or pos (point))) start)
8544 (save-excursion
8545 (goto-char (point-min))
8546 (setq start (point))
8547 (goto-char opoint)
8548 (forward-line 0)
8549 (1+ (count-lines start (point))))))
8551 (defun markdown-inside-link-p ()
8552 "Return t if point is within a link."
8553 (save-match-data
8554 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8556 (defun markdown-line-is-reference-definition-p ()
8557 "Return whether the current line is a (non-footnote) reference defition."
8558 (save-excursion
8559 (move-beginning-of-line 1)
8560 (and (looking-at-p markdown-regex-reference-definition)
8561 (not (looking-at-p "[ \t]*\\[^")))))
8563 (defun markdown-adaptive-fill-function ()
8564 "Return prefix for filling paragraph or nil if not determined."
8565 (cond
8566 ;; List item inside blockquote
8567 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8568 (markdown-replace-regexp-in-string
8569 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8570 ;; Blockquote
8571 ((looking-at markdown-regex-blockquote)
8572 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8573 ;; List items
8574 ((looking-at markdown-regex-list)
8575 (match-string-no-properties 0))
8576 ;; Footnote definition
8577 ((looking-at-p markdown-regex-footnote-definition)
8578 " ") ; four spaces
8579 ;; No match
8580 (t nil)))
8582 (defun markdown-fill-paragraph (&optional justify)
8583 "Fill paragraph at or after point.
8584 This function is like \\[fill-paragraph], but it skips Markdown
8585 code blocks. If the point is in a code block, or just before one,
8586 do not fill. Otherwise, call `fill-paragraph' as usual. If
8587 JUSTIFY is non-nil, justify text as well. Since this function
8588 handles filling itself, it always returns t so that
8589 `fill-paragraph' doesn't run."
8590 (interactive "P")
8591 (unless (or (markdown-code-block-at-point-p)
8592 (save-excursion
8593 (back-to-indentation)
8594 (skip-syntax-forward "-")
8595 (markdown-code-block-at-point-p)))
8596 (fill-paragraph justify))
8599 (make-obsolete 'markdown-fill-forward-paragraph-function
8600 'markdown-fill-forward-paragraph "v2.3")
8602 (defun markdown-fill-forward-paragraph (&optional arg)
8603 "Function used by `fill-paragraph' to move over ARG paragraphs.
8604 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8605 It is called with a single argument specifying the number of
8606 paragraphs to move. Just like `forward-paragraph', it should
8607 return the number of paragraphs left to move."
8608 (or arg (setq arg 1))
8609 (if (> arg 0)
8610 ;; With positive ARG, move across ARG non-code-block paragraphs,
8611 ;; one at a time. When passing a code block, don't decrement ARG.
8612 (while (and (not (eobp))
8613 (> arg 0)
8614 (= (forward-paragraph 1) 0)
8615 (or (markdown-code-block-at-pos (point-at-bol 0))
8616 (setq arg (1- arg)))))
8617 ;; Move backward by one paragraph with negative ARG (always -1).
8618 (let ((start (point)))
8619 (setq arg (forward-paragraph arg))
8620 (while (and (not (eobp))
8621 (progn (move-to-left-margin) (not (eobp)))
8622 (looking-at-p paragraph-separate))
8623 (forward-line 1))
8624 (cond
8625 ;; Move point past whitespace following list marker.
8626 ((looking-at markdown-regex-list)
8627 (goto-char (match-end 0)))
8628 ;; Move point past whitespace following pipe at beginning of line
8629 ;; to handle Pandoc line blocks.
8630 ((looking-at "^|\\s-*")
8631 (goto-char (match-end 0)))
8632 ;; Return point if the paragraph passed was a code block.
8633 ((markdown-code-block-at-pos (point-at-bol 2))
8634 (goto-char start)))))
8635 arg)
8637 (defun markdown--inhibit-electric-quote ()
8638 "Function added to `electric-quote-inhibit-functions'.
8639 Return non-nil if the quote has been inserted inside a code block
8640 or span."
8641 (let ((pos (1- (point))))
8642 (or (markdown-inline-code-at-pos pos)
8643 (markdown-code-block-at-pos pos))))
8646 ;;; Extension Framework =======================================================
8648 (defun markdown-reload-extensions ()
8649 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8650 (interactive)
8651 (when (member major-mode '(markdown-mode gfm-mode))
8652 ;; Update font lock keywords with extensions
8653 (setq markdown-mode-font-lock-keywords
8654 (append
8655 (markdown-mode-font-lock-keywords-math)
8656 markdown-mode-font-lock-keywords-basic))
8657 ;; Update font lock defaults
8658 (setq font-lock-defaults
8659 '(markdown-mode-font-lock-keywords
8660 nil nil nil nil
8661 (font-lock-syntactic-face-function . markdown-syntactic-face)))
8662 ;; Refontify buffer
8663 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8664 (font-lock-refresh-defaults))
8666 ;; Add or remove hooks related to extensions
8667 (markdown-setup-wiki-link-hooks)))
8669 (defun markdown-handle-local-variables ()
8670 "Run in `hack-local-variables-hook' to update font lock rules.
8671 Checks to see if there is actually a ‘markdown-mode’ file local variable
8672 before regenerating font-lock rules for extensions."
8673 (when (and (boundp 'file-local-variables-alist)
8674 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8675 (assoc 'markdown-enable-math file-local-variables-alist)))
8676 (when (assoc 'markdown-enable-math file-local-variables-alist)
8677 (markdown-toggle-math markdown-enable-math))
8678 (markdown-reload-extensions)))
8681 ;;; Wiki Links ================================================================
8683 (defun markdown-toggle-wiki-links (&optional arg)
8684 "Toggle support for wiki links.
8685 With a prefix argument ARG, enable wiki link support if ARG is positive,
8686 and disable it otherwise."
8687 (interactive (list (or current-prefix-arg 'toggle)))
8688 (setq markdown-enable-wiki-links
8689 (if (eq arg 'toggle)
8690 (not markdown-enable-wiki-links)
8691 (> (prefix-numeric-value arg) 0)))
8692 (if markdown-enable-wiki-links
8693 (message "markdown-mode wiki link support enabled")
8694 (message "markdown-mode wiki link support disabled"))
8695 (markdown-reload-extensions))
8697 (defun markdown-setup-wiki-link-hooks ()
8698 "Add or remove hooks for fontifying wiki links.
8699 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8700 ;; Anytime text changes make sure it gets fontified correctly
8701 (if (and markdown-enable-wiki-links
8702 markdown-wiki-link-fontify-missing)
8703 (add-hook 'after-change-functions
8704 'markdown-check-change-for-wiki-link-after-change t t)
8705 (remove-hook 'after-change-functions
8706 'markdown-check-change-for-wiki-link-after-change t))
8707 ;; If we left the buffer there is a really good chance we were
8708 ;; creating one of the wiki link documents. Make sure we get
8709 ;; refontified when we come back.
8710 (if (and markdown-enable-wiki-links
8711 markdown-wiki-link-fontify-missing)
8712 (progn
8713 (add-hook 'window-configuration-change-hook
8714 'markdown-fontify-buffer-wiki-links t t)
8715 (markdown-fontify-buffer-wiki-links))
8716 (remove-hook 'window-configuration-change-hook
8717 'markdown-fontify-buffer-wiki-links t)
8718 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8721 ;;; Math Support ==============================================================
8723 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8725 (defun markdown-toggle-math (&optional arg)
8726 "Toggle support for inline and display LaTeX math expressions.
8727 With a prefix argument ARG, enable math mode if ARG is positive,
8728 and disable it otherwise. If called from Lisp, enable the mode
8729 if ARG is omitted or nil."
8730 (interactive (list (or current-prefix-arg 'toggle)))
8731 (setq markdown-enable-math
8732 (if (eq arg 'toggle)
8733 (not markdown-enable-math)
8734 (> (prefix-numeric-value arg) 0)))
8735 (if markdown-enable-math
8736 (message "markdown-mode math support enabled")
8737 (message "markdown-mode math support disabled"))
8738 (markdown-reload-extensions))
8740 (defun markdown-mode-font-lock-keywords-math ()
8741 "Return math font lock keywords if support is enabled."
8742 (when markdown-enable-math
8743 (list
8744 ;; Equation reference (eq:foo)
8745 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
8746 (2 markdown-reference-face)
8747 (3 markdown-markup-face)))
8748 ;; Equation reference \eqref{foo}
8749 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
8750 (2 markdown-reference-face)
8751 (3 markdown-markup-face))))))
8754 ;;; GFM Checkboxes ============================================================
8756 (define-button-type 'markdown-gfm-checkbox-button
8757 'follow-link t
8758 'face 'markdown-gfm-checkbox-face
8759 'mouse-face 'markdown-highlight-face
8760 'action #'markdown-toggle-gfm-checkbox-button)
8762 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8763 "Return non-nil if there is a GFM task list item at the point.
8764 Optionally, the list item BOUNDS may be given if available, as
8765 returned by `markdown-cur-list-item-bounds'. When a task list item
8766 is found, the return value is the same value returned by
8767 `markdown-cur-list-item-bounds'."
8768 (unless bounds
8769 (setq bounds (markdown-cur-list-item-bounds)))
8770 (> (length (nth 5 bounds)) 0))
8772 (defun markdown-insert-gfm-checkbox ()
8773 "Add GFM checkbox at point.
8774 Returns t if added.
8775 Returns nil if non-applicable."
8776 (interactive)
8777 (let ((bounds (markdown-cur-list-item-bounds)))
8778 (if bounds
8779 (unless (cl-sixth bounds)
8780 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8781 (markup "[ ] "))
8782 (if (< pos (point))
8783 (save-excursion
8784 (goto-char pos)
8785 (insert markup))
8786 (goto-char pos)
8787 (insert markup))
8789 (unless (save-excursion
8790 (back-to-indentation)
8791 (or (markdown-list-item-at-point-p)
8792 (markdown-heading-at-point)
8793 (markdown-in-comment-p)
8794 (markdown-code-block-at-point-p)))
8795 (let ((pos (save-excursion
8796 (back-to-indentation)
8797 (point)))
8798 (markup (concat (or (save-excursion
8799 (beginning-of-line 0)
8800 (cl-fifth (markdown-cur-list-item-bounds)))
8801 markdown-unordered-list-item-prefix)
8802 "[ ] ")))
8803 (if (< pos (point))
8804 (save-excursion
8805 (goto-char pos)
8806 (insert markup))
8807 (goto-char pos)
8808 (insert markup))
8809 t)))))
8811 (defun markdown-toggle-gfm-checkbox ()
8812 "Toggle GFM checkbox at point.
8813 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8814 Returns nil if there is no task list item at the point."
8815 (interactive)
8816 (save-match-data
8817 (save-excursion
8818 (let ((bounds (markdown-cur-list-item-bounds)))
8819 (when bounds
8820 ;; Move to beginning of task list item
8821 (goto-char (cl-first bounds))
8822 ;; Advance to column of first non-whitespace after marker
8823 (forward-char (cl-fourth bounds))
8824 (cond ((looking-at "\\[ \\]")
8825 (replace-match
8826 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8827 nil t)
8828 (match-string-no-properties 0))
8829 ((looking-at "\\[[xX]\\]")
8830 (replace-match "[ ]" nil t)
8831 (match-string-no-properties 0))))))))
8833 (defun markdown-toggle-gfm-checkbox-button (button)
8834 "Toggle GFM checkbox BUTTON on click."
8835 (save-match-data
8836 (save-excursion
8837 (goto-char (button-start button))
8838 (markdown-toggle-gfm-checkbox))))
8840 (defun markdown-make-gfm-checkboxes-buttons (start end)
8841 "Make GFM checkboxes buttons in region between START and END."
8842 (save-excursion
8843 (goto-char start)
8844 (let ((case-fold-search t))
8845 (save-excursion
8846 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8847 (make-button (match-beginning 1) (match-end 1)
8848 :type 'markdown-gfm-checkbox-button))))))
8850 ;; Called when any modification is made to buffer text.
8851 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8852 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8853 BEG and END are the limits of scanned region."
8854 (save-excursion
8855 (save-match-data
8856 ;; Rescan between start of line from `beg' and start of line after `end'.
8857 (markdown-make-gfm-checkboxes-buttons
8858 (progn (goto-char beg) (beginning-of-line) (point))
8859 (progn (goto-char end) (forward-line 1) (point))))))
8861 (defun markdown-remove-gfm-checkbox-overlays ()
8862 "Remove all GFM checkbox overlays in buffer."
8863 (save-excursion
8864 (save-restriction
8865 (widen)
8866 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8869 ;;; Display inline image =================================================
8871 (defvar markdown-inline-image-overlays nil)
8872 (make-variable-buffer-local 'markdown-inline-image-overlays)
8874 (defun markdown-remove-inline-images ()
8875 "Remove inline image overlays from image links in the buffer.
8876 This can be toggled with `markdown-toggle-inline-images'
8877 or \\[markdown-toggle-inline-images]."
8878 (interactive)
8879 (mapc #'delete-overlay markdown-inline-image-overlays)
8880 (setq markdown-inline-image-overlays nil))
8882 (defun markdown-display-inline-images ()
8883 "Add inline image overlays to image links in the buffer.
8884 This can be toggled with `markdown-toggle-inline-images'
8885 or \\[markdown-toggle-inline-images]."
8886 (interactive)
8887 (unless (display-graphic-p)
8888 (error "Cannot show images"))
8889 (save-excursion
8890 (save-restriction
8891 (widen)
8892 (goto-char (point-min))
8893 (while (re-search-forward markdown-regex-link-inline nil t)
8894 (let ((start (match-beginning 0))
8895 (end (match-end 0))
8896 (file (match-string-no-properties 6)))
8897 (when (file-exists-p file)
8898 (let* ((abspath (if (file-name-absolute-p file)
8899 file
8900 (concat default-directory file)))
8901 (image (create-image abspath)))
8902 (when image
8903 (let ((ov (make-overlay start end)))
8904 (overlay-put ov 'display image)
8905 (overlay-put ov 'face 'default)
8906 (push ov markdown-inline-image-overlays))))))))))
8908 (defun markdown-toggle-inline-images ()
8909 "Toggle inline image overlays in the buffer."
8910 (interactive)
8911 (if markdown-inline-image-overlays
8912 (markdown-remove-inline-images)
8913 (markdown-display-inline-images)))
8916 ;;; GFM Code Block Fontification ==============================================
8918 (defcustom markdown-fontify-code-blocks-natively nil
8919 "When non-nil, fontify code in code blocks using the native major mode.
8920 This only works for fenced code blocks where the language is
8921 specified where we can automatically determine the appropriate
8922 mode to use. The language to mode mapping may be customized by
8923 setting the variable `markdown-code-lang-modes'."
8924 :group 'markdown
8925 :type 'boolean
8926 :safe 'booleanp
8927 :package-version '(markdown-mode . "2.3"))
8929 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8930 "Toggle the native fontification of code blocks.
8931 With a prefix argument ARG, enable if ARG is positive,
8932 and disable otherwise."
8933 (interactive (list (or current-prefix-arg 'toggle)))
8934 (setq markdown-fontify-code-blocks-natively
8935 (if (eq arg 'toggle)
8936 (not markdown-fontify-code-blocks-natively)
8937 (> (prefix-numeric-value arg) 0)))
8938 (if markdown-fontify-code-blocks-natively
8939 (message "markdown-mode native code block fontification enabled")
8940 (message "markdown-mode native code block fontification disabled"))
8941 (markdown-reload-extensions))
8943 ;; This is based on `org-src-lang-modes' from org-src.el
8944 (defcustom markdown-code-lang-modes
8945 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8946 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8947 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8948 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8949 ("bash" . sh-mode))
8950 "Alist mapping languages to their major mode.
8951 The key is the language name, the value is the major mode. For
8952 many languages this is simple, but for language where this is not
8953 the case, this variable provides a way to simplify things on the
8954 user side. For example, there is no ocaml-mode in Emacs, but the
8955 mode to use is `tuareg-mode'."
8956 :group 'markdown
8957 :type '(repeat
8958 (cons
8959 (string "Language name")
8960 (symbol "Major mode")))
8961 :package-version '(markdown-mode . "2.3"))
8963 (defun markdown-get-lang-mode (lang)
8964 "Return major mode that should be used for LANG.
8965 LANG is a string, and the returned major mode is a symbol."
8966 (cl-find-if
8967 'fboundp
8968 (list (cdr (assoc lang markdown-code-lang-modes))
8969 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8970 (intern (concat lang "-mode"))
8971 (intern (concat (downcase lang) "-mode")))))
8973 (defun markdown-fontify-code-blocks-generic (matcher last)
8974 "Add text properties to next code block from point to LAST.
8975 Use matching function MATCHER."
8976 (when (funcall matcher last)
8977 (save-excursion
8978 (save-match-data
8979 (let* ((start (match-beginning 0))
8980 (end (match-end 0))
8981 ;; Find positions outside opening and closing backquotes.
8982 (bol-prev (progn (goto-char start)
8983 (if (bolp) (point-at-bol 0) (point-at-bol))))
8984 (eol-next (progn (goto-char end)
8985 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8986 lang)
8987 (if (and markdown-fontify-code-blocks-natively
8988 (setq lang (markdown-code-block-lang)))
8989 (markdown-fontify-code-block-natively lang start end)
8990 (add-text-properties start end '(face markdown-pre-face)))
8991 ;; Set background for block as well as opening and closing lines.
8992 (font-lock-append-text-property
8993 bol-prev eol-next 'face 'markdown-code-face)
8994 ;; Set invisible property for lines before and after, including newline.
8995 (add-text-properties bol-prev start '(invisible markdown-markup))
8996 (add-text-properties end eol-next '(invisible markdown-markup)))))
8999 (defun markdown-fontify-gfm-code-blocks (last)
9000 "Add text properties to next GFM code block from point to LAST."
9001 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9003 (defun markdown-fontify-fenced-code-blocks (last)
9004 "Add text properties to next tilde fenced code block from point to LAST."
9005 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9007 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9008 (defun markdown-fontify-code-block-natively (lang start end)
9009 "Fontify given GFM or fenced code block.
9010 This function is called by Emacs for automatic fontification when
9011 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9012 language used in the block. START and END specify the block
9013 position."
9014 (let ((lang-mode (markdown-get-lang-mode lang)))
9015 (when (fboundp lang-mode)
9016 (let ((string (buffer-substring-no-properties start end))
9017 (modified (buffer-modified-p))
9018 (markdown-buffer (current-buffer)) pos next)
9019 (remove-text-properties start end '(face nil))
9020 (with-current-buffer
9021 (get-buffer-create
9022 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9023 ;; Make sure that modification hooks are not inhibited in
9024 ;; the org-src-fontification buffer in case we're called
9025 ;; from `jit-lock-function' (Bug#25132).
9026 (let ((inhibit-modification-hooks nil))
9027 (delete-region (point-min) (point-max))
9028 (insert string " ")) ;; so there's a final property change
9029 (unless (eq major-mode lang-mode) (funcall lang-mode))
9030 (markdown-font-lock-ensure)
9031 (setq pos (point-min))
9032 (while (setq next (next-single-property-change pos 'face))
9033 (let ((val (get-text-property pos 'face)))
9034 (when val
9035 (put-text-property
9036 (+ start (1- pos)) (1- (+ start next)) 'face
9037 val markdown-buffer)))
9038 (setq pos next)))
9039 (add-text-properties
9040 start end
9041 '(font-lock-fontified t fontified t font-lock-multiline t))
9042 (set-buffer-modified-p modified)))))
9044 (require 'edit-indirect nil t)
9045 (defvar edit-indirect-guess-mode-function)
9046 (defvar edit-indirect-after-commit-functions)
9048 (defun markdown--edit-indirect-after-commit-function (_beg end)
9049 "Ensure trailing newlines at the END of code blocks."
9050 (goto-char end)
9051 (unless (eq (char-before) ?\n)
9052 (insert "\n")))
9054 (defun markdown-edit-code-block ()
9055 "Edit Markdown code block in an indirect buffer."
9056 (interactive)
9057 (save-excursion
9058 (if (fboundp 'edit-indirect-region)
9059 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9060 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9061 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9062 (if (and begin end)
9063 (let* ((lang (markdown-code-block-lang))
9064 (mode (and lang (markdown-get-lang-mode lang)))
9065 (edit-indirect-guess-mode-function
9066 (lambda (_parent-buffer _beg _end)
9067 (funcall mode))))
9068 (edit-indirect-region begin end 'display-buffer))
9069 (user-error "Not inside a GFM or tilde fenced code block")))
9070 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9071 (progn (package-refresh-contents)
9072 (package-install 'edit-indirect)
9073 (markdown-edit-code-block))))))
9076 ;;; Table Editing
9078 ;; These functions were originally adapted from `org-table.el'.
9080 ;; General helper functions
9082 (defmacro markdown--with-gensyms (symbols &rest body)
9083 (declare (debug (sexp body)) (indent 1))
9084 `(let ,(mapcar (lambda (s)
9085 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9086 symbols)
9087 ,@body))
9089 (defun markdown--split-string (string &optional separators)
9090 "Splits STRING into substrings at SEPARATORS.
9091 SEPARATORS is a regular expression. If nil it defaults to
9092 `split-string-default-separators'. This version returns no empty
9093 strings if there are matches at the beginning and end of string."
9094 (let ((start 0) notfirst list)
9095 (while (and (string-match
9096 (or separators split-string-default-separators)
9097 string
9098 (if (and notfirst
9099 (= start (match-beginning 0))
9100 (< start (length string)))
9101 (1+ start) start))
9102 (< (match-beginning 0) (length string)))
9103 (setq notfirst t)
9104 (or (eq (match-beginning 0) 0)
9105 (and (eq (match-beginning 0) (match-end 0))
9106 (eq (match-beginning 0) start))
9107 (push (substring string start (match-beginning 0)) list))
9108 (setq start (match-end 0)))
9109 (or (eq start (length string))
9110 (push (substring string start) list))
9111 (nreverse list)))
9113 (defun markdown--string-width (s)
9114 "Return width of string S.
9115 This version ignores characters with invisibility property
9116 `markdown-markup'."
9117 (let (b)
9118 (when (or (eq t buffer-invisibility-spec)
9119 (member 'markdown-markup buffer-invisibility-spec))
9120 (while (setq b (text-property-any
9121 0 (length s)
9122 'invisible 'markdown-markup s))
9123 (setq s (concat
9124 (substring s 0 b)
9125 (substring s (or (next-single-property-change
9126 b 'invisible s)
9127 (length s))))))))
9128 (string-width s))
9130 (defun markdown--remove-invisible-markup (s)
9131 "Remove Markdown markup from string S.
9132 This version removes characters with invisibility property
9133 `markdown-markup'."
9134 (let (b)
9135 (while (setq b (text-property-any
9136 0 (length s)
9137 'invisible 'markdown-markup s))
9138 (setq s (concat
9139 (substring s 0 b)
9140 (substring s (or (next-single-property-change
9141 b 'invisible s)
9142 (length s)))))))
9145 ;; Functions for maintaining tables
9147 (defconst markdown-table-line-regexp "^[ \t]*|"
9148 "Regexp matching any line inside a table.")
9150 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9151 "Regexp matching hline inside a table.")
9153 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9154 "Regexp matching dline inside a table.")
9156 (defconst markdown-table-border-regexp "^[ \t]*[^| \t]"
9157 "Regexp matching any line outside a table.")
9159 (defun markdown-table-at-point-p ()
9160 "Return non-nil when point is inside a table."
9161 (save-excursion
9162 (beginning-of-line)
9163 (and (looking-at-p markdown-table-line-regexp)
9164 (not (markdown-code-block-at-point-p)))))
9166 (defun markdown-table-hline-at-point-p ()
9167 "Return non-nil when point is on a hline in a table.
9168 This function assumes point is on a table."
9169 (save-excursion
9170 (beginning-of-line)
9171 (looking-at-p markdown-table-hline-regexp)))
9173 (defun markdown-table-begin ()
9174 "Find the beginning of the table and return its position.
9175 This function assumes point is on a table."
9176 (cond
9177 ((save-excursion
9178 (and (re-search-backward markdown-table-border-regexp nil t)
9179 (line-beginning-position 2))))
9180 (t (point-min))))
9182 (defun markdown-table-end ()
9183 "Find the end of the table and return its position.
9184 This function assumes point is on a table."
9185 (save-excursion
9186 (cond
9187 ((re-search-forward markdown-table-border-regexp nil t)
9188 (match-beginning 0))
9189 (t (goto-char (point-max))
9190 (skip-chars-backward " \t")
9191 (if (bolp) (point) (line-end-position))))))
9193 (defun markdown-table-get-dline ()
9194 "Return index of the table data line at point.
9195 This function assumes point is on a table."
9196 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9197 (save-excursion
9198 (goto-char (markdown-table-begin))
9199 (while (and (re-search-forward
9200 markdown-table-dline-regexp end t)
9201 (setq cnt (1+ cnt))
9202 (< (point-at-eol) pos))))
9203 cnt))
9205 (defun markdown-table-get-column ()
9206 "Return table column at point.
9207 This function assumes point is on a table."
9208 (let ((pos (point)) (cnt 0))
9209 (save-excursion
9210 (beginning-of-line)
9211 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9212 cnt))
9214 (defun markdown-table-get-cell (&optional n)
9215 "Return the content of the cell in column N of current row.
9216 N defaults to column at point. This function assumes point is on
9217 a table."
9218 (and n (markdown-table-goto-column n))
9219 (skip-chars-backward "^|\n") (backward-char 1)
9220 (if (looking-at "|[^|\r\n]*")
9221 (let* ((pos (match-beginning 0))
9222 (val (buffer-substring (1+ pos) (match-end 0))))
9223 (goto-char (min (point-at-eol) (+ 2 pos)))
9224 ;; Trim whitespaces
9225 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9226 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9227 (forward-char 1) ""))
9229 (defun markdown-table-goto-dline (n)
9230 "Go to the Nth data line in the table at point.
9231 Return t when the line exists, nil otherwise. This function
9232 assumes point is on a table."
9233 (goto-char (markdown-table-begin))
9234 (let ((end (markdown-table-end)) (cnt 0))
9235 (while (and (re-search-forward
9236 markdown-table-dline-regexp end t)
9237 (< (setq cnt (1+ cnt)) n)))
9238 (= cnt n)))
9240 (defun markdown-table-goto-column (n &optional on-delim)
9241 "Go to the Nth column in the table line at point.
9242 With optional argument ON-DELIM, stop with point before the left
9243 delimiter of the cell. If there are less than N cells, just go
9244 beyond the last delimiter. This function assumes point is on a
9245 table."
9246 (beginning-of-line 1)
9247 (when (> n 0)
9248 (while (and (> (setq n (1- n)) -1)
9249 (search-forward "|" (point-at-eol) t)))
9250 (if on-delim
9251 (backward-char 1)
9252 (when (looking-at " ") (forward-char 1)))))
9254 (defmacro markdown-table-save-cell (&rest body)
9255 "Save cell at point, execute BODY and restore cell.
9256 This function assumes point is on a table."
9257 (declare (debug (body)))
9258 (markdown--with-gensyms (line column)
9259 `(let ((,line (copy-marker (line-beginning-position)))
9260 (,column (markdown-table-get-column)))
9261 (unwind-protect
9262 (progn ,@body)
9263 (goto-char ,line)
9264 (markdown-table-goto-column ,column)
9265 (set-marker ,line nil)))))
9267 (defun markdown-table-blank-line (s)
9268 "Convert a table line S into a line with blank cells."
9269 (if (string-match "^[ \t]*|-" s)
9270 (setq s (mapconcat
9271 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9272 s ""))
9273 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9274 (setq s (replace-match
9275 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9276 t t s)))
9279 (defun markdown-table-colfmt (fmtspec)
9280 "Process column alignment specifier FMTSPEC for tables."
9281 (when (stringp fmtspec)
9282 (mapcar (lambda (x)
9283 (cond ((string-match-p "^:.*:$" x) 'c)
9284 ((string-match-p "^:" x) 'l)
9285 ((string-match-p ":$" x) 'r)
9286 (t 'd)))
9287 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9289 (defun markdown-table-align ()
9290 "Align table at point.
9291 This function assumes point is on a table."
9292 (interactive)
9293 (let ((begin (markdown-table-begin))
9294 (end (copy-marker (markdown-table-end))))
9295 (markdown-table-save-cell
9296 (goto-char begin)
9297 (let* (fmtspec
9298 ;; Store table indent
9299 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9300 ;; Split table in lines and save column format specifier
9301 (lines (mapcar (lambda (l)
9302 (if (string-match-p "\\`[ \t]*|[-:]" l)
9303 (progn (setq fmtspec (or fmtspec l)) nil) l))
9304 (markdown--split-string (buffer-substring begin end) "\n")))
9305 ;; Split lines in cells
9306 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9307 (remq nil lines)))
9308 ;; Calculate maximum number of cells in a line
9309 (maxcells (if cells
9310 (apply #'max (mapcar #'length cells))
9311 (user-error "Empty table")))
9312 ;; Empty cells to fill short lines
9313 (emptycells (make-list maxcells "")) maxwidths)
9314 ;; Calculate maximum width for each column
9315 (dotimes (i maxcells)
9316 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9317 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9318 maxwidths)))
9319 (setq maxwidths (nreverse maxwidths))
9320 ;; Process column format specifier
9321 (setq fmtspec (markdown-table-colfmt fmtspec))
9322 ;; Compute formats needed for output of table lines
9323 (let ((hfmt (concat indent "|"))
9324 (rfmt (concat indent "|"))
9325 hfmt1 rfmt1 fmt)
9326 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9327 (setq fmt (pop fmtspec))
9328 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9329 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9330 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9331 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9332 (setq rfmt (concat rfmt (format rfmt1 width)))
9333 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9334 ;; Replace modified lines only
9335 (dolist (line lines)
9336 (let ((line (if line
9337 (apply #'format rfmt (append (pop cells) emptycells))
9338 hfmt))
9339 (previous (buffer-substring (point) (line-end-position))))
9340 (if (equal previous line)
9341 (forward-line)
9342 (insert line "\n")
9343 (delete-region (point) (line-beginning-position 2))))))
9344 (set-marker end nil)))))
9346 (defun markdown-table-insert-row (&optional arg)
9347 "Insert a new row above the row at point into the table.
9348 With optional argument ARG, insert below the current row."
9349 (interactive "P")
9350 (unless (markdown-table-at-point-p)
9351 (user-error "Not at a table"))
9352 (let* ((line (buffer-substring
9353 (line-beginning-position) (line-end-position)))
9354 (new (markdown-table-blank-line line)))
9355 (beginning-of-line (if arg 2 1))
9356 (unless (bolp) (insert "\n"))
9357 (insert-before-markers new "\n")
9358 (beginning-of-line 0)
9359 (re-search-forward "| ?" (line-end-position) t)))
9361 (defun markdown-table-delete-row ()
9362 "Delete row or horizontal line at point from the table."
9363 (interactive)
9364 (unless (markdown-table-at-point-p)
9365 (user-error "Not at a table"))
9366 (let ((col (current-column)))
9367 (kill-region (point-at-bol)
9368 (min (1+ (point-at-eol)) (point-max)))
9369 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9370 (move-to-column col)))
9372 (defun markdown-table-move-row (&optional up)
9373 "Move table line at point down.
9374 With optional argument UP, move it up."
9375 (interactive "P")
9376 (unless (markdown-table-at-point-p)
9377 (user-error "Not at a table"))
9378 (let* ((col (current-column)) (pos (point))
9379 (tonew (if up 0 2)) txt)
9380 (beginning-of-line tonew)
9381 (unless (markdown-table-at-point-p)
9382 (goto-char pos) (user-error "Cannot move row further"))
9383 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9384 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9385 (delete-region (point) (1+ (point-at-eol)))
9386 (beginning-of-line tonew)
9387 (insert txt) (beginning-of-line 0)
9388 (move-to-column col)))
9390 (defun markdown-table-move-row-up ()
9391 "Move table row at point up."
9392 (interactive)
9393 (markdown-table-move-row 'up))
9395 (defun markdown-table-move-row-down ()
9396 "Move table row at point down."
9397 (interactive)
9398 (markdown-table-move-row nil))
9400 (defun markdown-table-insert-column ()
9401 "Insert a new table column."
9402 (interactive)
9403 (unless (markdown-table-at-point-p)
9404 (user-error "Not at a table"))
9405 (let* ((col (max 1 (markdown-table-get-column)))
9406 (begin (markdown-table-begin))
9407 (end (copy-marker (markdown-table-end))))
9408 (markdown-table-save-cell
9409 (goto-char begin)
9410 (while (< (point) end)
9411 (markdown-table-goto-column col t)
9412 (if (markdown-table-hline-at-point-p)
9413 (insert "|---")
9414 (insert "| "))
9415 (forward-line)))
9416 (set-marker end nil)
9417 (markdown-table-align)))
9419 (defun markdown-table-delete-column ()
9420 "Delete column at point from table."
9421 (interactive)
9422 (unless (markdown-table-at-point-p)
9423 (user-error "Not at a table"))
9424 (let ((col (markdown-table-get-column))
9425 (begin (markdown-table-begin))
9426 (end (copy-marker (markdown-table-end))))
9427 (markdown-table-save-cell
9428 (goto-char begin)
9429 (while (< (point) end)
9430 (markdown-table-goto-column col t)
9431 (and (looking-at "|[^|\n]+|")
9432 (replace-match "|"))
9433 (forward-line)))
9434 (set-marker end nil)
9435 (markdown-table-goto-column (max 1 (1- col)))
9436 (markdown-table-align)))
9438 (defun markdown-table-move-column (&optional left)
9439 "Move table column at point to the right.
9440 With optional argument LEFT, move it to the left."
9441 (interactive "P")
9442 (unless (markdown-table-at-point-p)
9443 (user-error "Not at a table"))
9444 (let* ((col (markdown-table-get-column))
9445 (col1 (if left (1- col) col))
9446 (colpos (if left (1- col) (1+ col)))
9447 (begin (markdown-table-begin))
9448 (end (copy-marker (markdown-table-end))))
9449 (when (and left (= col 1))
9450 (user-error "Cannot move column further left"))
9451 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9452 (user-error "Cannot move column further right"))
9453 (markdown-table-save-cell
9454 (goto-char begin)
9455 (while (< (point) end)
9456 (markdown-table-goto-column col1 t)
9457 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9458 (replace-match "|\\2|\\1|"))
9459 (forward-line)))
9460 (set-marker end nil)
9461 (markdown-table-goto-column colpos)
9462 (markdown-table-align)))
9464 (defun markdown-table-move-column-left ()
9465 "Move table column at point to the left."
9466 (interactive)
9467 (markdown-table-move-column 'left))
9469 (defun markdown-table-move-column-right ()
9470 "Move table column at point to the right."
9471 (interactive)
9472 (markdown-table-move-column nil))
9474 (defun markdown-table-next-row ()
9475 "Go to the next row (same column) in the table.
9476 Create new table lines if required."
9477 (interactive)
9478 (unless (markdown-table-at-point-p)
9479 (user-error "Not at a table"))
9480 (if (or (looking-at "[ \t]*$")
9481 (save-excursion (skip-chars-backward " \t") (bolp)))
9482 (newline)
9483 (markdown-table-align)
9484 (let ((col (markdown-table-get-column)))
9485 (beginning-of-line 2)
9486 (if (or (not (markdown-table-at-point-p))
9487 (markdown-table-hline-at-point-p))
9488 (progn
9489 (beginning-of-line 0)
9490 (markdown-table-insert-row 'below)))
9491 (markdown-table-goto-column col)
9492 (skip-chars-backward "^|\n\r")
9493 (when (looking-at " ") (forward-char 1)))))
9495 (defun markdown-table-forward-cell ()
9496 "Go to the next cell in the table.
9497 Create new table lines if required."
9498 (interactive)
9499 (unless (markdown-table-at-point-p)
9500 (user-error "Not at a table"))
9501 (markdown-table-align)
9502 (let ((end (markdown-table-end)))
9503 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9504 (condition-case nil
9505 (progn
9506 (re-search-forward "|" end)
9507 (if (looking-at "[ \t]*$")
9508 (re-search-forward "|" end))
9509 (if (and (looking-at "[-:]")
9510 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9511 (goto-char (match-beginning 1)))
9512 (if (looking-at "[-:]")
9513 (progn
9514 (beginning-of-line 0)
9515 (markdown-table-insert-row 'below))
9516 (when (looking-at " ") (forward-char 1))))
9517 (error (markdown-table-insert-row 'below)))))
9519 (defun markdown-table-backward-cell ()
9520 "Go to the previous cell in the table."
9521 (interactive)
9522 (unless (markdown-table-at-point-p)
9523 (user-error "Not at a table"))
9524 (markdown-table-align)
9525 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9526 (condition-case nil
9527 (progn
9528 (re-search-backward "|" (markdown-table-begin))
9529 (re-search-backward "|" (markdown-table-begin)))
9530 (error (user-error "Cannot move to previous table cell")))
9531 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9532 (re-search-backward "|" (markdown-table-begin)))
9533 (when (looking-at "| ?") (goto-char (match-end 0))))
9535 (defun markdown-table-transpose ()
9536 "Transpose table at point.
9537 Horizontal separator lines will be eliminated."
9538 (interactive)
9539 (unless (markdown-table-at-point-p)
9540 (user-error "Not at a table"))
9541 (let* ((table (buffer-substring-no-properties
9542 (markdown-table-begin) (markdown-table-end)))
9543 ;; Convert table to a Lisp structure
9544 (table (delq nil
9545 (mapcar
9546 (lambda (x)
9547 (unless (string-match-p
9548 markdown-table-hline-regexp x)
9549 (markdown--split-string x "\\s-*|\\s-*")))
9550 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9551 (dline_old (markdown-table-get-dline))
9552 (col_old (markdown-table-get-column))
9553 (contents (mapcar (lambda (_)
9554 (let ((tp table))
9555 (mapcar
9556 (lambda (_)
9557 (prog1
9558 (pop (car tp))
9559 (setq tp (cdr tp))))
9560 table)))
9561 (car table))))
9562 (goto-char (markdown-table-begin))
9563 (re-search-forward "|") (backward-char)
9564 (delete-region (point) (markdown-table-end))
9565 (insert (mapconcat
9566 (lambda(x)
9567 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9568 contents ""))
9569 (markdown-table-goto-dline col_old)
9570 (markdown-table-goto-column dline_old))
9571 (markdown-table-align))
9573 (defun markdown-table-sort-lines (&optional sorting-type)
9574 "Sort table lines according to the column at point.
9576 The position of point indicates the column to be used for
9577 sorting, and the range of lines is the range between the nearest
9578 horizontal separator lines, or the entire table of no such lines
9579 exist. If point is before the first column, user will be prompted
9580 for the sorting column. If there is an active region, the mark
9581 specifies the first line and the sorting column, while point
9582 should be in the last line to be included into the sorting.
9584 The command then prompts for the sorting type which can be
9585 alphabetically or numerically. Sorting in reverse order is also
9586 possible.
9588 If SORTING-TYPE is specified when this function is called from a
9589 Lisp program, no prompting will take place. SORTING-TYPE must be
9590 a character, any of (?a ?A ?n ?N) where the capital letters
9591 indicate that sorting should be done in reverse order."
9592 (interactive)
9593 (unless (markdown-table-at-point-p)
9594 (user-error "Not at a table"))
9595 ;; Set sorting type and column used for sorting
9596 (let ((column (let ((c (markdown-table-get-column)))
9597 (cond ((> c 0) c)
9598 ((called-interactively-p 'any)
9599 (read-number "Use column N for sorting: "))
9600 (t 1))))
9601 (sorting-type
9602 (or sorting-type
9603 (read-char-exclusive
9604 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9605 (save-restriction
9606 ;; Narrow buffer to appropriate sorting area
9607 (if (region-active-p)
9608 (narrow-to-region
9609 (save-excursion
9610 (progn
9611 (goto-char (region-beginning)) (line-beginning-position)))
9612 (save-excursion
9613 (progn
9614 (goto-char (region-end)) (line-end-position))))
9615 (let ((start (markdown-table-begin))
9616 (end (markdown-table-end)))
9617 (narrow-to-region
9618 (save-excursion
9619 (if (re-search-backward
9620 markdown-table-hline-regexp start t)
9621 (line-beginning-position 2)
9622 start))
9623 (if (save-excursion (re-search-forward
9624 markdown-table-hline-regexp end t))
9625 (match-beginning 0)
9626 end))))
9627 ;; Determine arguments for `sort-subr'
9628 (let* ((extract-key-from-cell
9629 (cl-case sorting-type
9630 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9631 ((?n ?N) #'string-to-number)
9632 (t (user-error "Invalid sorting type: %c" sorting-type))))
9633 (predicate
9634 (cl-case sorting-type
9635 ((?n ?N) #'<)
9636 ((?a ?A) #'string<))))
9637 ;; Sort selected area
9638 (goto-char (point-min))
9639 (sort-subr (memq sorting-type '(?A ?N))
9640 (lambda ()
9641 (forward-line)
9642 (while (and (not (eobp))
9643 (not (looking-at
9644 markdown-table-dline-regexp)))
9645 (forward-line)))
9646 #'end-of-line
9647 (lambda ()
9648 (funcall extract-key-from-cell
9649 (markdown-table-get-cell column)))
9651 predicate)
9652 (goto-char (point-min))))))
9654 (defun markdown-table-convert-region (begin end &optional separator)
9655 "Convert region from BEGIN to END to table with SEPARATOR.
9657 If every line contains at least one TAB character, the function
9658 assumes that the material is tab separated (TSV). If every line
9659 contains a comma, comma-separated values (CSV) are assumed. If
9660 not, lines are split at whitespace into cells.
9662 You can use a prefix argument to force a specific separator:
9663 \\[universal-argument] once forces CSV, \\[universal-argument]
9664 twice forces TAB, and \\[universal-argument] three times will
9665 prompt for a regular expression to match the separator, and a
9666 numeric argument N indicates that at least N consecutive
9667 spaces, or alternatively a TAB should be used as the separator."
9669 (interactive "r\nP")
9670 (let* ((begin (min begin end)) (end (max begin end)) re)
9671 (goto-char begin) (beginning-of-line 1)
9672 (setq begin (point-marker))
9673 (goto-char end)
9674 (if (bolp) (backward-char 1) (end-of-line 1))
9675 (setq end (point-marker))
9676 (when (equal separator '(64))
9677 (setq separator (read-regexp "Regexp for cell separator: ")))
9678 (unless separator
9679 ;; Get the right cell separator
9680 (goto-char begin)
9681 (setq separator
9682 (cond
9683 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9684 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9685 (t 1))))
9686 (goto-char begin)
9687 (if (equal separator '(4))
9688 ;; Parse CSV
9689 (while (< (point) end)
9690 (cond
9691 ((looking-at "^") (insert "| "))
9692 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9693 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9694 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9695 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9696 ((looking-at "[ \t]*,") (replace-match " | "))
9697 (t (beginning-of-line 2))))
9698 (setq re
9699 (cond
9700 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9701 ((equal separator '(16)) "^\\|\t")
9702 ((integerp separator)
9703 (if (< separator 1)
9704 (user-error "Cell separator must contain one or more spaces")
9705 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9706 ((stringp separator) (format "^ *\\|%s" separator))
9707 (t (error "Invalid cell separator"))))
9708 (while (re-search-forward re end t) (replace-match "| " t t)))
9709 (goto-char begin)
9710 (markdown-table-align)))
9713 ;;; ElDoc Support
9715 (defun markdown-eldoc-function ()
9716 "Return a helpful string when appropriate based on context.
9717 * Report URL when point is at a hidden URL.
9718 * Report language name when point is a code block with hidden markup."
9719 (cond
9720 ;; Hidden URL or reference for inline link
9721 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9722 (thing-at-point-looking-at markdown-regex-link-reference))
9723 (or markdown-hide-urls markdown-hide-markup))
9724 (let* ((imagep (string-equal (match-string 1) "!"))
9725 (edit-keys (markdown--substitute-command-keys
9726 (if imagep
9727 "\\[markdown-insert-image]"
9728 "\\[markdown-insert-link]")))
9729 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9730 (referencep (string-equal (match-string 5) "["))
9731 (object (if referencep "reference" "URL")))
9732 (format "Hidden %s (%s to edit): %s" object edit-str
9733 (if referencep
9734 (concat
9735 (propertize "[" 'face 'markdown-markup-face)
9736 (propertize (match-string-no-properties 6)
9737 'face 'markdown-reference-face)
9738 (propertize "]" 'face 'markdown-markup-face))
9739 (propertize (match-string-no-properties 6)
9740 'face 'markdown-url-face)))))
9741 ;; Hidden language name for fenced code blocks
9742 ((and (markdown-code-block-at-point-p)
9743 (not (get-text-property (point) 'markdown-pre))
9744 markdown-hide-markup)
9745 (let ((lang (save-excursion (markdown-code-block-lang))))
9746 (unless lang (setq lang "[unspecified]"))
9747 (format "Hidden code block language: %s (%s to toggle markup)"
9748 (propertize lang 'face 'markdown-language-keyword-face)
9749 (markdown--substitute-command-keys
9750 "\\[markdown-toggle-markup-hiding]"))))))
9753 ;;; Mode Definition ==========================================================
9755 (defun markdown-show-version ()
9756 "Show the version number in the minibuffer."
9757 (interactive)
9758 (message "markdown-mode, version %s" markdown-mode-version))
9760 (defun markdown-mode-info ()
9761 "Open the `markdown-mode' homepage."
9762 (interactive)
9763 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9765 ;;;###autoload
9766 (define-derived-mode markdown-mode text-mode "Markdown"
9767 "Major mode for editing Markdown files."
9768 ;; Natural Markdown tab width
9769 (setq tab-width 4)
9770 ;; Comments
9771 (setq-local comment-start "<!-- ")
9772 (setq-local comment-end " -->")
9773 (setq-local comment-start-skip "<!--[ \t]*")
9774 (setq-local comment-column 0)
9775 (setq-local comment-auto-fill-only-comments nil)
9776 (setq-local comment-use-syntax t)
9777 ;; Syntax
9778 (add-hook 'syntax-propertize-extend-region-functions
9779 #'markdown-syntax-propertize-extend-region)
9780 (add-hook 'jit-lock-after-change-extend-region-functions
9781 #'markdown-font-lock-extend-region-function t t)
9782 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9783 ;; Font lock.
9784 (setq-local markdown-mode-font-lock-keywords nil)
9785 (setq-local font-lock-defaults nil)
9786 (setq-local font-lock-multiline t)
9787 (setq-local font-lock-extra-managed-props
9788 (append font-lock-extra-managed-props
9789 '(composition display invisible)))
9790 (if markdown-hide-markup
9791 (add-to-invisibility-spec 'markdown-markup)
9792 (remove-from-invisibility-spec 'markdown-markup))
9793 ;; Reload extensions
9794 (markdown-reload-extensions)
9795 ;; Add a buffer-local hook to reload after file-local variables are read
9796 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9797 ;; For imenu support
9798 (setq imenu-create-index-function
9799 (if markdown-nested-imenu-heading-index
9800 #'markdown-imenu-create-nested-index
9801 #'markdown-imenu-create-flat-index))
9802 ;; For menu support in XEmacs
9803 (easy-menu-add markdown-mode-menu markdown-mode-map)
9804 ;; Defun movement
9805 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9806 (setq-local end-of-defun-function #'markdown-end-of-defun)
9807 ;; Paragraph filling
9808 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9809 (setq-local paragraph-start
9810 ;; Should match start of lines that start or separate paragraphs
9811 (mapconcat #'identity
9813 "\f" ; starts with a literal line-feed
9814 "[ \t\f]*$" ; space-only line
9815 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9816 "[ \t]*[*+-][ \t]+" ; unordered list item
9817 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9818 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9819 "[ \t]*:[ \t]+" ; definition
9820 "^|" ; table or Pandoc line block
9822 "\\|"))
9823 (setq-local paragraph-separate
9824 ;; Should match lines that separate paragraphs without being
9825 ;; part of any paragraph:
9826 (mapconcat #'identity
9827 '("[ \t\f]*$" ; space-only line
9828 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9829 ;; The following is not ideal, but the Fill customization
9830 ;; options really only handle paragraph-starting prefixes,
9831 ;; not paragraph-ending suffixes:
9832 ".* $" ; line ending in two spaces
9833 "^#+"
9834 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9835 "\\|"))
9836 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9837 (setq-local adaptive-fill-regexp "\\s-*")
9838 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9839 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9840 ;; Outline mode
9841 (setq-local outline-regexp markdown-regex-header)
9842 (setq-local outline-level #'markdown-outline-level)
9843 ;; Cause use of ellipses for invisible text.
9844 (add-to-invisibility-spec '(outline . t))
9845 ;; ElDoc support
9846 (if (eval-when-compile (fboundp 'add-function))
9847 (add-function :before-until (local 'eldoc-documentation-function)
9848 #'markdown-eldoc-function)
9849 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9850 ;; Inhibiting line-breaking:
9851 ;; Separating out each condition into a separate function so that users can
9852 ;; override if desired (with remove-hook)
9853 (add-hook 'fill-nobreak-predicate
9854 #'markdown-line-is-reference-definition-p nil t)
9855 (add-hook 'fill-nobreak-predicate
9856 #'markdown-pipe-at-bol-p nil t)
9858 ;; Indentation
9859 (setq-local indent-line-function markdown-indent-function)
9861 ;; Flyspell
9862 (setq-local flyspell-generic-check-word-predicate
9863 #'markdown-flyspell-check-word-p)
9865 ;; Electric quoting
9866 (add-hook 'electric-quote-inhibit-functions
9867 #'markdown--inhibit-electric-quote nil :local)
9869 ;; Backwards compatibility with markdown-css-path
9870 (when (boundp 'markdown-css-path)
9871 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9872 (add-to-list 'markdown-css-paths markdown-css-path))
9874 ;; Prepare hooks for XEmacs compatibility
9875 (when (featurep 'xemacs)
9876 (make-local-hook 'after-change-functions)
9877 (make-local-hook 'font-lock-extend-region-functions)
9878 (make-local-hook 'window-configuration-change-hook))
9880 ;; Make checkboxes buttons
9881 (when markdown-make-gfm-checkboxes-buttons
9882 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9883 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9884 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9886 ;; edit-indirect
9887 (add-hook 'edit-indirect-after-commit-functions
9888 #'markdown--edit-indirect-after-commit-function
9889 nil 'local)
9891 ;; Marginalized headings
9892 (when markdown-marginalize-headers
9893 (add-hook 'window-configuration-change-hook
9894 #'markdown-marginalize-update-current nil t))
9896 ;; add live preview export hook
9897 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9898 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9900 ;;;###autoload
9901 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9902 ;;;###autoload
9903 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9906 ;;; GitHub Flavored Markdown Mode ============================================
9908 (defvar gfm-mode-hook nil
9909 "Hook run when entering GFM mode.")
9911 (defvar gfm-font-lock-keywords
9912 ;; Basic Markdown features (excluding possibly overridden ones)
9913 markdown-mode-font-lock-keywords-basic
9914 "Default highlighting expressions for GitHub Flavored Markdown mode.")
9916 ;;;###autoload
9917 (define-derived-mode gfm-mode markdown-mode "GFM"
9918 "Major mode for editing GitHub Flavored Markdown files."
9919 (setq markdown-link-space-sub-char "-")
9920 (setq markdown-wiki-link-search-subdirectories t)
9921 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
9922 ;; do the initial link fontification
9923 (markdown-gfm-parse-buffer-for-languages))
9926 ;;; Live Preview Mode ============================================
9927 (define-minor-mode markdown-live-preview-mode
9928 "Toggle native previewing on save for a specific markdown file."
9929 :lighter " MD-Preview"
9930 (if markdown-live-preview-mode
9931 (if (markdown-live-preview-get-filename)
9932 (markdown-display-buffer-other-window (markdown-live-preview-export))
9933 (markdown-live-preview-mode -1)
9934 (user-error "Buffer %s does not visit a file" (current-buffer)))
9935 (markdown-live-preview-remove)))
9938 (provide 'markdown-mode)
9940 ;; Local Variables:
9941 ;; indent-tabs-mode: nil
9942 ;; coding: utf-8
9943 ;; End:
9944 ;;; markdown-mode.el ends here