Insert references before local variables
[markdown-mode.git] / markdown-mode.el
blob37a03e54428c54468bc8e29f27d8e783bec23124
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).
401 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
403 ;; Headings, horizontal rules, and list items can be promoted and
404 ;; demoted, as well as bold and italic text. For headings,
405 ;; "promotion" means *decreasing* the level (i.e., moving from
406 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
407 ;; level. For horizontal rules, promotion and demotion means
408 ;; moving backward or forward through the list of rule strings in
409 ;; `markdown-hr-strings'. For bold and italic text, promotion and
410 ;; demotion means changing the markup from underscores to asterisks.
411 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
412 ;; if possible.
414 ;; To remember these commands, note that `-` is for decreasing the
415 ;; level (promoting), and `=` (on the same key as `+`) is for
416 ;; increasing the level (demoting). Similarly, the left and right
417 ;; arrow keys indicate the direction that the atx heading markup
418 ;; is moving in when promoting or demoting.
420 ;; * Completion: `C-c C-]`
422 ;; Complete markup is in normalized form, which means, for
423 ;; example, that the underline portion of a setext header is the
424 ;; same length as the heading text, or that the number of leading
425 ;; and trailing hash marks of an atx header are equal and that
426 ;; there is no extra whitespace in the header text. `C-c C-]`
427 ;; completes the markup at the point, if it is determined to be
428 ;; incomplete.
430 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
432 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
433 ;; command determines the appropriate marker (one of the possible
434 ;; unordered list markers or the next number in sequence for an
435 ;; ordered list) and indentation level by examining nearby list
436 ;; items. If there is no list before or after the point, start a
437 ;; new list. As with heading insertion, you may prefix this
438 ;; command by `C-u` to decrease the indentation by one level.
439 ;; Prefix this command by `C-u C-u` to increase the indentation by
440 ;; one level.
442 ;; Existing list items (and their nested sub-items) can be moved
443 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
444 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
446 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
448 ;; Entire subtrees of ATX headings can be promoted and demoted
449 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
450 ;; used for promotion and demotion of list items. If the point is in
451 ;; a list item, the operate on the list item. Otherwise, they operate
452 ;; on the current heading subtree. Similarly, subtrees can be
453 ;; moved up and down with `C-c UP` and `C-c DOWN`.
455 ;; These commands currently do not work properly if there are
456 ;; Setext headings in the affected region.
458 ;; Please note the following "boundary" behavior for promotion and
459 ;; demotion. Any level-six headings will not be demoted further
460 ;; (i.e., they remain at level six, since Markdown and HTML define
461 ;; only six levels) and any level-one headings will promoted away
462 ;; entirely (i.e., heading markup will be removed, since a
463 ;; level-zero heading is not defined).
465 ;; * Shifting the Region: `C-c <` and `C-c >`
467 ;; Text in the region can be indented or outdented as a group using
468 ;; `C-c >` to indent to the next indentation point (calculated in
469 ;; the current context), and `C-c <` to outdent to the previous
470 ;; indentation point. These keybindings are the same as those for
471 ;; similar commands in `python-mode'.
473 ;; * Killing Elements: `C-c C-k`
475 ;; Press `C-c C-k` to kill the thing at point and add important
476 ;; text, without markup, to the kill ring. Possible things to
477 ;; kill include (roughly in order of precedece): inline code,
478 ;; headings, horizonal rules, links (add link text to kill ring),
479 ;; images (add alt text to kill ring), angle URIs, email
480 ;; addresses, bold, italics, reference definitions (add URI to
481 ;; kill ring), footnote markers and text (kill both marker and
482 ;; text, add text to kill ring), and list items.
484 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
486 ;; These keys are used for hierarchical navigation in lists and
487 ;; headings. When the point is in a list, they move between list
488 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
489 ;; `C-c C-p` to move between the next and previous visible
490 ;; headings or list items of any level. Similarly, `C-c C-f` and
491 ;; `C-c C-b` move to the next and previous visible headings or
492 ;; list items at the same level as the one at the point. Finally,
493 ;; `C-c C-u` will move up to the parent heading or list item.
495 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
497 ;; Paragraphs in `markdown-mode' are regular paragraphs,
498 ;; paragraphs inside blockquotes, individual list items, headings,
499 ;; etc. These keys are usually bound to `forward-paragraph' and
500 ;; `backward-paragraph', but the built-in Emacs functions are
501 ;; based on simple regular expressions that fail in Markdown
502 ;; files. Instead, they are bound to `markdown-forward-paragraph'
503 ;; and `markdown-backward-paragraph'. To mark a paragraph,
504 ;; you can use `M-h` (`markdown-mark-paragraph').
506 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
508 ;; Markdown blocks are regular paragraphs in many cases, but
509 ;; contain many paragraphs in other cases: blocks are considered
510 ;; to be entire lists, entire code blocks, and entire blockquotes.
511 ;; To move backward one block use `C-M-{`
512 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
513 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
514 ;; (`markdown-mark-block`).
516 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
518 ;; The usual Emacs commands can be used to move by defuns
519 ;; (top-level major definitions). In markdown-mode, a defun is a
520 ;; section. As usual, `C-M-a` will move the point to the
521 ;; beginning of the current or preceding defun, `C-M-e` will move
522 ;; to the end of the current or following defun, and `C-M-h` will
523 ;; put the region around the entire defun.
525 ;; * Miscellaneous Commands:
527 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
528 ;; (`markdown-edit-code-block`) can be used to edit a code block
529 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
530 ;; to commit changes and return or `C-c C-k` to cancel.
532 ;; As noted, many of the commands above behave differently depending
533 ;; on whether Transient Mark mode is enabled or not. When it makes
534 ;; sense, if Transient Mark mode is on and the region is active, the
535 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
536 ;; region bold). For users who prefer to work outside of Transient
537 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
538 ;; `C-SPC C-SPC`. When this is not the case, many commands then
539 ;; proceed to look work with the word or line at the point.
541 ;; When applicable, commands that specifically act on the region even
542 ;; outside of Transient Mark mode have the same keybinding as their
543 ;; standard counterpart, but the letter is uppercase. For example,
544 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
545 ;; the region in Transient Mark mode while `markdown-blockquote-region'
546 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
548 ;; Note that these region-specific functions are useful in many
549 ;; cases where it may not be obvious. For example, yanking text from
550 ;; the kill ring sets the mark at the beginning of the yanked text
551 ;; and moves the point to the end. Therefore, the (inactive) region
552 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
553 ;; yank text and turn it into a blockquote.
555 ;; markdown-mode attempts to be flexible in how it handles
556 ;; indentation. When you press `TAB` repeatedly, the point will cycle
557 ;; through several possible indentation levels corresponding to things
558 ;; you might have in mind when you press `RET` at the end of a line or
559 ;; `TAB`. For example, you may want to start a new list item,
560 ;; continue a list item with hanging indentation, indent for a nested
561 ;; pre block, and so on. Outdenting is handled similarly when backspace
562 ;; is pressed at the beginning of the non-whitespace portion of a line.
564 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
565 ;; visibility cycling for atx- or hash-style headings. There are two
566 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
567 ;; the table of contents view (headings only), outline view (top-level
568 ;; headings only), and the full document view. Pressing `TAB` while the
569 ;; point is at a heading will cycle through levels of visibility for the
570 ;; subtree: completely folded, visible children, and fully visible.
571 ;; Note that mixing hash and underline style headings will give undesired
572 ;; results.
574 ;;; Customization:
576 ;; Although no configuration is *necessary* there are a few things
577 ;; that can be customized. The `M-x customize-mode` command
578 ;; provides an interface to all of the possible customizations:
580 ;; * `markdown-command' - the command used to run Markdown (default:
581 ;; `markdown`). This variable may be customized to pass
582 ;; command-line options to your Markdown processor of choice. It can
583 ;; also be a function; in this case `markdown' will call it with three
584 ;; arguments: the beginning and end of the region to process, and
585 ;; a buffer to write the output to.
587 ;; * `markdown-command-needs-filename' - set to `t' if
588 ;; `markdown-command' does not accept standard input (default:
589 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
590 ;; content to `markdown-command' using standard input (`stdin`).
591 ;; When set to `t', `markdown-mode' will pass the name of the file
592 ;; as the final command-line argument to `markdown-command'. Note
593 ;; that in the latter case, you will only be able to run
594 ;; `markdown-command' from buffers which are visiting a file. If
595 ;; `markdown-command' is a function, `markdown-command-needs-filename'
596 ;; is ignored.
598 ;; * `markdown-open-command' - the command used for calling a standalone
599 ;; Markdown previewer which is capable of opening Markdown source files
600 ;; directly (default: `nil'). This command will be called
601 ;; with a single argument, the filename of the current buffer.
602 ;; A representative program is the Mac app [Marked 2][], a
603 ;; live-updating Markdown previewer which can be [called from a
604 ;; simple shell script](https://jblevins.org/log/marked-2-command).
605 ;; This variable can also be a function; in this case `markdown-open'
606 ;; will call it without arguments to preview the current buffer.
608 ;; * `markdown-hr-strings' - list of strings to use when inserting
609 ;; horizontal rules. Different strings will not be distinguished
610 ;; when converted to HTML--they will all be converted to
611 ;; `<hr/>`--but they may add visual distinction and style to plain
612 ;; text documents. To maintain some notion of promotion and
613 ;; demotion, keep these sorted from largest to smallest.
615 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
616 ;; underscores when inserting bold text instead of two asterisks
617 ;; (default: `nil').
619 ;; * `markdown-italic-underscore' - set to a non-nil value to use
620 ;; underscores when inserting italic text instead of asterisks
621 ;; (default: `nil').
623 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
624 ;; asymmetric header styling, placing header characters only on
625 ;; the left of headers (default: `nil').
627 ;; * `markdown-header-scaling' - set to a non-nil value to use
628 ;; a variable-pitch font for headings where the size corresponds
629 ;; to the level of the heading (default: `nil').
631 ;; * `markdown-header-scaling-values' - list of scaling values,
632 ;; relative to baseline, for headers of levels one through six,
633 ;; used when `markdown-header-scaling' is non-nil
634 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
636 ;; * `markdown-list-indent-width' - depth of indentation for lists
637 ;; when inserting, promoting, and demoting list items (default: 4).
639 ;; * `markdown-indent-function' - the function to use for automatic
640 ;; indentation (default: `markdown-indent-line').
642 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
643 ;; automatically indent new lines when `RET' is pressed.
644 ;; Set to `indent-and-new-item' to additionally continue lists
645 ;; when `RET' is pressed (default: `t').
647 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
648 ;; links (default: `nil'). Set this to a non-nil value to turn on
649 ;; wiki link support by default. Wiki link support can be toggled
650 ;; later using the function `markdown-toggle-wiki-links'."
652 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
653 ;; treat aliased wiki links like `[[link text|PageName]]`
654 ;; (default: `t'). When set to nil, they will be treated as
655 ;; `[[PageName|link text]]'.
657 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
658 ;; for URIs that `markdown-mode' should highlight.
660 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
661 ;; math expressions (default: `nil'). Set this to `t' to turn on
662 ;; math support by default. Math support can be toggled
663 ;; interactively later using `C-c C-x C-e`
664 ;; (`markdown-toggle-math').
666 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
667 ;; (default: `nil`).
669 ;; * `markdown-content-type' - when set to a nonempty string, an
670 ;; `http-equiv` attribute will be included in the XHTML `<head>`
671 ;; block (default: `""`). If needed, the suggested values are
672 ;; `application/xhtml+xml` or `text/html`. See also:
673 ;; `markdown-coding-system'.
675 ;; * `markdown-coding-system' - used for specifying the character
676 ;; set identifier in the `http-equiv` attribute when included
677 ;; (default: `nil'). See `markdown-content-type', which must
678 ;; be set before this variable has any effect. When set to `nil',
679 ;; `buffer-file-coding-system' will be used to automatically
680 ;; determine the coding system string (falling back to
681 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
682 ;; and `iso-latin-1'.
684 ;; * `markdown-xhtml-header-content' - additional content to include
685 ;; in the XHTML `<head>` block (default: `""`).
687 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
688 ;; `markdown-mode' uses to determine whether the output of
689 ;; `markdown-command' is a standalone XHTML document or an XHTML
690 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
691 ;; this regular expression not matched in the first five lines of
692 ;; output, `markdown-mode' assumes the output is a fragment and
693 ;; adds a header and footer.
695 ;; * `markdown-link-space-sub-char' - a character to replace spaces
696 ;; when mapping wiki links to filenames (default: `"_"`).
697 ;; For example, use an underscore for compatibility with the
698 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
699 ;; set to `"-"` to conform with GitHub wiki links.
701 ;; * `markdown-reference-location' - where to insert reference
702 ;; definitions (default: `header`). The possible locations are
703 ;; the end of the document (`end`), after the current block
704 ;; (`immediately`), the end of the current subtree (`subtree'),
705 ;; or before the next header (`header`).
707 ;; * `markdown-footnote-location' - where to insert footnote text
708 ;; (default: `end`). The set of location options is the same as
709 ;; for `markdown-reference-location'.
711 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
712 ;; heading instead of a flat index (default: `t'). A nested
713 ;; index may provide more natural browsing from the menu, but a
714 ;; flat list may allow for faster keyboard navigation via tab
715 ;; completion.
717 ;; * `comment-auto-fill-only-comments' - variable is made
718 ;; buffer-local and set to `nil' by default. In programming
719 ;; language modes, when this variable is non-nil, only comments
720 ;; will be filled by auto-fill-mode. However, comments in
721 ;; Markdown documents are rare and the most users probably intend
722 ;; for the actual content of the document to be filled. Making
723 ;; this variable buffer-local allows `markdown-mode' to override
724 ;; the default behavior induced when the global variable is non-nil.
726 ;; * `markdown-gfm-additional-languages', - additional languages to
727 ;; make available, aside from those predefined in
728 ;; `markdown-gfm-recognized-languages', when inserting GFM code
729 ;; blocks (default: `nil`). Language strings must have be trimmed
730 ;; of whitespace and not contain any curly braces. They may be of
731 ;; arbitrary capitalization, though.
733 ;; * `markdown-gfm-use-electric-backquote' - use
734 ;; `markdown-electric-backquote' for interactive insertion of GFM
735 ;; code blocks when backquote is pressed three times (default: `t`).
737 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
738 ;; Flavored Markdown style task lists (checkboxes) should be
739 ;; turned into buttons that can be toggled with mouse-1 or RET. If
740 ;; non-nil (default), then buttons are enabled. This works in
741 ;; `markdown-mode' as well as `gfm-mode'.
743 ;; * `markdown-hide-urls' - Determines whether URL and reference
744 ;; labels are hidden for inline and reference links (default: `nil').
745 ;; When non-nil, inline links will appear in the buffer as
746 ;; `[link](∞)` instead of
747 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
748 ;; placeholder (composition) character used, set the variable
749 ;; `markdown-url-compose-char'. URL hiding can be toggled
750 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
751 ;; or from the Markdown | Links & Images menu.
753 ;; * `markdown-hide-markup' - Determines whether all possible markup
754 ;; is hidden or otherwise beautified (default: `nil'). The actual
755 ;; buffer text remains unchanged, but the display will be altered.
756 ;; Brackets and URLs for links will be hidden, asterisks and
757 ;; underscores for italic and bold text will be hidden, text
758 ;; bullets for unordered lists will be replaced by Unicode
759 ;; bullets, and so on. Since this includes URLs and reference
760 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
761 ;; Markup hiding can be toggled using `C-c C-x C-m`
762 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
763 ;; Hide menu.
765 ;; Unicode bullets are used to replace ASCII list item markers.
766 ;; The list of characters used, in order of list level, can be
767 ;; specified by setting the variable `markdown-list-item-bullets'.
768 ;; The placeholder characters used to replace other markup can
769 ;; be changed by customizing the corresponding variables:
770 ;; `markdown-blockquote-display-char',
771 ;; `markdown-hr-display-char', and
772 ;; `markdown-definition-display-char'.
774 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
775 ;; code in code blocks using the native major mode. This only
776 ;; works for fenced code blocks where the language is specified
777 ;; where we can automatically determine the appropriate mode to
778 ;; use. The language to mode mapping may be customized by setting
779 ;; the variable `markdown-code-lang-modes'. This can be toggled
780 ;; interactively by pressing `C-c C-x C-f`
781 ;; (`markdown-toggle-fontify-code-blocks-natively').
783 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
784 ;; task list items with `[X]` instead of `[x]` (default: `nil').
785 ;; This is useful for compatibility with `org-mode', which doesn't
786 ;; recognize the lowercase variant.
788 ;; Additionally, the faces used for syntax highlighting can be modified to
789 ;; your liking by issuing `M-x customize-group RET markdown-faces`
790 ;; or by using the "Markdown Faces" link at the bottom of the mode
791 ;; customization screen.
793 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
795 ;;; Extensions:
797 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
798 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
799 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
800 ;; Wiki links may be followed by pressing `C-c C-o` when the point
801 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
802 ;; previous and next links (including links of other types).
803 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
804 ;; are also supported. Since some wikis reverse these components, set
805 ;; `markdown-wiki-link-alias-first' to nil to treat them as
806 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
807 ;; is also non-nil, Markdown Mode will highlight wiki links with
808 ;; missing target file in a different color. By default, Markdown
809 ;; Mode only searches for target files in the current directory.
810 ;; Search in subdirectories can be enabled by setting
811 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
812 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
813 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
814 ;; to a non-nil value.
816 ;; [Ikiwiki]: https://ikiwiki.info
818 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
819 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
820 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
821 ;; You can do this either by using `M-x customize-group markdown`
822 ;; or by placing the following in your `.emacs` file:
824 ;; ``` Lisp
825 ;; (setq markdown-command "markdown | smartypants")
826 ;; ```
828 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
830 ;; Syntax highlighting for mathematical expressions written
831 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
832 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
833 ;; either via customize or by placing `(setq markdown-enable-math t)`
834 ;; in `.emacs`, and then restarting Emacs or calling
835 ;; `markdown-reload-extensions'.
837 ;;; GitHub Flavored Markdown (GFM):
839 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
840 ;; available. The GitHub implementation differs slightly from
841 ;; standard Markdown in that it supports things like different
842 ;; behavior for underscores inside of words, automatic linking of
843 ;; URLs, strikethrough text, and fenced code blocks with an optional
844 ;; language keyword.
846 ;; The GFM-specific features above apply to `README.md` files, wiki
847 ;; pages, and other Markdown-formatted files in repositories on
848 ;; GitHub. GitHub also enables [additional features][GFM comments] for
849 ;; writing on the site (for issues, pull requests, messages, etc.)
850 ;; that are further extensions of GFM. These features include task
851 ;; lists (checkboxes), newlines corresponding to hard line breaks,
852 ;; auto-linked references to issues and commits, wiki links, and so
853 ;; on. To make matters more confusing, although task lists are not
854 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
855 ;; read-only fashion) in all Markdown documents in repositories on the
856 ;; site. These additional extensions are supported to varying degrees
857 ;; by `markdown-mode' and `gfm-mode' as described below.
859 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
860 ;; highlighting of URLs without angle brackets.
862 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
863 ;; toggle support for underscores inside of words. In this mode
864 ;; variable names such as `a_test_variable` will not trigger
865 ;; emphasis (italics).
867 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
868 ;; optional programming language keywords, are highlighted in
869 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
870 ;; `C-c C-s C`. If there is an active region, the text in the
871 ;; region will be placed inside the code block. You will be
872 ;; prompted for the name of the language, but may press enter to
873 ;; continue without naming a language.
875 ;; * **Strikethrough:** Strikethrough text is supported in both
876 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
877 ;; using `C-c C-s s`.
879 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
880 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
881 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
882 ;; (and it is set to t by default). These checkboxes can be
883 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
884 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
885 ;; in the task list item.
887 ;; * **Wiki links:** Generic wiki links are supported in
888 ;; `markdown-mode', but in `gfm-mode' specifically they will be
889 ;; treated as they are on GitHub: spaces will be replaced by hyphens
890 ;; in filenames and the first letter of the filename will be
891 ;; capitalized. For example, `[[wiki link]]' will map to a file
892 ;; named `Wiki-link` with the same extension as the current file.
893 ;; If a file with this name does not exist in the current directory,
894 ;; the first match in a subdirectory, if any, will be used instead.
896 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
897 ;; specifically with respect to newline behavior. If you use
898 ;; `gfm-mode' mostly to write text for comments or issues on the
899 ;; GitHub site--where newlines are significant and correspond to
900 ;; hard line breaks--then you may want to enable `visual-line-mode'
901 ;; for line wrapping in buffers. You can do this with a
902 ;; `gfm-mode-hook' as follows:
904 ;; ``` Lisp
905 ;; ;; Use visual-line-mode in gfm-mode
906 ;; (defun my-gfm-mode-hook ()
907 ;; (visual-line-mode 1))
908 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
909 ;; ```
911 ;; * **Preview:** GFM-specific preview can be powered by setting
912 ;; `markdown-command' to use [Docter][]. This may also be
913 ;; configured to work with [Marked 2][] for `markdown-open-command'.
915 ;; [GFM]: http://github.github.com/github-flavored-markdown/
916 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
917 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
918 ;; [Docter]: https://github.com/alampros/Docter
920 ;;; Acknowledgments:
922 ;; markdown-mode has benefited greatly from the efforts of the many
923 ;; volunteers who have sent patches, test cases, bug reports,
924 ;; suggestions, helped with packaging, etc. Thank you for your
925 ;; contributions! See the [contributors graph][contrib] for details.
927 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
929 ;;; Bugs:
931 ;; markdown-mode is developed and tested primarily for compatibility
932 ;; with GNU Emacs 24.3 and later. If you find any bugs in
933 ;; markdown-mode, please construct a test case or a patch and open a
934 ;; ticket on the [GitHub issue tracker][issues]. See the
935 ;; contributing guidelines in `CONTRIBUTING.md` for details on
936 ;; creating pull requests.
938 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
940 ;;; History:
942 ;; markdown-mode was written and is maintained by Jason Blevins. The
943 ;; first version was released on May 24, 2007.
945 ;; * 2007-05-24: [Version 1.1][]
946 ;; * 2007-05-25: [Version 1.2][]
947 ;; * 2007-06-05: [Version 1.3][]
948 ;; * 2007-06-29: [Version 1.4][]
949 ;; * 2007-10-11: [Version 1.5][]
950 ;; * 2008-06-04: [Version 1.6][]
951 ;; * 2009-10-01: [Version 1.7][]
952 ;; * 2011-08-12: [Version 1.8][]
953 ;; * 2011-08-15: [Version 1.8.1][]
954 ;; * 2013-01-25: [Version 1.9][]
955 ;; * 2013-03-24: [Version 2.0][]
956 ;; * 2016-01-09: [Version 2.1][]
957 ;; * 2017-05-26: [Version 2.2][]
958 ;; * 2017-08-31: [Version 2.3][]
960 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
961 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
962 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
963 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
964 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
965 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
966 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
967 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
968 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
969 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
970 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
971 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
972 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
973 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
976 ;;; Code:
978 (require 'easymenu)
979 (require 'outline)
980 (require 'thingatpt)
981 (require 'cl-lib)
982 (require 'url-parse)
983 (require 'button)
984 (require 'color)
985 (require 'rx)
987 (defvar jit-lock-start)
988 (defvar jit-lock-end)
989 (defvar flyspell-generic-check-word-predicate)
991 (declare-function eww-open-file "eww")
992 (declare-function url-path-and-query "url-parse")
995 ;;; Constants =================================================================
997 (defconst markdown-mode-version "2.4-dev"
998 "Markdown mode version number.")
1000 (defconst markdown-output-buffer-name "*markdown-output*"
1001 "Name of temporary buffer for markdown command output.")
1003 (defconst markdown-sub-superscript-display
1004 '(((raise -0.3) (height 0.7)) ; subscript
1005 ((raise 0.3) (height 0.7))) ; superscript
1006 "Parameters for sub- and superscript formatting.")
1009 ;;; Global Variables ==========================================================
1011 (defvar markdown-reference-label-history nil
1012 "History of used reference labels.")
1014 (defvar markdown-live-preview-mode nil
1015 "Sentinel variable for command `markdown-live-preview-mode'.")
1017 (defvar markdown-gfm-language-history nil
1018 "History list of languages used in the current buffer in GFM code blocks.")
1021 ;;; Customizable Variables ====================================================
1023 (defvar markdown-mode-hook nil
1024 "Hook run when entering Markdown mode.")
1026 (defvar markdown-before-export-hook nil
1027 "Hook run before running Markdown to export XHTML output.
1028 The hook may modify the buffer, which will be restored to it's
1029 original state after exporting is complete.")
1031 (defvar markdown-after-export-hook nil
1032 "Hook run after XHTML output has been saved.
1033 Any changes to the output buffer made by this hook will be saved.")
1035 (defgroup markdown nil
1036 "Major mode for editing text files in Markdown format."
1037 :prefix "markdown-"
1038 :group 'wp
1039 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1041 (defcustom markdown-command "markdown"
1042 "Command to run markdown."
1043 :group 'markdown
1044 :type '(choice (string :tag "Shell command") function))
1046 (defcustom markdown-command-needs-filename nil
1047 "Set to non-nil if `markdown-command' does not accept input from stdin.
1048 Instead, it will be passed a filename as the final command line
1049 option. As a result, you will only be able to run Markdown from
1050 buffers which are visiting a file."
1051 :group 'markdown
1052 :type 'boolean)
1054 (defcustom markdown-open-command nil
1055 "Command used for opening Markdown files directly.
1056 For example, a standalone Markdown previewer. This command will
1057 be called with a single argument: the filename of the current
1058 buffer. It can also be a function, which will be called without
1059 arguments."
1060 :group 'markdown
1061 :type '(choice file function (const :tag "None" nil)))
1063 (defcustom markdown-hr-strings
1064 '("-------------------------------------------------------------------------------"
1065 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1066 "---------------------------------------"
1067 "* * * * * * * * * * * * * * * * * * * *"
1068 "---------"
1069 "* * * * *")
1070 "Strings to use when inserting horizontal rules.
1071 The first string in the list will be the default when inserting a
1072 horizontal rule. Strings should be listed in decreasing order of
1073 prominence (as in headings from level one to six) for use with
1074 promotion and demotion functions."
1075 :group 'markdown
1076 :type '(repeat string))
1078 (defcustom markdown-bold-underscore nil
1079 "Use two underscores when inserting bold text instead of two asterisks."
1080 :group 'markdown
1081 :type 'boolean)
1083 (defcustom markdown-italic-underscore nil
1084 "Use underscores when inserting italic text instead of asterisks."
1085 :group 'markdown
1086 :type 'boolean)
1088 (defcustom markdown-asymmetric-header nil
1089 "Determines if atx header style will be asymmetric.
1090 Set to a non-nil value to use asymmetric header styling, placing
1091 header markup only at the beginning of the line. By default,
1092 balanced markup will be inserted at the beginning and end of the
1093 line around the header title."
1094 :group 'markdown
1095 :type 'boolean)
1097 (defcustom markdown-indent-function 'markdown-indent-line
1098 "Function to use to indent."
1099 :group 'markdown
1100 :type 'function)
1102 (defcustom markdown-indent-on-enter t
1103 "Determines indentation behavior when pressing \\[newline].
1104 Possible settings are nil, t, and 'indent-and-new-item.
1106 When non-nil, pressing \\[newline] will call `newline-and-indent'
1107 to indent the following line according to the context using
1108 `markdown-indent-function'. In this case, note that
1109 \\[electric-newline-and-maybe-indent] can still be used to insert
1110 a newline without indentation.
1112 When set to 'indent-and-new-item and the point is in a list item
1113 when \\[newline] is pressed, the list will be continued on the next
1114 line, where a new item will be inserted.
1116 When set to nil, simply call `newline' as usual. In this case,
1117 you can still indent lines using \\[markdown-cycle] and continue
1118 lists with \\[markdown-insert-list-item].
1120 Note that this assumes the variable `electric-indent-mode' is
1121 non-nil (enabled). When it is *disabled*, the behavior of
1122 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1123 reversed."
1124 :group 'markdown
1125 :type '(choice (const :tag "Don't automatically indent" nil)
1126 (const :tag "Automatically indent" t)
1127 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1129 (defcustom markdown-enable-wiki-links nil
1130 "Syntax highlighting for wiki links.
1131 Set this to a non-nil value to turn on wiki link support by default.
1132 Support can be toggled later using the `markdown-toggle-wiki-links'
1133 function or \\[markdown-toggle-wiki-links]."
1134 :group 'markdown
1135 :type 'boolean
1136 :safe 'booleanp
1137 :package-version '(markdown-mode . "2.2"))
1139 (defcustom markdown-wiki-link-alias-first t
1140 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1141 Otherwise, they will be treated as [[PageName|alias text]]."
1142 :group 'markdown
1143 :type 'boolean
1144 :safe 'booleanp)
1146 (defcustom markdown-wiki-link-search-subdirectories nil
1147 "When non-nil, search for wiki link targets in subdirectories.
1148 This is the default search behavior for GitHub and is
1149 automatically set to t in `gfm-mode'."
1150 :group 'markdown
1151 :type 'boolean
1152 :safe 'booleanp
1153 :package-version '(markdown-mode . "2.2"))
1155 (defcustom markdown-wiki-link-search-parent-directories nil
1156 "When non-nil, search for wiki link targets in parent directories.
1157 This is the default search behavior of Ikiwiki."
1158 :group 'markdown
1159 :type 'boolean
1160 :safe 'booleanp
1161 :package-version '(markdown-mode . "2.2"))
1163 (defcustom markdown-wiki-link-fontify-missing nil
1164 "When non-nil, change wiki link face according to existence of target files.
1165 This is expensive because it requires checking for the file each time the buffer
1166 changes or the user switches windows. It is disabled by default because it may
1167 cause lag when typing on slower machines."
1168 :group 'markdown
1169 :type 'boolean
1170 :safe 'booleanp
1171 :package-version '(markdown-mode . "2.2"))
1173 (defcustom markdown-uri-types
1174 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1175 "gopher" "http" "https" "imap" "ldap" "mailto"
1176 "mid" "message" "modem" "news" "nfs" "nntp"
1177 "pop" "prospero" "rtsp" "service" "sip" "tel"
1178 "telnet" "tip" "urn" "vemmi" "wais")
1179 "Link types for syntax highlighting of URIs."
1180 :group 'markdown
1181 :type '(repeat (string :tag "URI scheme")))
1183 (defcustom markdown-url-compose-char
1184 (cond
1185 ((char-displayable-p ?∞) ?∞)
1186 ((char-displayable-p ?…) ?…)
1187 (t ?#))
1188 "Placeholder character for hidden URLs.
1189 Depending on your font, some good choices are …, ⋯, #, ∞, ★, and ⚓."
1190 :type 'character
1191 :safe 'characterp
1192 :package-version '(markdown-mode . "2.3"))
1194 (defcustom markdown-blockquote-display-char
1195 (cond
1196 ((char-displayable-p ?▌) "▌")
1197 ((char-displayable-p ?┃) "┃")
1198 ((char-displayable-p ?│) "│")
1199 ((char-displayable-p ?|) "|")
1200 (t ">"))
1201 "Character for hiding blockquote markup."
1202 :type 'string
1203 :safe 'stringp
1204 :package-version '(markdown-mode . "2.3"))
1206 (defcustom markdown-hr-display-char
1207 (cond ((char-displayable-p ?─) ?─)
1208 ((char-displayable-p ?━) ?━)
1209 (t ?-))
1210 "Character for hiding horizontal rule markup."
1211 :type 'character
1212 :safe 'characterp
1213 :package-version '(markdown-mode . "2.3"))
1215 (defcustom markdown-definition-display-char
1216 (cond ((char-displayable-p ?⁘) ?⁘)
1217 ((char-displayable-p ?⁙) ?⁙)
1218 ((char-displayable-p ?≡) ?≡)
1219 ((char-displayable-p ?⌑) ?⌑)
1220 ((char-displayable-p ?◊) ?◊)
1221 (t nil))
1222 "Character for replacing definition list markup."
1223 :type 'character
1224 :safe 'characterp
1225 :package-version '(markdown-mode . "2.3"))
1227 (defcustom markdown-enable-math nil
1228 "Syntax highlighting for inline LaTeX and itex expressions.
1229 Set this to a non-nil value to turn on math support by default.
1230 Math support can be enabled, disabled, or toggled later using
1231 `markdown-toggle-math' or \\[markdown-toggle-math]."
1232 :group 'markdown
1233 :type 'boolean
1234 :safe 'booleanp)
1235 (make-variable-buffer-local 'markdown-enable-math)
1237 (defcustom markdown-css-paths nil
1238 "URL of CSS file to link to in the output XHTML."
1239 :group 'markdown
1240 :type 'list)
1242 (defcustom markdown-content-type ""
1243 "Content type string for the http-equiv header in XHTML output.
1244 When set to a non-empty string, insert the http-equiv attribute.
1245 Otherwise, this attribute is omitted."
1246 :group 'markdown
1247 :type 'string)
1249 (defcustom markdown-coding-system nil
1250 "Character set string for the http-equiv header in XHTML output.
1251 Defaults to `buffer-file-coding-system' (and falling back to
1252 `iso-8859-1' when not available). Common settings are `utf-8'
1253 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1254 :group 'markdown
1255 :type 'coding-system)
1257 (defcustom markdown-xhtml-header-content ""
1258 "Additional content to include in the XHTML <head> block."
1259 :group 'markdown
1260 :type 'string)
1262 (defcustom markdown-xhtml-standalone-regexp
1263 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1264 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1265 :group 'markdown
1266 :type 'regexp)
1268 (defcustom markdown-link-space-sub-char "_"
1269 "Character to use instead of spaces when mapping wiki links to filenames."
1270 :group 'markdown
1271 :type 'string)
1273 (defcustom markdown-reference-location 'header
1274 "Position where new reference definitions are inserted in the document."
1275 :group 'markdown
1276 :type '(choice (const :tag "At the end of the document" end)
1277 (const :tag "Immediately after the current block" immediately)
1278 (const :tag "At the end of the subtree" subtree)
1279 (const :tag "Before next header" header)))
1281 (defcustom markdown-footnote-location 'end
1282 "Position where new footnotes are inserted in the document."
1283 :group 'markdown
1284 :type '(choice (const :tag "At the end of the document" end)
1285 (const :tag "Immediately after the current block" immediately)
1286 (const :tag "At the end of the subtree" subtree)
1287 (const :tag "Before next header" header)))
1289 (defcustom markdown-unordered-list-item-prefix " * "
1290 "String inserted before unordered list items."
1291 :group 'markdown
1292 :type 'string)
1294 (defcustom markdown-nested-imenu-heading-index t
1295 "Use nested or flat imenu heading index.
1296 A nested index may provide more natural browsing from the menu,
1297 but a flat list may allow for faster keyboard navigation via tab
1298 completion."
1299 :group 'markdown
1300 :type 'boolean
1301 :safe 'booleanp
1302 :package-version '(markdown-mode . "2.2"))
1304 (defcustom markdown-make-gfm-checkboxes-buttons t
1305 "When non-nil, make GFM checkboxes into buttons."
1306 :group 'markdown
1307 :type 'boolean)
1309 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1310 "When non-nil, allow YAML metadata anywhere in the document."
1311 :group 'markdown
1312 :type 'boolean)
1314 (defcustom markdown-split-window-direction 'any
1315 "Preference for splitting windows for static and live preview.
1316 The default value is 'any, which instructs Emacs to use
1317 `split-window-sensibly' to automatically choose how to split
1318 windows based on the values of `split-width-threshold' and
1319 `split-height-threshold' and the available windows. To force
1320 vertically split (left and right) windows, set this to 'vertical
1321 or 'right. To force horizontally split (top and bottom) windows,
1322 set this to 'horizontal or 'below."
1323 :group 'markdown
1324 :type '(choice (const :tag "Automatic" any)
1325 (const :tag "Right (vertical)" right)
1326 (const :tag "Below (horizontal)" below))
1327 :package-version '(markdown-mode . "2.2"))
1329 (defcustom markdown-live-preview-window-function
1330 'markdown-live-preview-window-eww
1331 "Function to display preview of Markdown output within Emacs.
1332 Function must update the buffer containing the preview and return
1333 the buffer."
1334 :group 'markdown
1335 :type 'function)
1337 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1338 "Delete exported HTML file when using `markdown-live-preview-export'.
1339 If set to 'delete-on-export, delete on every export. When set to
1340 'delete-on-destroy delete when quitting from command
1341 `markdown-live-preview-mode'. Never delete if set to nil."
1342 :group 'markdown
1343 :type '(choice
1344 (const :tag "Delete on every export" delete-on-export)
1345 (const :tag "Delete when quitting live preview" delete-on-destroy)
1346 (const :tag "Never delete" nil)))
1348 (defcustom markdown-list-indent-width 4
1349 "Depth of indentation for markdown lists.
1350 Used in `markdown-demote-list-item' and
1351 `markdown-promote-list-item'."
1352 :group 'markdown
1353 :type 'integer)
1355 (defcustom markdown-enable-prefix-prompts t
1356 "Display prompts for certain prefix commands.
1357 Set to nil to disable these prompts."
1358 :group 'markdown
1359 :type 'boolean
1360 :safe 'booleanp
1361 :package-version '(markdown-mode . "2.3"))
1363 (defcustom markdown-gfm-additional-languages nil
1364 "Extra languages made available when inserting GFM code blocks.
1365 Language strings must have be trimmed of whitespace and not
1366 contain any curly braces. They may be of arbitrary
1367 capitalization, though."
1368 :group 'markdown
1369 :type '(repeat (string :validate markdown-validate-language-string)))
1371 (defcustom markdown-gfm-use-electric-backquote t
1372 "Use `markdown-electric-backquote' when backquote is hit three times."
1373 :group 'markdown
1374 :type 'boolean)
1376 (defcustom markdown-gfm-downcase-languages t
1377 "If non-nil, downcase suggested languages.
1378 This applies to insertions done with
1379 `markdown-electric-backquote'."
1380 :group 'markdown
1381 :type 'boolean)
1383 (defcustom markdown-gfm-uppercase-checkbox nil
1384 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1385 :group 'markdown
1386 :type 'boolean
1387 :safe 'booleanp)
1389 (defcustom markdown-hide-urls nil
1390 "Hide URLs of inline links and reference tags of reference links.
1391 Such URLs will be replaced by a single customizable
1392 character (∞), or `markdown-url-compose-char', but are still part
1393 of the buffer. Links can be edited interactively with
1394 \\[markdown-insert-link] or, for example, by deleting the final
1395 parenthesis to remove the invisibility property. You can also
1396 hover your mouse pointer over the link text to see the URL.
1397 Set this to a non-nil value to turn this feature on by default.
1398 You can interactively set the value of this variable by calling
1399 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1400 or from the menu Markdown > Links & Images menu."
1401 :group 'markdown
1402 :type 'boolean
1403 :safe 'booleanp
1404 :package-version '(markdown-mode . "2.3"))
1405 (make-variable-buffer-local 'markdown-hide-urls)
1408 ;;; Regular Expressions =======================================================
1410 (defconst markdown-regex-comment-start
1411 "<!--"
1412 "Regular expression matches HTML comment opening.")
1414 (defconst markdown-regex-comment-end
1415 "--[ \t]*>"
1416 "Regular expression matches HTML comment closing.")
1418 (defconst markdown-regex-link-inline
1419 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1420 "Regular expression for a [text](file) or an image link ![text](file).
1421 Group 1 matches the leading exclamation point (optional).
1422 Group 2 matches the opening square bracket.
1423 Group 3 matches the text inside the square brackets.
1424 Group 4 matches the closing square bracket.
1425 Group 5 matches the opening parenthesis.
1426 Group 6 matches the URL.
1427 Group 7 matches the title (optional).
1428 Group 8 matches the closing parenthesis.")
1430 (defconst markdown-regex-link-reference
1431 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1432 "Regular expression for a reference link [text][id].
1433 Group 1 matches the leading exclamation point (optional).
1434 Group 2 matches the opening square bracket for the link text.
1435 Group 3 matches the text inside the square brackets.
1436 Group 4 matches the closing square bracket for the link text.
1437 Group 5 matches the opening square bracket for the reference label.
1438 Group 6 matches the reference label.
1439 Group 7 matches the closing square bracket for the reference label.")
1441 (defconst markdown-regex-reference-definition
1442 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1443 "Regular expression for a reference definition.
1444 Group 1 matches the opening square bracket.
1445 Group 2 matches the reference label.
1446 Group 3 matches the closing square bracket.
1447 Group 4 matches the colon.
1448 Group 5 matches the URL.
1449 Group 6 matches the title attribute (optional).")
1451 (defconst markdown-regex-footnote
1452 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1453 "Regular expression for a footnote marker [^fn].
1454 Group 1 matches the opening square bracket and carat.
1455 Group 2 matches only the label, without the surrounding markup.
1456 Group 3 matches the closing square bracket.")
1458 (defconst markdown-regex-header
1459 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1460 "Regexp identifying Markdown headings.
1461 Group 1 matches the text of a setext heading.
1462 Group 2 matches the underline of a level-1 setext heading.
1463 Group 3 matches the underline of a level-2 setext heading.
1464 Group 4 matches the opening hash marks of an atx heading and whitespace.
1465 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1466 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1468 (defconst markdown-regex-header-setext
1469 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1470 "Regular expression for generic setext-style (underline) headers.")
1472 (defconst markdown-regex-header-atx
1473 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1474 "Regular expression for generic atx-style (hash mark) headers.")
1476 (defconst markdown-regex-hr
1477 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1478 "Regular expression for matching Markdown horizontal rules.")
1480 (defconst markdown-regex-code
1481 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1482 "Regular expression for matching inline code fragments.
1484 Group 1 matches the entire code fragment including the backquotes.
1485 Group 2 matches the opening backquotes.
1486 Group 3 matches the code fragment itself, without backquotes.
1487 Group 4 matches the closing backquotes.
1489 The leading, unnumbered group ensures that the leading backquote
1490 character is not escaped.
1491 The last group, also unnumbered, requires that the character
1492 following the code fragment is not a backquote.
1493 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1494 but not two newlines in a row.")
1496 (defconst markdown-regex-kbd
1497 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1498 "Regular expression for matching <kbd> tags.
1499 Groups 1 and 3 match the opening and closing tags.
1500 Group 2 matches the key sequence.")
1502 (defconst markdown-regex-gfm-code-block-open
1503 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1504 "Regular expression matching opening of GFM code blocks.
1505 Group 1 matches the opening three backquotes and any following whitespace.
1506 Group 2 matches the opening brace (optional) and surrounding whitespace.
1507 Group 3 matches the language identifier (optional).
1508 Group 4 matches the info string (optional).
1509 Group 5 matches the closing brace (optional), whitespace, and newline.
1510 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1512 (defconst markdown-regex-gfm-code-block-close
1513 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1514 "Regular expression matching closing of GFM code blocks.
1515 Group 1 matches the closing three backquotes.
1516 Group 2 matches any whitespace and the final newline.")
1518 (defconst markdown-regex-pre
1519 "^\\( \\|\t\\).*$"
1520 "Regular expression for matching preformatted text sections.")
1522 (defconst markdown-regex-list
1523 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1524 "Regular expression for matching list items.")
1526 (defconst markdown-regex-bold
1527 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1528 "Regular expression for matching bold text.
1529 Group 1 matches the character before the opening asterisk or
1530 underscore, if any, ensuring that it is not a backslash escape.
1531 Group 2 matches the entire expression, including delimiters.
1532 Groups 3 and 5 matches the opening and closing delimiters.
1533 Group 4 matches the text inside the delimiters.")
1535 (defconst markdown-regex-italic
1536 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1537 "Regular expression for matching italic text.
1538 The leading unnumbered matches the character before the opening
1539 asterisk or underscore, if any, ensuring that it is not a
1540 backslash escape.
1541 Group 1 matches the entire expression, including delimiters.
1542 Groups 2 and 4 matches the opening and closing delimiters.
1543 Group 3 matches the text inside the delimiters.")
1545 (defconst markdown-regex-strike-through
1546 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1547 "Regular expression for matching strike-through text.
1548 Group 1 matches the character before the opening tilde, if any,
1549 ensuring that it is not a backslash escape.
1550 Group 2 matches the entire expression, including delimiters.
1551 Groups 3 and 5 matches the opening and closing delimiters.
1552 Group 4 matches the text inside the delimiters.")
1554 (defconst markdown-regex-gfm-italic
1555 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1556 "Regular expression for matching italic text in GitHub Flavored Markdown.
1557 Underscores in words are not treated as special.
1558 Group 1 matches the entire expression, including delimiters.
1559 Groups 2 and 4 matches the opening and closing delimiters.
1560 Group 3 matches the text inside the delimiters.")
1562 (defconst markdown-regex-blockquote
1563 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1564 "Regular expression for matching blockquote lines.
1565 Also accounts for a potential capital letter preceding the angle
1566 bracket, for use with Leanpub blocks (asides, warnings, info
1567 blocks, etc.).
1568 Group 1 matches the leading angle bracket.
1569 Group 2 matches the separating whitespace.
1570 Group 3 matches the text.")
1572 (defconst markdown-regex-line-break
1573 "[^ \n\t][ \t]*\\( \\)$"
1574 "Regular expression for matching line breaks.")
1576 (defconst markdown-regex-wiki-link
1577 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1578 "Regular expression for matching wiki links.
1579 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1580 wiki links of the form [[PageName|link text]].
1581 The meanings of the first and second components depend
1582 on the value of `markdown-wiki-link-alias-first'.
1584 Group 1 matches the entire link.
1585 Group 2 matches the opening square brackets.
1586 Group 3 matches the first component of the wiki link.
1587 Group 4 matches the pipe separator, when present.
1588 Group 5 matches the second component of the wiki link, when present.
1589 Group 6 matches the closing square brackets.")
1591 (defconst markdown-regex-uri
1592 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1593 "Regular expression for matching inline URIs.")
1595 (defconst markdown-regex-angle-uri
1596 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1597 "Regular expression for matching inline URIs in angle brackets.")
1599 (defconst markdown-regex-email
1600 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1601 "Regular expression for matching inline email addresses.")
1603 (defsubst markdown-make-regex-link-generic ()
1604 "Make regular expression for matching any recognized link."
1605 (concat "\\(?:" markdown-regex-link-inline
1606 (when markdown-enable-wiki-links
1607 (concat "\\|" markdown-regex-wiki-link))
1608 "\\|" markdown-regex-link-reference
1609 "\\|" markdown-regex-angle-uri "\\)"))
1611 (defconst markdown-regex-gfm-checkbox
1612 " \\(\\[[ xX]\\]\\) "
1613 "Regular expression for matching GFM checkboxes.
1614 Group 1 matches the text to become a button.")
1616 (defconst markdown-regex-block-separator
1617 "\n[\n\t\f ]*\n"
1618 "Regular expression for matching block boundaries.")
1620 (defconst markdown-regex-block-separator-noindent
1621 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1622 "Regexp for block separators before lines with no indentation.")
1624 (defconst markdown-regex-math-inline-single
1625 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1626 "Regular expression for itex $..$ math mode expressions.
1627 Groups 1 and 3 match the opening and closing dollar signs.
1628 Group 3 matches the mathematical expression contained within.")
1630 (defconst markdown-regex-math-inline-double
1631 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1632 "Regular expression for itex $$..$$ math mode expressions.
1633 Groups 1 and 3 match opening and closing dollar signs.
1634 Group 3 matches the mathematical expression contained within.")
1636 (defconst markdown-regex-math-display
1637 "^\\(\\\\\\[\\)\\(\\(?:.\\|\n\\)*?\\)?\\(\\\\\\]\\)$"
1638 "Regular expression for itex \[..\] display mode expressions.
1639 Groups 1 and 3 match the opening and closing delimiters.
1640 Group 2 matches the mathematical expression contained within.")
1642 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1643 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1644 END-OF-LINE is the regexp construct to indicate end of line; $ if
1645 missing."
1646 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1647 (or end-of-line "$")))
1649 (defconst markdown-regex-tilde-fence-begin
1650 (markdown-make-tilde-fence-regex
1651 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1652 "Regular expression for matching tilde-fenced code blocks.
1653 Group 1 matches the opening tildes.
1654 Group 2 matches (optional) opening brace and surrounding whitespace.
1655 Group 3 matches the language identifier (optional).
1656 Group 4 matches the info string (optional).
1657 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1658 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1660 (defconst markdown-regex-declarative-metadata
1661 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1662 "Regular expression for matching declarative metadata statements.
1663 This matches MultiMarkdown metadata as well as YAML and TOML
1664 assignments such as the following:
1666 variable: value
1670 variable = value")
1672 (defconst markdown-regex-pandoc-metadata
1673 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1674 "Regular expression for matching Pandoc metadata.")
1676 (defconst markdown-regex-yaml-metadata-border
1677 "\\(-\\{3\\}\\)$"
1678 "Regular expression for matching YAML metadata.")
1680 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1681 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1682 "Regular expression for matching YAML metadata end borders.")
1684 (defsubst markdown-get-yaml-metadata-start-border ()
1685 "Return YAML metadata start border depending upon whether Pandoc is used."
1686 (concat
1687 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1688 markdown-regex-yaml-metadata-border))
1690 (defsubst markdown-get-yaml-metadata-end-border (_)
1691 "Return YAML metadata end border depending upon whether Pandoc is used."
1692 (if markdown-use-pandoc-style-yaml-metadata
1693 markdown-regex-yaml-pandoc-metadata-end-border
1694 markdown-regex-yaml-metadata-border))
1696 (defconst markdown-regex-inline-attributes
1697 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1698 "Regular expression for matching inline identifiers or attribute lists.
1699 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1701 (defconst markdown-regex-leanpub-sections
1702 (concat
1703 "^\\({\\)\\("
1704 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1705 "\\)\\(}\\)[ \t]*\n")
1706 "Regular expression for Leanpub section markers and related syntax.")
1708 (defconst markdown-regex-sub-superscript
1709 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1710 "The regular expression matching a sub- or superscript.
1711 The leading un-numbered group matches the character before the
1712 opening tilde or carat, if any, ensuring that it is not a
1713 backslash escape, carat, or tilde.
1714 Group 1 matches the entire expression, including markup.
1715 Group 2 matches the opening markup--a tilde or carat.
1716 Group 3 matches the text inside the delimiters.
1717 Group 4 matches the closing markup--a tilde or carat.")
1719 (defconst markdown-regex-include
1720 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1721 "Regular expression matching common forms of include syntax.
1722 Marked 2, Leanpub, and other processors support some of these forms:
1724 <<[sections/section1.md]
1725 <<(folder/filename)
1726 <<[Code title](folder/filename)
1727 <<{folder/raw_file.html}
1729 Group 1 matches the opening two angle brackets.
1730 Groups 2-4 match the opening square bracket, the text inside,
1731 and the closing square bracket, respectively.
1732 Groups 5-7 match the opening parenthesis, the text inside, and
1733 the closing parenthesis.
1734 Groups 8-10 match the opening brace, the text inside, and the brace.")
1736 (defconst markdown-regex-pandoc-inline-footnote
1737 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1738 "Regular expression for Pandoc inline footnote^[footnote text].
1739 Group 1 matches the opening caret.
1740 Group 2 matches the opening square bracket.
1741 Group 3 matches the footnote text, without the surrounding markup.
1742 Group 4 matches the closing square bracket.")
1745 ;;; Syntax ====================================================================
1747 (defsubst markdown-in-comment-p (&optional pos)
1748 "Return non-nil if POS is in a comment.
1749 If POS is not given, use point instead."
1750 (nth 4 (syntax-ppss pos)))
1752 (defun markdown-syntax-propertize-extend-region (start end)
1753 "Extend START to END region to include an entire block of text.
1754 This helps improve syntax analysis for block constructs.
1755 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1756 Function is called repeatedly until it returns nil. For details, see
1757 `syntax-propertize-extend-region-functions'."
1758 (save-match-data
1759 (save-excursion
1760 (let* ((new-start (progn (goto-char start)
1761 (skip-chars-forward "\n")
1762 (if (re-search-backward "\n\n" nil t)
1763 (min start (match-end 0))
1764 (point-min))))
1765 (new-end (progn (goto-char end)
1766 (skip-chars-backward "\n")
1767 (if (re-search-forward "\n\n" nil t)
1768 (max end (match-beginning 0))
1769 (point-max))))
1770 (code-match (markdown-code-block-at-pos new-start))
1771 (new-start (or (and code-match (cl-first code-match)) new-start))
1772 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1773 (new-end (or (and code-match (cl-second code-match)) new-end)))
1774 (unless (and (eq new-start start) (eq new-end end))
1775 (cons new-start (min new-end (point-max))))))))
1777 (defun markdown-font-lock-extend-region-function (start end _)
1778 "Used in `jit-lock-after-change-extend-region-functions'.
1779 Delegates to `markdown-syntax-propertize-extend-region'. START
1780 and END are the previous region to refontify."
1781 (let ((res (markdown-syntax-propertize-extend-region start end)))
1782 (when res
1783 ;; syntax-propertize-function is not called when character at
1784 ;; (point-max) is deleted, but font-lock-extend-region-functions
1785 ;; are called. Force a syntax property update in that case.
1786 (when (= end (point-max))
1787 ;; This function is called in a buffer modification hook.
1788 ;; `markdown-syntax-propertize' doesn't save the match data,
1789 ;; so we have to do it here.
1790 (save-match-data
1791 (markdown-syntax-propertize (car res) (cdr res))))
1792 (setq jit-lock-start (car res)
1793 jit-lock-end (cdr res)))))
1795 (defun markdown-syntax-propertize-pre-blocks (start end)
1796 "Match preformatted text blocks from START to END."
1797 (save-excursion
1798 (goto-char start)
1799 (let ((levels (markdown-calculate-list-levels))
1800 indent pre-regexp close-regexp open close)
1801 (while (and (< (point) end) (not close))
1802 ;; Search for a region with sufficient indentation
1803 (if (null levels)
1804 (setq indent 1)
1805 (setq indent (1+ (length levels))))
1806 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1807 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1809 (cond
1810 ;; If not at the beginning of a line, move forward
1811 ((not (bolp)) (forward-line))
1812 ;; Move past blank lines
1813 ((markdown-cur-line-blank) (forward-line))
1814 ;; At headers and horizontal rules, reset levels
1815 ((markdown-new-baseline) (forward-line) (setq levels nil))
1816 ;; If the current line has sufficient indentation, mark out pre block
1817 ;; The opening should be preceded by a blank line.
1818 ((and (looking-at pre-regexp)
1819 (markdown-prev-line-blank-p))
1820 (setq open (match-beginning 0))
1821 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1822 (not (eobp)))
1823 (forward-line))
1824 (skip-syntax-backward "-")
1825 (setq close (point)))
1826 ;; If current line has a list marker, update levels, move to end of block
1827 ((looking-at markdown-regex-list)
1828 (setq levels (markdown-update-list-levels
1829 (match-string 2) (current-indentation) levels))
1830 (markdown-end-of-text-block))
1831 ;; If this is the end of the indentation level, adjust levels accordingly.
1832 ;; Only match end of indentation level if levels is not the empty list.
1833 ((and (car levels) (looking-at-p close-regexp))
1834 (setq levels (markdown-update-list-levels
1835 nil (current-indentation) levels))
1836 (markdown-end-of-text-block))
1837 (t (markdown-end-of-text-block))))
1839 (when (and open close)
1840 ;; Set text property data
1841 (put-text-property open close 'markdown-pre (list open close))
1842 ;; Recursively search again
1843 (markdown-syntax-propertize-pre-blocks (point) end)))))
1845 (defconst markdown-fenced-block-pairs
1846 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
1847 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
1848 markdown-fenced-code)
1849 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
1850 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
1851 markdown-yaml-metadata-section)
1852 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
1853 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
1854 markdown-gfm-code))
1855 "Mapping of regular expressions to \"fenced-block\" constructs.
1856 These constructs are distinguished by having a distinctive start
1857 and end pattern, both of which take up an entire line of text,
1858 but no special pattern to identify text within the fenced
1859 blocks (unlike blockquotes and indented-code sections).
1861 Each element within this list takes the form:
1863 ((START-REGEX-OR-FUN START-PROPERTY)
1864 (END-REGEX-OR-FUN END-PROPERTY)
1865 MIDDLE-PROPERTY)
1867 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
1868 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
1869 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
1870 which is the length of the first group of the START-REGEX-OR-FUN match, which
1871 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
1872 evaluate these into \"real\" regexps.
1874 The *-PROPERTY elements are the text properties applied to each part of the
1875 block construct when it is matched using
1876 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
1877 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
1878 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
1879 `match-data' when the regexp was matched to the text. In the case of
1880 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
1881 begin and end set to the edges of the \"middle\" text. This makes fontification
1882 easier.")
1884 (defun markdown-text-property-at-point (prop)
1885 (get-text-property (point) prop))
1887 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
1888 (cond ((functionp object)
1889 (if arg (funcall object arg) (funcall object)))
1890 ((stringp object) object)
1891 (t (error "Object cannot be turned into regex"))))
1893 (defsubst markdown-get-start-fence-regexp ()
1894 "Return regexp to find all \"start\" sections of fenced block constructs.
1895 Which construct is actually contained in the match must be found separately."
1896 (mapconcat
1897 #'identity
1898 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
1899 markdown-fenced-block-pairs)
1900 "\\|"))
1902 (defun markdown-get-fenced-block-begin-properties ()
1903 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
1905 (defun markdown-get-fenced-block-end-properties ()
1906 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
1908 (defun markdown-get-fenced-block-middle-properties ()
1909 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
1911 (defun markdown-find-previous-prop (prop &optional lim)
1912 "Find previous place where property PROP is non-nil, up to LIM.
1913 Return a cons of (pos . property). pos is point if point contains
1914 non-nil PROP."
1915 (let ((res
1916 (if (get-text-property (point) prop) (point)
1917 (previous-single-property-change
1918 (point) prop nil (or lim (point-min))))))
1919 (when (and (not (get-text-property res prop))
1920 (> res (point-min))
1921 (get-text-property (1- res) prop))
1922 (cl-decf res))
1923 (when (and res (get-text-property res prop)) (cons res prop))))
1925 (defun markdown-find-next-prop (prop &optional lim)
1926 "Find next place where property PROP is non-nil, up to LIM.
1927 Return a cons of (POS . PROPERTY) where POS is point if point
1928 contains non-nil PROP."
1929 (let ((res
1930 (if (get-text-property (point) prop) (point)
1931 (next-single-property-change
1932 (point) prop nil (or lim (point-max))))))
1933 (when (and res (get-text-property res prop)) (cons res prop))))
1935 (defun markdown-min-of-seq (map-fn seq)
1936 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
1937 (cl-loop for el in seq
1938 with min = 1.0e+INF ; infinity
1939 with min-el = nil
1940 do (let ((res (funcall map-fn el)))
1941 (when (< res min)
1942 (setq min res)
1943 (setq min-el el)))
1944 finally return min-el))
1946 (defun markdown-max-of-seq (map-fn seq)
1947 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
1948 (cl-loop for el in seq
1949 with max = -1.0e+INF ; negative infinity
1950 with max-el = nil
1951 do (let ((res (funcall map-fn el)))
1952 (when (and res (> res max))
1953 (setq max res)
1954 (setq max-el el)))
1955 finally return max-el))
1957 (defun markdown-find-previous-block ()
1958 "Find previous block.
1959 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
1960 unable to propertize the entire block, but was able to propertize the beginning
1961 of the block. If so, return a cons of (pos . property) where the beginning of
1962 the block was propertized."
1963 (let ((start-pt (point))
1964 (closest-open
1965 (markdown-max-of-seq
1966 #'car
1967 (cl-remove-if
1968 #'null
1969 (cl-mapcar
1970 #'markdown-find-previous-prop
1971 (markdown-get-fenced-block-begin-properties))))))
1972 (when closest-open
1973 (let* ((length-of-open-match
1974 (let ((match-d
1975 (get-text-property (car closest-open) (cdr closest-open))))
1976 (- (cl-fourth match-d) (cl-third match-d))))
1977 (end-regexp
1978 (markdown-maybe-funcall-regexp
1979 (cl-caadr
1980 (cl-find-if
1981 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
1982 markdown-fenced-block-pairs))
1983 length-of-open-match))
1984 (end-prop-loc
1985 (save-excursion
1986 (save-match-data
1987 (goto-char (car closest-open))
1988 (and (re-search-forward end-regexp start-pt t)
1989 (match-beginning 0))))))
1990 (and (not end-prop-loc) closest-open)))))
1992 (defun markdown-get-fenced-block-from-start (prop)
1993 "Return limits of an enclosing fenced block from its start, using PROP.
1994 Return value is a list usable as `match-data'."
1995 (catch 'no-rest-of-block
1996 (let* ((correct-entry
1997 (cl-find-if
1998 (lambda (entry) (eq (cl-cadar entry) prop))
1999 markdown-fenced-block-pairs))
2000 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2001 (middle-prop (cl-third correct-entry))
2002 (end-prop (cl-cadadr correct-entry))
2003 (end-of-end
2004 (save-excursion
2005 (goto-char (match-end 0)) ; end of begin
2006 (unless (eobp) (forward-char))
2007 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2008 (if (not mid-prop-v) ; no middle
2009 (progn
2010 ;; try to find end by advancing one
2011 (let ((end-prop-v
2012 (markdown-text-property-at-point end-prop)))
2013 (if end-prop-v (cl-second end-prop-v)
2014 (throw 'no-rest-of-block nil))))
2015 (set-match-data mid-prop-v)
2016 (goto-char (match-end 0)) ; end of middle
2017 (beginning-of-line) ; into end
2018 (cl-second (markdown-text-property-at-point end-prop)))))))
2019 (list begin-of-begin end-of-end))))
2021 (defun markdown-get-fenced-block-from-middle (prop)
2022 "Return limits of an enclosing fenced block from its middle, using PROP.
2023 Return value is a list usable as `match-data'."
2024 (let* ((correct-entry
2025 (cl-find-if
2026 (lambda (entry) (eq (cl-third entry) prop))
2027 markdown-fenced-block-pairs))
2028 (begin-prop (cl-cadar correct-entry))
2029 (begin-of-begin
2030 (save-excursion
2031 (goto-char (match-beginning 0))
2032 (unless (bobp) (forward-line -1))
2033 (beginning-of-line)
2034 (cl-first (markdown-text-property-at-point begin-prop))))
2035 (end-prop (cl-cadadr correct-entry))
2036 (end-of-end
2037 (save-excursion
2038 (goto-char (match-end 0))
2039 (beginning-of-line)
2040 (cl-second (markdown-text-property-at-point end-prop)))))
2041 (list begin-of-begin end-of-end)))
2043 (defun markdown-get-fenced-block-from-end (prop)
2044 "Return limits of an enclosing fenced block from its end, using PROP.
2045 Return value is a list usable as `match-data'."
2046 (let* ((correct-entry
2047 (cl-find-if
2048 (lambda (entry) (eq (cl-cadadr entry) prop))
2049 markdown-fenced-block-pairs))
2050 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2051 (middle-prop (cl-third correct-entry))
2052 (begin-prop (cl-cadar correct-entry))
2053 (begin-of-begin
2054 (save-excursion
2055 (goto-char (match-beginning 0)) ; beginning of end
2056 (unless (bobp) (backward-char)) ; into middle
2057 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2058 (if (not mid-prop-v)
2059 (progn
2060 (beginning-of-line)
2061 (cl-first (markdown-text-property-at-point begin-prop)))
2062 (set-match-data mid-prop-v)
2063 (goto-char (match-beginning 0)) ; beginning of middle
2064 (unless (bobp) (forward-line -1)) ; into beginning
2065 (beginning-of-line)
2066 (cl-first (markdown-text-property-at-point begin-prop)))))))
2067 (list begin-of-begin end-of-end)))
2069 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2070 "Get \"fake\" match data for block enclosing POS.
2071 Returns fake match data which encloses the start, middle, and end
2072 of the block construct enclosing POS, if it exists. Used in
2073 `markdown-code-block-at-pos'."
2074 (save-excursion
2075 (when pos (goto-char pos))
2076 (beginning-of-line)
2077 (car
2078 (cl-remove-if
2079 #'null
2080 (cl-mapcar
2081 (lambda (fun-and-prop)
2082 (cl-destructuring-bind (fun prop) fun-and-prop
2083 (when prop
2084 (save-match-data
2085 (set-match-data (markdown-text-property-at-point prop))
2086 (funcall fun prop)))))
2087 `((markdown-get-fenced-block-from-start
2088 ,(cl-find-if
2089 #'markdown-text-property-at-point
2090 (markdown-get-fenced-block-begin-properties)))
2091 (markdown-get-fenced-block-from-middle
2092 ,(cl-find-if
2093 #'markdown-text-property-at-point
2094 (markdown-get-fenced-block-middle-properties)))
2095 (markdown-get-fenced-block-from-end
2096 ,(cl-find-if
2097 #'markdown-text-property-at-point
2098 (markdown-get-fenced-block-end-properties)))))))))
2100 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2101 "Get match for REG up to END, if exists, and propertize appropriately.
2102 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2103 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2104 (when (re-search-forward reg end t)
2105 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2106 (close-end (match-end 0)) ; End of closing line.
2107 (close-data (match-data t))) ; Match data for closing line.
2108 ;; Propertize middle section of fenced block.
2109 (put-text-property middle-begin close-begin
2110 (cl-third fence-spec)
2111 (list middle-begin close-begin))
2112 ;; Propertize closing line of fenced block.
2113 (put-text-property close-begin close-end
2114 (cl-cadadr fence-spec) close-data))))
2116 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2117 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2118 If unable to propertize an entire block (if the start of a block is within START
2119 and END, but the end of the block is not), propertize the start section of a
2120 block, then in a subsequent call propertize both middle and end by finding the
2121 start which was previously propertized."
2122 (let ((start-reg (markdown-get-start-fence-regexp)))
2123 (save-excursion
2124 (goto-char start)
2125 ;; start from previous unclosed block, if exists
2126 (let ((prev-begin-block (markdown-find-previous-block)))
2127 (when prev-begin-block
2128 (let* ((correct-entry
2129 (cl-find-if (lambda (entry)
2130 (eq (cdr prev-begin-block) (cl-cadar entry)))
2131 markdown-fenced-block-pairs))
2132 (enclosed-text-start (1+ (car prev-begin-block)))
2133 (start-length
2134 (save-excursion
2135 (goto-char (car prev-begin-block))
2136 (string-match
2137 (markdown-maybe-funcall-regexp
2138 (caar correct-entry))
2139 (buffer-substring
2140 (point-at-bol) (point-at-eol)))
2141 (- (match-end 1) (match-beginning 1))))
2142 (end-reg (markdown-maybe-funcall-regexp
2143 (cl-caadr correct-entry) start-length)))
2144 (markdown-propertize-end-match
2145 end-reg end correct-entry enclosed-text-start))))
2146 ;; find all new blocks within region
2147 (while (re-search-forward start-reg end t)
2148 ;; we assume the opening constructs take up (only) an entire line,
2149 ;; so we re-check the current line
2150 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2151 ;; find entry in `markdown-fenced-block-pairs' corresponding
2152 ;; to regex which was matched
2153 (correct-entry
2154 (cl-find-if
2155 (lambda (fenced-pair)
2156 (string-match-p
2157 (markdown-maybe-funcall-regexp (caar fenced-pair))
2158 cur-line))
2159 markdown-fenced-block-pairs))
2160 (enclosed-text-start
2161 (save-excursion (1+ (point-at-eol))))
2162 (end-reg
2163 (markdown-maybe-funcall-regexp
2164 (cl-caadr correct-entry)
2165 (if (and (match-beginning 1) (match-end 1))
2166 (- (match-end 1) (match-beginning 1))
2167 0))))
2168 ;; get correct match data
2169 (save-excursion
2170 (beginning-of-line)
2171 (re-search-forward
2172 (markdown-maybe-funcall-regexp (caar correct-entry))
2173 (point-at-eol)))
2174 ;; mark starting, even if ending is outside of region
2175 (put-text-property (match-beginning 0) (match-end 0)
2176 (cl-cadar correct-entry) (match-data t))
2177 (markdown-propertize-end-match
2178 end-reg end correct-entry enclosed-text-start))))))
2180 (defun markdown-syntax-propertize-blockquotes (start end)
2181 "Match blockquotes from START to END."
2182 (save-excursion
2183 (goto-char start)
2184 (while (and (re-search-forward markdown-regex-blockquote end t)
2185 (not (markdown-code-block-at-pos (match-beginning 0))))
2186 (put-text-property (match-beginning 0) (match-end 0)
2187 'markdown-blockquote
2188 (match-data t)))))
2190 (defun markdown-syntax-propertize-hrs (start end)
2191 "Match horizontal rules from START to END."
2192 (save-excursion
2193 (goto-char start)
2194 (while (re-search-forward markdown-regex-hr end t)
2195 (unless (or (markdown-on-heading-p)
2196 (markdown-code-block-at-point-p))
2197 (put-text-property (match-beginning 0) (match-end 0)
2198 'markdown-hr
2199 (match-data t))))))
2201 (defun markdown-syntax-propertize-yaml-metadata (start end)
2202 (save-excursion
2203 (goto-char start)
2204 (cl-loop
2205 while (re-search-forward markdown-regex-declarative-metadata end t)
2206 do (when (get-text-property (match-beginning 0)
2207 'markdown-yaml-metadata-section)
2208 (put-text-property (match-beginning 1) (match-end 1)
2209 'markdown-metadata-key (match-data t))
2210 (put-text-property (match-beginning 2) (match-end 2)
2211 'markdown-metadata-markup (match-data t))
2212 (put-text-property (match-beginning 3) (match-end 3)
2213 'markdown-metadata-value (match-data t))))))
2215 (defun markdown-syntax-propertize-headings (start end)
2216 "Match headings of type SYMBOL with REGEX from START to END."
2217 (goto-char start)
2218 (while (re-search-forward markdown-regex-header end t)
2219 (unless (markdown-code-block-at-pos (match-beginning 0))
2220 (put-text-property
2221 (match-beginning 0) (match-end 0) 'markdown-heading
2222 (match-data t))
2223 (put-text-property
2224 (match-beginning 0) (match-end 0)
2225 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2226 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2227 (t (let ((atx-level (length (markdown-trim-whitespace
2228 (match-string-no-properties 4)))))
2229 (intern (format "markdown-heading-%d-atx" atx-level)))))
2230 (match-data t)))))
2232 (defun markdown-syntax-propertize-comments (start end)
2233 "Match HTML comments from the START to END."
2234 (let* ((in-comment (markdown-in-comment-p)))
2235 (goto-char start)
2236 (cond
2237 ;; Comment start
2238 ((and (not in-comment)
2239 (re-search-forward markdown-regex-comment-start end t)
2240 (not (markdown-inline-code-at-point-p))
2241 (not (markdown-code-block-at-point-p)))
2242 (let ((open-beg (match-beginning 0)))
2243 (put-text-property open-beg (1+ open-beg)
2244 'syntax-table (string-to-syntax "<"))
2245 (markdown-syntax-propertize-comments
2246 (min (1+ (match-end 0)) end (point-max)) end)))
2247 ;; Comment end
2248 ((and in-comment
2249 (re-search-forward markdown-regex-comment-end end t))
2250 (put-text-property (1- (match-end 0)) (match-end 0)
2251 'syntax-table (string-to-syntax ">"))
2252 (markdown-syntax-propertize-comments
2253 (min (1+ (match-end 0)) end (point-max)) end))
2254 ;; Nothing found
2255 (t nil))))
2257 (defvar markdown--syntax-properties
2258 (list 'markdown-tilde-fence-begin nil
2259 'markdown-tilde-fence-end nil
2260 'markdown-fenced-code nil
2261 'markdown-yaml-metadata-begin nil
2262 'markdown-yaml-metadata-end nil
2263 'markdown-yaml-metadata-section nil
2264 'markdown-gfm-block-begin nil
2265 'markdown-gfm-block-end nil
2266 'markdown-gfm-code nil
2267 'markdown-pre nil
2268 'markdown-blockquote nil
2269 'markdown-hr nil
2270 'markdown-heading nil
2271 'markdown-heading-1-setext nil
2272 'markdown-heading-2-setext nil
2273 'markdown-heading-1-atx nil
2274 'markdown-heading-2-atx nil
2275 'markdown-heading-3-atx nil
2276 'markdown-heading-4-atx nil
2277 'markdown-heading-5-atx nil
2278 'markdown-heading-6-atx nil
2279 'markdown-metadata-key nil
2280 'markdown-metadata-value nil
2281 'markdown-metadata-markup nil)
2282 "Property list of all Markdown syntactic properties.")
2284 (defun markdown-syntax-propertize (start end)
2285 "Function used as `syntax-propertize-function'.
2286 START and END delimit region to propertize."
2287 (with-silent-modifications
2288 (save-excursion
2289 (remove-text-properties start end markdown--syntax-properties)
2290 (markdown-syntax-propertize-fenced-block-constructs start end)
2291 (markdown-syntax-propertize-yaml-metadata start end)
2292 (markdown-syntax-propertize-pre-blocks start end)
2293 (markdown-syntax-propertize-blockquotes start end)
2294 (markdown-syntax-propertize-headings start end)
2295 (markdown-syntax-propertize-hrs start end)
2296 (markdown-syntax-propertize-comments start end))))
2299 ;;; Markup Hiding
2301 (defconst markdown-markup-properties
2302 '(face markdown-markup-face invisible markdown-markup)
2303 "List of properties and values to apply to markup.")
2305 (defconst markdown-language-keyword-properties
2306 '(face markdown-language-keyword-face invisible markdown-markup)
2307 "List of properties and values to apply to code block language names.")
2309 (defconst markdown-language-info-properties
2310 '(face markdown-language-info-face invisible markdown-markup)
2311 "List of properties and values to apply to code block language info strings.")
2313 (defconst markdown-include-title-properties
2314 '(face markdown-link-title-face invisible markdown-markup)
2315 "List of properties and values to apply to included code titles.")
2317 (defconst markdown-inline-footnote-properties
2318 '(face nil display ((raise 0.2) (height 0.8)))
2319 "Properties to apply to footnote markers and inline footnotes.")
2321 (defcustom markdown-hide-markup nil
2322 "Determines whether markup in the buffer will be hidden.
2323 When set to nil, all markup is displayed in the buffer as it
2324 appears in the file. An exception is when `markdown-hide-urls'
2325 is non-nil.
2326 Set this to a non-nil value to turn this feature on by default.
2327 You can interactively toggle the value of this variable with
2328 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2329 or from the Markdown > Show & Hide menu.
2331 Markup hiding works by adding text properties to positions in the
2332 buffer---either the `invisible' property or the `display' property
2333 in cases where alternative glyphs are used (e.g., list bullets).
2334 This does not, however, affect printing or other output.
2335 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2336 not honor these text properties. For printing, it would be better
2337 to first convert to HTML or PDF (e.g,. using Pandoc)."
2338 :group 'markdown
2339 :type 'boolean
2340 :safe 'booleanp
2341 :package-version '(markdown-mode . "2.3"))
2342 (make-variable-buffer-local 'markdown-hide-markup)
2344 (defun markdown-toggle-markup-hiding (&optional arg)
2345 "Toggle the display or hiding of markup.
2346 With a prefix argument ARG, enable markup hiding if ARG is positive,
2347 and disable it otherwise.
2348 See `markdown-hide-markup' for additional details."
2349 (interactive (list (or current-prefix-arg 'toggle)))
2350 (setq markdown-hide-markup
2351 (if (eq arg 'toggle)
2352 (not markdown-hide-markup)
2353 (> (prefix-numeric-value arg) 0)))
2354 (if markdown-hide-markup
2355 (progn (add-to-invisibility-spec 'markdown-markup)
2356 (message "markdown-mode markup hiding enabled"))
2357 (progn (remove-from-invisibility-spec 'markdown-markup)
2358 (message "markdown-mode markup hiding disabled")))
2359 (markdown-reload-extensions))
2362 ;;; Font Lock =================================================================
2364 (require 'font-lock)
2366 (defvar markdown-italic-face 'markdown-italic-face
2367 "Face name to use for italic text.")
2369 (defvar markdown-bold-face 'markdown-bold-face
2370 "Face name to use for bold text.")
2372 (defvar markdown-strike-through-face 'markdown-strike-through-face
2373 "Face name to use for strike-through text.")
2375 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2376 "Face name to use as a base for header delimiters.")
2378 (defvar markdown-header-rule-face 'markdown-header-rule-face
2379 "Face name to use as a base for header rules.")
2381 (defvar markdown-header-face 'markdown-header-face
2382 "Face name to use as a base for headers.")
2384 (defvar markdown-header-face-1 'markdown-header-face-1
2385 "Face name to use for level-1 headers.")
2387 (defvar markdown-header-face-2 'markdown-header-face-2
2388 "Face name to use for level-2 headers.")
2390 (defvar markdown-header-face-3 'markdown-header-face-3
2391 "Face name to use for level-3 headers.")
2393 (defvar markdown-header-face-4 'markdown-header-face-4
2394 "Face name to use for level-4 headers.")
2396 (defvar markdown-header-face-5 'markdown-header-face-5
2397 "Face name to use for level-5 headers.")
2399 (defvar markdown-header-face-6 'markdown-header-face-6
2400 "Face name to use for level-6 headers.")
2402 (defvar markdown-inline-code-face 'markdown-inline-code-face
2403 "Face name to use for inline code.")
2405 (defvar markdown-list-face 'markdown-list-face
2406 "Face name to use for list markers.")
2408 (defvar markdown-blockquote-face 'markdown-blockquote-face
2409 "Face name to use for blockquote.")
2411 (defvar markdown-pre-face 'markdown-pre-face
2412 "Face name to use for preformatted text.")
2414 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2415 "Face name to use for programming language identifiers.")
2417 (defvar markdown-language-info-face 'markdown-language-info-face
2418 "Face name to use for programming info strings.")
2420 (defvar markdown-link-face 'markdown-link-face
2421 "Face name to use for links.")
2423 (defvar markdown-missing-link-face 'markdown-missing-link-face
2424 "Face name to use for links where the linked file does not exist.")
2426 (defvar markdown-reference-face 'markdown-reference-face
2427 "Face name to use for reference.")
2429 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2430 "Face name to use for footnote markers.")
2432 (defvar markdown-url-face 'markdown-url-face
2433 "Face name to use for URLs.")
2435 (defvar markdown-link-title-face 'markdown-link-title-face
2436 "Face name to use for reference link titles.")
2438 (defvar markdown-line-break-face 'markdown-line-break-face
2439 "Face name to use for hard line breaks.")
2441 (defvar markdown-comment-face 'markdown-comment-face
2442 "Face name to use for HTML comments.")
2444 (defvar markdown-math-face 'markdown-math-face
2445 "Face name to use for LaTeX expressions.")
2447 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2448 "Face name to use for metadata keys.")
2450 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2451 "Face name to use for metadata values.")
2453 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2454 "Face name to use for GFM checkboxes.")
2456 (defvar markdown-highlight-face 'markdown-highlight-face
2457 "Face name to use for mouse highlighting.")
2459 (defvar markdown-markup-face 'markdown-markup-face
2460 "Face name to use for markup elements.")
2462 (defgroup markdown-faces nil
2463 "Faces used in Markdown Mode"
2464 :group 'markdown
2465 :group 'faces)
2467 (defface markdown-italic-face
2468 '((t (:inherit italic)))
2469 "Face for italic text."
2470 :group 'markdown-faces)
2472 (defface markdown-bold-face
2473 '((t (:inherit bold)))
2474 "Face for bold text."
2475 :group 'markdown-faces)
2477 (defface markdown-strike-through-face
2478 '((t (:strike-through t)))
2479 "Face for strike-through text."
2480 :group 'markdown-faces)
2482 (defface markdown-markup-face
2483 '((t (:inherit shadow :slant normal :weight normal)))
2484 "Face for markup elements."
2485 :group 'markdown-faces)
2487 (defface markdown-header-rule-face
2488 '((t (:inherit markdown-markup-face)))
2489 "Base face for headers rules."
2490 :group 'markdown-faces)
2492 (defface markdown-header-delimiter-face
2493 '((t (:inherit markdown-markup-face)))
2494 "Base face for headers hash delimiter."
2495 :group 'markdown-faces)
2497 (defface markdown-list-face
2498 '((t (:inherit markdown-markup-face)))
2499 "Face for list item markers."
2500 :group 'markdown-faces)
2502 (defface markdown-blockquote-face
2503 '((t (:inherit font-lock-doc-face)))
2504 "Face for blockquote sections."
2505 :group 'markdown-faces)
2507 (defface markdown-code-face
2508 (let* ((default-bg (or (face-background 'default) "unspecified-bg"))
2509 (light-bg (if (equal default-bg "unspecified-bg")
2510 "unspecified-bg"
2511 (color-darken-name default-bg 3)))
2512 (dark-bg (if (equal default-bg "unspecified-bg")
2513 "unspecified-bg"
2514 (color-lighten-name default-bg 3))))
2515 `((default :inherit fixed-pitch)
2516 (((type graphic) (class color) (background dark)) (:background ,dark-bg))
2517 (((type graphic) (class color) (background light)) (:background ,light-bg))))
2518 "Face for inline code, pre blocks, and fenced code blocks."
2519 :group 'markdown-faces)
2521 (defface markdown-code-face
2522 `((t (:inherit fixed-pitch)))
2523 "Face for inline code, pre blocks, and fenced code blocks."
2524 :group 'markdown-faces)
2526 (defface markdown-inline-code-face
2527 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2528 "Face for inline code."
2529 :group 'markdown-faces)
2531 (defface markdown-pre-face
2532 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2533 "Face for preformatted text."
2534 :group 'markdown-faces)
2536 (defface markdown-language-keyword-face
2537 '((t (:inherit font-lock-type-face)))
2538 "Face for programming language identifiers."
2539 :group 'markdown-faces)
2541 (defface markdown-language-info-face
2542 '((t (:inherit font-lock-string-face)))
2543 "Face for programming language info strings."
2544 :group 'markdown-faces)
2546 (defface markdown-link-face
2547 '((t (:inherit link)))
2548 "Face for links."
2549 :group 'markdown-faces)
2551 (defface markdown-missing-link-face
2552 '((t (:inherit font-lock-warning-face)))
2553 "Face for missing links."
2554 :group 'markdown-faces)
2556 (defface markdown-reference-face
2557 '((t (:inherit markdown-markup-face)))
2558 "Face for link references."
2559 :group 'markdown-faces)
2561 (define-obsolete-face-alias 'markdown-footnote-face
2562 'markdown-footnote-marker-face "v2.3")
2564 (defface markdown-footnote-marker-face
2565 '((t (:inherit markdown-markup-face)))
2566 "Face for footnote markers."
2567 :group 'markdown-faces)
2569 (defface markdown-footnote-text-face
2570 '((t (:inherit font-lock-comment-face)))
2571 "Face for footnote text."
2572 :group 'markdown-faces)
2574 (defface markdown-url-face
2575 '((t (:inherit font-lock-string-face)))
2576 "Face for URLs that are part of markup.
2577 For example, this applies to URLs in inline links:
2578 [link text](http://example.com/)."
2579 :group 'markdown-faces)
2581 (defface markdown-plain-url-face
2582 '((t (:inherit markdown-link-face)))
2583 "Face for URLs that are also links.
2584 For example, this applies to plain angle bracket URLs:
2585 <http://example.com/>."
2586 :group 'markdown-faces)
2588 (defface markdown-link-title-face
2589 '((t (:inherit font-lock-comment-face)))
2590 "Face for reference link titles."
2591 :group 'markdown-faces)
2593 (defface markdown-line-break-face
2594 '((t (:inherit font-lock-constant-face :underline t)))
2595 "Face for hard line breaks."
2596 :group 'markdown-faces)
2598 (defface markdown-comment-face
2599 '((t (:inherit font-lock-comment-face)))
2600 "Face for HTML comments."
2601 :group 'markdown-faces)
2603 (defface markdown-math-face
2604 '((t (:inherit font-lock-string-face)))
2605 "Face for LaTeX expressions."
2606 :group 'markdown-faces)
2608 (defface markdown-metadata-key-face
2609 '((t (:inherit font-lock-variable-name-face)))
2610 "Face for metadata keys."
2611 :group 'markdown-faces)
2613 (defface markdown-metadata-value-face
2614 '((t (:inherit font-lock-string-face)))
2615 "Face for metadata values."
2616 :group 'markdown-faces)
2618 (defface markdown-gfm-checkbox-face
2619 '((t (:inherit font-lock-builtin-face)))
2620 "Face for GFM checkboxes."
2621 :group 'markdown-faces)
2623 (defface markdown-highlight-face
2624 '((t (:inherit highlight)))
2625 "Face for mouse highlighting."
2626 :group 'markdown-faces)
2628 (defface markdown-hr-face
2629 '((t (:inherit markdown-markup-face)))
2630 "Face for horizontal rules."
2631 :group 'markdown-faces)
2633 (defcustom markdown-header-scaling nil
2634 "Whether to use variable-height faces for headers.
2635 When non-nil, `markdown-header-face' will inherit from
2636 `variable-pitch' and the scaling values in
2637 `markdown-header-scaling-values' will be applied to
2638 headers of levels one through six respectively."
2639 :type 'boolean
2640 :initialize 'custom-initialize-default
2641 :set (lambda (symbol value)
2642 (set-default symbol value)
2643 (markdown-update-header-faces value))
2644 :group 'markdown-faces
2645 :package-version '(markdown-mode . "2.2"))
2647 (defcustom markdown-header-scaling-values
2648 '(2.0 1.7 1.4 1.1 1.0 1.0)
2649 "List of scaling values for headers of level one through six.
2650 Used when `markdown-header-scaling' is non-nil."
2651 :type 'list
2652 :initialize 'custom-initialize-default
2653 :set (lambda (symbol value)
2654 (set-default symbol value)
2655 (markdown-update-header-faces markdown-header-scaling value))
2656 :group 'markdown-faces)
2658 (defun markdown-make-header-faces ()
2659 "Build the faces used for Markdown headers."
2660 (let ((inherit-faces '(font-lock-function-name-face)))
2661 (when markdown-header-scaling
2662 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2663 (defface markdown-header-face
2664 `((t (:inherit ,inherit-faces :weight bold)))
2665 "Base face for headers."
2666 :group 'markdown-faces))
2667 (dotimes (num 6)
2668 (let* ((num1 (1+ num))
2669 (face-name (intern (format "markdown-header-face-%s" num1)))
2670 (scale (if markdown-header-scaling
2671 (float (nth num markdown-header-scaling-values))
2672 1.0)))
2673 (eval
2674 `(defface ,face-name
2675 '((t (:inherit markdown-header-face :height ,scale)))
2676 (format "Face for level %s headers.
2677 You probably don't want to customize this face directly. Instead
2678 you can customize the base face `markdown-header-face' or the
2679 variable-height variable `markdown-header-scaling'." ,num1)
2680 :group 'markdown-faces)))))
2682 (markdown-make-header-faces)
2684 (defun markdown-update-header-faces (&optional scaling scaling-values)
2685 "Update header faces, depending on if header SCALING is desired.
2686 If so, use given list of SCALING-VALUES relative to the baseline
2687 size of `markdown-header-face'."
2688 (dotimes (num 6)
2689 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2690 (scale (cond ((not scaling) 1.0)
2691 (scaling-values (float (nth num scaling-values)))
2692 (t (float (nth num markdown-header-scaling-values))))))
2693 (unless (get face-name 'saved-face) ; Don't update customized faces
2694 (set-face-attribute face-name nil :height scale)))))
2696 (defun markdown-syntactic-face (state)
2697 "Return font-lock face for characters with given STATE.
2698 See `font-lock-syntactic-face-function' for details."
2699 (let ((in-comment (nth 4 state)))
2700 (cond
2701 (in-comment 'markdown-comment-face)
2702 (t nil))))
2704 (defcustom markdown-list-item-bullets
2705 '("●" "◎" "○" "◆" "◇" "►" "•")
2706 "List of bullets to use for unordered lists.
2707 It can contain any number of symbols, which will be repeated.
2708 Depending on your font, some reasonable choices are:
2709 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2710 :group 'markdown
2711 :type '(repeat (string :tag "Bullet character"))
2712 :package-version '(markdown-mode . "2.3"))
2714 (defvar markdown-mode-font-lock-keywords-basic
2715 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2716 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2717 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2718 (2 markdown-markup-face)
2719 (3 markdown-metadata-value-face)))
2720 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2721 (2 markdown-markup-properties nil t)
2722 (3 markdown-language-keyword-properties nil t)
2723 (4 markdown-language-info-properties nil t)
2724 (5 markdown-markup-properties nil t)))
2725 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2726 (markdown-fontify-gfm-code-blocks)
2727 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2728 (2 markdown-markup-properties nil t)
2729 (3 markdown-language-keyword-properties nil t)
2730 (4 markdown-language-info-properties nil t)
2731 (5 markdown-markup-properties nil t)))
2732 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2733 (markdown-fontify-fenced-code-blocks)
2734 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2735 (markdown-fontify-headings)
2736 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2737 (2 markdown-markup-face)
2738 (3 markdown-metadata-value-face)))
2739 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2740 (2 markdown-markup-face)
2741 (3 markdown-metadata-value-face)))
2742 (markdown-fontify-hrs)
2743 (markdown-match-code . ((1 markdown-markup-properties prepend)
2744 (2 markdown-inline-code-face prepend)
2745 (3 markdown-markup-properties prepend)))
2746 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2747 (2 markdown-inline-code-face)
2748 (3 markdown-markup-properties)))
2749 (markdown-fontify-angle-uris)
2750 (,markdown-regex-email . 'markdown-plain-url-face)
2751 (markdown-fontify-list-items)
2752 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2753 (1 markdown-markup-properties) ; [^
2754 (2 markdown-footnote-marker-face) ; label
2755 (3 markdown-markup-properties))) ; ]
2756 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2757 (1 markdown-markup-properties) ; ^
2758 (2 markdown-markup-properties) ; [
2759 (3 'markdown-footnote-text-face) ; text
2760 (4 markdown-markup-properties))) ; ]
2761 (markdown-match-includes . ((1 markdown-markup-properties)
2762 (2 markdown-markup-properties nil t)
2763 (3 markdown-include-title-properties nil t)
2764 (4 markdown-markup-properties nil t)
2765 (5 markdown-markup-properties)
2766 (6 'markdown-url-face)
2767 (7 markdown-markup-properties)))
2768 (markdown-fontify-inline-links)
2769 (markdown-fontify-reference-links)
2770 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2771 (2 markdown-reference-face) ; label
2772 (3 markdown-markup-face) ; ]
2773 (4 markdown-markup-face) ; :
2774 (5 markdown-url-face) ; url
2775 (6 markdown-link-title-face))) ; "title" (optional)
2776 (markdown-fontify-plain-uris)
2777 ;; Math mode $..$
2778 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2779 (2 markdown-math-face append)
2780 (3 markdown-markup-face prepend)))
2781 ;; Math mode $$..$$
2782 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2783 (2 markdown-math-face append)
2784 (3 markdown-markup-face prepend)))
2785 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2786 (2 markdown-bold-face append)
2787 (3 markdown-markup-properties prepend)))
2788 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2789 (2 markdown-italic-face append)
2790 (3 markdown-markup-properties prepend)))
2791 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2792 (4 markdown-strike-through-face)
2793 (5 markdown-markup-properties)))
2794 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
2795 (markdown-fontify-sub-superscripts)
2796 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
2797 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
2798 (markdown-fontify-blockquotes))
2799 "Syntax highlighting for Markdown files.")
2801 (defvar markdown-mode-font-lock-keywords nil
2802 "Default highlighting expressions for Markdown mode.
2803 This variable is defined as a buffer-local variable for dynamic
2804 extension support.")
2806 ;; Footnotes
2807 (defvar markdown-footnote-counter 0
2808 "Counter for footnote numbers.")
2809 (make-variable-buffer-local 'markdown-footnote-counter)
2811 (defconst markdown-footnote-chars
2812 "[[:alnum:]-]"
2813 "Regular expression matching any character that is allowed in a footnote identifier.")
2815 (defconst markdown-regex-footnote-definition
2816 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
2817 "Regular expression matching a footnote definition, capturing the label.")
2820 ;;; Compatibility =============================================================
2822 (defun markdown-replace-regexp-in-string (regexp rep string)
2823 "Replace ocurrences of REGEXP with REP in STRING.
2824 This is a compatibility wrapper to provide `replace-regexp-in-string'
2825 in XEmacs 21."
2826 (if (featurep 'xemacs)
2827 (replace-in-string string regexp rep)
2828 (replace-regexp-in-string regexp rep string)))
2830 ;; `markdown-use-region-p' is a compatibility function which checks
2831 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
2832 (eval-and-compile
2833 (cond
2834 ;; Emacs 24 and newer
2835 ((fboundp 'use-region-p)
2836 (defalias 'markdown-use-region-p 'use-region-p))
2837 ;; XEmacs
2838 ((fboundp 'region-active-p)
2839 (defalias 'markdown-use-region-p 'region-active-p))))
2841 ;; Use new names for outline-mode functions in Emacs 25 and later.
2842 (eval-and-compile
2843 (defalias 'markdown-hide-sublevels
2844 (if (fboundp 'outline-hide-sublevels)
2845 'outline-hide-sublevels
2846 'hide-sublevels))
2847 (defalias 'markdown-show-all
2848 (if (fboundp 'outline-show-all)
2849 'outline-show-all
2850 'show-all))
2851 (defalias 'markdown-hide-body
2852 (if (fboundp 'outline-hide-body)
2853 'outline-hide-body
2854 'hide-body))
2855 (defalias 'markdown-show-children
2856 (if (fboundp 'outline-show-children)
2857 'outline-show-children
2858 'show-children))
2859 (defalias 'markdown-show-subtree
2860 (if (fboundp 'outline-show-subtree)
2861 'outline-show-subtree
2862 'show-subtree))
2863 (defalias 'markdown-hide-subtree
2864 (if (fboundp 'outline-hide-subtree)
2865 'outline-hide-subtree
2866 'hide-subtree)))
2868 ;; Provide directory-name-p to Emacs 24
2869 (defsubst markdown-directory-name-p (name)
2870 "Return non-nil if NAME ends with a directory separator character.
2871 Taken from `directory-name-p' from Emacs 25 and provided here for
2872 backwards compatibility."
2873 (let ((len (length name))
2874 (lastc ?.))
2875 (if (> len 0)
2876 (setq lastc (aref name (1- len))))
2877 (or (= lastc ?/)
2878 (and (memq system-type '(windows-nt ms-dos))
2879 (= lastc ?\\)))))
2881 ;; Provide a function to find files recursively in Emacs 24.
2882 (defalias 'markdown-directory-files-recursively
2883 (if (fboundp 'directory-files-recursively)
2884 'directory-files-recursively
2885 (lambda (dir regexp)
2886 "Return list of all files under DIR that have file names matching REGEXP.
2887 This function works recursively. Files are returned in \"depth first\"
2888 order, and files from each directory are sorted in alphabetical order.
2889 Each file name appears in the returned list in its absolute form.
2890 Based on `directory-files-recursively' from Emacs 25 and provided
2891 here for backwards compatibility."
2892 (let ((result nil)
2893 (files nil)
2894 ;; When DIR is "/", remote file names like "/method:" could
2895 ;; also be offered. We shall suppress them.
2896 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
2897 (dolist (file (sort (file-name-all-completions "" dir)
2898 'string<))
2899 (unless (member file '("./" "../"))
2900 (if (markdown-directory-name-p file)
2901 (let* ((leaf (substring file 0 (1- (length file))))
2902 (full-file (expand-file-name leaf dir)))
2903 (setq result
2904 (nconc result (markdown-directory-files-recursively
2905 full-file regexp))))
2906 (when (string-match-p regexp file)
2907 (push (expand-file-name file dir) files)))))
2908 (nconc result (nreverse files))))))
2910 (defun markdown-flyspell-check-word-p ()
2911 "Return t if `flyspell' should check word just before point.
2912 Used for `flyspell-generic-check-word-predicate'."
2913 (save-excursion
2914 (goto-char (1- (point)))
2915 (not (or (markdown-code-block-at-point-p)
2916 (markdown-inline-code-at-point-p)
2917 (markdown-in-comment-p)
2918 (let ((faces (get-text-property (point) 'face)))
2919 (if (listp faces)
2920 (or (memq 'markdown-reference-face faces)
2921 (memq 'markdown-markup-face faces)
2922 (memq 'markdown-plain-url-face faces)
2923 (memq 'markdown-inline-code-face faces)
2924 (memq 'markdown-url-face faces))
2925 (memq faces '(markdown-reference-face
2926 markdown-markup-face
2927 markdown-plain-url-face
2928 markdown-inline-code-face
2929 markdown-url-face))))))))
2931 (defun markdown-font-lock-ensure ()
2932 "Provide `font-lock-ensure' in Emacs 24."
2933 (if (fboundp 'font-lock-ensure)
2934 (font-lock-ensure)
2935 (with-no-warnings
2936 ;; Suppress warning about non-interactive use of
2937 ;; `font-lock-fontify-buffer' in Emacs 25.
2938 (font-lock-fontify-buffer))))
2941 ;;; Markdown Parsing Functions ================================================
2943 (defun markdown-cur-line-blank (&optional predicate)
2944 "Return t if the current line is blank and nil otherwise.
2945 When PREDICATE is non-nil, don't modify the match data."
2946 (save-excursion
2947 (beginning-of-line)
2948 (let ((regexp "^\\s *$"))
2949 (if predicate
2950 (looking-at-p regexp)
2951 (looking-at regexp)))))
2953 (defun markdown-cur-line-blank-p ()
2954 "Same as `markdown-cur-line-blank', but does not change the match data."
2955 (markdown-cur-line-blank t))
2957 (defun markdown-prev-line-blank (&optional predicate)
2958 "Return t if the previous line is blank and nil otherwise.
2959 If we are at the first line, then consider the previous line to be blank.
2960 When PREDICATE is non-nil, don't modify the match data."
2961 (or (= (line-beginning-position) (point-min))
2962 (save-excursion
2963 (forward-line -1)
2964 (markdown-cur-line-blank predicate))))
2966 (defun markdown-prev-line-blank-p ()
2967 "Same as `markdown-prev-line-blank', but does not change the match data."
2968 (markdown-prev-line-blank t))
2970 (defun markdown-next-line-blank (&optional predicate)
2971 "Return t if the next line is blank and nil otherwise.
2972 If we are at the last line, then consider the next line to be blank.
2973 When PREDICATE is non-nil, don't modify the match data."
2974 (or (= (line-end-position) (point-max))
2975 (save-excursion
2976 (forward-line 1)
2977 (markdown-cur-line-blank predicate))))
2979 (defun markdown-next-line-blank-p ()
2980 "Same as `markdown-next-line-blank', but does not change the match data."
2981 (markdown-next-line-blank t))
2983 (defun markdown-prev-line-indent ()
2984 "Return the number of leading whitespace characters in the previous line.
2985 Return 0 if the current line is the first line in the buffer."
2986 (save-excursion
2987 (if (= (line-beginning-position) (point-min))
2989 (forward-line -1)
2990 (current-indentation))))
2992 (defun markdown-next-line-indent ()
2993 "Return the number of leading whitespace characters in the next line.
2994 Return 0 if line is the last line in the buffer."
2995 (save-excursion
2996 (if (= (line-end-position) (point-max))
2998 (forward-line 1)
2999 (current-indentation))))
3001 (defun markdown-cur-non-list-indent ()
3002 "Return beginning position of list item text (not including the list marker).
3003 Return nil if the current line is not the beginning of a list item."
3004 (save-match-data
3005 (save-excursion
3006 (beginning-of-line)
3007 (when (re-search-forward markdown-regex-list (line-end-position) t)
3008 (current-column)))))
3010 (defun markdown-prev-non-list-indent ()
3011 "Return position of the first non-list-marker on the previous line."
3012 (save-excursion
3013 (forward-line -1)
3014 (markdown-cur-non-list-indent)))
3016 (defun markdown-new-baseline ()
3017 "Determine if the current line begins a new baseline level."
3018 (save-excursion
3019 (beginning-of-line)
3020 (or (looking-at markdown-regex-header)
3021 (looking-at markdown-regex-hr)
3022 (and (null (markdown-cur-non-list-indent))
3023 (= (current-indentation) 0)
3024 (markdown-prev-line-blank)))))
3026 (defun markdown-search-backward-baseline ()
3027 "Search backward baseline point with no indentation and not a list item."
3028 (end-of-line)
3029 (let (stop)
3030 (while (not (or stop (bobp)))
3031 (re-search-backward markdown-regex-block-separator-noindent nil t)
3032 (when (match-end 2)
3033 (goto-char (match-end 2))
3034 (cond
3035 ((markdown-new-baseline)
3036 (setq stop t))
3037 ((looking-at-p markdown-regex-list)
3038 (setq stop nil))
3039 (t (setq stop t)))))))
3041 (defun markdown-update-list-levels (marker indent levels)
3042 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3043 Here, MARKER is a string representing the type of list, INDENT is an integer
3044 giving the indentation, in spaces, of the current block, and LEVELS is a
3045 list of the indentation levels of parent list items. When LEVELS is nil,
3046 it means we are at baseline (not inside of a nested list)."
3047 (cond
3048 ;; New list item at baseline.
3049 ((and marker (null levels))
3050 (setq levels (list indent)))
3051 ;; List item with greater indentation (four or more spaces).
3052 ;; Increase list level.
3053 ((and marker (>= indent (+ (car levels) 4)))
3054 (setq levels (cons indent levels)))
3055 ;; List item with greater or equal indentation (less than four spaces).
3056 ;; Do not increase list level.
3057 ((and marker (>= indent (car levels)))
3058 levels)
3059 ;; Lesser indentation level.
3060 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3061 ;; indentation could move back more than one list level). Note
3062 ;; that this block need not be the beginning of list item.
3063 ((< indent (car levels))
3064 (while (and (> (length levels) 1)
3065 (< indent (+ (cadr levels) 4)))
3066 (setq levels (cdr levels)))
3067 levels)
3068 ;; Otherwise, do nothing.
3069 (t levels)))
3071 (defun markdown-calculate-list-levels ()
3072 "Calculate list levels at point.
3073 Return a list of the form (n1 n2 n3 ...) where n1 is the
3074 indentation of the deepest nested list item in the branch of
3075 the list at the point, n2 is the indentation of the parent
3076 list item, and so on. The depth of the list item is therefore
3077 the length of the returned list. If the point is not at or
3078 immediately after a list item, return nil."
3079 (save-excursion
3080 (let ((first (point)) levels indent pre-regexp)
3081 ;; Find a baseline point with zero list indentation
3082 (markdown-search-backward-baseline)
3083 ;; Search for all list items between baseline and LOC
3084 (while (and (< (point) first)
3085 (re-search-forward markdown-regex-list first t))
3086 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3087 (beginning-of-line)
3088 (cond
3089 ;; Make sure this is not a header or hr
3090 ((markdown-new-baseline) (setq levels nil))
3091 ;; Make sure this is not a line from a pre block
3092 ((looking-at-p pre-regexp))
3093 ;; If not, then update levels
3095 (setq indent (current-indentation))
3096 (setq levels (markdown-update-list-levels (match-string 2)
3097 indent levels))))
3098 (end-of-line))
3099 levels)))
3101 (defun markdown-prev-list-item (level)
3102 "Search backward from point for a list item with indentation LEVEL.
3103 Set point to the beginning of the item, and return point, or nil
3104 upon failure."
3105 (let (bounds indent prev)
3106 (setq prev (point))
3107 (forward-line -1)
3108 (setq indent (current-indentation))
3109 (while
3110 (cond
3111 ;; List item
3112 ((and (looking-at-p markdown-regex-list)
3113 (setq bounds (markdown-cur-list-item-bounds)))
3114 (cond
3115 ;; Stop and return point at item of equal indentation
3116 ((= (nth 3 bounds) level)
3117 (setq prev (point))
3118 nil)
3119 ;; Stop and return nil at item with lesser indentation
3120 ((< (nth 3 bounds) level)
3121 (setq prev nil)
3122 nil)
3123 ;; Stop at beginning of buffer
3124 ((bobp) (setq prev nil))
3125 ;; Continue at item with greater indentation
3126 ((> (nth 3 bounds) level) t)))
3127 ;; Stop at beginning of buffer
3128 ((bobp) (setq prev nil))
3129 ;; Continue if current line is blank
3130 ((markdown-cur-line-blank-p) t)
3131 ;; Continue while indentation is the same or greater
3132 ((>= indent level) t)
3133 ;; Stop if current indentation is less than list item
3134 ;; and the next is blank
3135 ((and (< indent level)
3136 (markdown-next-line-blank-p))
3137 (setq prev nil))
3138 ;; Stop at a header
3139 ((looking-at-p markdown-regex-header) (setq prev nil))
3140 ;; Stop at a horizontal rule
3141 ((looking-at-p markdown-regex-hr) (setq prev nil))
3142 ;; Otherwise, continue.
3143 (t t))
3144 (forward-line -1)
3145 (setq indent (current-indentation)))
3146 prev))
3148 (defun markdown-next-list-item (level)
3149 "Search forward from point for the next list item with indentation LEVEL.
3150 Set point to the beginning of the item, and return point, or nil
3151 upon failure."
3152 (let (bounds indent next)
3153 (setq next (point))
3154 (if (looking-at markdown-regex-header-setext)
3155 (goto-char (match-end 0)))
3156 (forward-line)
3157 (setq indent (current-indentation))
3158 (while
3159 (cond
3160 ;; Stop at end of the buffer.
3161 ((eobp) nil)
3162 ;; Continue if the current line is blank
3163 ((markdown-cur-line-blank-p) t)
3164 ;; List item
3165 ((and (looking-at-p markdown-regex-list)
3166 (setq bounds (markdown-cur-list-item-bounds)))
3167 (cond
3168 ;; Continue at item with greater indentation
3169 ((> (nth 3 bounds) level) t)
3170 ;; Stop and return point at item of equal indentation
3171 ((= (nth 3 bounds) level)
3172 (setq next (point))
3173 nil)
3174 ;; Stop and return nil at item with lesser indentation
3175 ((< (nth 3 bounds) level)
3176 (setq next nil)
3177 nil)))
3178 ;; Continue while indentation is the same or greater
3179 ((>= indent level) t)
3180 ;; Stop if current indentation is less than list item
3181 ;; and the previous line was blank.
3182 ((and (< indent level)
3183 (markdown-prev-line-blank-p))
3184 (setq next nil))
3185 ;; Stop at a header
3186 ((looking-at-p markdown-regex-header) (setq next nil))
3187 ;; Stop at a horizontal rule
3188 ((looking-at-p markdown-regex-hr) (setq next nil))
3189 ;; Otherwise, continue.
3190 (t t))
3191 (forward-line)
3192 (setq indent (current-indentation)))
3193 next))
3195 (defun markdown-cur-list-item-end (level)
3196 "Move to the end of the current list item with nonlist indentation LEVEL.
3197 If the point is not in a list item, do nothing."
3198 (let (indent)
3199 (forward-line)
3200 (setq indent (current-indentation))
3201 (while
3202 (cond
3203 ;; Stop at end of the buffer.
3204 ((eobp) nil)
3205 ;; Continue if the current line is blank
3206 ((markdown-cur-line-blank-p) t)
3207 ;; Continue while indentation is the same or greater
3208 ((>= indent level) t)
3209 ;; Stop if current indentation is less than list item
3210 ;; and the previous line was blank.
3211 ((and (< indent level)
3212 (markdown-prev-line-blank-p))
3213 nil)
3214 ;; Stop at a new list item of the same or lesser indentation
3215 ((looking-at-p markdown-regex-list) nil)
3216 ;; Stop at a header
3217 ((looking-at-p markdown-regex-header) nil)
3218 ;; Stop at a horizontal rule
3219 ((looking-at-p markdown-regex-hr) nil)
3220 ;; Otherwise, continue.
3221 (t t))
3222 (forward-line)
3223 (setq indent (current-indentation)))
3224 ;; Don't skip over whitespace for empty list items (marker and
3225 ;; whitespace only), just move to end of whitespace.
3226 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3227 (goto-char (match-end 3))
3228 (skip-syntax-backward "-"))))
3230 (defun markdown-cur-list-item-bounds ()
3231 "Return bounds and indentation of the current list item.
3232 Return a list of the following form:
3234 (begin end indent nonlist-indent marker checkbox)
3236 The named components are:
3238 - begin: Position of beginning of list item, including leading indentation.
3239 - end: Position of the end of the list item, including list item text.
3240 - indent: Number of characters of indentation before list marker (an integer).
3241 - nonlist-indent: Number characters of indentation, list
3242 marker, and whitespace following list marker (an integer).
3243 - marker: String containing the list marker and following whitespace
3244 (e.g., \"- \" or \"* \").
3245 - checkbox: String containing the GFM checkbox portion, if any,
3246 including any trailing whitespace before the text
3247 begins (e.g., \"[x] \").
3249 As an example, for the following unordered list item
3251 - item
3253 the returned list would be
3255 (1 14 3 5 \"- \" nil)
3257 If the point is not inside a list item, return nil.
3258 Leave match data intact for `markdown-regex-list'."
3259 (save-excursion
3260 (let ((cur (point)))
3261 (end-of-line)
3262 (when (re-search-backward markdown-regex-list nil t)
3263 (let* ((begin (match-beginning 0))
3264 (indent (length (match-string-no-properties 1)))
3265 (nonlist-indent (length (match-string 0)))
3266 (marker (concat (match-string-no-properties 2)
3267 (match-string-no-properties 3)))
3268 (checkbox (progn (goto-char (match-end 0))
3269 (when (looking-at "\\[[xX ]\\]\\s-*")
3270 (match-string-no-properties 0))))
3271 (end (save-match-data
3272 (markdown-cur-list-item-end nonlist-indent)
3273 (point))))
3274 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3275 (list begin end indent nonlist-indent marker checkbox)))))))
3277 (defun markdown-list-item-at-point-p ()
3278 "Return t if there is a list item at the point and nil otherwise."
3279 (save-match-data (markdown-cur-list-item-bounds)))
3281 (defun markdown-prev-list-item-bounds ()
3282 "Return bounds of previous item in the same list of any level.
3283 The return value has the same form as that of
3284 `markdown-cur-list-item-bounds'."
3285 (save-excursion
3286 (let ((cur-bounds (markdown-cur-list-item-bounds))
3287 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3288 stop)
3289 (when cur-bounds
3290 (goto-char (nth 0 cur-bounds))
3291 (while (and (not stop) (not (bobp))
3292 (re-search-backward markdown-regex-list
3293 beginning-of-list t))
3294 (unless (or (looking-at markdown-regex-hr)
3295 (markdown-code-block-at-point-p))
3296 (setq stop (point))))
3297 (markdown-cur-list-item-bounds)))))
3299 (defun markdown-next-list-item-bounds ()
3300 "Return bounds of next item in the same list of any level.
3301 The return value has the same form as that of
3302 `markdown-cur-list-item-bounds'."
3303 (save-excursion
3304 (let ((cur-bounds (markdown-cur-list-item-bounds))
3305 (end-of-list (save-excursion (markdown-end-of-list)))
3306 stop)
3307 (when cur-bounds
3308 (goto-char (nth 0 cur-bounds))
3309 (end-of-line)
3310 (while (and (not stop) (not (eobp))
3311 (re-search-forward markdown-regex-list
3312 end-of-list t))
3313 (unless (or (looking-at markdown-regex-hr)
3314 (markdown-code-block-at-point-p))
3315 (setq stop (point))))
3316 (when stop
3317 (markdown-cur-list-item-bounds))))))
3319 (defun markdown-beginning-of-list ()
3320 "Move point to beginning of list at point, if any."
3321 (interactive)
3322 (let ((orig-point (point))
3323 (list-begin (save-excursion
3324 (markdown-search-backward-baseline)
3325 ;; Stop at next list item, regardless of the indentation.
3326 (markdown-next-list-item (point-max))
3327 (when (looking-at markdown-regex-list)
3328 (point)))))
3329 (when (and list-begin (<= list-begin orig-point))
3330 (goto-char list-begin))))
3332 (defun markdown-end-of-list ()
3333 "Move point to end of list at point, if any."
3334 (interactive)
3335 (let ((start (point))
3336 (end (save-excursion
3337 (when (markdown-beginning-of-list)
3338 ;; Items can't have nonlist-indent <= 1, so this
3339 ;; moves past all list items.
3340 (markdown-next-list-item 1)
3341 (skip-syntax-backward "-")
3342 (unless (eobp) (forward-char 1))
3343 (point)))))
3344 (when (and end (>= end start))
3345 (goto-char end))))
3347 (defun markdown-up-list ()
3348 "Move point to beginning of parent list item."
3349 (interactive)
3350 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3351 (when cur-bounds
3352 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3353 (let ((up-bounds (markdown-cur-list-item-bounds)))
3354 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3355 (point))))))
3357 (defun markdown-bounds-of-thing-at-point (thing)
3358 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3359 Does not include trailing newlines when THING is 'line. Handles the
3360 end of buffer case by setting both endpoints equal to the value of
3361 `point-max', since an empty region will trigger empty markup insertion.
3362 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3363 (let* ((bounds (bounds-of-thing-at-point thing))
3364 (a (car bounds))
3365 (b (cdr bounds)))
3366 (when bounds
3367 (when (eq thing 'line)
3368 (cond ((and (eobp) (markdown-cur-line-blank-p))
3369 (setq a b))
3370 ((char-equal (char-before b) ?\^J)
3371 (setq b (1- b)))))
3372 (cons a b))))
3374 (defun markdown-reference-definition (reference)
3375 "Find out whether Markdown REFERENCE is defined.
3376 REFERENCE should not include the square brackets.
3377 When REFERENCE is defined, return a list of the form (text start end)
3378 containing the definition text itself followed by the start and end
3379 locations of the text. Otherwise, return nil.
3380 Leave match data for `markdown-regex-reference-definition'
3381 intact additional processing."
3382 (let ((reference (downcase reference)))
3383 (save-excursion
3384 (goto-char (point-min))
3385 (catch 'found
3386 (while (re-search-forward markdown-regex-reference-definition nil t)
3387 (when (string= reference (downcase (match-string-no-properties 2)))
3388 (throw 'found
3389 (list (match-string-no-properties 5)
3390 (match-beginning 5) (match-end 5)))))))))
3392 (defun markdown-get-defined-references ()
3393 "Return a list of all defined reference labels (not including square brackets)."
3394 (save-excursion
3395 (goto-char (point-min))
3396 (let (refs)
3397 (while (re-search-forward markdown-regex-reference-definition nil t)
3398 (let ((target (match-string-no-properties 2)))
3399 (cl-pushnew target refs :test #'equal)))
3400 (reverse refs))))
3402 (defun markdown-get-used-uris ()
3403 "Return a list of all used URIs in the buffer."
3404 (save-excursion
3405 (goto-char (point-min))
3406 (let (uris)
3407 (while (re-search-forward
3408 (concat "\\(?:" markdown-regex-link-inline
3409 "\\|" markdown-regex-angle-uri
3410 "\\|" markdown-regex-uri
3411 "\\|" markdown-regex-email
3412 "\\)")
3413 nil t)
3414 (unless (or (markdown-inline-code-at-point-p)
3415 (markdown-code-block-at-point-p))
3416 (cl-pushnew (or (match-string-no-properties 6)
3417 (match-string-no-properties 10)
3418 (match-string-no-properties 12)
3419 (match-string-no-properties 13))
3420 uris :test #'equal)))
3421 (reverse uris))))
3423 (defun markdown-inline-code-at-pos (pos)
3424 "Return non-nil if there is an inline code fragment at POS.
3425 Return nil otherwise. Set match data according to
3426 `markdown-match-code' upon success.
3427 This function searches the block for a code fragment that
3428 contains the point using `markdown-match-code'. We do this
3429 because `thing-at-point-looking-at' does not work reliably with
3430 `markdown-regex-code'.
3432 The match data is set as follows:
3433 Group 1 matches the opening backquotes.
3434 Group 2 matches the code fragment itself, without backquotes.
3435 Group 3 matches the closing backquotes."
3436 (save-excursion
3437 (goto-char pos)
3438 (let ((old-point (point))
3439 (end-of-block (progn (markdown-end-of-text-block) (point)))
3440 found)
3441 (markdown-beginning-of-text-block)
3442 (while (and (markdown-match-code end-of-block)
3443 (setq found t)
3444 (< (match-end 0) old-point)))
3445 (and found ; matched something
3446 (<= (match-beginning 0) old-point) ; match contains old-point
3447 (>= (match-end 0) old-point)))))
3449 (defun markdown-inline-code-at-pos-p (pos)
3450 "Return non-nil if there is an inline code fragment at POS.
3451 Like `markdown-inline-code-at-pos`, but preserves match data."
3452 (save-match-data (markdown-inline-code-at-pos pos)))
3454 (defun markdown-inline-code-at-point ()
3455 "Return non-nil if the point is at an inline code fragment.
3456 See `markdown-inline-code-at-pos' for details."
3457 (markdown-inline-code-at-pos (point)))
3459 (defun markdown-inline-code-at-point-p ()
3460 "Return non-nil if there is inline code at the point.
3461 This is a predicate function counterpart to
3462 `markdown-inline-code-at-point' which does not modify the match
3463 data. See `markdown-code-block-at-point-p' for code blocks."
3464 (save-match-data (markdown-inline-code-at-pos (point))))
3466 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3468 (defun markdown-code-block-at-pos (pos)
3469 "Return match data list if there is a code block at POS.
3470 Uses text properties at the beginning of the line position.
3471 This includes pre blocks, tilde-fenced code blocks, and GFM
3472 quoted code blocks. Return nil otherwise."
3473 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3474 (or (get-text-property pos 'markdown-pre)
3475 (markdown-get-enclosing-fenced-block-construct pos)
3476 ;; polymode removes text properties set by markdown-mode, so
3477 ;; check if `poly-markdown-mode' is active and whether the
3478 ;; `chunkmode' property is non-nil at POS.
3479 (and (bound-and-true-p poly-markdown-mode)
3480 (get-text-property pos 'chunkmode))))
3482 ;; Function was renamed to emphasize that it does not modify match-data.
3483 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3485 (defun markdown-code-block-at-point-p ()
3486 "Return non-nil if there is a code block at the point.
3487 This includes pre blocks, tilde-fenced code blocks, and GFM
3488 quoted code blocks. This function does not modify the match
3489 data. See `markdown-inline-code-at-point-p' for inline code."
3490 (save-match-data (markdown-code-block-at-pos (point))))
3492 (defun markdown-heading-at-point ()
3493 "Return non-nil if there is a heading at the point.
3494 Set match data for `markdown-regex-header'."
3495 (let ((match-data (get-text-property (point) 'markdown-heading)))
3496 (when match-data
3497 (set-match-data match-data)
3498 t)))
3500 (defun markdown-pipe-at-bol-p ()
3501 "Return non-nil if the line begins with a pipe symbol.
3502 This may be useful for tables and Pandoc's line_blocks extension."
3503 (char-equal (char-after (point-at-bol)) ?|))
3506 ;;; Markdown Font Lock Matching Functions =====================================
3508 (defun markdown-range-property-any (begin end prop prop-values)
3509 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3510 Also returns t if PROP is a list containing one of the PROP-VALUES.
3511 Return nil otherwise."
3512 (let (props)
3513 (catch 'found
3514 (dolist (loc (number-sequence begin end))
3515 (when (setq props (get-text-property loc prop))
3516 (cond ((listp props)
3517 ;; props is a list, check for membership
3518 (dolist (val prop-values)
3519 (when (memq val props) (throw 'found loc))))
3521 ;; props is a scalar, check for equality
3522 (dolist (val prop-values)
3523 (when (eq val props) (throw 'found loc))))))))))
3525 (defun markdown-range-properties-exist (begin end props)
3526 (cl-loop
3527 for loc in (number-sequence begin end)
3528 with result = nil
3529 while (not
3530 (setq result
3531 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3532 finally return result))
3534 (defun markdown-match-inline-generic (regex last &optional faceless)
3535 "Match inline REGEX from the point to LAST.
3536 When FACELESS is non-nil, do not return matches where faces have been applied."
3537 (when (re-search-forward regex last t)
3538 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3539 (face (and faceless (text-property-not-all
3540 (match-beginning 0) (match-end 0) 'face nil))))
3541 (cond
3542 ;; In code block: move past it and recursively search again
3543 (bounds
3544 (when (< (goto-char (cl-second bounds)) last)
3545 (markdown-match-inline-generic regex last faceless)))
3546 ;; When faces are found in the match range, skip over the match and
3547 ;; recursively search again.
3548 (face
3549 (when (< (goto-char (match-end 0)) last)
3550 (markdown-match-inline-generic regex last faceless)))
3551 ;; Keep match data and return t when in bounds.
3553 (<= (match-end 0) last))))))
3555 (defun markdown-match-code (last)
3556 "Match inline code fragments from point to LAST."
3557 (unless (bobp)
3558 (backward-char 1))
3559 (when (markdown-match-inline-generic markdown-regex-code last)
3560 (let ((begin (match-beginning 1))
3561 (end (match-end 1))
3562 (open-begin (match-beginning 2))
3563 (open-end (match-end 2))
3564 (code-begin (match-beginning 3))
3565 (code-end (match-end 3))
3566 (close-begin (match-beginning 4))
3567 (close-end (match-end 4)))
3568 (if (or (markdown-in-comment-p begin)
3569 (markdown-in-comment-p end)
3570 (markdown-code-block-at-pos begin))
3571 (progn (goto-char (min (1+ begin) last))
3572 (when (< (point) last)
3573 (markdown-match-code last)))
3574 (set-match-data (list begin end
3575 open-begin open-end
3576 code-begin code-end
3577 close-begin close-end))
3578 t))))
3580 (defun markdown-match-bold (last)
3581 "Match inline bold from the point to LAST."
3582 (when (markdown-match-inline-generic markdown-regex-bold last)
3583 (let ((begin (match-beginning 2))
3584 (end (match-end 2)))
3585 (if (or (markdown-inline-code-at-pos-p begin)
3586 (markdown-inline-code-at-pos-p end)
3587 (markdown-in-comment-p)
3588 (markdown-range-property-any
3589 begin begin 'face '(markdown-url-face
3590 markdown-plain-url-face))
3591 (markdown-range-property-any
3592 begin end 'face '(markdown-inline-code-face
3593 markdown-math-face)))
3594 (progn (goto-char (min (1+ begin) last))
3595 (when (< (point) last)
3596 (markdown-match-italic last)))
3597 (set-match-data (list (match-beginning 2) (match-end 2)
3598 (match-beginning 3) (match-end 3)
3599 (match-beginning 4) (match-end 4)
3600 (match-beginning 5) (match-end 5)))
3601 t))))
3603 (defun markdown-match-italic (last)
3604 "Match inline italics from the point to LAST."
3605 (let ((regex (if (eq major-mode 'gfm-mode)
3606 markdown-regex-gfm-italic markdown-regex-italic)))
3607 (when (markdown-match-inline-generic regex last)
3608 (let ((begin (match-beginning 1))
3609 (end (match-end 1)))
3610 (if (or (markdown-inline-code-at-pos-p begin)
3611 (markdown-inline-code-at-pos-p end)
3612 (markdown-in-comment-p)
3613 (markdown-range-property-any
3614 begin begin 'face '(markdown-url-face
3615 markdown-plain-url-face))
3616 (markdown-range-property-any
3617 begin end 'face '(markdown-inline-code-face
3618 markdown-bold-face
3619 markdown-list-face
3620 markdown-math-face)))
3621 (progn (goto-char (min (1+ begin) last))
3622 (when (< (point) last)
3623 (markdown-match-italic last)))
3624 (set-match-data (list (match-beginning 1) (match-end 1)
3625 (match-beginning 2) (match-end 2)
3626 (match-beginning 3) (match-end 3)
3627 (match-beginning 4) (match-end 4)))
3628 t)))))
3630 (defun markdown-match-math-generic (regex last)
3631 "Match REGEX from point to LAST.
3632 REGEX is either `markdown-regex-math-inline-single' for matching
3633 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3634 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3635 (let ((begin (match-beginning 1)) (end (match-end 1)))
3636 (prog1
3637 (if (or (markdown-range-property-any
3638 begin end 'face (list markdown-inline-code-face
3639 markdown-bold-face))
3640 (markdown-range-properties-exist
3641 begin end
3642 (markdown-get-fenced-block-middle-properties)))
3643 (markdown-match-math-generic regex last)
3645 (goto-char (1+ (match-end 0)))))))
3647 (defun markdown-match-list-items (last)
3648 "Match list items from point to LAST."
3649 (when (markdown-match-inline-generic markdown-regex-list last)
3650 (let ((begin (match-beginning 2))
3651 (end (match-end 2)))
3652 (if (or (markdown-range-property-any
3653 begin end 'face (list markdown-inline-code-face
3654 markdown-bold-face
3655 markdown-math-face))
3656 (markdown-range-properties-exist begin end '(markdown-hr))
3657 (markdown-in-comment-p))
3658 (progn (goto-char (min (1+ (match-end 0)) last))
3659 (markdown-match-list-items last))
3660 (set-match-data (list (match-beginning 0) (match-end 0)
3661 (match-beginning 1) (match-end 1)
3662 (match-beginning 2) (match-end 2)))
3663 (goto-char (1+ (match-end 0)))))))
3665 (defun markdown-match-math-single (last)
3666 "Match single quoted $..$ math from point to LAST."
3667 (markdown-match-math-generic markdown-regex-math-inline-single last))
3669 (defun markdown-match-math-double (last)
3670 "Match double quoted $$..$$ math from point to LAST."
3671 (markdown-match-math-generic markdown-regex-math-inline-double last))
3673 (defun markdown-match-propertized-text (property last)
3674 "Match text with PROPERTY from point to LAST.
3675 Restore match data previously stored in PROPERTY."
3676 (let ((saved (get-text-property (point) property))
3677 pos)
3678 (unless saved
3679 (setq pos (next-single-char-property-change (point) property nil last))
3680 (setq saved (get-text-property pos property)))
3681 (when saved
3682 (set-match-data saved)
3683 ;; Step at least one character beyond point. Otherwise
3684 ;; `font-lock-fontify-keywords-region' infloops.
3685 (goto-char (min (1+ (max (match-end 0) (point)))
3686 (point-max)))
3687 saved)))
3689 (defun markdown-match-pre-blocks (last)
3690 "Match preformatted blocks from point to LAST.
3691 Use data stored in 'markdown-pre text property during syntax
3692 analysis."
3693 (markdown-match-propertized-text 'markdown-pre last))
3695 (defun markdown-match-gfm-code-blocks (last)
3696 "Match GFM quoted code blocks from point to LAST.
3697 Use data stored in 'markdown-gfm-code text property during syntax
3698 analysis."
3699 (markdown-match-propertized-text 'markdown-gfm-code last))
3701 (defun markdown-match-gfm-open-code-blocks (last)
3702 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3704 (defun markdown-match-gfm-close-code-blocks (last)
3705 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3707 (defun markdown-match-fenced-code-blocks (last)
3708 "Match fenced code blocks from the point to LAST."
3709 (markdown-match-propertized-text 'markdown-fenced-code last))
3711 (defun markdown-match-fenced-start-code-block (last)
3712 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3714 (defun markdown-match-fenced-end-code-block (last)
3715 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3717 (defun markdown-match-blockquotes (last)
3718 "Match blockquotes from point to LAST.
3719 Use data stored in 'markdown-blockquote text property during syntax
3720 analysis."
3721 (markdown-match-propertized-text 'markdown-blockquote last))
3723 (defun markdown-match-hr (last)
3724 "Match horizontal rules comments from the point to LAST."
3725 (markdown-match-propertized-text 'markdown-hr last))
3727 (defun markdown-match-comments (last)
3728 "Match HTML comments from the point to LAST."
3729 (when (and (skip-syntax-forward "^<" last))
3730 (let ((beg (point)))
3731 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3732 (forward-char)
3733 (set-match-data (list beg (point)))
3734 t))))
3736 (defun markdown-match-generic-links (last ref)
3737 "Match inline links from point to LAST.
3738 When REF is non-nil, match reference links instead of standard
3739 links with URLs."
3740 ;; Search for the next potential link (not in a code block).
3741 (while (and (progn
3742 ;; Clear match data to test for a match after functions returns.
3743 (set-match-data nil)
3744 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3745 ;; Keep searching if this is in a code block, inline
3746 ;; code, or a comment, or if it is include syntax.
3747 (or (markdown-code-block-at-point-p)
3748 (markdown-inline-code-at-pos-p (match-beginning 0))
3749 (markdown-inline-code-at-pos-p (match-end 0))
3750 (markdown-in-comment-p)
3751 (and (char-equal (char-after (point-at-bol)) ?<)
3752 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3753 (< (point) last)))
3754 ;; Match opening exclamation point (optional) and left bracket.
3755 (when (match-beginning 2)
3756 (let* ((bang (match-beginning 1))
3757 (first-begin (match-beginning 2))
3758 ;; Find end of block to prevent matching across blocks.
3759 (end-of-block (save-excursion
3760 (progn
3761 (goto-char (match-beginning 2))
3762 (markdown-end-of-text-block)
3763 (point))))
3764 ;; Move over balanced expressions to closing right bracket.
3765 ;; Catch unbalanced expression errors and return nil.
3766 (first-end (condition-case nil
3767 (and (goto-char first-begin)
3768 (scan-sexps (point) 1))
3769 (error nil)))
3770 ;; Continue with point at CONT-POINT upon failure.
3771 (cont-point (min (1+ first-begin) last))
3772 second-begin second-end url-begin url-end
3773 title-begin title-end)
3774 ;; When bracket found, in range, and followed by a left paren/bracket...
3775 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3776 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3777 ;; Scan across balanced expressions for closing parenthesis/bracket.
3778 (setq second-begin (point)
3779 second-end (condition-case nil
3780 (scan-sexps (point) 1)
3781 (error nil)))
3782 ;; Check that closing parenthesis/bracket is in range.
3783 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3784 (progn
3785 ;; Search for (optional) title inside closing parenthesis
3786 (when (and (not ref) (search-forward "\"" second-end t))
3787 (setq title-begin (1- (point))
3788 title-end (and (goto-char second-end)
3789 (search-backward "\"" (1+ title-begin) t))
3790 title-end (and title-end (1+ title-end))))
3791 ;; Store URL/reference range
3792 (setq url-begin (1+ second-begin)
3793 url-end (1- (or title-begin second-end)))
3794 ;; Set match data, move point beyond link, and return
3795 (set-match-data
3796 (list (or bang first-begin) second-end ; 0 - all
3797 bang (and bang (1+ bang)) ; 1 - bang
3798 first-begin (1+ first-begin) ; 2 - markup
3799 (1+ first-begin) (1- first-end) ; 3 - link text
3800 (1- first-end) first-end ; 4 - markup
3801 second-begin (1+ second-begin) ; 5 - markup
3802 url-begin url-end ; 6 - url/reference
3803 title-begin title-end ; 7 - title
3804 (1- second-end) second-end)) ; 8 - markup
3805 ;; Nullify cont-point and leave point at end and
3806 (setq cont-point nil)
3807 (goto-char second-end))
3808 ;; If no closing parenthesis in range, update continuation point
3809 (setq cont-point (min end-of-block second-begin))))
3810 (cond
3811 ;; On failure, continue searching at cont-point
3812 ((and cont-point (< cont-point last))
3813 (goto-char cont-point)
3814 (markdown-match-generic-links last ref))
3815 ;; No more text, return nil
3816 ((and cont-point (= cont-point last))
3817 nil)
3818 ;; Return t if a match occurred
3819 (t t)))))
3821 (defun markdown-match-inline-links (last)
3822 "Match standard inline links from point to LAST."
3823 (markdown-match-generic-links last nil))
3825 (defun markdown-match-reference-links (last)
3826 "Match inline reference links from point to LAST."
3827 (markdown-match-generic-links last t))
3829 (defun markdown-match-angle-uris (last)
3830 "Match angle bracket URIs from point to LAST."
3831 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
3832 (goto-char (1+ (match-end 0)))))
3834 (defun markdown-match-plain-uris (last)
3835 "Match plain URIs from point to LAST."
3836 (when (markdown-match-inline-generic markdown-regex-uri last t)
3837 (goto-char (1+ (match-end 0)))))
3839 (defun markdown-get-match-boundaries (start-header end-header last &optional pos)
3840 (save-excursion
3841 (goto-char (or pos (point-min)))
3842 (cl-loop
3843 with cur-result = nil
3844 and st-hdr = (or start-header "\\`")
3845 and end-hdr = (or end-header "\n\n\\|\n\\'\\|\\'")
3846 while (and (< (point) last)
3847 (re-search-forward st-hdr last t)
3848 (progn
3849 (setq cur-result (match-data))
3850 (re-search-forward end-hdr nil t)))
3851 collect (list cur-result (match-data)))))
3853 (defvar markdown-conditional-search-function #'re-search-forward
3854 "Conditional search function used in `markdown-search-until-condition'.
3855 Made into a variable to allow for dynamic let-binding.")
3857 (defun markdown-search-until-condition (condition &rest args)
3858 (let (ret)
3859 (while (and (not ret) (apply markdown-conditional-search-function args))
3860 (setq ret (funcall condition)))
3861 ret))
3863 (defun markdown-match-generic-metadata
3864 (regexp last &optional start-header end-header)
3865 "Match generic metadata specified by REGEXP from the point to LAST.
3866 If START-HEADER is nil, we assume metadata can only occur at the
3867 very top of a file (\"\\`\"). If END-HEADER is nil, we assume it
3868 is \"\n\n\""
3869 (let* ((header-bounds
3870 (markdown-get-match-boundaries start-header end-header last))
3871 (enclosing-header
3872 (cl-find-if ; just take first if multiple
3873 (lambda (match-bounds)
3874 (cl-destructuring-bind (begin end) (cl-second match-bounds)
3875 (and (< (point) begin)
3876 (save-excursion (re-search-forward regexp end t)))))
3877 header-bounds))
3878 (header-begin
3879 (when enclosing-header (cl-second (cl-first enclosing-header))))
3880 (header-end
3881 (when enclosing-header (cl-first (cl-second enclosing-header)))))
3882 (cond ((null enclosing-header)
3883 ;; Don't match anything outside of a header.
3884 nil)
3885 ((markdown-search-until-condition
3886 (lambda () (> (point) header-begin)) regexp (min last header-end) t)
3887 ;; If a metadata item is found, it may span several lines.
3888 (let ((key-beginning (match-beginning 1))
3889 (key-end (match-end 1))
3890 (markup-begin (match-beginning 2))
3891 (markup-end (match-end 2))
3892 (value-beginning (match-beginning 3)))
3893 (set-match-data (list key-beginning (point) ; complete metadata
3894 key-beginning key-end ; key
3895 markup-begin markup-end ; markup
3896 value-beginning (point))) ; value
3898 (t nil))))
3900 (defun markdown-match-declarative-metadata (last)
3901 "Match declarative metadata from the point to LAST."
3902 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
3904 (defun markdown-match-pandoc-metadata (last)
3905 "Match Pandoc metadata from the point to LAST."
3906 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
3908 (defun markdown-match-yaml-metadata-begin (last)
3909 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
3911 (defun markdown-match-yaml-metadata-end (last)
3912 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
3914 (defun markdown-match-yaml-metadata-key (last)
3915 (markdown-match-propertized-text 'markdown-metadata-key last))
3917 (defun markdown-match-inline-attributes (last)
3918 "Match inline attributes from point to LAST."
3919 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
3920 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3921 (markdown-inline-code-at-pos-p (match-end 0))
3922 (markdown-in-comment-p))
3923 t)))
3925 (defun markdown-match-leanpub-sections (last)
3926 "Match Leanpub section markers from point to LAST."
3927 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
3928 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
3929 (markdown-inline-code-at-pos-p (match-end 0))
3930 (markdown-in-comment-p))
3931 t)))
3933 (defun markdown-match-includes (last)
3934 "Match include statements from point to LAST.
3935 Sets match data for the following seven groups:
3936 Group 1: opening two angle brackets
3937 Group 2: opening title delimiter (optional)
3938 Group 3: title text (optional)
3939 Group 4: closing title delimiter (optional)
3940 Group 5: opening filename delimiter
3941 Group 6: filename
3942 Group 7: closing filename delimiter"
3943 (when (markdown-match-inline-generic markdown-regex-include last)
3944 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
3945 (markdown-in-comment-p (match-end 0))
3946 (markdown-code-block-at-pos (match-beginning 0))))))
3947 (cond
3948 ;; Parentheses and maybe square brackets, but no curly braces:
3949 ;; match optional title in square brackets and file in parentheses.
3950 ((and valid (match-beginning 5)
3951 (not (match-beginning 8)))
3952 (set-match-data (list (match-beginning 1) (match-end 7)
3953 (match-beginning 1) (match-end 1)
3954 (match-beginning 2) (match-end 2)
3955 (match-beginning 3) (match-end 3)
3956 (match-beginning 4) (match-end 4)
3957 (match-beginning 5) (match-end 5)
3958 (match-beginning 6) (match-end 6)
3959 (match-beginning 7) (match-end 7))))
3960 ;; Only square brackets present: match file in square brackets.
3961 ((and valid (match-beginning 2)
3962 (not (match-beginning 5))
3963 (not (match-beginning 7)))
3964 (set-match-data (list (match-beginning 1) (match-end 4)
3965 (match-beginning 1) (match-end 1)
3966 nil nil
3967 nil nil
3968 nil nil
3969 (match-beginning 2) (match-end 2)
3970 (match-beginning 3) (match-end 3)
3971 (match-beginning 4) (match-end 4))))
3972 ;; Only curly braces present: match file in curly braces.
3973 ((and valid (match-beginning 8)
3974 (not (match-beginning 2))
3975 (not (match-beginning 5)))
3976 (set-match-data (list (match-beginning 1) (match-end 10)
3977 (match-beginning 1) (match-end 1)
3978 nil nil
3979 nil nil
3980 nil nil
3981 (match-beginning 8) (match-end 8)
3982 (match-beginning 9) (match-end 9)
3983 (match-beginning 10) (match-end 10))))
3985 ;; Not a valid match, move to next line and search again.
3986 (forward-line)
3987 (when (< (point) last)
3988 (setq valid (markdown-match-includes last)))))
3989 valid)))
3992 ;;; Markdown Font Fontification Functions =====================================
3994 (defun markdown-fontify-headings (last)
3995 "Add text properties to headings from point to LAST."
3996 (when (markdown-match-propertized-text 'markdown-heading last)
3997 (let* ((level (markdown-outline-level))
3998 (heading-face
3999 (intern (format "markdown-header-face-%d" level)))
4000 (heading-props `(face ,heading-face))
4001 (markup-props `(face markdown-header-delimiter-face
4002 ,@(when markdown-hide-markup `(display ""))))
4003 (rule-props `(face markdown-header-rule-face
4004 ,@(when markdown-hide-markup `(display "")))))
4005 (if (match-end 1)
4006 ;; Setext heading
4007 (progn (add-text-properties
4008 (match-beginning 1) (match-end 1) heading-props)
4009 (if (= level 1)
4010 (add-text-properties
4011 (match-beginning 2) (match-end 2) rule-props)
4012 (add-text-properties
4013 (match-beginning 3) (match-end 3) rule-props)))
4014 ;; atx heading
4015 (add-text-properties
4016 (match-beginning 4) (match-end 4) markup-props)
4017 (add-text-properties
4018 (match-beginning 5) (match-end 5) heading-props)
4019 (when (match-end 6)
4020 (add-text-properties
4021 (match-beginning 6) (match-end 6) markup-props))))
4024 (defun markdown-fontify-blockquotes (last)
4025 "Apply font-lock properties to blockquotes from point to LAST."
4026 (when (markdown-match-blockquotes last)
4027 (add-text-properties
4028 (match-beginning 1) (match-end 1)
4029 (if markdown-hide-markup
4030 `(face markdown-blockquote-face
4031 display ,markdown-blockquote-display-char)
4032 `(face markdown-markup-face
4033 ,@(when markdown-hide-markup
4034 `(display ,markdown-blockquote-display-char)))))
4035 (font-lock-append-text-property
4036 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4039 (defun markdown-fontify-list-items (last)
4040 "Apply font-lock properties to list markers from point to LAST."
4041 (when (markdown-match-list-items last)
4042 (let* ((indent (length (match-string-no-properties 1)))
4043 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4044 (bullet (nth (mod level (length markdown-list-item-bullets))
4045 markdown-list-item-bullets)))
4046 (add-text-properties
4047 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4048 (when markdown-hide-markup
4049 (cond
4050 ;; Unordered lists
4051 ((string-match-p "[\\*\\+-]" (match-string 2))
4052 (add-text-properties
4053 (match-beginning 2) (match-end 2) `(display ,bullet)))
4054 ;; Definition lists
4055 ((string-equal ":" (match-string 2))
4056 (add-text-properties
4057 (match-beginning 2) (match-end 2)
4058 `(display ,(char-to-string markdown-definition-display-char)))))))
4061 (defun markdown-fontify-hrs (last)
4062 "Add text properties to horizontal rules from point to LAST."
4063 (when (markdown-match-hr last)
4064 (add-text-properties
4065 (match-beginning 0) (match-end 0)
4066 `(face markdown-hr-face
4067 font-lock-multiline t
4068 ,@(when markdown-hide-markup
4069 `(display ,(make-string
4070 (window-body-width) markdown-hr-display-char)))))
4073 (defun markdown-fontify-sub-superscripts (last)
4074 "Apply text properties to sub- and superscripts from point to LAST."
4075 (when (markdown-search-until-condition
4076 (lambda () (and (not (markdown-code-block-at-point-p))
4077 (not (markdown-inline-code-at-point-p))
4078 (not (markdown-in-comment-p))))
4079 markdown-regex-sub-superscript last t)
4080 (let* ((subscript-p (string= (match-string 2) "~"))
4081 (index (if subscript-p 0 1))
4082 (mp (list 'face 'markdown-markup-face
4083 'invisible 'markdown-markup)))
4084 (when markdown-hide-markup
4085 (put-text-property (match-beginning 3) (match-end 3)
4086 'display
4087 (nth index markdown-sub-superscript-display)))
4088 (add-text-properties (match-beginning 2) (match-end 2) mp)
4089 (add-text-properties (match-beginning 4) (match-end 4) mp)
4090 t)))
4093 ;;; Syntax Table ==============================================================
4095 (defvar markdown-mode-syntax-table
4096 (let ((tab (make-syntax-table text-mode-syntax-table)))
4097 (modify-syntax-entry ?\" "." tab)
4098 tab)
4099 "Syntax table for `markdown-mode'.")
4102 ;;; Element Insertion =========================================================
4104 (defun markdown-ensure-blank-line-before ()
4105 "If previous line is not already blank, insert a blank line before point."
4106 (unless (bolp) (insert "\n"))
4107 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4109 (defun markdown-ensure-blank-line-after ()
4110 "If following line is not already blank, insert a blank line after point.
4111 Return the point where it was originally."
4112 (save-excursion
4113 (unless (eolp) (insert "\n"))
4114 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4116 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4117 "Insert the strings S1 and S2, wrapping around region or THING.
4118 If a region is specified by the optional BEG and END arguments,
4119 wrap the strings S1 and S2 around that region.
4120 If there is an active region, wrap the strings S1 and S2 around
4121 the region. If there is not an active region but the point is at
4122 THING, wrap that thing (which defaults to word). Otherwise, just
4123 insert S1 and S2 and place the cursor in between. Return the
4124 bounds of the entire wrapped string, or nil if nothing was wrapped
4125 and S1 and S2 were only inserted."
4126 (let (a b bounds new-point)
4127 (cond
4128 ;; Given region
4129 ((and beg end)
4130 (setq a beg
4131 b end
4132 new-point (+ (point) (length s1))))
4133 ;; Active region
4134 ((markdown-use-region-p)
4135 (setq a (region-beginning)
4136 b (region-end)
4137 new-point (+ (point) (length s1))))
4138 ;; Thing (word) at point
4139 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4140 (setq a (car bounds)
4141 b (cdr bounds)
4142 new-point (+ (point) (length s1))))
4143 ;; No active region and no word
4145 (setq a (point)
4146 b (point))))
4147 (goto-char b)
4148 (insert s2)
4149 (goto-char a)
4150 (insert s1)
4151 (when new-point (goto-char new-point))
4152 (if (= a b)
4154 (setq b (+ b (length s1) (length s2)))
4155 (cons a b))))
4157 (defun markdown-point-after-unwrap (cur prefix suffix)
4158 "Return desired position of point after an unwrapping operation.
4159 CUR gives the position of the point before the operation.
4160 Additionally, two cons cells must be provided. PREFIX gives the
4161 bounds of the prefix string and SUFFIX gives the bounds of the
4162 suffix string."
4163 (cond ((< cur (cdr prefix)) (car prefix))
4164 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4165 ((<= cur (cdr suffix))
4166 (- cur (+ (- (cdr prefix) (car prefix))
4167 (- cur (car suffix)))))
4168 (t cur)))
4170 (defun markdown-unwrap-thing-at-point (regexp all text)
4171 "Remove prefix and suffix of thing at point and reposition the point.
4172 When the thing at point matches REGEXP, replace the subexpression
4173 ALL with the string in subexpression TEXT. Reposition the point
4174 in an appropriate location accounting for the removal of prefix
4175 and suffix strings. Return new bounds of string from group TEXT.
4176 When REGEXP is nil, assumes match data is already set."
4177 (when (or (null regexp)
4178 (thing-at-point-looking-at regexp))
4179 (let ((cur (point))
4180 (prefix (cons (match-beginning all) (match-beginning text)))
4181 (suffix (cons (match-end text) (match-end all)))
4182 (bounds (cons (match-beginning text) (match-end text))))
4183 ;; Replace the thing at point
4184 (replace-match (match-string text) t t nil all)
4185 ;; Reposition the point
4186 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4187 ;; Adjust bounds
4188 (setq bounds (cons (car prefix)
4189 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4191 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4192 "Remove prefix and suffix of all things in region from BEG to END.
4193 When a thing in the region matches REGEXP, replace the
4194 subexpression ALL with the string in subexpression TEXT.
4195 Return a cons cell containing updated bounds for the region."
4196 (save-excursion
4197 (goto-char beg)
4198 (let ((removed 0) len-all len-text)
4199 (while (re-search-forward regexp (- end removed) t)
4200 (setq len-all (length (match-string-no-properties all)))
4201 (setq len-text (length (match-string-no-properties text)))
4202 (setq removed (+ removed (- len-all len-text)))
4203 (replace-match (match-string text) t t nil all))
4204 (cons beg (- end removed)))))
4206 (defun markdown-insert-hr (arg)
4207 "Insert or replace a horizonal rule.
4208 By default, use the first element of `markdown-hr-strings'. When
4209 ARG is non-nil, as when given a prefix, select a different
4210 element as follows. When prefixed with \\[universal-argument],
4211 use the last element of `markdown-hr-strings' instead. When
4212 prefixed with an integer from 1 to the length of
4213 `markdown-hr-strings', use the element in that position instead."
4214 (interactive "*P")
4215 (when (thing-at-point-looking-at markdown-regex-hr)
4216 (delete-region (match-beginning 0) (match-end 0)))
4217 (markdown-ensure-blank-line-before)
4218 (cond ((equal arg '(4))
4219 (insert (car (reverse markdown-hr-strings))))
4220 ((and (integerp arg) (> arg 0)
4221 (<= arg (length markdown-hr-strings)))
4222 (insert (nth (1- arg) markdown-hr-strings)))
4224 (insert (car markdown-hr-strings))))
4225 (markdown-ensure-blank-line-after))
4227 (defun markdown-insert-bold ()
4228 "Insert markup to make a region or word bold.
4229 If there is an active region, make the region bold. If the point
4230 is at a non-bold word, make the word bold. If the point is at a
4231 bold word or phrase, remove the bold markup. Otherwise, simply
4232 insert bold delimiters and place the cursor in between them."
4233 (interactive)
4234 (let ((delim (if markdown-bold-underscore "__" "**")))
4235 (if (markdown-use-region-p)
4236 ;; Active region
4237 (let ((bounds (markdown-unwrap-things-in-region
4238 (region-beginning) (region-end)
4239 markdown-regex-bold 2 4)))
4240 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4241 ;; Bold markup removal, bold word at point, or empty markup insertion
4242 (if (thing-at-point-looking-at markdown-regex-bold)
4243 (markdown-unwrap-thing-at-point nil 2 4)
4244 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4246 (defun markdown-insert-italic ()
4247 "Insert markup to make a region or word italic.
4248 If there is an active region, make the region italic. If the point
4249 is at a non-italic word, make the word italic. If the point is at an
4250 italic word or phrase, remove the italic markup. Otherwise, simply
4251 insert italic delimiters and place the cursor in between them."
4252 (interactive)
4253 (let ((delim (if markdown-italic-underscore "_" "*")))
4254 (if (markdown-use-region-p)
4255 ;; Active region
4256 (let ((bounds (markdown-unwrap-things-in-region
4257 (region-beginning) (region-end)
4258 markdown-regex-italic 1 3)))
4259 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4260 ;; Italic markup removal, italic word at point, or empty markup insertion
4261 (if (thing-at-point-looking-at markdown-regex-italic)
4262 (markdown-unwrap-thing-at-point nil 1 3)
4263 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4265 (defun markdown-insert-strike-through ()
4266 "Insert markup to make a region or word strikethrough.
4267 If there is an active region, make the region strikethrough. If the point
4268 is at a non-bold word, make the word strikethrough. If the point is at a
4269 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4270 simply insert bold delimiters and place the cursor in between them."
4271 (interactive)
4272 (let ((delim "~~"))
4273 (if (markdown-use-region-p)
4274 ;; Active region
4275 (let ((bounds (markdown-unwrap-things-in-region
4276 (region-beginning) (region-end)
4277 markdown-regex-strike-through 2 4)))
4278 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4279 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4280 (if (thing-at-point-looking-at markdown-regex-strike-through)
4281 (markdown-unwrap-thing-at-point nil 2 4)
4282 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4284 (defun markdown-insert-code ()
4285 "Insert markup to make a region or word an inline code fragment.
4286 If there is an active region, make the region an inline code
4287 fragment. If the point is at a word, make the word an inline
4288 code fragment. Otherwise, simply insert code delimiters and
4289 place the cursor in between them."
4290 (interactive)
4291 (if (markdown-use-region-p)
4292 ;; Active region
4293 (let ((bounds (markdown-unwrap-things-in-region
4294 (region-beginning) (region-end)
4295 markdown-regex-code 1 3)))
4296 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4297 ;; Code markup removal, code markup for word, or empty markup insertion
4298 (if (markdown-inline-code-at-point)
4299 (markdown-unwrap-thing-at-point nil 0 2)
4300 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4302 (defun markdown-insert-kbd ()
4303 "Insert markup to wrap region or word in <kbd> tags.
4304 If there is an active region, use the region. If the point is at
4305 a word, use the word. Otherwise, simply insert <kbd> tags and
4306 place the cursor in between them."
4307 (interactive)
4308 (if (markdown-use-region-p)
4309 ;; Active region
4310 (let ((bounds (markdown-unwrap-things-in-region
4311 (region-beginning) (region-end)
4312 markdown-regex-kbd 0 2)))
4313 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4314 ;; Markup removal, markup for word, or empty markup insertion
4315 (if (thing-at-point-looking-at markdown-regex-kbd)
4316 (markdown-unwrap-thing-at-point nil 0 2)
4317 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4319 (defun markdown-insert-inline-link (text url &optional title)
4320 "Insert an inline link with TEXT pointing to URL.
4321 Optionally, the user can provide a TITLE."
4322 (let ((cur (point)))
4323 (setq title (and title (concat " \"" title "\"")))
4324 (insert (concat "[" text "](" url title ")"))
4325 (cond ((not text) (goto-char (+ 1 cur)))
4326 ((not url) (goto-char (+ 3 (length text) cur))))))
4328 (defun markdown-insert-inline-image (text url &optional title)
4329 "Insert an inline link with alt TEXT pointing to URL.
4330 Optionally, also provide a TITLE."
4331 (let ((cur (point)))
4332 (setq title (and title (concat " \"" title "\"")))
4333 (insert (concat "![" text "](" url title ")"))
4334 (cond ((not text) (goto-char (+ 2 cur)))
4335 ((not url) (goto-char (+ 4 (length text) cur))))))
4337 (defun markdown-insert-reference-link (text label &optional url title)
4338 "Insert a reference link and, optionally, a reference definition.
4339 The link TEXT will be inserted followed by the optional LABEL.
4340 If a URL is given, also insert a definition for the reference
4341 LABEL according to `markdown-reference-location'. If a TITLE is
4342 given, it will be added to the end of the reference definition
4343 and will be used to populate the title attribute when converted
4344 to XHTML. If URL is nil, insert only the link portion (for
4345 example, when a reference label is already defined)."
4346 (insert (concat "[" text "][" label "]"))
4347 (when url
4348 (markdown-insert-reference-definition
4349 (if (string-equal label "") text label)
4350 url title)))
4352 (defun markdown-insert-reference-image (text label &optional url title)
4353 "Insert a reference image and, optionally, a reference definition.
4354 The alt TEXT will be inserted followed by the optional LABEL.
4355 If a URL is given, also insert a definition for the reference
4356 LABEL according to `markdown-reference-location'. If a TITLE is
4357 given, it will be added to the end of the reference definition
4358 and will be used to populate the title attribute when converted
4359 to XHTML. If URL is nil, insert only the link portion (for
4360 example, when a reference label is already defined)."
4361 (insert (concat "![" text "][" label "]"))
4362 (when url
4363 (markdown-insert-reference-definition
4364 (if (string-equal label "") text label)
4365 url title)))
4367 (defun markdown-insert-reference-definition (label &optional url title)
4368 "Add definition for reference LABEL with URL and TITLE.
4369 LABEL is a Markdown reference label without square brackets.
4370 URL and TITLE are optional. When given, the TITLE will
4371 be used to populate the title attribute when converted to XHTML."
4372 ;; END specifies where to leave the point upon return
4373 (let ((end (point)))
4374 (cl-case markdown-reference-location
4375 (end (goto-char (point-max)))
4376 (immediately (markdown-end-of-text-block))
4377 (subtree (markdown-end-of-subtree))
4378 (header (markdown-end-of-defun)))
4379 ;; Skip backwards over local variables. This logic is similar to the one
4380 ;; used in ‘hack-local-variables’.
4381 (when (and enable-local-variables (eobp))
4382 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4383 (when (let ((case-fold-search t))
4384 (search-forward "Local Variables:" nil :move))
4385 (beginning-of-line 0)
4386 (when (eq (char-before) ?\n) (backward-char))))
4387 (unless (or (markdown-cur-line-blank-p)
4388 (thing-at-point-looking-at markdown-regex-reference-definition))
4389 (insert "\n"))
4390 (insert "\n[" label "]: ")
4391 (if url
4392 (insert url)
4393 ;; When no URL is given, leave cursor at END following the colon
4394 (setq end (point)))
4395 (when (> (length title) 0)
4396 (insert " \"" title "\""))
4397 (unless (looking-at-p "\n")
4398 (insert "\n"))
4399 (goto-char end)
4400 (when url
4401 (message
4402 (markdown--substitute-command-keys
4403 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4404 label))))
4406 (define-obsolete-function-alias
4407 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4408 (define-obsolete-function-alias
4409 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4411 (defun markdown--insert-link-or-image (image)
4412 "Interactively insert new or update an existing link or image.
4413 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4414 This is an internal function called by
4415 `markdown-insert-link' and `markdown-insert-image'."
4416 (cl-multiple-value-bind (begin end text uri ref title)
4417 (if (markdown-use-region-p)
4418 ;; Use region as either link text or URL as appropriate.
4419 (let ((region (buffer-substring-no-properties
4420 (region-beginning) (region-end))))
4421 (if (string-match markdown-regex-uri region)
4422 ;; Region contains a URL; use it as such.
4423 (list (region-beginning) (region-end)
4424 nil (match-string 0 region) nil nil)
4425 ;; Region doesn't contain a URL, so use it as text.
4426 (list (region-beginning) (region-end)
4427 region nil nil nil)))
4428 ;; Extract and use properties of existing link, if any.
4429 (markdown-link-at-pos (point)))
4430 (let* ((ref (when ref (concat "[" ref "]")))
4431 (defined-refs (append
4432 (mapcar (lambda (ref) (concat "[" ref "]"))
4433 (markdown-get-defined-references))))
4434 (used-uris (markdown-get-used-uris))
4435 (uri-or-ref (completing-read
4436 "URL or [reference]: "
4437 (append defined-refs used-uris)
4438 nil nil (or uri ref)))
4439 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4440 (match-string 1 uri-or-ref))
4441 ((string-equal "" uri-or-ref)
4442 "")))
4443 (uri (unless ref uri-or-ref))
4444 (text-prompt (if image
4445 "Alt text: "
4446 (if ref
4447 "Link text: "
4448 "Link text (blank for plain URL): ")))
4449 (text (read-string text-prompt text))
4450 (text (if (= (length text) 0) nil text))
4451 (plainp (and uri (not text)))
4452 (implicitp (string-equal ref ""))
4453 (ref (if implicitp text ref))
4454 (definedp (and ref (markdown-reference-definition ref)))
4455 (ref-url (unless (or uri definedp)
4456 (completing-read "Reference URL: " used-uris)))
4457 (title (unless (or plainp definedp)
4458 (read-string "Title (tooltip text, optional): " title)))
4459 (title (if (= (length title) 0) nil title)))
4460 (when (and image implicitp)
4461 (user-error "Reference required: implicit image references are invalid"))
4462 (when (and begin end)
4463 (delete-region begin end))
4464 (cond
4465 ((and (not image) uri text)
4466 (markdown-insert-inline-link text uri title))
4467 ((and image uri text)
4468 (markdown-insert-inline-image text uri title))
4469 ((and ref text)
4470 (if image
4471 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4472 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4473 (unless definedp
4474 (markdown-insert-reference-definition ref ref-url title)))
4475 ((and (not image) uri)
4476 (markdown-insert-uri uri))))))
4478 (defun markdown-insert-link ()
4479 "Insert new or update an existing link, with interactive prompts.
4480 If the point is at an existing link or URL, update the link text,
4481 URL, reference label, and/or title. Otherwise, insert a new link.
4482 The type of link inserted (inline, reference, or plain URL)
4483 depends on which values are provided:
4485 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4486 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4487 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4488 * If only a URL is given, insert a plain link: <URL>.
4490 In other words, to create an implicit reference link, leave the
4491 URL prompt empty and to create a plain URL link, leave the link
4492 text empty.
4494 If there is an active region, use the text as the default URL, if
4495 it seems to be a URL, or link text value otherwise.
4497 If a given reference is not defined, this function will
4498 additionally prompt for the URL and optional title. In this case,
4499 the reference definition is placed at the location determined by
4500 `markdown-reference-location'.
4502 Through updating the link, this function can be used to convert a
4503 link of one type (inline, reference, or plain) to another type by
4504 selectively adding or removing information via the prompts."
4505 (interactive)
4506 (markdown--insert-link-or-image nil))
4508 (defun markdown-insert-image ()
4509 "Insert new or update an existing image, with interactive prompts.
4510 If the point is at an existing image, update the alt text, URL,
4511 reference label, and/or title. Otherwise, insert a new image.
4512 The type of image inserted (inline or reference) depends on which
4513 values are provided:
4515 * If a URL and ALT-TEXT are given, insert an inline image:
4516 ![ALT-TEXT](URL).
4517 * If [REF] and ALT-TEXT are given, insert a reference image:
4518 ![ALT-TEXT][REF].
4520 If there is an active region, use the text as the default URL, if
4521 it seems to be a URL, or alt text value otherwise.
4523 If a given reference is not defined, this function will
4524 additionally prompt for the URL and optional title. In this case,
4525 the reference definition is placed at the location determined by
4526 `markdown-reference-location'.
4528 Through updating the image, this function can be used to convert an
4529 image of one type (inline or reference) to another type by
4530 selectively adding or removing information via the prompts."
4531 (interactive)
4532 (markdown--insert-link-or-image t))
4534 (defun markdown-insert-uri (&optional uri)
4535 "Insert markup for an inline URI.
4536 If there is an active region, use it as the URI. If the point is
4537 at a URI, wrap it with angle brackets. If the point is at an
4538 inline URI, remove the angle brackets. Otherwise, simply insert
4539 angle brackets place the point between them."
4540 (interactive)
4541 (if (markdown-use-region-p)
4542 ;; Active region
4543 (let ((bounds (markdown-unwrap-things-in-region
4544 (region-beginning) (region-end)
4545 markdown-regex-angle-uri 0 2)))
4546 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4547 ;; Markup removal, URI at point, new URI, or empty markup insertion
4548 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4549 (markdown-unwrap-thing-at-point nil 0 2)
4550 (if uri
4551 (insert "<" uri ">")
4552 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4554 (defun markdown-insert-wiki-link ()
4555 "Insert a wiki link of the form [[WikiLink]].
4556 If there is an active region, use the region as the link text.
4557 If the point is at a word, use the word as the link text. If
4558 there is no active region and the point is not at word, simply
4559 insert link markup."
4560 (interactive)
4561 (if (markdown-use-region-p)
4562 ;; Active region
4563 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4564 ;; Markup removal, wiki link at at point, or empty markup insertion
4565 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4566 (if (or markdown-wiki-link-alias-first
4567 (null (match-string 5)))
4568 (markdown-unwrap-thing-at-point nil 1 3)
4569 (markdown-unwrap-thing-at-point nil 1 5))
4570 (markdown-wrap-or-insert "[[" "]]"))))
4572 (defun markdown-remove-header ()
4573 "Remove header markup if point is at a header.
4574 Return bounds of remaining header text if a header was removed
4575 and nil otherwise."
4576 (interactive "*")
4577 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4578 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4580 (defun markdown-insert-header (&optional level text setext)
4581 "Insert or replace header markup.
4582 The level of the header is specified by LEVEL and header text is
4583 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4584 default value is 1.
4585 When TEXT is nil, the header text is obtained as follows.
4586 If there is an active region, it is used as the header text.
4587 Otherwise, the current line will be used as the header text.
4588 If there is not an active region and the point is at a header,
4589 remove the header markup and replace with level N header.
4590 Otherwise, insert empty header markup and place the cursor in
4591 between.
4592 The style of the header will be atx (hash marks) unless
4593 SETEXT is non-nil, in which case a setext-style (underlined)
4594 header will be inserted."
4595 (interactive "p\nsHeader text: ")
4596 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4597 ;; Determine header text if not given
4598 (when (null text)
4599 (if (markdown-use-region-p)
4600 ;; Active region
4601 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4602 ;; No active region
4603 (markdown-remove-header)
4604 (setq text (delete-and-extract-region
4605 (line-beginning-position) (line-end-position)))
4606 (when (and setext (string-match-p "^[ \t]*$" text))
4607 (setq text (read-string "Header text: "))))
4608 (setq text (markdown-compress-whitespace-string text)))
4609 ;; Insertion with given text
4610 (markdown-ensure-blank-line-before)
4611 (let (hdr)
4612 (cond (setext
4613 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4614 (insert text "\n" hdr))
4616 (setq hdr (make-string level ?#))
4617 (insert hdr " " text)
4618 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4619 (markdown-ensure-blank-line-after)
4620 ;; Leave point at end of text
4621 (cond (setext
4622 (backward-char (1+ (string-width text))))
4623 ((null markdown-asymmetric-header)
4624 (backward-char (1+ level)))))
4626 (defun markdown-insert-header-dwim (&optional arg setext)
4627 "Insert or replace header markup.
4628 The level and type of the header are determined automatically by
4629 the type and level of the previous header, unless a prefix
4630 argument is given via ARG.
4631 With a numeric prefix valued 1 to 6, insert a header of the given
4632 level, with the type being determined automatically (note that
4633 only level 1 or 2 setext headers are possible).
4635 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4636 promote the heading by one level.
4637 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4638 demote the heading by one level.
4639 When SETEXT is non-nil, prefer setext-style headers when
4640 possible (levels one and two).
4642 When there is an active region, use it for the header text. When
4643 the point is at an existing header, change the type and level
4644 according to the rules above.
4645 Otherwise, if the line is not empty, create a header using the
4646 text on the current line as the header text.
4647 Finally, if the point is on a blank line, insert empty header
4648 markup (atx) or prompt for text (setext).
4649 See `markdown-insert-header' for more details about how the
4650 header text is determined."
4651 (interactive "*P")
4652 (let (level)
4653 (save-excursion
4654 (when (or (thing-at-point-looking-at markdown-regex-header)
4655 (re-search-backward markdown-regex-header nil t))
4656 ;; level of current or previous header
4657 (setq level (markdown-outline-level))
4658 ;; match group 1 indicates a setext header
4659 (setq setext (match-end 1))))
4660 ;; check prefix argument
4661 (cond
4662 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4663 (cl-decf level))
4664 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4665 (cl-incf level))
4666 (arg ;; numeric prefix
4667 (setq level (prefix-numeric-value arg))))
4668 ;; setext headers must be level one or two
4669 (and level (setq setext (and setext (<= level 2))))
4670 ;; insert the heading
4671 (markdown-insert-header level nil setext)))
4673 (defun markdown-insert-header-setext-dwim (&optional arg)
4674 "Insert or replace header markup, with preference for setext.
4675 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4676 (interactive "*P")
4677 (markdown-insert-header-dwim arg t))
4679 (defun markdown-insert-header-atx-1 ()
4680 "Insert a first level atx-style (hash mark) header.
4681 See `markdown-insert-header'."
4682 (interactive "*")
4683 (markdown-insert-header 1 nil nil))
4685 (defun markdown-insert-header-atx-2 ()
4686 "Insert a level two atx-style (hash mark) header.
4687 See `markdown-insert-header'."
4688 (interactive "*")
4689 (markdown-insert-header 2 nil nil))
4691 (defun markdown-insert-header-atx-3 ()
4692 "Insert a level three atx-style (hash mark) header.
4693 See `markdown-insert-header'."
4694 (interactive "*")
4695 (markdown-insert-header 3 nil nil))
4697 (defun markdown-insert-header-atx-4 ()
4698 "Insert a level four atx-style (hash mark) header.
4699 See `markdown-insert-header'."
4700 (interactive "*")
4701 (markdown-insert-header 4 nil nil))
4703 (defun markdown-insert-header-atx-5 ()
4704 "Insert a level five atx-style (hash mark) header.
4705 See `markdown-insert-header'."
4706 (interactive "*")
4707 (markdown-insert-header 5 nil nil))
4709 (defun markdown-insert-header-atx-6 ()
4710 "Insert a sixth level atx-style (hash mark) header.
4711 See `markdown-insert-header'."
4712 (interactive "*")
4713 (markdown-insert-header 6 nil nil))
4715 (defun markdown-insert-header-setext-1 ()
4716 "Insert a setext-style (underlined) first-level header.
4717 See `markdown-insert-header'."
4718 (interactive "*")
4719 (markdown-insert-header 1 nil t))
4721 (defun markdown-insert-header-setext-2 ()
4722 "Insert a setext-style (underlined) second-level header.
4723 See `markdown-insert-header'."
4724 (interactive "*")
4725 (markdown-insert-header 2 nil t))
4727 (defun markdown-blockquote-indentation (loc)
4728 "Return string containing necessary indentation for a blockquote at LOC.
4729 Also see `markdown-pre-indentation'."
4730 (save-excursion
4731 (goto-char loc)
4732 (let* ((list-level (length (markdown-calculate-list-levels)))
4733 (indent ""))
4734 (dotimes (_ list-level indent)
4735 (setq indent (concat indent " "))))))
4737 (defun markdown-insert-blockquote ()
4738 "Start a blockquote section (or blockquote the region).
4739 If Transient Mark mode is on and a region is active, it is used as
4740 the blockquote text."
4741 (interactive)
4742 (if (markdown-use-region-p)
4743 (markdown-blockquote-region (region-beginning) (region-end))
4744 (markdown-ensure-blank-line-before)
4745 (insert (markdown-blockquote-indentation (point)) "> ")
4746 (markdown-ensure-blank-line-after)))
4748 (defun markdown-block-region (beg end prefix)
4749 "Format the region using a block prefix.
4750 Arguments BEG and END specify the beginning and end of the
4751 region. The characters PREFIX will appear at the beginning
4752 of each line."
4753 (save-excursion
4754 (let* ((end-marker (make-marker))
4755 (beg-marker (make-marker))
4756 (prefix-without-trailing-whitespace
4757 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
4758 ;; Ensure blank line after and remove extra whitespace
4759 (goto-char end)
4760 (skip-syntax-backward "-")
4761 (set-marker end-marker (point))
4762 (delete-horizontal-space)
4763 (markdown-ensure-blank-line-after)
4764 ;; Ensure blank line before and remove extra whitespace
4765 (goto-char beg)
4766 (skip-syntax-forward "-")
4767 (delete-horizontal-space)
4768 (markdown-ensure-blank-line-before)
4769 (set-marker beg-marker (point))
4770 ;; Insert PREFIX before each line
4771 (goto-char beg-marker)
4772 (while (and (< (line-beginning-position) end-marker)
4773 (not (eobp)))
4774 ;; Don’t insert trailing whitespace.
4775 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
4776 (forward-line)))))
4778 (defun markdown-blockquote-region (beg end)
4779 "Blockquote the region.
4780 Arguments BEG and END specify the beginning and end of the region."
4781 (interactive "*r")
4782 (markdown-block-region
4783 beg end (concat (markdown-blockquote-indentation
4784 (max (point-min) (1- beg))) "> ")))
4786 (defun markdown-pre-indentation (loc)
4787 "Return string containing necessary whitespace for a pre block at LOC.
4788 Also see `markdown-blockquote-indentation'."
4789 (save-excursion
4790 (goto-char loc)
4791 (let* ((list-level (length (markdown-calculate-list-levels)))
4792 indent)
4793 (dotimes (_ (1+ list-level) indent)
4794 (setq indent (concat indent " "))))))
4796 (defun markdown-insert-pre ()
4797 "Start a preformatted section (or apply to the region).
4798 If Transient Mark mode is on and a region is active, it is marked
4799 as preformatted text."
4800 (interactive)
4801 (if (markdown-use-region-p)
4802 (markdown-pre-region (region-beginning) (region-end))
4803 (markdown-ensure-blank-line-before)
4804 (insert (markdown-pre-indentation (point)))
4805 (markdown-ensure-blank-line-after)))
4807 (defun markdown-pre-region (beg end)
4808 "Format the region as preformatted text.
4809 Arguments BEG and END specify the beginning and end of the region."
4810 (interactive "*r")
4811 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
4812 (markdown-block-region beg end indent)))
4814 (defun markdown-electric-backquote (arg)
4815 "Insert a backquote.
4816 The numeric prefix argument ARG says how many times to repeat the insertion.
4817 Call `markdown-insert-gfm-code-block' interactively
4818 if three backquotes inserted at the beginning of line."
4819 (interactive "*P")
4820 (self-insert-command (prefix-numeric-value arg))
4821 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
4822 (replace-match "")
4823 (call-interactively #'markdown-insert-gfm-code-block)))
4825 (defconst markdown-gfm-recognized-languages
4826 ;; To reproduce/update, evaluate the let-form in
4827 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
4828 ;; but with appropriate use of a keyboard macro, indenting and filling it
4829 ;; properly is pretty fast.
4830 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
4831 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
4832 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
4833 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
4834 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
4835 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
4836 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
4837 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
4838 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
4839 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
4840 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
4841 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
4842 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
4843 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
4844 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
4845 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
4846 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
4847 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
4848 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
4849 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
4850 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
4851 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
4852 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
4853 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
4854 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
4855 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
4856 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
4857 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
4858 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
4859 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
4860 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
4861 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
4862 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
4863 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
4864 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
4865 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
4866 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
4867 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
4868 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
4869 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
4870 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
4871 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
4872 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
4873 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
4874 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
4875 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
4876 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
4877 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
4878 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
4879 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
4880 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
4881 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
4882 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
4883 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
4884 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
4885 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
4886 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
4887 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
4888 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
4889 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
4890 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
4891 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
4892 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
4893 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
4894 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
4895 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
4896 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
4897 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
4898 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
4899 "Language specifiers recognized by GitHub's syntax highlighting features.")
4901 (defvar markdown-gfm-used-languages nil
4902 "Language names used in GFM code blocks.")
4903 (make-variable-buffer-local 'markdown-gfm-used-languages)
4905 (defun markdown-trim-whitespace (str)
4906 (markdown-replace-regexp-in-string
4907 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
4909 (defun markdown-clean-language-string (str)
4910 (markdown-replace-regexp-in-string
4911 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
4913 (defun markdown-validate-language-string (widget)
4914 (let ((str (widget-value widget)))
4915 (unless (string= str (markdown-clean-language-string str))
4916 (widget-put widget :error (format "Invalid language spec: '%s'" str))
4917 widget)))
4919 (defun markdown-gfm-get-corpus ()
4920 "Create corpus of recognized GFM code block languages for the given buffer."
4921 (let ((given-corpus (append markdown-gfm-additional-languages
4922 markdown-gfm-recognized-languages)))
4923 (append
4924 markdown-gfm-used-languages
4925 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
4926 given-corpus))))
4928 (defun markdown-gfm-add-used-language (lang)
4929 "Clean LANG and add to list of used languages."
4930 (setq markdown-gfm-used-languages
4931 (cons lang (remove lang markdown-gfm-used-languages))))
4933 (defcustom markdown-spaces-after-code-fence 1
4934 "Number of space characters to insert after a code fence.
4935 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
4936 opening code fence and an info string."
4937 :group 'markdown
4938 :type 'integer
4939 :safe #'natnump
4940 :package-version '(markdown-mode . "2.3"))
4942 (defun markdown-insert-gfm-code-block (&optional lang)
4943 "Insert GFM code block for language LANG.
4944 If LANG is nil, the language will be queried from user. If a
4945 region is active, wrap this region with the markup instead. If
4946 the region boundaries are not on empty lines, these are added
4947 automatically in order to have the correct markup."
4948 (interactive
4949 (list (let ((completion-ignore-case nil))
4950 (condition-case nil
4951 (markdown-clean-language-string
4952 (completing-read
4953 "Programming language: "
4954 (markdown-gfm-get-corpus)
4955 nil 'confirm (car markdown-gfm-used-languages)
4956 'markdown-gfm-language-history))
4957 (quit "")))))
4958 (unless (string= lang "") (markdown-gfm-add-used-language lang))
4959 (when (> (length lang) 0)
4960 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
4961 lang)))
4962 (if (markdown-use-region-p)
4963 (let* ((b (region-beginning)) (e (region-end))
4964 (indent (progn (goto-char b) (current-indentation))))
4965 (goto-char e)
4966 ;; if we're on a blank line, don't newline, otherwise the ```
4967 ;; should go on its own line
4968 (unless (looking-back "\n" nil)
4969 (newline))
4970 (indent-to indent)
4971 (insert "```")
4972 (markdown-ensure-blank-line-after)
4973 (goto-char b)
4974 ;; if we're on a blank line, insert the quotes here, otherwise
4975 ;; add a new line first
4976 (unless (looking-at-p "\n")
4977 (newline)
4978 (forward-line -1))
4979 (markdown-ensure-blank-line-before)
4980 (indent-to indent)
4981 (insert "```" lang))
4982 (let ((indent (current-indentation)))
4983 (delete-horizontal-space :backward-only)
4984 (markdown-ensure-blank-line-before)
4985 (indent-to indent)
4986 (insert "```" lang "\n")
4987 (indent-to indent)
4988 (insert ?\n)
4989 (indent-to indent)
4990 (insert "```")
4991 (markdown-ensure-blank-line-after))
4992 (end-of-line 0)))
4994 (defun markdown-code-block-lang (&optional pos-prop)
4995 "Return the language name for a GFM or tilde fenced code block.
4996 The beginning of the block may be described by POS-PROP,
4997 a cons of (pos . prop) giving the position and property
4998 at the beginning of the block."
4999 (or pos-prop
5000 (setq pos-prop
5001 (markdown-max-of-seq
5002 #'car
5003 (cl-remove-if
5004 #'null
5005 (cl-mapcar
5006 #'markdown-find-previous-prop
5007 (markdown-get-fenced-block-begin-properties))))))
5008 (when pos-prop
5009 (goto-char (car pos-prop))
5010 (set-match-data (get-text-property (point) (cdr pos-prop)))
5011 ;; Note: Hard-coded group number assumes tilde
5012 ;; and GFM fenced code regexp groups agree.
5013 (let ((begin (match-beginning 3))
5014 (end (match-end 3)))
5015 (when (and begin end)
5016 ;; Fix language strings beginning with periods, like ".ruby".
5017 (when (eq (char-after begin) ?.)
5018 (setq begin (1+ begin)))
5019 (buffer-substring-no-properties begin end)))))
5021 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5022 (with-current-buffer (or buffer (current-buffer))
5023 (save-excursion
5024 (goto-char (point-min))
5025 (cl-loop
5026 with prop = 'markdown-gfm-block-begin
5027 for pos-prop = (markdown-find-next-prop prop)
5028 while pos-prop
5029 for lang = (markdown-code-block-lang pos-prop)
5030 do (progn (when lang (markdown-gfm-add-used-language lang))
5031 (goto-char (next-single-property-change (point) prop)))))))
5034 ;;; Footnotes ==================================================================
5036 (defun markdown-footnote-counter-inc ()
5037 "Increment `markdown-footnote-counter' and return the new value."
5038 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5039 (save-excursion
5040 (goto-char (point-min))
5041 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5042 (point-max) t)
5043 (let ((fn (string-to-number (match-string 1))))
5044 (when (> fn markdown-footnote-counter)
5045 (setq markdown-footnote-counter fn))))))
5046 (cl-incf markdown-footnote-counter))
5048 (defun markdown-insert-footnote ()
5049 "Insert footnote with a new number and move point to footnote definition."
5050 (interactive)
5051 (let ((fn (markdown-footnote-counter-inc)))
5052 (insert (format "[^%d]" fn))
5053 (markdown-footnote-text-find-new-location)
5054 (markdown-ensure-blank-line-before)
5055 (unless (markdown-cur-line-blank-p)
5056 (insert "\n"))
5057 (insert (format "[^%d]: " fn))
5058 (markdown-ensure-blank-line-after)))
5060 (defun markdown-footnote-text-find-new-location ()
5061 "Position the cursor at the proper location for a new footnote text."
5062 (cond
5063 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5064 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5065 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5066 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5068 (defun markdown-footnote-kill ()
5069 "Kill the footnote at point.
5070 The footnote text is killed (and added to the kill ring), the
5071 footnote marker is deleted. Point has to be either at the
5072 footnote marker or in the footnote text."
5073 (interactive)
5074 (let ((marker-pos nil)
5075 (skip-deleting-marker nil)
5076 (starting-footnote-text-positions
5077 (markdown-footnote-text-positions)))
5078 (when starting-footnote-text-positions
5079 ;; We're starting in footnote text, so mark our return position and jump
5080 ;; to the marker if possible.
5081 (let ((marker-pos (markdown-footnote-find-marker
5082 (cl-first starting-footnote-text-positions))))
5083 (if marker-pos
5084 (goto-char (1- marker-pos))
5085 ;; If there isn't a marker, we still want to kill the text.
5086 (setq skip-deleting-marker t))))
5087 ;; Either we didn't start in the text, or we started in the text and jumped
5088 ;; to the marker. We want to assume we're at the marker now and error if
5089 ;; we're not.
5090 (unless skip-deleting-marker
5091 (let ((marker (markdown-footnote-delete-marker)))
5092 (unless marker
5093 (error "Not at a footnote"))
5094 ;; Even if we knew the text position before, it changed when we deleted
5095 ;; the label.
5096 (setq marker-pos (cl-second marker))
5097 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5098 (unless new-text-pos
5099 (error "No text for footnote `%s'" (cl-first marker)))
5100 (goto-char new-text-pos))))
5101 (let ((pos (markdown-footnote-kill-text)))
5102 (goto-char (if starting-footnote-text-positions
5104 marker-pos)))))
5106 (defun markdown-footnote-delete-marker ()
5107 "Delete a footnote marker at point.
5108 Returns a list (ID START) containing the footnote ID and the
5109 start position of the marker before deletion. If no footnote
5110 marker was deleted, this function returns NIL."
5111 (let ((marker (markdown-footnote-marker-positions)))
5112 (when marker
5113 (delete-region (cl-second marker) (cl-third marker))
5114 (butlast marker))))
5116 (defun markdown-footnote-kill-text ()
5117 "Kill footnote text at point.
5118 Returns the start position of the footnote text before deletion,
5119 or NIL if point was not inside a footnote text.
5121 The killed text is placed in the kill ring (without the footnote
5122 number)."
5123 (let ((fn (markdown-footnote-text-positions)))
5124 (when fn
5125 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5126 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5127 (kill-new (match-string 1 text))
5128 (when (and (markdown-cur-line-blank-p)
5129 (markdown-prev-line-blank-p)
5130 (not (bobp)))
5131 (delete-region (1- (point)) (point)))
5132 (cl-second fn)))))
5134 (defun markdown-footnote-goto-text ()
5135 "Jump to the text of the footnote at point."
5136 (interactive)
5137 (let ((fn (car (markdown-footnote-marker-positions))))
5138 (unless fn
5139 (user-error "Not at a footnote marker"))
5140 (let ((new-pos (markdown-footnote-find-text fn)))
5141 (unless new-pos
5142 (error "No definition found for footnote `%s'" fn))
5143 (goto-char new-pos))))
5145 (defun markdown-footnote-return ()
5146 "Return from a footnote to its footnote number in the main text."
5147 (interactive)
5148 (let ((fn (save-excursion
5149 (car (markdown-footnote-text-positions)))))
5150 (unless fn
5151 (user-error "Not in a footnote"))
5152 (let ((new-pos (markdown-footnote-find-marker fn)))
5153 (unless new-pos
5154 (error "Footnote marker `%s' not found" fn))
5155 (goto-char new-pos))))
5157 (defun markdown-footnote-find-marker (id)
5158 "Find the location of the footnote marker with ID.
5159 The actual buffer position returned is the position directly
5160 following the marker's closing bracket. If no marker is found,
5161 NIL is returned."
5162 (save-excursion
5163 (goto-char (point-min))
5164 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5165 (skip-chars-backward "^]")
5166 (point))))
5168 (defun markdown-footnote-find-text (id)
5169 "Find the location of the text of footnote ID.
5170 The actual buffer position returned is the position of the first
5171 character of the text, after the footnote's identifier. If no
5172 footnote text is found, NIL is returned."
5173 (save-excursion
5174 (goto-char (point-min))
5175 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5176 (skip-chars-forward "[ \t]")
5177 (point))))
5179 (defun markdown-footnote-marker-positions ()
5180 "Return the position and ID of the footnote marker point is on.
5181 The return value is a list (ID START END). If point is not on a
5182 footnote, NIL is returned."
5183 ;; first make sure we're at a footnote marker
5184 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5185 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5186 (save-excursion
5187 ;; move point between [ and ^:
5188 (if (looking-at-p "\\[")
5189 (forward-char 1)
5190 (skip-chars-backward "^["))
5191 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5192 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5194 (defun markdown-footnote-text-positions ()
5195 "Return the start and end positions of the footnote text point is in.
5196 The exact return value is a list of three elements: (ID START END).
5197 The start position is the position of the opening bracket
5198 of the footnote id. The end position is directly after the
5199 newline that ends the footnote. If point is not in a footnote,
5200 NIL is returned instead."
5201 (save-excursion
5202 (let (result)
5203 (move-beginning-of-line 1)
5204 ;; Try to find the label. If we haven't found the label and we're at a blank
5205 ;; or indented line, back up if possible.
5206 (while (and
5207 (not (and (looking-at markdown-regex-footnote-definition)
5208 (setq result (list (match-string 1) (point)))))
5209 (and (not (bobp))
5210 (or (markdown-cur-line-blank-p)
5211 (>= (current-indentation) 4))))
5212 (forward-line -1))
5213 (when result
5214 ;; Advance if there is a next line that is either blank or indented.
5215 ;; (Need to check if we're on the last line, because
5216 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5217 (while (and (/= (line-end-position) (point-max))
5218 (or (markdown-next-line-blank-p)
5219 (>= (markdown-next-line-indent) 4)))
5220 (forward-line))
5221 ;; Move back while the current line is blank.
5222 (while (markdown-cur-line-blank-p)
5223 (forward-line -1))
5224 ;; Advance to capture this line and a single trailing newline (if there
5225 ;; is one).
5226 (forward-line)
5227 (append result (list (point)))))))
5230 ;;; Element Removal ===========================================================
5232 (defun markdown-kill-thing-at-point ()
5233 "Kill thing at point and add important text, without markup, to kill ring.
5234 Possible things to kill include (roughly in order of precedence):
5235 inline code, headers, horizonal rules, links (add link text to
5236 kill ring), images (add alt text to kill ring), angle uri, email
5237 addresses, bold, italics, reference definition (add URI to kill
5238 ring), footnote markers and text (kill both marker and text, add
5239 text to kill ring), and list items."
5240 (interactive "*")
5241 (let (val)
5242 (cond
5243 ;; Inline code
5244 ((markdown-inline-code-at-point)
5245 (kill-new (match-string 2))
5246 (delete-region (match-beginning 0) (match-end 0)))
5247 ;; ATX header
5248 ((thing-at-point-looking-at markdown-regex-header-atx)
5249 (kill-new (match-string 2))
5250 (delete-region (match-beginning 0) (match-end 0)))
5251 ;; Setext header
5252 ((thing-at-point-looking-at markdown-regex-header-setext)
5253 (kill-new (match-string 1))
5254 (delete-region (match-beginning 0) (match-end 0)))
5255 ;; Horizonal rule
5256 ((thing-at-point-looking-at markdown-regex-hr)
5257 (kill-new (match-string 0))
5258 (delete-region (match-beginning 0) (match-end 0)))
5259 ;; Inline link or image (add link or alt text to kill ring)
5260 ((thing-at-point-looking-at markdown-regex-link-inline)
5261 (kill-new (match-string 3))
5262 (delete-region (match-beginning 0) (match-end 0)))
5263 ;; Reference link or image (add link or alt text to kill ring)
5264 ((thing-at-point-looking-at markdown-regex-link-reference)
5265 (kill-new (match-string 3))
5266 (delete-region (match-beginning 0) (match-end 0)))
5267 ;; Angle URI (add URL to kill ring)
5268 ((thing-at-point-looking-at markdown-regex-angle-uri)
5269 (kill-new (match-string 2))
5270 (delete-region (match-beginning 0) (match-end 0)))
5271 ;; Email address in angle brackets (add email address to kill ring)
5272 ((thing-at-point-looking-at markdown-regex-email)
5273 (kill-new (match-string 1))
5274 (delete-region (match-beginning 0) (match-end 0)))
5275 ;; Wiki link (add alias text to kill ring)
5276 ((and markdown-enable-wiki-links
5277 (thing-at-point-looking-at markdown-regex-wiki-link))
5278 (kill-new (markdown-wiki-link-alias))
5279 (delete-region (match-beginning 1) (match-end 1)))
5280 ;; Bold
5281 ((thing-at-point-looking-at markdown-regex-bold)
5282 (kill-new (match-string 4))
5283 (delete-region (match-beginning 2) (match-end 2)))
5284 ;; Italics
5285 ((thing-at-point-looking-at markdown-regex-italic)
5286 (kill-new (match-string 3))
5287 (delete-region (match-beginning 1) (match-end 1)))
5288 ;; Strikethrough
5289 ((thing-at-point-looking-at markdown-regex-strike-through)
5290 (kill-new (match-string 4))
5291 (delete-region (match-beginning 2) (match-end 2)))
5292 ;; Footnote marker (add footnote text to kill ring)
5293 ((thing-at-point-looking-at markdown-regex-footnote)
5294 (markdown-footnote-kill))
5295 ;; Footnote text (add footnote text to kill ring)
5296 ((setq val (markdown-footnote-text-positions))
5297 (markdown-footnote-kill))
5298 ;; Reference definition (add URL to kill ring)
5299 ((thing-at-point-looking-at markdown-regex-reference-definition)
5300 (kill-new (match-string 5))
5301 (delete-region (match-beginning 0) (match-end 0)))
5302 ;; List item
5303 ((setq val (markdown-cur-list-item-bounds))
5304 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5306 (user-error "Nothing found at point to kill")))))
5309 ;;; Indentation ====================================================================
5311 (defun markdown-indent-find-next-position (cur-pos positions)
5312 "Return the position after the index of CUR-POS in POSITIONS.
5313 Positions are calculated by `markdown-calc-indents'."
5314 (while (and positions
5315 (not (equal cur-pos (car positions))))
5316 (setq positions (cdr positions)))
5317 (or (cadr positions) 0))
5319 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5320 'markdown-outdent-find-next-position "v2.3")
5322 (defun markdown-outdent-find-next-position (cur-pos positions)
5323 "Return the maximal element that precedes CUR-POS from POSITIONS.
5324 Positions are calculated by `markdown-calc-indents'."
5325 (let ((result 0))
5326 (dolist (i positions)
5327 (when (< i cur-pos)
5328 (setq result (max result i))))
5329 result))
5331 (defun markdown-indent-line ()
5332 "Indent the current line using some heuristics.
5333 If the _previous_ command was either `markdown-enter-key' or
5334 `markdown-cycle', then we should cycle to the next
5335 reasonable indentation position. Otherwise, we could have been
5336 called directly by `markdown-enter-key', by an initial call of
5337 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5338 these cases, indent to the default position.
5339 Positions are calculated by `markdown-calc-indents'."
5340 (interactive)
5341 (let ((positions (markdown-calc-indents))
5342 (cursor-pos (current-column))
5343 (_ (back-to-indentation))
5344 (cur-pos (current-column)))
5345 (if (not (equal this-command 'markdown-cycle))
5346 (indent-line-to (car positions))
5347 (setq positions (sort (delete-dups positions) '<))
5348 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5349 (new-cursor-pos
5350 (if (< cur-pos next-pos)
5351 (+ cursor-pos (- next-pos cur-pos))
5352 (- cursor-pos cur-pos))))
5353 (indent-line-to next-pos)
5354 (move-to-column new-cursor-pos)))))
5356 (defun markdown-calc-indents ()
5357 "Return a list of indentation columns to cycle through.
5358 The first element in the returned list should be considered the
5359 default indentation level. This function does not worry about
5360 duplicate positions, which are handled up by calling functions."
5361 (let (pos prev-line-pos positions)
5363 ;; Indentation of previous line
5364 (setq prev-line-pos (markdown-prev-line-indent))
5365 (setq positions (cons prev-line-pos positions))
5367 ;; Indentation of previous non-list-marker text
5368 (when (setq pos (markdown-prev-non-list-indent))
5369 (setq positions (cons pos positions)))
5371 ;; Indentation required for a pre block in current context
5372 (setq pos (length (markdown-pre-indentation (point))))
5373 (setq positions (cons pos positions))
5375 ;; Indentation of the previous line + tab-width
5376 (if prev-line-pos
5377 (setq positions (cons (+ prev-line-pos tab-width) positions))
5378 (setq positions (cons tab-width positions)))
5380 ;; Indentation of the previous line - tab-width
5381 (if (and prev-line-pos (> prev-line-pos tab-width))
5382 (setq positions (cons (- prev-line-pos tab-width) positions)))
5384 ;; Indentation of all preceeding list markers (when in a list)
5385 (when (setq pos (markdown-calculate-list-levels))
5386 (setq positions (append pos positions)))
5388 ;; First column
5389 (setq positions (cons 0 positions))
5391 ;; Return reversed list
5392 (reverse positions)))
5394 (defun markdown-enter-key ()
5395 "Handle RET according to value of `markdown-indent-on-enter'.
5396 When it is nil, simply call `newline'. Otherwise, indent the next line
5397 following RET using `markdown-indent-line'. Furthermore, when it
5398 is set to 'indent-and-new-item and the point is in a list item,
5399 start a new item with the same indentation. If the point is in an
5400 empty list item, remove it (so that pressing RET twice when in a
5401 list simply adds a blank line)."
5402 (interactive)
5403 (if (not markdown-indent-on-enter)
5404 (newline)
5405 (let (bounds)
5406 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5407 (setq bounds (markdown-cur-list-item-bounds)))
5408 (let ((beg (cl-first bounds))
5409 (end (cl-second bounds))
5410 (length (cl-fourth bounds)))
5411 ;; Point is in a list item
5412 (if (= (- end beg) length)
5413 ;; Delete blank list
5414 (progn
5415 (delete-region beg end)
5416 (newline)
5417 (markdown-indent-line))
5418 (call-interactively #'markdown-insert-list-item)))
5419 ;; Point is not in a list
5420 (newline)
5421 (markdown-indent-line)))))
5423 (define-obsolete-function-alias 'markdown-exdent-or-delete
5424 'markdown-outdent-or-delete "v2.3")
5426 (defun markdown-outdent-or-delete (arg)
5427 "Handle BACKSPACE by cycling through indentation points.
5428 When BACKSPACE is pressed, if there is only whitespace
5429 before the current point, then outdent the line one level.
5430 Otherwise, do normal delete by repeating
5431 `backward-delete-char-untabify' ARG times."
5432 (interactive "*p")
5433 (if (use-region-p)
5434 (backward-delete-char-untabify arg)
5435 (let ((cur-pos (current-column))
5436 (start-of-indention (save-excursion
5437 (back-to-indentation)
5438 (current-column)))
5439 (positions (markdown-calc-indents)))
5440 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5441 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5442 (backward-delete-char-untabify arg)))))
5444 (defun markdown-find-leftmost-column (beg end)
5445 "Find the leftmost column in the region from BEG to END."
5446 (let ((mincol 1000))
5447 (save-excursion
5448 (goto-char beg)
5449 (while (< (point) end)
5450 (back-to-indentation)
5451 (unless (looking-at-p "[ \t]*$")
5452 (setq mincol (min mincol (current-column))))
5453 (forward-line 1)
5455 mincol))
5457 (defun markdown-indent-region (beg end arg)
5458 "Indent the region from BEG to END using some heuristics.
5459 When ARG is non-nil, outdent the region instead.
5460 See `markdown-indent-line' and `markdown-indent-line'."
5461 (interactive "*r\nP")
5462 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5463 (leftmostcol (markdown-find-leftmost-column beg end))
5464 (next-pos (if arg
5465 (markdown-outdent-find-next-position leftmostcol positions)
5466 (markdown-indent-find-next-position leftmostcol positions))))
5467 (indent-rigidly beg end (- next-pos leftmostcol))
5468 (setq deactivate-mark nil)))
5470 (define-obsolete-function-alias 'markdown-exdent-region
5471 'markdown-outdent-region "v2.3")
5473 (defun markdown-outdent-region (beg end)
5474 "Call `markdown-indent-region' on region from BEG to END with prefix."
5475 (interactive "*r")
5476 (markdown-indent-region beg end t))
5479 ;;; Markup Completion =========================================================
5481 (defconst markdown-complete-alist
5482 '((markdown-regex-header-atx . markdown-complete-atx)
5483 (markdown-regex-header-setext . markdown-complete-setext)
5484 (markdown-regex-hr . markdown-complete-hr))
5485 "Association list of form (regexp . function) for markup completion.")
5487 (defun markdown-incomplete-atx-p ()
5488 "Return t if ATX header markup is incomplete and nil otherwise.
5489 Assumes match data is available for `markdown-regex-header-atx'.
5490 Checks that the number of trailing hash marks equals the number of leading
5491 hash marks, that there is only a single space before and after the text,
5492 and that there is no extraneous whitespace in the text."
5494 ;; Number of starting and ending hash marks differs
5495 (not (= (length (match-string 1)) (length (match-string 3))))
5496 ;; When the header text is not empty...
5497 (and (> (length (match-string 2)) 0)
5498 ;; ...if there are extra leading, trailing, or interior spaces
5499 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5500 (not (= (match-beginning 3) (1+ (match-end 2))))
5501 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5502 ;; When the header text is empty...
5503 (and (= (length (match-string 2)) 0)
5504 ;; ...if there are too many or too few spaces
5505 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5507 (defun markdown-complete-atx ()
5508 "Complete and normalize ATX headers.
5509 Add or remove hash marks to the end of the header to match the
5510 beginning. Ensure that there is only a single space between hash
5511 marks and header text. Removes extraneous whitespace from header text.
5512 Assumes match data is available for `markdown-regex-header-atx'.
5513 Return nil if markup was complete and non-nil if markup was completed."
5514 (when (markdown-incomplete-atx-p)
5515 (let* ((new-marker (make-marker))
5516 (new-marker (set-marker new-marker (match-end 2))))
5517 ;; Hash marks and spacing at end
5518 (goto-char (match-end 2))
5519 (delete-region (match-end 2) (match-end 3))
5520 (insert " " (match-string 1))
5521 ;; Remove extraneous whitespace from title
5522 (replace-match (markdown-compress-whitespace-string (match-string 2))
5523 t t nil 2)
5524 ;; Spacing at beginning
5525 (goto-char (match-end 1))
5526 (delete-region (match-end 1) (match-beginning 2))
5527 (insert " ")
5528 ;; Leave point at end of text
5529 (goto-char new-marker))))
5531 (defun markdown-incomplete-setext-p ()
5532 "Return t if setext header markup is incomplete and nil otherwise.
5533 Assumes match data is available for `markdown-regex-header-setext'.
5534 Checks that length of underline matches text and that there is no
5535 extraneous whitespace in the text."
5536 (or (not (= (length (match-string 1)) (length (match-string 2))))
5537 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5539 (defun markdown-complete-setext ()
5540 "Complete and normalize setext headers.
5541 Add or remove underline characters to match length of header
5542 text. Removes extraneous whitespace from header text. Assumes
5543 match data is available for `markdown-regex-header-setext'.
5544 Return nil if markup was complete and non-nil if markup was completed."
5545 (when (markdown-incomplete-setext-p)
5546 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5547 (char (char-after (match-beginning 2)))
5548 (level (if (char-equal char ?-) 2 1)))
5549 (goto-char (match-beginning 0))
5550 (delete-region (match-beginning 0) (match-end 0))
5551 (markdown-insert-header level text t)
5552 t)))
5554 (defun markdown-incomplete-hr-p ()
5555 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5556 Assumes match data is available for `markdown-regex-hr'."
5557 (not (member (match-string 0) markdown-hr-strings)))
5559 (defun markdown-complete-hr ()
5560 "Complete horizontal rules.
5561 If horizontal rule string is a member of `markdown-hr-strings',
5562 do nothing. Otherwise, replace with the car of
5563 `markdown-hr-strings'.
5564 Assumes match data is available for `markdown-regex-hr'.
5565 Return nil if markup was complete and non-nil if markup was completed."
5566 (when (markdown-incomplete-hr-p)
5567 (replace-match (car markdown-hr-strings))
5570 (defun markdown-complete ()
5571 "Complete markup of object near point or in region when active.
5572 Handle all objects in `markdown-complete-alist', in order.
5573 See `markdown-complete-at-point' and `markdown-complete-region'."
5574 (interactive "*")
5575 (if (markdown-use-region-p)
5576 (markdown-complete-region (region-beginning) (region-end))
5577 (markdown-complete-at-point)))
5579 (defun markdown-complete-at-point ()
5580 "Complete markup of object near point.
5581 Handle all elements of `markdown-complete-alist' in order."
5582 (interactive "*")
5583 (let ((list markdown-complete-alist) found changed)
5584 (while list
5585 (let ((regexp (eval (caar list)))
5586 (function (cdar list)))
5587 (setq list (cdr list))
5588 (when (thing-at-point-looking-at regexp)
5589 (setq found t)
5590 (setq changed (funcall function))
5591 (setq list nil))))
5592 (if found
5593 (or changed (user-error "Markup at point is complete"))
5594 (user-error "Nothing to complete at point"))))
5596 (defun markdown-complete-region (beg end)
5597 "Complete markup of objects in region from BEG to END.
5598 Handle all objects in `markdown-complete-alist', in order. Each
5599 match is checked to ensure that a previous regexp does not also
5600 match."
5601 (interactive "*r")
5602 (let ((end-marker (set-marker (make-marker) end))
5603 previous)
5604 (dolist (element markdown-complete-alist)
5605 (let ((regexp (eval (car element)))
5606 (function (cdr element)))
5607 (goto-char beg)
5608 (while (re-search-forward regexp end-marker 'limit)
5609 (when (match-string 0)
5610 ;; Make sure this is not a match for any of the preceding regexps.
5611 ;; This prevents mistaking an HR for a Setext subheading.
5612 (let (match)
5613 (save-match-data
5614 (dolist (prev-regexp previous)
5615 (or match (setq match (looking-back prev-regexp nil)))))
5616 (unless match
5617 (save-excursion (funcall function))))))
5618 (cl-pushnew regexp previous :test #'equal)))
5619 previous))
5621 (defun markdown-complete-buffer ()
5622 "Complete markup for all objects in the current buffer."
5623 (interactive "*")
5624 (markdown-complete-region (point-min) (point-max)))
5627 ;;; Markup Cycling ============================================================
5629 (defun markdown-cycle-atx (arg &optional remove)
5630 "Cycle ATX header markup.
5631 Promote header (decrease level) when ARG is 1 and demote
5632 header (increase level) if arg is -1. When REMOVE is non-nil,
5633 remove the header when the level reaches zero and stop cycling
5634 when it reaches six. Otherwise, perform a proper cycling through
5635 levels one through six. Assumes match data is available for
5636 `markdown-regex-header-atx'."
5637 (let* ((old-level (length (match-string 1)))
5638 (new-level (+ old-level arg))
5639 (text (match-string 2)))
5640 (when (not remove)
5641 (setq new-level (% new-level 6))
5642 (setq new-level (cond ((= new-level 0) 6)
5643 ((< new-level 0) (+ new-level 6))
5644 (t new-level))))
5645 (cond
5646 ((= new-level 0)
5647 (markdown-unwrap-thing-at-point nil 0 2))
5648 ((<= new-level 6)
5649 (goto-char (match-beginning 0))
5650 (delete-region (match-beginning 0) (match-end 0))
5651 (markdown-insert-header new-level text nil)))))
5653 (defun markdown-cycle-setext (arg &optional remove)
5654 "Cycle setext header markup.
5655 Promote header (increase level) when ARG is 1 and demote
5656 header (decrease level or remove) if arg is -1. When demoting a
5657 level-two setext header, replace with a level-three atx header.
5658 When REMOVE is non-nil, remove the header when the level reaches
5659 zero. Otherwise, cycle back to a level six atx header. Assumes
5660 match data is available for `markdown-regex-header-setext'."
5661 (let* ((char (char-after (match-beginning 2)))
5662 (old-level (if (char-equal char ?=) 1 2))
5663 (new-level (+ old-level arg)))
5664 (when (and (not remove) (= new-level 0))
5665 (setq new-level 6))
5666 (cond
5667 ((= new-level 0)
5668 (markdown-unwrap-thing-at-point nil 0 1))
5669 ((<= new-level 2)
5670 (markdown-insert-header new-level nil t))
5671 ((<= new-level 6)
5672 (markdown-insert-header new-level nil nil)))))
5674 (defun markdown-cycle-hr (arg &optional remove)
5675 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5676 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5677 backwards (promote). When REMOVE is non-nil, remove the hr instead
5678 of cycling when the end of the list is reached.
5679 Assumes match data is available for `markdown-regex-hr'."
5680 (let* ((strings (if (= arg -1)
5681 (reverse markdown-hr-strings)
5682 markdown-hr-strings))
5683 (tail (member (match-string 0) strings))
5684 (new (or (cadr tail)
5685 (if remove
5686 (if (= arg 1)
5688 (car tail))
5689 (car strings)))))
5690 (replace-match new)))
5692 (defun markdown-cycle-bold ()
5693 "Cycle bold markup between underscores and asterisks.
5694 Assumes match data is available for `markdown-regex-bold'."
5695 (save-excursion
5696 (let* ((old-delim (match-string 3))
5697 (new-delim (if (string-equal old-delim "**") "__" "**")))
5698 (replace-match new-delim t t nil 3)
5699 (replace-match new-delim t t nil 5))))
5701 (defun markdown-cycle-italic ()
5702 "Cycle italic markup between underscores and asterisks.
5703 Assumes match data is available for `markdown-regex-italic'."
5704 (save-excursion
5705 (let* ((old-delim (match-string 2))
5706 (new-delim (if (string-equal old-delim "*") "_" "*")))
5707 (replace-match new-delim t t nil 2)
5708 (replace-match new-delim t t nil 4))))
5711 ;;; Keymap ====================================================================
5713 (defun markdown--style-map-prompt ()
5714 "Return a formatted prompt for Markdown markup insertion."
5715 (when markdown-enable-prefix-prompts
5716 (concat
5717 "Markdown: "
5718 (propertize "bold" 'face 'markdown-bold-face) ", "
5719 (propertize "italic" 'face 'markdown-italic-face) ", "
5720 (propertize "code" 'face 'markdown-inline-code-face) ", "
5721 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
5722 (propertize "pre" 'face 'markdown-pre-face) ", "
5723 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
5724 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
5725 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
5726 (propertize "- = hr" 'face 'markdown-hr-face) ", "
5727 "C-h = more")))
5729 (defun markdown--command-map-prompt ()
5730 "Return prompt for Markdown buffer-wide commands."
5731 (when markdown-enable-prefix-prompts
5732 (concat
5733 "Command: "
5734 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
5735 (propertize "p" 'face 'markdown-bold-face) "review, "
5736 (propertize "o" 'face 'markdown-bold-face) "pen, "
5737 (propertize "e" 'face 'markdown-bold-face) "xport, "
5738 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
5739 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
5740 "C-h = more")))
5742 (defvar markdown-mode-style-map
5743 (let ((map (make-keymap (markdown--style-map-prompt))))
5744 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
5745 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
5746 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
5747 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
5748 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
5749 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
5750 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
5751 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
5752 (define-key map (kbd "b") 'markdown-insert-bold)
5753 (define-key map (kbd "c") 'markdown-insert-code)
5754 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
5755 (define-key map (kbd "f") 'markdown-insert-footnote)
5756 (define-key map (kbd "h") 'markdown-insert-header-dwim)
5757 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
5758 (define-key map (kbd "i") 'markdown-insert-italic)
5759 (define-key map (kbd "k") 'markdown-insert-kbd)
5760 (define-key map (kbd "l") 'markdown-insert-link)
5761 (define-key map (kbd "p") 'markdown-insert-pre)
5762 (define-key map (kbd "P") 'markdown-pre-region)
5763 (define-key map (kbd "q") 'markdown-insert-blockquote)
5764 (define-key map (kbd "s") 'markdown-insert-strike-through)
5765 (define-key map (kbd "Q") 'markdown-blockquote-region)
5766 (define-key map (kbd "w") 'markdown-insert-wiki-link)
5767 (define-key map (kbd "-") 'markdown-insert-hr)
5768 ;; Deprecated keys that may be removed in a future version
5769 (define-key map (kbd "e") 'markdown-insert-italic)
5770 map)
5771 "Keymap for Markdown text styling commands.")
5773 (defvar markdown-mode-command-map
5774 (let ((map (make-keymap (markdown--command-map-prompt))))
5775 (define-key map (kbd "m") 'markdown-other-window)
5776 (define-key map (kbd "p") 'markdown-preview)
5777 (define-key map (kbd "e") 'markdown-export)
5778 (define-key map (kbd "v") 'markdown-export-and-preview)
5779 (define-key map (kbd "o") 'markdown-open)
5780 (define-key map (kbd "l") 'markdown-live-preview-mode)
5781 (define-key map (kbd "w") 'markdown-kill-ring-save)
5782 (define-key map (kbd "c") 'markdown-check-refs)
5783 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
5784 (define-key map (kbd "]") 'markdown-complete-buffer)
5785 map)
5786 "Keymap for Markdown buffer-wide commands.")
5788 (defvar markdown-mode-map
5789 (let ((map (make-keymap)))
5790 ;; Markup insertion & removal
5791 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
5792 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
5793 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
5794 ;; Promotion, demotion, and cycling
5795 (define-key map (kbd "C-c C--") 'markdown-promote)
5796 (define-key map (kbd "C-c C-=") 'markdown-demote)
5797 (define-key map (kbd "C-c C-]") 'markdown-complete)
5798 ;; Following and doing things
5799 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
5800 (define-key map (kbd "C-c C-d") 'markdown-do)
5801 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
5802 ;; Indentation
5803 (define-key map (kbd "C-m") 'markdown-enter-key)
5804 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
5805 (define-key map (kbd "C-c >") 'markdown-indent-region)
5806 (define-key map (kbd "C-c <") 'markdown-outdent-region)
5807 ;; Visibility cycling
5808 (define-key map (kbd "TAB") 'markdown-cycle)
5809 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
5810 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
5811 (define-key map (kbd "<backtab>") 'markdown-shifttab)
5812 ;; Heading and list navigation
5813 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
5814 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
5815 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
5816 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
5817 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
5818 ;; Buffer-wide commands
5819 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
5820 ;; Subtree and list editing
5821 (define-key map (kbd "C-c <up>") 'markdown-move-up)
5822 (define-key map (kbd "C-c <down>") 'markdown-move-down)
5823 (define-key map (kbd "C-c <left>") 'markdown-promote)
5824 (define-key map (kbd "C-c <right>") 'markdown-demote)
5825 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
5826 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
5827 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
5828 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
5829 ;; Paragraphs (Markdown context aware)
5830 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
5831 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
5832 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
5833 ;; Blocks (one or more paragraphs)
5834 (define-key map (kbd "C-M-{") 'markdown-backward-block)
5835 (define-key map (kbd "C-M-}") 'markdown-forward-block)
5836 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
5837 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
5838 ;; Pages (top-level sections)
5839 (define-key map [remap backward-page] 'markdown-backward-page)
5840 (define-key map [remap forward-page] 'markdown-forward-page)
5841 (define-key map [remap mark-page] 'markdown-mark-page)
5842 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
5843 ;; Link Movement
5844 (define-key map (kbd "M-n") 'markdown-next-link)
5845 (define-key map (kbd "M-p") 'markdown-previous-link)
5846 ;; Toggling functionality
5847 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
5848 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
5849 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
5850 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
5851 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
5852 ;; Alternative keys (in case of problems with the arrow keys)
5853 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
5854 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
5855 (define-key map (kbd "C-c C-x l") 'markdown-promote)
5856 (define-key map (kbd "C-c C-x r") 'markdown-demote)
5857 ;; Deprecated keys that may be removed in a future version
5858 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
5859 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
5860 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
5861 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
5862 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
5863 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
5864 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
5865 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
5866 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
5867 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
5868 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
5869 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
5870 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
5871 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
5872 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
5873 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
5874 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
5875 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
5876 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
5877 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
5878 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
5879 (define-key map (kbd "C-c -") 'markdown-insert-hr)
5880 map)
5881 "Keymap for Markdown major mode.")
5883 (defvar markdown-mode-mouse-map
5884 (let ((map (make-sparse-keymap)))
5885 (define-key map [follow-link] 'mouse-face)
5886 (define-key map [mouse-2] 'markdown-follow-link-at-point)
5887 map)
5888 "Keymap for following links with mouse.")
5890 (defvar gfm-mode-map
5891 (let ((map (make-sparse-keymap)))
5892 (set-keymap-parent map markdown-mode-map)
5893 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
5894 (define-key map "`" 'markdown-electric-backquote)
5895 map)
5896 "Keymap for `gfm-mode'.
5897 See also `markdown-mode-map'.")
5900 ;;; Menu ==================================================================
5902 (easy-menu-define markdown-mode-menu markdown-mode-map
5903 "Menu for Markdown mode"
5904 '("Markdown"
5905 "---"
5906 ("Movement"
5907 ["Jump" markdown-do]
5908 ["Follow Link" markdown-follow-thing-at-point]
5909 ["Next Link" markdown-next-link]
5910 ["Previous Link" markdown-previous-link]
5911 "---"
5912 ["Next Heading or List Item" markdown-outline-next]
5913 ["Previous Heading or List Item" markdown-outline-previous]
5914 ["Next at Same Level" markdown-outline-next-same-level]
5915 ["Previous at Same Level" markdown-outline-previous-same-level]
5916 ["Up to Parent" markdown-outline-up]
5917 "---"
5918 ["Forward Paragraph" markdown-forward-paragraph]
5919 ["Backward Paragraph" markdown-backward-paragraph]
5920 ["Forward Block" markdown-forward-block]
5921 ["Backward Block" markdown-backward-block])
5922 ("Show & Hide"
5923 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
5924 ["Cycle Heading Visibility (Global)" markdown-shifttab]
5925 "---"
5926 ["Narrow to Region" narrow-to-region]
5927 ["Narrow to Block" markdown-narrow-to-block]
5928 ["Narrow to Section" narrow-to-defun]
5929 ["Narrow to Subtree" markdown-narrow-to-subtree]
5930 ["Widen" widen (buffer-narrowed-p)]
5931 "---"
5932 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
5933 :keys "C-c C-x C-m"
5934 :style radio
5935 :selected markdown-hide-markup])
5936 "---"
5937 ("Headings & Structure"
5938 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
5939 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
5940 ("Specific Heading (atx)"
5941 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
5942 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
5943 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
5944 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
5945 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
5946 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
5947 ("Specific Heading (Setext)"
5948 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
5949 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
5950 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
5951 "---"
5952 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5953 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5954 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
5955 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
5956 ("Region & Mark"
5957 ["Indent Region" markdown-indent-region]
5958 ["Outdent Region" markdown-outdent-region]
5959 "--"
5960 ["Mark Paragraph" mark-paragraph]
5961 ["Mark Block" markdown-mark-block]
5962 ["Mark Section" mark-defun]
5963 ["Mark Subtree" markdown-mark-subtree])
5964 ("Lists"
5965 ["Insert List Item" markdown-insert-list-item]
5966 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
5967 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
5968 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
5969 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
5970 ["Renumber List" markdown-cleanup-list-numbers]
5971 ["Toggle Task List Item" markdown-toggle-gfm-checkbox :keys "C-c C-d"])
5972 ("Links & Images"
5973 ["Insert Link" markdown-insert-link]
5974 ["Insert Image" markdown-insert-image]
5975 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
5976 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
5977 "---"
5978 ["Check References" markdown-check-refs]
5979 ["Toggle URL Hiding" markdown-toggle-url-hiding
5980 :style radio
5981 :selected markdown-hide-urls]
5982 ["Toggle Inline Images" markdown-toggle-inline-images
5983 :keys "C-c C-x C-i"
5984 :style radio
5985 :selected markdown-inline-image-overlays]
5986 ["Toggle Wiki Links" markdown-toggle-wiki-links
5987 :style radio
5988 :selected markdown-enable-wiki-links])
5989 ("Styles"
5990 ["Bold" markdown-insert-bold]
5991 ["Italic" markdown-insert-italic]
5992 ["Code" markdown-insert-code]
5993 ["Strikethrough" markdown-insert-strike-through]
5994 ["Keyboard" markdown-insert-kbd]
5995 "---"
5996 ["Blockquote" markdown-insert-blockquote]
5997 ["Preformatted" markdown-insert-pre]
5998 ["GFM Code Block" markdown-insert-gfm-code-block]
5999 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6000 "---"
6001 ["Blockquote Region" markdown-blockquote-region]
6002 ["Preformatted Region" markdown-pre-region]
6003 "---"
6004 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6005 :style radio
6006 :selected markdown-fontify-code-blocks-natively]
6007 ["LaTeX Math Support" markdown-toggle-math
6008 :style radio
6009 :selected markdown-enable-math])
6010 "---"
6011 ("Preview & Export"
6012 ["Compile" markdown-other-window]
6013 ["Preview" markdown-preview]
6014 ["Export" markdown-export]
6015 ["Export & View" markdown-export-and-preview]
6016 ["Open" markdown-open]
6017 ["Live Export" markdown-live-preview-mode
6018 :style radio
6019 :selected markdown-live-preview-mode]
6020 ["Kill ring save" markdown-kill-ring-save])
6021 ("Markup Completion and Cycling"
6022 ["Complete Markup" markdown-complete]
6023 ["Promote Element" markdown-promote :keys "C-c C--"]
6024 ["Demote Element" markdown-demote :keys "C-c C-="])
6025 "---"
6026 ["Kill Element" markdown-kill-thing-at-point]
6027 "---"
6028 ("Documentation"
6029 ["Version" markdown-show-version]
6030 ["Homepage" markdown-mode-info]
6031 ["Describe Mode" (describe-function 'markdown-mode)]
6032 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6035 ;;; imenu =====================================================================
6037 (defun markdown-imenu-create-nested-index ()
6038 "Create and return a nested imenu index alist for the current buffer.
6039 See `imenu-create-index-function' and `imenu--index-alist' for details."
6040 (let* ((root '(nil . nil))
6041 cur-alist
6042 (cur-level 0)
6043 (empty-heading "-")
6044 (self-heading ".")
6045 hashes pos level heading)
6046 (save-excursion
6047 (goto-char (point-min))
6048 (while (re-search-forward markdown-regex-header (point-max) t)
6049 (unless (markdown-code-block-at-point-p)
6050 (cond
6051 ((match-string-no-properties 2) ;; level 1 setext
6052 (setq heading (match-string-no-properties 1))
6053 (setq pos (match-beginning 1)
6054 level 1))
6055 ((match-string-no-properties 3) ;; level 2 setext
6056 (setq heading (match-string-no-properties 1))
6057 (setq pos (match-beginning 1)
6058 level 2))
6059 ((setq hashes (markdown-trim-whitespace
6060 (match-string-no-properties 4)))
6061 (setq heading (match-string-no-properties 5)
6062 pos (match-beginning 4)
6063 level (length hashes))))
6064 (let ((alist (list (cons heading pos))))
6065 (cond
6066 ((= cur-level level) ; new sibling
6067 (setcdr cur-alist alist)
6068 (setq cur-alist alist))
6069 ((< cur-level level) ; first child
6070 (dotimes (_ (- level cur-level 1))
6071 (setq alist (list (cons empty-heading alist))))
6072 (if cur-alist
6073 (let* ((parent (car cur-alist))
6074 (self-pos (cdr parent)))
6075 (setcdr parent (cons (cons self-heading self-pos) alist)))
6076 (setcdr root alist)) ; primogenitor
6077 (setq cur-alist alist)
6078 (setq cur-level level))
6079 (t ; new sibling of an ancestor
6080 (let ((sibling-alist (last (cdr root))))
6081 (dotimes (_ (1- level))
6082 (setq sibling-alist (last (cdar sibling-alist))))
6083 (setcdr sibling-alist alist)
6084 (setq cur-alist alist))
6085 (setq cur-level level))))))
6086 (cdr root))))
6088 (defun markdown-imenu-create-flat-index ()
6089 "Create and return a flat imenu index alist for the current buffer.
6090 See `imenu-create-index-function' and `imenu--index-alist' for details."
6091 (let* ((empty-heading "-") index heading pos)
6092 (save-excursion
6093 (goto-char (point-min))
6094 (while (re-search-forward markdown-regex-header (point-max) t)
6095 (when (and (not (markdown-code-block-at-point-p))
6096 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6097 (cond
6098 ((setq heading (match-string-no-properties 1))
6099 (setq pos (match-beginning 1)))
6100 ((setq heading (match-string-no-properties 5))
6101 (setq pos (match-beginning 4))))
6102 (or (> (length heading) 0)
6103 (setq heading empty-heading))
6104 (setq index (append index (list (cons heading pos))))))
6105 index)))
6108 ;;; References ================================================================
6110 (defun markdown-reference-goto-definition ()
6111 "Jump to the definition of the reference at point or create it."
6112 (interactive)
6113 (when (thing-at-point-looking-at markdown-regex-link-reference)
6114 (let* ((text (match-string-no-properties 3))
6115 (reference (match-string-no-properties 6))
6116 (target (downcase (if (string= reference "") text reference)))
6117 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6118 (if loc
6119 (goto-char loc)
6120 (goto-char (match-beginning 0))
6121 (markdown-insert-reference-definition target)))))
6123 (defun markdown-reference-find-links (reference)
6124 "Return a list of all links for REFERENCE.
6125 REFERENCE should not include the surrounding square brackets.
6126 Elements of the list have the form (text start line), where
6127 text is the link text, start is the location at the beginning of
6128 the link, and line is the line number on which the link appears."
6129 (let* ((ref-quote (regexp-quote reference))
6130 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6131 ref-quote ref-quote))
6132 links)
6133 (save-excursion
6134 (goto-char (point-min))
6135 (while (re-search-forward regexp nil t)
6136 (let* ((text (or (match-string-no-properties 1)
6137 (match-string-no-properties 2)))
6138 (start (match-beginning 0))
6139 (line (markdown-line-number-at-pos)))
6140 (cl-pushnew (list text start line) links :test #'equal))))
6141 links))
6143 (defun markdown-get-undefined-refs ()
6144 "Return a list of undefined Markdown references.
6145 Result is an alist of pairs (reference . occurrences), where
6146 occurrences is itself another alist of pairs (label . line-number).
6147 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6148 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6149 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6150 (let ((missing))
6151 (save-excursion
6152 (goto-char (point-min))
6153 (while
6154 (re-search-forward markdown-regex-link-reference nil t)
6155 (let* ((text (match-string-no-properties 3))
6156 (reference (match-string-no-properties 6))
6157 (target (downcase (if (string= reference "") text reference))))
6158 (unless (markdown-reference-definition target)
6159 (let ((entry (assoc target missing)))
6160 (if (not entry)
6161 (cl-pushnew
6162 (cons target (list (cons text (markdown-line-number-at-pos))))
6163 missing :test #'equal)
6164 (setcdr entry
6165 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6166 (reverse missing))))
6168 (defconst markdown-reference-check-buffer
6169 "*Undefined references for %buffer%*"
6170 "Pattern for name of buffer for listing undefined references.
6171 The string %buffer% will be replaced by the corresponding
6172 `markdown-mode' buffer name.")
6174 (defun markdown-reference-check-buffer (&optional buffer-name)
6175 "Name and return buffer for reference checking.
6176 BUFFER-NAME is the name of the main buffer being visited."
6177 (or buffer-name (setq buffer-name (buffer-name)))
6178 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6179 "%buffer%" buffer-name
6180 markdown-reference-check-buffer))))
6181 (with-current-buffer refbuf
6182 (when view-mode
6183 (View-exit-and-edit))
6184 (use-local-map button-buffer-map)
6185 (erase-buffer))
6186 refbuf))
6188 (defconst markdown-reference-links-buffer
6189 "*Reference links for %buffer%*"
6190 "Pattern for name of buffer for listing references.
6191 The string %buffer% will be replaced by the corresponding buffer name.")
6193 (defun markdown-reference-links-buffer (&optional buffer-name)
6194 "Name, setup, and return a buffer for listing links.
6195 BUFFER-NAME is the name of the main buffer being visited."
6196 (or buffer-name (setq buffer-name (buffer-name)))
6197 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6198 "%buffer%" buffer-name
6199 markdown-reference-links-buffer))))
6200 (with-current-buffer linkbuf
6201 (when view-mode
6202 (View-exit-and-edit))
6203 (use-local-map button-buffer-map)
6204 (erase-buffer))
6205 linkbuf))
6207 ;; Add an empty Markdown reference definition to buffer
6208 ;; specified in the 'target-buffer property. The reference name is
6209 ;; the button's label.
6210 (define-button-type 'markdown-undefined-reference-button
6211 'help-echo "mouse-1, RET: create definition for undefined reference"
6212 'follow-link t
6213 'face 'bold
6214 'action (lambda (b)
6215 (let ((buffer (button-get b 'target-buffer))
6216 (line (button-get b 'target-line))
6217 (label (button-label b)))
6218 (switch-to-buffer-other-window buffer)
6219 (goto-char (point-min))
6220 (forward-line line)
6221 (markdown-insert-reference-definition label)
6222 (markdown-check-refs t))))
6224 ;; Jump to line in buffer specified by 'target-buffer property.
6225 ;; Line number is button's 'line property.
6226 (define-button-type 'markdown-goto-line-button
6227 'help-echo "mouse-1, RET: go to line"
6228 'follow-link t
6229 'face 'italic
6230 'action (lambda (b)
6231 (message (button-get b 'buffer))
6232 (switch-to-buffer-other-window (button-get b 'target-buffer))
6233 ;; use call-interactively to silence compiler
6234 (let ((current-prefix-arg (button-get b 'target-line)))
6235 (call-interactively 'goto-line))))
6237 ;; Jumps to a particular link at location given by 'target-char
6238 ;; property in buffer given by 'target-buffer property.
6239 (define-button-type 'markdown-location-button
6240 'help-echo "mouse-1, RET: jump to location of link"
6241 'follow-link t
6242 'face 'bold
6243 'action (lambda (b)
6244 (let ((target (button-get b 'target-buffer))
6245 (loc (button-get b 'target-char)))
6246 (kill-buffer-and-window)
6247 (switch-to-buffer target)
6248 (goto-char loc))))
6250 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6251 "Insert a button for creating REFERENCE in buffer OLDBUF.
6252 REFERENCE should be a list of the form (reference . occurrences),
6253 as by `markdown-get-undefined-refs'."
6254 (let ((label (car reference)))
6255 ;; Create a reference button
6256 (insert-button label
6257 :type 'markdown-undefined-reference-button
6258 'target-buffer oldbuf
6259 'target-line (cdr (car (cdr reference))))
6260 (insert " (")
6261 (dolist (occurrence (cdr reference))
6262 (let ((line (cdr occurrence)))
6263 ;; Create a line number button
6264 (insert-button (number-to-string line)
6265 :type 'markdown-goto-line-button
6266 'target-buffer oldbuf
6267 'target-line line)
6268 (insert " ")))
6269 (delete-char -1)
6270 (insert ")")
6271 (newline)))
6273 (defun markdown-insert-link-button (link oldbuf)
6274 "Insert a button for jumping to LINK in buffer OLDBUF.
6275 LINK should be a list of the form (text char line) containing
6276 the link text, location, and line number."
6277 (let ((label (cl-first link))
6278 (char (cl-second link))
6279 (line (cl-third link)))
6280 ;; Create a reference button
6281 (insert-button label
6282 :type 'markdown-location-button
6283 'target-buffer oldbuf
6284 'target-char char)
6285 (insert (format " (line %d)\n" line))))
6287 (defun markdown-reference-goto-link (&optional reference)
6288 "Jump to the location of the first use of REFERENCE."
6289 (interactive)
6290 (unless reference
6291 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6292 (setq reference (match-string-no-properties 2))
6293 (user-error "No reference definition at point")))
6294 (let ((links (markdown-reference-find-links reference)))
6295 (cond ((= (length links) 1)
6296 (goto-char (cadr (car links))))
6297 ((> (length links) 1)
6298 (let ((oldbuf (current-buffer))
6299 (linkbuf (markdown-reference-links-buffer)))
6300 (with-current-buffer linkbuf
6301 (insert "Links using reference " reference ":\n\n")
6302 (dolist (link (reverse links))
6303 (markdown-insert-link-button link oldbuf)))
6304 (view-buffer-other-window linkbuf)
6305 (goto-char (point-min))
6306 (forward-line 2)))
6308 (error "No links for reference %s" reference)))))
6310 (defun markdown-check-refs (&optional silent)
6311 "Show all undefined Markdown references in current `markdown-mode' buffer.
6312 If SILENT is non-nil, do not message anything when no undefined
6313 references found.
6314 Links which have empty reference definitions are considered to be
6315 defined."
6316 (interactive "P")
6317 (when (not (eq major-mode 'markdown-mode))
6318 (user-error "Not available in current mode"))
6319 (let ((oldbuf (current-buffer))
6320 (refs (markdown-get-undefined-refs))
6321 (refbuf (markdown-reference-check-buffer)))
6322 (if (null refs)
6323 (progn
6324 (when (not silent)
6325 (message "No undefined references found"))
6326 (kill-buffer refbuf))
6327 (with-current-buffer refbuf
6328 (insert "The following references are undefined:\n\n")
6329 (dolist (ref refs)
6330 (markdown-insert-undefined-reference-button ref oldbuf))
6331 (view-buffer-other-window refbuf)
6332 (goto-char (point-min))
6333 (forward-line 2)))))
6336 ;;; Lists =====================================================================
6338 (defun markdown-insert-list-item (&optional arg)
6339 "Insert a new list item.
6340 If the point is inside unordered list, insert a bullet mark. If
6341 the point is inside ordered list, insert the next number followed
6342 by a period. Use the previous list item to determine the amount
6343 of whitespace to place before and after list markers.
6345 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6346 decrease the indentation by one level.
6348 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6349 increase the indentation by one level."
6350 (interactive "p")
6351 (let (bounds cur-indent marker indent new-indent new-loc)
6352 (save-match-data
6353 ;; Look for a list item on current or previous non-blank line
6354 (save-excursion
6355 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6356 (not (bobp))
6357 (markdown-cur-line-blank-p))
6358 (forward-line -1)))
6359 (when bounds
6360 (cond ((save-excursion
6361 (skip-chars-backward " \t")
6362 (looking-at-p markdown-regex-list))
6363 (beginning-of-line)
6364 (insert "\n")
6365 (forward-line -1))
6366 ((not (markdown-cur-line-blank-p))
6367 (newline)))
6368 (setq new-loc (point)))
6369 ;; Look ahead for a list item on next non-blank line
6370 (unless bounds
6371 (save-excursion
6372 (while (and (null bounds)
6373 (not (eobp))
6374 (markdown-cur-line-blank-p))
6375 (forward-line)
6376 (setq bounds (markdown-cur-list-item-bounds))))
6377 (when bounds
6378 (setq new-loc (point))
6379 (unless (markdown-cur-line-blank-p)
6380 (newline))))
6381 (if (not bounds)
6382 ;; When not in a list, start a new unordered one
6383 (progn
6384 (unless (markdown-cur-line-blank-p)
6385 (insert "\n"))
6386 (insert markdown-unordered-list-item-prefix))
6387 ;; Compute indentation and marker for new list item
6388 (setq cur-indent (nth 2 bounds))
6389 (setq marker (nth 4 bounds))
6390 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6391 (when (nth 5 bounds)
6392 (setq marker
6393 (concat marker
6394 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6395 (cond
6396 ;; Dedent: decrement indentation, find previous marker.
6397 ((= arg 4)
6398 (setq indent (max (- cur-indent 4) 0))
6399 (let ((prev-bounds
6400 (save-excursion
6401 (goto-char (nth 0 bounds))
6402 (when (markdown-up-list)
6403 (markdown-cur-list-item-bounds)))))
6404 (when prev-bounds
6405 (setq marker (nth 4 prev-bounds)))))
6406 ;; Indent: increment indentation by 4, use same marker.
6407 ((= arg 16) (setq indent (+ cur-indent 4)))
6408 ;; Same level: keep current indentation and marker.
6409 (t (setq indent cur-indent)))
6410 (setq new-indent (make-string indent 32))
6411 (goto-char new-loc)
6412 (cond
6413 ;; Ordered list
6414 ((string-match-p "[0-9]" marker)
6415 (if (= arg 16) ;; starting a new column indented one more level
6416 (insert (concat new-indent "1. "))
6417 ;; Don't use previous match-data
6418 (set-match-data nil)
6419 ;; travel up to the last item and pick the correct number. If
6420 ;; the argument was nil, "new-indent = cur-indent" is the same,
6421 ;; so we don't need special treatment. Neat.
6422 (save-excursion
6423 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6424 (>= (forward-line -1) 0))))
6425 (let* ((old-prefix (match-string 1))
6426 (old-spacing (match-string 2))
6427 (new-prefix (if old-prefix
6428 (int-to-string (1+ (string-to-number old-prefix)))
6429 "1"))
6430 (space-adjust (- (length old-prefix) (length new-prefix)))
6431 (new-spacing (if (and (match-string 2)
6432 (not (string-match-p "\t" old-spacing))
6433 (< space-adjust 0)
6434 (> space-adjust (- 1 (length (match-string 2)))))
6435 (substring (match-string 2) 0 space-adjust)
6436 (or old-spacing ". "))))
6437 (insert (concat new-indent new-prefix new-spacing)))))
6438 ;; Unordered list, GFM task list, or ordered list with hash mark
6439 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6440 (insert new-indent marker)))))))
6442 (defun markdown-move-list-item-up ()
6443 "Move the current list item up in the list when possible.
6444 In nested lists, move child items with the parent item."
6445 (interactive)
6446 (let (cur prev old)
6447 (when (setq cur (markdown-cur-list-item-bounds))
6448 (setq old (point))
6449 (goto-char (nth 0 cur))
6450 (if (markdown-prev-list-item (nth 3 cur))
6451 (progn
6452 (setq prev (markdown-cur-list-item-bounds))
6453 (condition-case nil
6454 (progn
6455 (transpose-regions (nth 0 prev) (nth 1 prev)
6456 (nth 0 cur) (nth 1 cur) t)
6457 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6458 ;; Catch error in case regions overlap.
6459 (error (goto-char old))))
6460 (goto-char old)))))
6462 (defun markdown-move-list-item-down ()
6463 "Move the current list item down in the list when possible.
6464 In nested lists, move child items with the parent item."
6465 (interactive)
6466 (let (cur next old)
6467 (when (setq cur (markdown-cur-list-item-bounds))
6468 (setq old (point))
6469 (if (markdown-next-list-item (nth 3 cur))
6470 (progn
6471 (setq next (markdown-cur-list-item-bounds))
6472 (condition-case nil
6473 (progn
6474 (transpose-regions (nth 0 cur) (nth 1 cur)
6475 (nth 0 next) (nth 1 next) nil)
6476 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6477 ;; Catch error in case regions overlap.
6478 (error (goto-char old))))
6479 (goto-char old)))))
6481 (defun markdown-demote-list-item (&optional bounds)
6482 "Indent (or demote) the current list item.
6483 Optionally, BOUNDS of the current list item may be provided if available.
6484 In nested lists, demote child items as well."
6485 (interactive)
6486 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6487 (save-excursion
6488 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6489 (goto-char (nth 0 bounds))
6490 (while (< (point) end-marker)
6491 (unless (markdown-cur-line-blank-p)
6492 (insert (make-string markdown-list-indent-width ? )))
6493 (forward-line))))))
6495 (defun markdown-promote-list-item (&optional bounds)
6496 "Unindent (or promote) the current list item.
6497 Optionally, BOUNDS of the current list item may be provided if available.
6498 In nested lists, demote child items as well."
6499 (interactive)
6500 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6501 (save-excursion
6502 (save-match-data
6503 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6504 num regexp)
6505 (goto-char (nth 0 bounds))
6506 (when (looking-at (format "^[ ]\\{1,%d\\}"
6507 markdown-list-indent-width))
6508 (setq num (- (match-end 0) (match-beginning 0)))
6509 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6510 (while (and (< (point) end-marker)
6511 (re-search-forward regexp end-marker t))
6512 (replace-match "" nil nil)
6513 (forward-line))))))))
6515 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6516 "Update the numbering for level PFX (as a string of spaces).
6518 Assume that the previously found match was for a numbered item in
6519 a list."
6520 (let ((cpfx pfx)
6521 (idx 0)
6522 (continue t)
6523 (step t)
6524 (sep nil))
6525 (while (and continue (not (eobp)))
6526 (setq step t)
6527 (cond
6528 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6529 (setq cpfx (match-string-no-properties 1))
6530 (cond
6531 ((string= cpfx pfx)
6532 (save-excursion
6533 (replace-match
6534 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6535 (setq sep nil))
6536 ;; indented a level
6537 ((string< pfx cpfx)
6538 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6539 (setq step nil))
6540 ;; exit the loop
6542 (setq step nil)
6543 (setq continue nil))))
6545 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6546 (setq cpfx (match-string-no-properties 1))
6547 (cond
6548 ;; reset if separated before
6549 ((string= cpfx pfx) (when sep (setq idx 0)))
6550 ((string< cpfx pfx)
6551 (setq step nil)
6552 (setq continue nil))))
6553 (t (setq sep t)))
6555 (when step
6556 (beginning-of-line)
6557 (setq continue (= (forward-line) 0))))
6558 sep))
6560 (defun markdown-cleanup-list-numbers ()
6561 "Update the numbering of ordered lists."
6562 (interactive)
6563 (save-excursion
6564 (goto-char (point-min))
6565 (markdown-cleanup-list-numbers-level "")))
6568 ;;; Movement ==================================================================
6570 (defun markdown-beginning-of-defun (&optional arg)
6571 "`beginning-of-defun-function' for Markdown.
6572 This is used to find the beginning of the defun and should behave
6573 like ‘beginning-of-defun’, returning non-nil if it found the
6574 beginning of a defun. It moves the point backward, right before a
6575 heading which defines a defun. When ARG is non-nil, repeat that
6576 many times. When ARG is negative, move forward to the ARG-th
6577 following section."
6578 (or arg (setq arg 1))
6579 (when (< arg 0) (end-of-line))
6580 ;; Adjust position for setext headings.
6581 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6582 (not (= (point) (match-beginning 0)))
6583 (not (markdown-code-block-at-point-p)))
6584 (goto-char (match-end 0)))
6585 (let (found)
6586 ;; Move backward with positive argument.
6587 (while (and (not (bobp)) (> arg 0))
6588 (setq found nil)
6589 (while (and (not found)
6590 (not (bobp))
6591 (re-search-backward markdown-regex-header nil 'move))
6592 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6593 (setq found (match-beginning 0)))
6594 (setq arg (1- arg)))
6595 ;; Move forward with negative argument.
6596 (while (and (not (eobp)) (< arg 0))
6597 (setq found nil)
6598 (while (and (not found)
6599 (not (eobp))
6600 (re-search-forward markdown-regex-header nil 'move))
6601 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6602 (setq found (match-beginning 0)))
6603 (setq arg (1+ arg)))
6604 (when found
6605 (beginning-of-line)
6606 t)))
6608 (defun markdown-end-of-defun ()
6609 "`end-of-defun-function’ for Markdown.
6610 This is used to find the end of the defun at point.
6611 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6612 so it can assume that point is at the beginning of the defun body.
6613 It should move point to the first position after the defun."
6614 (or (eobp) (forward-char 1))
6615 (let (found)
6616 (while (and (not found)
6617 (not (eobp))
6618 (re-search-forward markdown-regex-header nil 'move))
6619 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6620 (setq found (match-beginning 0))))
6621 (when found
6622 (goto-char found)
6623 (skip-syntax-backward "-"))))
6625 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6627 (defun markdown-beginning-of-text-block ()
6628 "Move backward to previous beginning of a plain text block.
6629 This function simply looks for blank lines without considering
6630 the surrounding context in light of Markdown syntax. For that, see
6631 `markdown-backward-block'."
6632 (interactive)
6633 (let ((start (point)))
6634 (if (re-search-backward markdown-regex-block-separator nil t)
6635 (goto-char (match-end 0))
6636 (goto-char (point-min)))
6637 (when (and (= start (point)) (not (bobp)))
6638 (forward-line -1)
6639 (if (re-search-backward markdown-regex-block-separator nil t)
6640 (goto-char (match-end 0))
6641 (goto-char (point-min))))))
6643 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6645 (defun markdown-end-of-text-block ()
6646 "Move forward to next beginning of a plain text block.
6647 This function simply looks for blank lines without considering
6648 the surrounding context in light of Markdown syntax. For that, see
6649 `markdown-forward-block'."
6650 (interactive)
6651 (beginning-of-line)
6652 (skip-syntax-forward "-")
6653 (when (= (point) (point-min))
6654 (forward-char))
6655 (if (re-search-forward markdown-regex-block-separator nil t)
6656 (goto-char (match-end 0))
6657 (goto-char (point-max)))
6658 (skip-syntax-backward "-")
6659 (forward-line))
6661 (defun markdown-backward-paragraph (&optional arg)
6662 "Move the point to the start of the current paragraph.
6663 With argument ARG, do it ARG times; a negative argument ARG = -N
6664 means move forward N blocks."
6665 (interactive "^p")
6666 (or arg (setq arg 1))
6667 (if (< arg 0)
6668 (markdown-forward-paragraph (- arg))
6669 (dotimes (_ arg)
6670 ;; Skip over whitespace in between paragraphs when moving backward.
6671 (skip-syntax-backward "-")
6672 (beginning-of-line)
6673 ;; Skip over code block endings.
6674 (when (markdown-range-properties-exist
6675 (point-at-bol) (point-at-eol)
6676 '(markdown-gfm-block-end
6677 markdown-tilde-fence-end))
6678 (forward-line -1))
6679 ;; Skip over blank lines inside blockquotes.
6680 (while (and (not (eobp))
6681 (looking-at markdown-regex-blockquote)
6682 (= (length (match-string 3)) 0))
6683 (forward-line -1))
6684 ;; Proceed forward based on the type of block of paragraph.
6685 (let (bounds skip)
6686 (cond
6687 ;; Blockquotes
6688 ((looking-at markdown-regex-blockquote)
6689 (while (and (not (bobp))
6690 (looking-at markdown-regex-blockquote)
6691 (> (length (match-string 3)) 0)) ;; not blank
6692 (forward-line -1))
6693 (forward-line))
6694 ;; List items
6695 ((setq bounds (markdown-cur-list-item-bounds))
6696 (goto-char (nth 0 bounds)))
6697 ;; Other
6699 (while (and (not (bobp))
6700 (not skip)
6701 (not (markdown-cur-line-blank-p))
6702 (not (looking-at markdown-regex-blockquote))
6703 (not (markdown-range-properties-exist
6704 (point-at-bol) (point-at-eol)
6705 '(markdown-gfm-block-end
6706 markdown-tilde-fence-end))))
6707 (setq skip (markdown-range-properties-exist
6708 (point-at-bol) (point-at-eol)
6709 '(markdown-gfm-block-begin
6710 markdown-tilde-fence-begin)))
6711 (forward-line -1))
6712 (unless (bobp)
6713 (forward-line 1))))))))
6715 (defun markdown-forward-paragraph (&optional arg)
6716 "Move forward to the next end of a paragraph.
6717 With argument ARG, do it ARG times; a negative argument ARG = -N
6718 means move backward N blocks."
6719 (interactive "^p")
6720 (or arg (setq arg 1))
6721 (if (< arg 0)
6722 (markdown-backward-paragraph (- arg))
6723 (dotimes (_ arg)
6724 ;; Skip whitespace in between paragraphs.
6725 (when (markdown-cur-line-blank-p)
6726 (skip-syntax-forward "-")
6727 (beginning-of-line))
6728 ;; Proceed forward based on the type of block.
6729 (let (bounds skip)
6730 (cond
6731 ;; Blockquotes
6732 ((looking-at markdown-regex-blockquote)
6733 ;; Skip over blank lines inside blockquotes.
6734 (while (and (not (eobp))
6735 (looking-at markdown-regex-blockquote)
6736 (= (length (match-string 3)) 0))
6737 (forward-line))
6738 ;; Move to end of quoted text block
6739 (while (and (not (eobp))
6740 (looking-at markdown-regex-blockquote)
6741 (> (length (match-string 3)) 0)) ;; not blank
6742 (forward-line)))
6743 ;; List items
6744 ((and (markdown-cur-list-item-bounds)
6745 (setq bounds (markdown-next-list-item-bounds)))
6746 (goto-char (nth 0 bounds)))
6747 ;; Other
6749 (forward-line)
6750 (while (and (not (eobp))
6751 (not skip)
6752 (not (markdown-cur-line-blank-p))
6753 (not (looking-at markdown-regex-blockquote))
6754 (not (markdown-range-properties-exist
6755 (point-at-bol) (point-at-eol)
6756 '(markdown-gfm-block-begin
6757 markdown-tilde-fence-begin))))
6758 (setq skip (markdown-range-properties-exist
6759 (point-at-bol) (point-at-eol)
6760 '(markdown-gfm-block-end
6761 markdown-tilde-fence-end)))
6762 (forward-line))))))))
6764 (defun markdown-backward-block (&optional arg)
6765 "Move the point to the start of the current Markdown block.
6766 Moves across complete code blocks, list items, and blockquotes,
6767 but otherwise stops at blank lines, headers, and horizontal
6768 rules. With argument ARG, do it ARG times; a negative argument
6769 ARG = -N means move forward N blocks."
6770 (interactive "^p")
6771 (or arg (setq arg 1))
6772 (if (< arg 0)
6773 (markdown-forward-block (- arg))
6774 (dotimes (_ arg)
6775 ;; Skip over whitespace in between blocks when moving backward,
6776 ;; unless at a block boundary with no whitespace.
6777 (skip-syntax-backward "-")
6778 (beginning-of-line)
6779 ;; Proceed forward based on the type of block.
6780 (cond
6781 ;; Code blocks
6782 ((and (markdown-code-block-at-pos (point)) ;; this line
6783 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
6784 (forward-line -1)
6785 (while (and (markdown-code-block-at-point-p) (not (bobp)))
6786 (forward-line -1))
6787 (forward-line))
6788 ;; Headings
6789 ((markdown-heading-at-point)
6790 (goto-char (match-beginning 0)))
6791 ;; Horizontal rules
6792 ((looking-at markdown-regex-hr))
6793 ;; Blockquotes
6794 ((looking-at markdown-regex-blockquote)
6795 (forward-line -1)
6796 (while (and (looking-at markdown-regex-blockquote)
6797 (not (bobp)))
6798 (forward-line -1))
6799 (forward-line))
6800 ;; List items
6801 ((markdown-cur-list-item-bounds)
6802 (markdown-beginning-of-list))
6803 ;; Other
6805 ;; Move forward in case it is a one line regular paragraph.
6806 (unless (markdown-next-line-blank-p)
6807 (forward-line))
6808 (unless (markdown-prev-line-blank-p)
6809 (markdown-backward-paragraph)))))))
6811 (defun markdown-forward-block (&optional arg)
6812 "Move forward to the next end of a Markdown block.
6813 Moves across complete code blocks, list items, and blockquotes,
6814 but otherwise stops at blank lines, headers, and horizontal
6815 rules. With argument ARG, do it ARG times; a negative argument
6816 ARG = -N means move backward N blocks."
6817 (interactive "^p")
6818 (or arg (setq arg 1))
6819 (if (< arg 0)
6820 (markdown-backward-block (- arg))
6821 (dotimes (_ arg)
6822 ;; Skip over whitespace in between blocks when moving forward.
6823 (if (markdown-cur-line-blank-p)
6824 (skip-syntax-forward "-")
6825 (beginning-of-line))
6826 ;; Proceed forward based on the type of block.
6827 (cond
6828 ;; Code blocks
6829 ((markdown-code-block-at-point-p)
6830 (forward-line)
6831 (while (and (markdown-code-block-at-point-p) (not (eobp)))
6832 (forward-line)))
6833 ;; Headings
6834 ((looking-at markdown-regex-header)
6835 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
6836 (forward-line))
6837 ;; Horizontal rules
6838 ((looking-at markdown-regex-hr)
6839 (forward-line))
6840 ;; Blockquotes
6841 ((looking-at markdown-regex-blockquote)
6842 (forward-line)
6843 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
6844 (forward-line)))
6845 ;; List items
6846 ((markdown-cur-list-item-bounds)
6847 (markdown-end-of-list)
6848 (forward-line))
6849 ;; Other
6850 (t (markdown-forward-paragraph))))
6851 (skip-syntax-backward "-")
6852 (unless (eobp)
6853 (forward-char 1))))
6855 (defun markdown-backward-page (&optional count)
6856 "Move backward to boundary of the current toplevel section.
6857 With COUNT, repeat, or go forward if negative."
6858 (interactive "p")
6859 (or count (setq count 1))
6860 (if (< count 0)
6861 (markdown-forward-page (- count))
6862 (skip-syntax-backward "-")
6863 (or (markdown-back-to-heading-over-code-block t t)
6864 (goto-char (point-min)))
6865 (when (looking-at markdown-regex-header)
6866 (let ((level (markdown-outline-level)))
6867 (when (> level 1) (markdown-up-heading level))
6868 (when (> count 1)
6869 (condition-case nil
6870 (markdown-backward-same-level (1- count))
6871 (error (goto-char (point-min)))))))))
6873 (defun markdown-forward-page (&optional count)
6874 "Move forward to boundary of the current toplevel section.
6875 With COUNT, repeat, or go backward if negative."
6876 (interactive "p")
6877 (or count (setq count 1))
6878 (if (< count 0)
6879 (markdown-backward-page (- count))
6880 (if (markdown-back-to-heading-over-code-block t t)
6881 (let ((level (markdown-outline-level)))
6882 (when (> level 1) (markdown-up-heading level))
6883 (condition-case nil
6884 (markdown-forward-same-level count)
6885 (error (goto-char (point-max)))))
6886 (markdown-next-visible-heading 1))))
6888 (defun markdown-next-link ()
6889 "Jump to next inline, reference, or wiki link.
6890 If successful, return point. Otherwise, return nil.
6891 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
6892 (interactive)
6893 (let ((opoint (point)))
6894 (when (or (markdown-link-p) (markdown-wiki-link-p))
6895 ;; At a link already, move past it.
6896 (goto-char (+ (match-end 0) 1)))
6897 ;; Search for the next wiki link and move to the beginning.
6898 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
6899 (markdown-code-block-at-point-p)
6900 (< (point) (point-max))))
6901 (if (and (not (eq (point) opoint))
6902 (or (markdown-link-p) (markdown-wiki-link-p)))
6903 ;; Group 1 will move past non-escape character in wiki link regexp.
6904 ;; Go to beginning of group zero for all other link types.
6905 (goto-char (or (match-beginning 1) (match-beginning 0)))
6906 (goto-char opoint)
6907 nil)))
6909 (defun markdown-previous-link ()
6910 "Jump to previous wiki link.
6911 If successful, return point. Otherwise, return nil.
6912 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
6913 (interactive)
6914 (let ((opoint (point)))
6915 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
6916 (markdown-code-block-at-point-p)
6917 (> (point) (point-min))))
6918 (if (and (not (eq (point) opoint))
6919 (or (markdown-link-p) (markdown-wiki-link-p)))
6920 (goto-char (or (match-beginning 1) (match-beginning 0)))
6921 (goto-char opoint)
6922 nil)))
6925 ;;; Outline ===================================================================
6927 (defun markdown-move-heading-common (move-fn &optional arg adjust)
6928 "Wrapper for `outline-mode' functions to skip false positives.
6929 MOVE-FN is a function and ARG is its argument. For example,
6930 headings inside preformatted code blocks may match
6931 `outline-regexp' but should not be considered as headings.
6932 When ADJUST is non-nil, adjust the point for interactive calls
6933 to avoid leaving the point at invisible markup. This adjustment
6934 generally should only be done for interactive calls, since other
6935 functions may expect the point to be at the beginning of the
6936 regular expression."
6937 (let ((prev -1) (start (point)))
6938 (if arg (funcall move-fn arg) (funcall move-fn))
6939 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
6940 (setq prev (point))
6941 (if arg (funcall move-fn arg) (funcall move-fn)))
6942 ;; Adjust point for setext headings and invisible text.
6943 (save-match-data
6944 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
6945 (if markdown-hide-markup
6946 ;; Move to beginning of heading text if markup is hidden.
6947 (goto-char (or (match-beginning 1) (match-beginning 5)))
6948 ;; Move to beginning of markup otherwise.
6949 (goto-char (or (match-beginning 1) (match-beginning 4))))))
6950 (if (= (point) start) nil (point))))
6952 (defun markdown-next-visible-heading (arg)
6953 "Move to the next visible heading line of any level.
6954 With argument, repeats or can move backward if negative. ARG is
6955 passed to `outline-next-visible-heading'."
6956 (interactive "p")
6957 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
6959 (defun markdown-previous-visible-heading (arg)
6960 "Move to the previous visible heading line of any level.
6961 With argument, repeats or can move backward if negative. ARG is
6962 passed to `outline-previous-visible-heading'."
6963 (interactive "p")
6964 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
6966 (defun markdown-next-heading ()
6967 "Move to the next heading line of any level."
6968 (markdown-move-heading-common #'outline-next-heading))
6970 (defun markdown-previous-heading ()
6971 "Move to the previous heading line of any level."
6972 (markdown-move-heading-common #'outline-previous-heading))
6974 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
6975 "Move back to the beginning of the previous heading.
6976 Returns t if the point is at a heading, the location if a heading
6977 was found, and nil otherwise.
6978 Only visible heading lines are considered, unless INVISIBLE-OK is
6979 non-nil. Throw an error if there is no previous heading unless
6980 NO-ERROR is non-nil.
6981 Leaves match data intact for `markdown-regex-header'."
6982 (beginning-of-line)
6983 (or (and (markdown-heading-at-point)
6984 (not (markdown-code-block-at-point-p)))
6985 (let (found)
6986 (save-excursion
6987 (while (and (not found)
6988 (re-search-backward markdown-regex-header nil t))
6989 (when (and (or invisible-ok (not (outline-invisible-p)))
6990 (not (markdown-code-block-at-point-p)))
6991 (setq found (point))))
6992 (if (not found)
6993 (unless no-error (user-error "Before first heading"))
6994 (setq found (point))))
6995 (when found (goto-char found)))))
6997 (defun markdown-forward-same-level (arg)
6998 "Move forward to the ARG'th heading at same level as this one.
6999 Stop at the first and last headings of a superior heading."
7000 (interactive "p")
7001 (markdown-back-to-heading-over-code-block)
7002 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7004 (defun markdown-backward-same-level (arg)
7005 "Move backward to the ARG'th heading at same level as this one.
7006 Stop at the first and last headings of a superior heading."
7007 (interactive "p")
7008 (markdown-back-to-heading-over-code-block)
7009 (while (> arg 0)
7010 (let ((point-to-move-to
7011 (save-excursion
7012 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7013 (if point-to-move-to
7014 (progn
7015 (goto-char point-to-move-to)
7016 (setq arg (1- arg)))
7017 (user-error "No previous same-level heading")))))
7019 (defun markdown-up-heading (arg)
7020 "Move to the visible heading line of which the present line is a subheading.
7021 With argument, move up ARG levels."
7022 (interactive "p")
7023 (and (called-interactively-p 'any)
7024 (not (eq last-command 'markdown-up-heading)) (push-mark))
7025 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7027 (defun markdown-back-to-heading (&optional invisible-ok)
7028 "Move to previous heading line, or beg of this line if it's a heading.
7029 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7030 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7032 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7034 (defun markdown-on-heading-p ()
7035 "Return non-nil if point is on a heading line."
7036 (get-text-property (point-at-bol) 'markdown-heading))
7038 (defun markdown-end-of-subtree (&optional invisible-OK)
7039 "Move to the end of the current subtree.
7040 Only visible heading lines are considered, unless INVISIBLE-OK is
7041 non-nil.
7042 Derived from `org-end-of-subtree'."
7043 (markdown-back-to-heading invisible-OK)
7044 (let ((first t)
7045 (level (markdown-outline-level)))
7046 (while (and (not (eobp))
7047 (or first (> (markdown-outline-level) level)))
7048 (setq first nil)
7049 (markdown-next-heading))
7050 (if (memq (preceding-char) '(?\n ?\^M))
7051 (progn
7052 ;; Go to end of line before heading
7053 (forward-char -1)
7054 (if (memq (preceding-char) '(?\n ?\^M))
7055 ;; leave blank line before heading
7056 (forward-char -1)))))
7057 (point))
7059 (defun markdown-outline-fix-visibility ()
7060 "Hide any false positive headings that should not be shown.
7061 For example, headings inside preformatted code blocks may match
7062 `outline-regexp' but should not be shown as headings when cycling.
7063 Also, the ending --- line in metadata blocks appears to be a
7064 setext header, but should not be folded."
7065 (save-excursion
7066 (goto-char (point-min))
7067 ;; Unhide any false positives in metadata blocks
7068 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7069 (let ((body (progn (forward-line)
7070 (markdown-text-property-at-point
7071 'markdown-yaml-metadata-section))))
7072 (when body
7073 (let ((end (progn (goto-char (cl-second body))
7074 (markdown-text-property-at-point
7075 'markdown-yaml-metadata-end))))
7076 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7077 ;; Hide any false positives in code blocks
7078 (unless (outline-on-heading-p)
7079 (outline-next-visible-heading 1))
7080 (while (< (point) (point-max))
7081 (when (markdown-code-block-at-point-p)
7082 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7083 (outline-next-visible-heading 1))))
7085 (defvar markdown-cycle-global-status 1)
7086 (defvar markdown-cycle-subtree-status nil)
7088 (defun markdown-next-preface ()
7089 (let (finish)
7090 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7091 nil 'move))
7092 (unless (markdown-code-block-at-point-p)
7093 (goto-char (match-beginning 0))
7094 (setq finish t))))
7095 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7096 (forward-char -1)))
7098 (defun markdown-show-entry ()
7099 (save-excursion
7100 (outline-back-to-heading t)
7101 (outline-flag-region (1- (point))
7102 (progn
7103 (markdown-next-preface)
7104 (if (= 1 (- (point-max) (point)))
7105 (point-max)
7106 (point)))
7107 nil)))
7109 ;; This function was originally derived from `org-cycle' from org.el.
7110 (defun markdown-cycle (&optional arg)
7111 "Visibility cycling for Markdown mode.
7112 If ARG is t, perform global visibility cycling. If the point is
7113 at an atx-style header, cycle visibility of the corresponding
7114 subtree. Otherwise, indent the current line or insert a tab,
7115 as appropriate, by calling `indent-for-tab-command'."
7116 (interactive "P")
7117 (cond
7118 ((eq arg t) ;; Global cycling
7119 (cond
7120 ((and (eq last-command this-command)
7121 (eq markdown-cycle-global-status 2))
7122 ;; Move from overview to contents
7123 (markdown-hide-sublevels 1)
7124 (message "CONTENTS")
7125 (setq markdown-cycle-global-status 3)
7126 (markdown-outline-fix-visibility))
7128 ((and (eq last-command this-command)
7129 (eq markdown-cycle-global-status 3))
7130 ;; Move from contents to all
7131 (markdown-show-all)
7132 (message "SHOW ALL")
7133 (setq markdown-cycle-global-status 1))
7136 ;; Defaults to overview
7137 (markdown-hide-body)
7138 (message "OVERVIEW")
7139 (setq markdown-cycle-global-status 2)
7140 (markdown-outline-fix-visibility))))
7142 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7143 ;; At a heading: rotate between three different views
7144 (markdown-back-to-heading)
7145 (let ((goal-column 0) eoh eol eos)
7146 ;; Determine boundaries
7147 (save-excursion
7148 (markdown-back-to-heading)
7149 (save-excursion
7150 (beginning-of-line 2)
7151 (while (and (not (eobp)) ;; this is like `next-line'
7152 (get-char-property (1- (point)) 'invisible))
7153 (beginning-of-line 2)) (setq eol (point)))
7154 (markdown-end-of-heading) (setq eoh (point))
7155 (markdown-end-of-subtree t)
7156 (skip-chars-forward " \t\n")
7157 (beginning-of-line 1) ; in case this is an item
7158 (setq eos (1- (point))))
7159 ;; Find out what to do next and set `this-command'
7160 (cond
7161 ((= eos eoh)
7162 ;; Nothing is hidden behind this heading
7163 (message "EMPTY ENTRY")
7164 (setq markdown-cycle-subtree-status nil))
7165 ((>= eol eos)
7166 ;; Entire subtree is hidden in one line: open it
7167 (markdown-show-entry)
7168 (markdown-show-children)
7169 (message "CHILDREN")
7170 (setq markdown-cycle-subtree-status 'children))
7171 ((and (eq last-command this-command)
7172 (eq markdown-cycle-subtree-status 'children))
7173 ;; We just showed the children, now show everything.
7174 (markdown-show-subtree)
7175 (message "SUBTREE")
7176 (setq markdown-cycle-subtree-status 'subtree))
7178 ;; Default action: hide the subtree.
7179 (markdown-hide-subtree)
7180 (message "FOLDED")
7181 (setq markdown-cycle-subtree-status 'folded)))))
7184 (indent-for-tab-command))))
7186 (defun markdown-shifttab ()
7187 "Global visibility cycling.
7188 Calls `markdown-cycle' with argument t."
7189 (interactive)
7190 (markdown-cycle t))
7192 (defun markdown-outline-level ()
7193 "Return the depth to which a statement is nested in the outline."
7194 (cond
7195 ((and (match-beginning 0)
7196 (markdown-code-block-at-pos (match-beginning 0)))
7197 7) ;; Only 6 header levels are defined.
7198 ((match-end 2) 1)
7199 ((match-end 3) 2)
7200 ((match-end 4)
7201 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7203 (defun markdown-promote-subtree (&optional arg)
7204 "Promote the current subtree of ATX headings.
7205 Note that Markdown does not support heading levels higher than
7206 six and therefore level-six headings will not be promoted
7207 further. If ARG is non-nil promote the heading, otherwise
7208 demote."
7209 (interactive "*P")
7210 (save-excursion
7211 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7212 (re-search-backward markdown-regex-header-atx nil t))
7213 (not (markdown-code-block-at-point-p)))
7214 (let ((level (length (match-string 1)))
7215 (promote-or-demote (if arg 1 -1))
7216 (remove 't))
7217 (markdown-cycle-atx promote-or-demote remove)
7218 (catch 'end-of-subtree
7219 (while (and (markdown-next-heading)
7220 (looking-at markdown-regex-header-atx))
7221 ;; Exit if this not a higher level heading; promote otherwise.
7222 (if (and (looking-at markdown-regex-header-atx)
7223 (<= (length (match-string-no-properties 1)) level))
7224 (throw 'end-of-subtree nil)
7225 (markdown-cycle-atx promote-or-demote remove))))))))
7227 (defun markdown-demote-subtree ()
7228 "Demote the current subtree of ATX headings."
7229 (interactive)
7230 (markdown-promote-subtree t))
7232 (defun markdown-move-subtree-up ()
7233 "Move the current subtree of ATX headings up."
7234 (interactive)
7235 (outline-move-subtree-up 1))
7237 (defun markdown-move-subtree-down ()
7238 "Move the current subtree of ATX headings down."
7239 (interactive)
7240 (outline-move-subtree-down 1))
7242 (defun markdown-outline-next ()
7243 "Move to next list item, when in a list, or next visible heading."
7244 (interactive)
7245 (let ((bounds (markdown-next-list-item-bounds)))
7246 (if bounds
7247 (goto-char (nth 0 bounds))
7248 (markdown-next-visible-heading 1))))
7250 (defun markdown-outline-previous ()
7251 "Move to previous list item, when in a list, or previous visible heading."
7252 (interactive)
7253 (let ((bounds (markdown-prev-list-item-bounds)))
7254 (if bounds
7255 (goto-char (nth 0 bounds))
7256 (markdown-previous-visible-heading 1))))
7258 (defun markdown-outline-next-same-level ()
7259 "Move to next list item or heading of same level."
7260 (interactive)
7261 (let ((bounds (markdown-cur-list-item-bounds)))
7262 (if bounds
7263 (markdown-next-list-item (nth 3 bounds))
7264 (markdown-forward-same-level 1))))
7266 (defun markdown-outline-previous-same-level ()
7267 "Move to previous list item or heading of same level."
7268 (interactive)
7269 (let ((bounds (markdown-cur-list-item-bounds)))
7270 (if bounds
7271 (markdown-prev-list-item (nth 3 bounds))
7272 (markdown-backward-same-level 1))))
7274 (defun markdown-outline-up ()
7275 "Move to previous list item, when in a list, or next heading."
7276 (interactive)
7277 (unless (markdown-up-list)
7278 (markdown-up-heading 1)))
7281 ;;; Marking and Narrowing =====================================================
7283 (defun markdown-mark-paragraph ()
7284 "Put mark at end of this block, point at beginning.
7285 The block marked is the one that contains point or follows point.
7287 Interactively, if this command is repeated or (in Transient Mark
7288 mode) if the mark is active, it marks the next block after the
7289 ones already marked."
7290 (interactive)
7291 (if (or (and (eq last-command this-command) (mark t))
7292 (and transient-mark-mode mark-active))
7293 (set-mark
7294 (save-excursion
7295 (goto-char (mark))
7296 (markdown-forward-paragraph)
7297 (point)))
7298 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7299 (end-of-defun-function 'markdown-forward-paragraph))
7300 (mark-defun))))
7302 (defun markdown-mark-block ()
7303 "Put mark at end of this block, point at beginning.
7304 The block marked is the one that contains point or follows point.
7306 Interactively, if this command is repeated or (in Transient Mark
7307 mode) if the mark is active, it marks the next block after the
7308 ones already marked."
7309 (interactive)
7310 (if (or (and (eq last-command this-command) (mark t))
7311 (and transient-mark-mode mark-active))
7312 (set-mark
7313 (save-excursion
7314 (goto-char (mark))
7315 (markdown-forward-block)
7316 (point)))
7317 (let ((beginning-of-defun-function 'markdown-backward-block)
7318 (end-of-defun-function 'markdown-forward-block))
7319 (mark-defun))))
7321 (defun markdown-narrow-to-block ()
7322 "Make text outside current block invisible.
7323 The current block is the one that contains point or follows point."
7324 (interactive)
7325 (let ((beginning-of-defun-function 'markdown-backward-block)
7326 (end-of-defun-function 'markdown-forward-block))
7327 (narrow-to-defun)))
7329 (defun markdown-mark-text-block ()
7330 "Put mark at end of this plain text block, point at beginning.
7331 The block marked is the one that contains point or follows point.
7333 Interactively, if this command is repeated or (in Transient Mark
7334 mode) if the mark is active, it marks the next block after the
7335 ones already marked."
7336 (interactive)
7337 (if (or (and (eq last-command this-command) (mark t))
7338 (and transient-mark-mode mark-active))
7339 (set-mark
7340 (save-excursion
7341 (goto-char (mark))
7342 (markdown-end-of-text-block)
7343 (point)))
7344 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7345 (end-of-defun-function 'markdown-end-of-text-block))
7346 (mark-defun))))
7348 (defun markdown-mark-page ()
7349 "Put mark at end of this top level section, point at beginning.
7350 The top level section marked is the one that contains point or
7351 follows point.
7353 Interactively, if this command is repeated or (in Transient Mark
7354 mode) if the mark is active, it marks the next page after the
7355 ones already marked."
7356 (interactive)
7357 (if (or (and (eq last-command this-command) (mark t))
7358 (and transient-mark-mode mark-active))
7359 (set-mark
7360 (save-excursion
7361 (goto-char (mark))
7362 (markdown-forward-page)
7363 (point)))
7364 (let ((beginning-of-defun-function 'markdown-backward-page)
7365 (end-of-defun-function 'markdown-forward-page))
7366 (mark-defun))))
7368 (defun markdown-narrow-to-page ()
7369 "Make text outside current top level section invisible.
7370 The current section is the one that contains point or follows point."
7371 (interactive)
7372 (let ((beginning-of-defun-function 'markdown-backward-page)
7373 (end-of-defun-function 'markdown-forward-page))
7374 (narrow-to-defun)))
7376 (defun markdown-mark-subtree ()
7377 "Mark the current subtree.
7378 This puts point at the start of the current subtree, and mark at the end."
7379 (interactive)
7380 (let ((beg))
7381 (if (markdown-heading-at-point)
7382 (beginning-of-line)
7383 (markdown-previous-visible-heading 1))
7384 (setq beg (point))
7385 (markdown-end-of-subtree)
7386 (push-mark (point) nil t)
7387 (goto-char beg)))
7389 (defun markdown-narrow-to-subtree ()
7390 "Narrow buffer to the current subtree."
7391 (interactive)
7392 (save-excursion
7393 (save-match-data
7394 (narrow-to-region
7395 (progn (markdown-back-to-heading-over-code-block t) (point))
7396 (progn (markdown-end-of-subtree)
7397 (if (and (markdown-heading-at-point) (not (eobp)))
7398 (backward-char 1))
7399 (point))))))
7402 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7404 (defun markdown-move-up ()
7405 "Move thing at point up.
7406 When in a list item, call `markdown-move-list-item-up'.
7407 Otherwise, move the current heading subtree up with
7408 `markdown-move-subtree-up'."
7409 (interactive)
7410 (cond
7411 ((markdown-list-item-at-point-p)
7412 (markdown-move-list-item-up))
7414 (markdown-move-subtree-up))))
7416 (defun markdown-move-down ()
7417 "Move thing at point down.
7418 When in a list item, call `markdown-move-list-item-down'.
7419 Otherwise, move the current heading subtree up with
7420 `markdown-move-subtree-down'."
7421 (interactive)
7422 (cond
7423 ((markdown-list-item-at-point-p)
7424 (markdown-move-list-item-down))
7426 (markdown-move-subtree-down))))
7428 (defun markdown-promote ()
7429 "Either promote header or list item at point or cycle markup.
7430 See `markdown-cycle-atx', `markdown-cycle-setext', and
7431 `markdown-promote-list-item'."
7432 (interactive)
7433 (let (bounds)
7434 (cond
7435 ;; Promote atx heading subtree
7436 ((thing-at-point-looking-at markdown-regex-header-atx)
7437 (markdown-promote-subtree))
7438 ;; Promote setext heading
7439 ((thing-at-point-looking-at markdown-regex-header-setext)
7440 (markdown-cycle-setext -1))
7441 ;; Promote horizonal rule
7442 ((thing-at-point-looking-at markdown-regex-hr)
7443 (markdown-cycle-hr -1))
7444 ;; Promote list item
7445 ((setq bounds (markdown-cur-list-item-bounds))
7446 (markdown-promote-list-item bounds))
7447 ;; Promote bold
7448 ((thing-at-point-looking-at markdown-regex-bold)
7449 (markdown-cycle-bold))
7450 ;; Promote italic
7451 ((thing-at-point-looking-at markdown-regex-italic)
7452 (markdown-cycle-italic))
7454 (user-error "Nothing to promote at point")))))
7456 (defun markdown-demote ()
7457 "Either demote header or list item at point or cycle or remove markup.
7458 See `markdown-cycle-atx', `markdown-cycle-setext', and
7459 `markdown-demote-list-item'."
7460 (interactive)
7461 (let (bounds)
7462 (cond
7463 ;; Demote atx heading subtree
7464 ((thing-at-point-looking-at markdown-regex-header-atx)
7465 (markdown-demote-subtree))
7466 ;; Demote setext heading
7467 ((thing-at-point-looking-at markdown-regex-header-setext)
7468 (markdown-cycle-setext 1))
7469 ;; Demote horizonal rule
7470 ((thing-at-point-looking-at markdown-regex-hr)
7471 (markdown-cycle-hr 1))
7472 ;; Demote list item
7473 ((setq bounds (markdown-cur-list-item-bounds))
7474 (markdown-demote-list-item bounds))
7475 ;; Demote bold
7476 ((thing-at-point-looking-at markdown-regex-bold)
7477 (markdown-cycle-bold))
7478 ;; Demote italic
7479 ((thing-at-point-looking-at markdown-regex-italic)
7480 (markdown-cycle-italic))
7482 (user-error "Nothing to demote at point")))))
7485 ;;; Commands ==================================================================
7487 (defun markdown (&optional output-buffer-name)
7488 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7489 The output buffer name defaults to `markdown-output-buffer-name'.
7490 Return the name of the output buffer used."
7491 (interactive)
7492 (save-window-excursion
7493 (let ((begin-region)
7494 (end-region))
7495 (if (markdown-use-region-p)
7496 (setq begin-region (region-beginning)
7497 end-region (region-end))
7498 (setq begin-region (point-min)
7499 end-region (point-max)))
7501 (unless output-buffer-name
7502 (setq output-buffer-name markdown-output-buffer-name))
7503 (cond
7504 ;; Handle case when `markdown-command' does not read from stdin
7505 ((and (stringp markdown-command) markdown-command-needs-filename)
7506 (if (not buffer-file-name)
7507 (user-error "Must be visiting a file")
7508 (shell-command (concat markdown-command " "
7509 (shell-quote-argument buffer-file-name))
7510 output-buffer-name)))
7511 ;; Pass region to `markdown-command' via stdin
7513 (let ((buf (get-buffer-create output-buffer-name)))
7514 (with-current-buffer buf
7515 (setq buffer-read-only nil)
7516 (erase-buffer))
7517 (if (stringp markdown-command)
7518 (call-process-region begin-region end-region
7519 shell-file-name nil buf nil
7520 shell-command-switch markdown-command)
7521 (funcall markdown-command begin-region end-region buf))))))
7522 output-buffer-name))
7524 (defun markdown-standalone (&optional output-buffer-name)
7525 "Special function to provide standalone HTML output.
7526 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7527 (interactive)
7528 (setq output-buffer-name (markdown output-buffer-name))
7529 (with-current-buffer output-buffer-name
7530 (set-buffer output-buffer-name)
7531 (unless (markdown-output-standalone-p)
7532 (markdown-add-xhtml-header-and-footer output-buffer-name))
7533 (goto-char (point-min))
7534 (html-mode))
7535 output-buffer-name)
7537 (defun markdown-other-window (&optional output-buffer-name)
7538 "Run `markdown-command' on current buffer and display in other window.
7539 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7540 that name."
7541 (interactive)
7542 (markdown-display-buffer-other-window
7543 (markdown-standalone output-buffer-name)))
7545 (defun markdown-output-standalone-p ()
7546 "Determine whether `markdown-command' output is standalone XHTML.
7547 Standalone XHTML output is identified by an occurrence of
7548 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7549 (save-excursion
7550 (goto-char (point-min))
7551 (save-match-data
7552 (re-search-forward
7553 markdown-xhtml-standalone-regexp
7554 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7555 t))))
7557 (defun markdown-stylesheet-link-string (stylesheet-path)
7558 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7559 stylesheet-path
7560 "\" />"))
7562 (defun markdown-add-xhtml-header-and-footer (title)
7563 "Wrap XHTML header and footer with given TITLE around current buffer."
7564 (goto-char (point-min))
7565 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7566 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7567 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7568 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7569 "<head>\n<title>")
7570 (insert title)
7571 (insert "</title>\n")
7572 (when (> (length markdown-content-type) 0)
7573 (insert
7574 (format
7575 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7576 markdown-content-type
7577 (or (and markdown-coding-system
7578 (fboundp 'coding-system-get)
7579 (coding-system-get markdown-coding-system
7580 'mime-charset))
7581 (and (fboundp 'coding-system-get)
7582 (coding-system-get buffer-file-coding-system
7583 'mime-charset))
7584 "iso-8859-1"))))
7585 (if (> (length markdown-css-paths) 0)
7586 (insert (mapconcat #'markdown-stylesheet-link-string
7587 markdown-css-paths "\n")))
7588 (when (> (length markdown-xhtml-header-content) 0)
7589 (insert markdown-xhtml-header-content))
7590 (insert "\n</head>\n\n"
7591 "<body>\n\n")
7592 (goto-char (point-max))
7593 (insert "\n"
7594 "</body>\n"
7595 "</html>\n"))
7597 (defun markdown-preview (&optional output-buffer-name)
7598 "Run `markdown-command' on the current buffer and view output in browser.
7599 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7600 that name."
7601 (interactive)
7602 (browse-url-of-buffer
7603 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7605 (defun markdown-export-file-name (&optional extension)
7606 "Attempt to generate a filename for Markdown output.
7607 The file extension will be EXTENSION if given, or .html by default.
7608 If the current buffer is visiting a file, we construct a new
7609 output filename based on that filename. Otherwise, return nil."
7610 (when (buffer-file-name)
7611 (unless extension
7612 (setq extension ".html"))
7613 (let ((candidate
7614 (concat
7615 (cond
7616 ((buffer-file-name)
7617 (file-name-sans-extension (buffer-file-name)))
7618 (t (buffer-name)))
7619 extension)))
7620 (cond
7621 ((equal candidate (buffer-file-name))
7622 (concat candidate extension))
7624 candidate)))))
7626 (defun markdown-export (&optional output-file)
7627 "Run Markdown on the current buffer, save to file, and return the filename.
7628 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7629 generated by `markdown-export-file-name', which will be constructed using the
7630 current filename, but with the extension removed and replaced with .html."
7631 (interactive)
7632 (unless output-file
7633 (setq output-file (markdown-export-file-name ".html")))
7634 (when output-file
7635 (let* ((init-buf (current-buffer))
7636 (init-point (point))
7637 (init-buf-string (buffer-string))
7638 (output-buffer (find-file-noselect output-file))
7639 (output-buffer-name (buffer-name output-buffer)))
7640 (run-hooks 'markdown-before-export-hook)
7641 (markdown-standalone output-buffer-name)
7642 (with-current-buffer output-buffer
7643 (run-hooks 'markdown-after-export-hook)
7644 (save-buffer))
7645 ;; if modified, restore initial buffer
7646 (when (buffer-modified-p init-buf)
7647 (erase-buffer)
7648 (insert init-buf-string)
7649 (save-buffer)
7650 (goto-char init-point))
7651 output-file)))
7653 (defun markdown-export-and-preview ()
7654 "Export to XHTML using `markdown-export' and browse the resulting file."
7655 (interactive)
7656 (browse-url-of-file (markdown-export)))
7658 (defvar markdown-live-preview-buffer nil
7659 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7660 (make-variable-buffer-local 'markdown-live-preview-buffer)
7662 (defvar markdown-live-preview-source-buffer nil
7663 "Source buffer from which current buffer was generated.
7664 This is the inverse of `markdown-live-preview-buffer'.")
7665 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7667 (defvar markdown-live-preview-currently-exporting nil)
7669 (defun markdown-live-preview-get-filename ()
7670 "Standardize the filename exported by `markdown-live-preview-export'."
7671 (markdown-export-file-name ".html"))
7673 (defun markdown-live-preview-window-eww (file)
7674 "Preview FILE with eww.
7675 To be used with `markdown-live-preview-window-function'."
7676 (if (require 'eww nil t)
7677 (progn
7678 (eww-open-file file)
7679 (get-buffer "*eww*"))
7680 (error "EWW is not present or not loaded on this version of Emacs")))
7682 (defun markdown-visual-lines-between-points (beg end)
7683 (save-excursion
7684 (goto-char beg)
7685 (cl-loop with count = 0
7686 while (progn (end-of-visual-line)
7687 (and (< (point) end) (line-move-visual 1 t)))
7688 do (cl-incf count)
7689 finally return count)))
7691 (defun markdown-live-preview-window-serialize (buf)
7692 "Get window point and scroll data for all windows displaying BUF."
7693 (when (buffer-live-p buf)
7694 (with-current-buffer buf
7695 (mapcar
7696 (lambda (win)
7697 (with-selected-window win
7698 (let* ((start (window-start))
7699 (pt (window-point))
7700 (pt-or-sym (cond ((= pt (point-min)) 'min)
7701 ((= pt (point-max)) 'max)
7702 (t pt)))
7703 (diff (markdown-visual-lines-between-points
7704 start pt)))
7705 (list win pt-or-sym diff))))
7706 (get-buffer-window-list buf)))))
7708 (defun markdown-get-point-back-lines (pt num-lines)
7709 (save-excursion
7710 (goto-char pt)
7711 (line-move-visual (- num-lines) t)
7712 ;; in testing, can occasionally overshoot the number of lines to traverse
7713 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
7714 (when (> actual-num-lines num-lines)
7715 (line-move-visual (- actual-num-lines num-lines) t)))
7716 (point)))
7718 (defun markdown-live-preview-window-deserialize (window-posns)
7719 "Apply window point and scroll data from WINDOW-POSNS.
7720 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
7721 (cl-destructuring-bind (win pt-or-sym diff) window-posns
7722 (when (window-live-p win)
7723 (with-current-buffer markdown-live-preview-buffer
7724 (set-window-buffer win (current-buffer))
7725 (cl-destructuring-bind (actual-pt actual-diff)
7726 (cl-case pt-or-sym
7727 (min (list (point-min) 0))
7728 (max (list (point-max) diff))
7729 (t (list pt-or-sym diff)))
7730 (set-window-start
7731 win (markdown-get-point-back-lines actual-pt actual-diff))
7732 (set-window-point win actual-pt))))))
7734 (defun markdown-live-preview-export ()
7735 "Export to XHTML using `markdown-export'.
7736 Browse the resulting file within Emacs using
7737 `markdown-live-preview-window-function' Return the buffer
7738 displaying the rendered output."
7739 (interactive)
7740 (let ((filename (markdown-live-preview-get-filename)))
7741 (when filename
7742 (let* ((markdown-live-preview-currently-exporting t)
7743 (cur-buf (current-buffer))
7744 (export-file (markdown-export filename))
7745 ;; get positions in all windows currently displaying output buffer
7746 (window-data
7747 (markdown-live-preview-window-serialize
7748 markdown-live-preview-buffer)))
7749 (save-window-excursion
7750 (let ((output-buffer
7751 (funcall markdown-live-preview-window-function export-file)))
7752 (with-current-buffer output-buffer
7753 (setq markdown-live-preview-source-buffer cur-buf)
7754 (add-hook 'kill-buffer-hook
7755 #'markdown-live-preview-remove-on-kill t t))
7756 (with-current-buffer cur-buf
7757 (setq markdown-live-preview-buffer output-buffer))))
7758 (with-current-buffer cur-buf
7759 ;; reset all windows displaying output buffer to where they were,
7760 ;; now with the new output
7761 (mapc #'markdown-live-preview-window-deserialize window-data)
7762 ;; delete html editing buffer
7763 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
7764 (when (and export-file (file-exists-p export-file)
7765 (eq markdown-live-preview-delete-export
7766 'delete-on-export))
7767 (delete-file export-file))
7768 markdown-live-preview-buffer)))))
7770 (defun markdown-live-preview-remove ()
7771 (when (buffer-live-p markdown-live-preview-buffer)
7772 (kill-buffer markdown-live-preview-buffer))
7773 (setq markdown-live-preview-buffer nil)
7774 ;; if set to 'delete-on-export, the output has already been deleted
7775 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
7776 (let ((outfile-name (markdown-live-preview-get-filename)))
7777 (when (and outfile-name (file-exists-p outfile-name))
7778 (delete-file outfile-name)))))
7780 (defun markdown-get-other-window ()
7781 "Find another window to display preview or output content."
7782 (cond
7783 ((memq markdown-split-window-direction '(vertical below))
7784 (or (window-in-direction 'below) (split-window-vertically)))
7785 ((memq markdown-split-window-direction '(horizontal right))
7786 (or (window-in-direction 'right) (split-window-horizontally)))
7787 (t (split-window-sensibly (get-buffer-window)))))
7789 (defun markdown-display-buffer-other-window (buf)
7790 "Display preview or output buffer BUF in another window."
7791 (let ((cur-buf (current-buffer))
7792 (window (markdown-get-other-window)))
7793 (set-window-buffer window buf)
7794 (set-buffer cur-buf)))
7796 (defun markdown-live-preview-if-markdown ()
7797 (when (and (derived-mode-p 'markdown-mode)
7798 markdown-live-preview-mode)
7799 (unless markdown-live-preview-currently-exporting
7800 (if (buffer-live-p markdown-live-preview-buffer)
7801 (markdown-live-preview-export)
7802 (markdown-display-buffer-other-window
7803 (markdown-live-preview-export))))))
7805 (defun markdown-live-preview-remove-on-kill ()
7806 (cond ((and (derived-mode-p 'markdown-mode)
7807 markdown-live-preview-mode)
7808 (markdown-live-preview-remove))
7809 (markdown-live-preview-source-buffer
7810 (with-current-buffer markdown-live-preview-source-buffer
7811 (setq markdown-live-preview-buffer nil))
7812 (setq markdown-live-preview-source-buffer nil))))
7814 (defun markdown-live-preview-switch-to-output ()
7815 "Switch to output buffer."
7816 (interactive)
7817 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
7818 output buffer in another window."
7819 (if markdown-live-preview-mode
7820 (markdown-display-buffer-other-window (markdown-live-preview-export)))
7821 (markdown-live-preview-mode))
7823 (defun markdown-live-preview-re-export ()
7824 "Re export source buffer."
7825 (interactive)
7826 "If the current buffer is a buffer displaying the exported version of a
7827 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
7828 update this buffer's contents."
7829 (when markdown-live-preview-source-buffer
7830 (with-current-buffer markdown-live-preview-source-buffer
7831 (markdown-live-preview-export))))
7833 (defun markdown-open ()
7834 "Open file for the current buffer with `markdown-open-command'."
7835 (interactive)
7836 (unless markdown-open-command
7837 (user-error "Variable `markdown-open-command' must be set"))
7838 (if (stringp markdown-open-command)
7839 (if (not buffer-file-name)
7840 (user-error "Must be visiting a file")
7841 (call-process markdown-open-command nil nil nil buffer-file-name))
7842 (funcall markdown-open-command))
7843 nil)
7845 (defun markdown-kill-ring-save ()
7846 "Run Markdown on file and store output in the kill ring."
7847 (interactive)
7848 (save-window-excursion
7849 (markdown)
7850 (with-current-buffer markdown-output-buffer-name
7851 (kill-ring-save (point-min) (point-max)))))
7854 ;;; Links =====================================================================
7856 (defun markdown-link-p ()
7857 "Return non-nil when `point' is at a non-wiki link.
7858 See `markdown-wiki-link-p' for more information."
7859 (let ((case-fold-search nil))
7860 (and (not (markdown-wiki-link-p))
7861 (not (markdown-code-block-at-point-p))
7862 (or (thing-at-point-looking-at markdown-regex-link-inline)
7863 (thing-at-point-looking-at markdown-regex-link-reference)
7864 (thing-at-point-looking-at markdown-regex-uri)
7865 (thing-at-point-looking-at markdown-regex-angle-uri)))))
7867 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
7869 (defun markdown-link-at-pos (pos)
7870 "Return properties of link or image at position POS.
7871 Value is a list of elements describing the link:
7872 0. beginning position
7873 1. end position
7874 2. link text
7875 3. URL
7876 4. reference label
7877 5. title text
7878 6. bang (nil or \"!\")"
7879 (save-excursion
7880 (goto-char pos)
7881 (let (begin end text url reference title bang)
7882 (cond
7883 ;; Inline or reference image or link at point.
7884 ((or (thing-at-point-looking-at markdown-regex-link-inline)
7885 (thing-at-point-looking-at markdown-regex-link-reference))
7886 (setq bang (match-string-no-properties 1)
7887 begin (match-beginning 0)
7888 end (match-end 0)
7889 text (match-string-no-properties 3))
7890 (if (char-equal (char-after (match-beginning 5)) ?\[)
7891 ;; Reference link
7892 (setq reference (match-string-no-properties 6))
7893 ;; Inline link
7894 (setq url (match-string-no-properties 6))
7895 (when (match-end 7)
7896 (setq title (substring (match-string-no-properties 7) 1 -1)))))
7897 ;; Angle bracket URI at point.
7898 ((thing-at-point-looking-at markdown-regex-angle-uri)
7899 (setq begin (match-beginning 0)
7900 end (match-end 0)
7901 url (match-string-no-properties 2)))
7902 ;; Plain URI at point.
7903 ((thing-at-point-looking-at markdown-regex-uri)
7904 (setq begin (match-beginning 0)
7905 end (match-end 0)
7906 url (match-string-no-properties 1))))
7907 (list begin end text url reference title bang))))
7909 (defun markdown-link-url ()
7910 "Return the URL part of the regular (non-wiki) link at point.
7911 Works with both inline and reference style links, and with images.
7912 If point is not at a link or the link reference is not defined
7913 returns nil."
7914 (let* ((values (markdown-link-at-pos (point)))
7915 (text (nth 2 values))
7916 (url (nth 3 values))
7917 (ref (nth 4 values)))
7918 (or url (and ref (car (markdown-reference-definition
7919 (downcase (if (string= ref "") text ref))))))))
7921 (defun markdown-follow-link-at-point ()
7922 "Open the current non-wiki link.
7923 If the link is a complete URL, open in browser with `browse-url'.
7924 Otherwise, open with `find-file' after stripping anchor and/or query string."
7925 (interactive)
7926 (if (markdown-link-p)
7927 (let* ((url (markdown-link-url))
7928 (struct (url-generic-parse-url url))
7929 (full (url-fullness struct))
7930 (file url))
7931 ;; Parse URL, determine fullness, strip query string
7932 (if (fboundp 'url-path-and-query)
7933 (setq file (car (url-path-and-query struct)))
7934 (when (and (setq file (url-filename struct))
7935 (string-match "\\?" file))
7936 (setq file (substring file 0 (match-beginning 0)))))
7937 ;; Open full URLs in browser, files in Emacs
7938 (if full
7939 (browse-url url)
7940 (when (and file (> (length file) 0)) (find-file file))))
7941 (user-error "Point is not at a Markdown link or URL")))
7943 (defun markdown-fontify-inline-links (last)
7944 "Add text properties to next inline link from point to LAST."
7945 (when (markdown-match-generic-links last nil)
7946 (let* ((link-start (match-beginning 3))
7947 (link-end (match-end 3))
7948 (url-start (match-beginning 6))
7949 (url-end (match-end 6))
7950 (url (match-string-no-properties 6))
7951 (title-start (match-beginning 7))
7952 (title-end (match-end 7))
7953 (title (match-string-no-properties 7))
7954 ;; Markup part
7955 (mp (list 'face 'markdown-markup-face
7956 'invisible 'markdown-markup
7957 'rear-nonsticky t
7958 'font-lock-multiline t))
7959 ;; Link part
7960 (lp (list 'keymap markdown-mode-mouse-map
7961 'face markdown-link-face
7962 'mouse-face 'markdown-highlight-face
7963 'font-lock-multiline t
7964 'help-echo (if title (concat title "\n" url) url)))
7965 ;; URL part
7966 (up (list 'keymap markdown-mode-mouse-map
7967 'face 'markdown-url-face
7968 'invisible 'markdown-markup
7969 'mouse-face 'markdown-highlight-face
7970 'font-lock-multiline t))
7971 ;; Title part
7972 (tp (list 'face 'markdown-link-title-face
7973 'invisible 'markdown-markup
7974 'font-lock-multiline t)))
7975 (dolist (g '(1 2 4 5 8))
7976 (when (match-end g)
7977 (add-text-properties (match-beginning g) (match-end g) mp)))
7978 (when link-start (add-text-properties link-start link-end lp))
7979 (when url-start (add-text-properties url-start url-end up))
7980 (when title-start (add-text-properties url-end title-end tp))
7981 (when (and markdown-hide-urls url-start)
7982 (compose-region url-start (or title-end url-end)
7983 markdown-url-compose-char))
7984 t)))
7986 (defun markdown-fontify-reference-links (last)
7987 "Add text properties to next reference link from point to LAST."
7988 (when (markdown-match-generic-links last t)
7989 (let* ((link-start (match-beginning 3))
7990 (link-end (match-end 3))
7991 (ref-start (match-beginning 6))
7992 (ref-end (match-end 6))
7993 ;; Markup part
7994 (mp (list 'face 'markdown-markup-face
7995 'invisible 'markdown-markup
7996 'rear-nonsticky t
7997 'font-lock-multiline t))
7998 ;; Link part
7999 (lp (list 'keymap markdown-mode-mouse-map
8000 'face markdown-link-face
8001 'mouse-face 'markdown-highlight-face
8002 'font-lock-multiline t
8003 'help-echo (lambda (_ __ pos)
8004 (save-match-data
8005 (save-excursion
8006 (goto-char pos)
8007 (or (markdown-link-url)
8008 "Undefined reference"))))))
8009 ;; Reference part
8010 (rp (list 'face 'markdown-reference-face
8011 'invisible 'markdown-markup
8012 'font-lock-multiline t)))
8013 (dolist (g '(1 2 4 5 8))
8014 (when (match-end g)
8015 (add-text-properties (match-beginning g) (match-end g) mp)))
8016 (when link-start (add-text-properties link-start link-end lp))
8017 (when ref-start (add-text-properties ref-start ref-end rp)
8018 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8019 (compose-region ref-start ref-end markdown-url-compose-char)))
8020 t)))
8022 (defun markdown-fontify-angle-uris (last)
8023 "Add text properties to angle URIs from point to LAST."
8024 (when (markdown-match-angle-uris last)
8025 (let* ((url-start (match-beginning 2))
8026 (url-end (match-end 2))
8027 ;; Markup part
8028 (mp (list 'face 'markdown-markup-face
8029 'invisible 'markdown-markup
8030 'rear-nonsticky t
8031 'font-lock-multiline t))
8032 ;; URI part
8033 (up (list 'keymap markdown-mode-mouse-map
8034 'face 'markdown-plain-url-face
8035 'mouse-face 'markdown-highlight-face
8036 'font-lock-multiline t)))
8037 (dolist (g '(1 3))
8038 (add-text-properties (match-beginning g) (match-end g) mp))
8039 (add-text-properties url-start url-end up)
8040 t)))
8042 (defun markdown-fontify-plain-uris (last)
8043 "Add text properties to plain URLs from point to LAST."
8044 (when (markdown-match-plain-uris last)
8045 (let* ((start (match-beginning 0))
8046 (end (match-end 0))
8047 (props (list 'keymap markdown-mode-mouse-map
8048 'face 'markdown-plain-url-face
8049 'mouse-face 'markdown-highlight-face
8050 'rear-nonsticky t
8051 'font-lock-multiline t)))
8052 (add-text-properties start end props)
8053 t)))
8055 (defun markdown-toggle-url-hiding (&optional arg)
8056 "Toggle the display or hiding of URLs.
8057 With a prefix argument ARG, enable URL hiding if ARG is positive,
8058 and disable it otherwise."
8059 (interactive (list (or current-prefix-arg 'toggle)))
8060 (setq markdown-hide-urls
8061 (if (eq arg 'toggle)
8062 (not markdown-hide-urls)
8063 (> (prefix-numeric-value arg) 0)))
8064 (if markdown-hide-urls
8065 (message "markdown-mode URL hiding enabled")
8066 (message "markdown-mode URL hiding disabled"))
8067 (markdown-reload-extensions))
8070 ;;; WikiLink Following/Markup =================================================
8072 (defun markdown-wiki-link-p ()
8073 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8074 A true wiki link name matches `markdown-regex-wiki-link' but does
8075 not match the current file name after conversion. This modifies
8076 the data returned by `match-data'. Note that the potential wiki
8077 link name must be available via `match-string'."
8078 (when markdown-enable-wiki-links
8079 (let ((case-fold-search nil))
8080 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8081 (not (markdown-code-block-at-point-p))
8082 (or (not buffer-file-name)
8083 (not (string-equal (buffer-file-name)
8084 (markdown-convert-wiki-link-to-filename
8085 (markdown-wiki-link-link)))))))))
8087 (defun markdown-wiki-link-link ()
8088 "Return the link part of the wiki link using current match data.
8089 The location of the link component depends on the value of
8090 `markdown-wiki-link-alias-first'."
8091 (if markdown-wiki-link-alias-first
8092 (or (match-string-no-properties 5) (match-string-no-properties 3))
8093 (match-string-no-properties 3)))
8095 (defun markdown-wiki-link-alias ()
8096 "Return the alias or text part of the wiki link using current match data.
8097 The location of the alias component depends on the value of
8098 `markdown-wiki-link-alias-first'."
8099 (if markdown-wiki-link-alias-first
8100 (match-string-no-properties 3)
8101 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8103 (defun markdown-convert-wiki-link-to-filename (name)
8104 "Generate a filename from the wiki link NAME.
8105 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8106 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8107 and [[test test]] both map to Test-test.ext. Look in the current
8108 directory first, then in subdirectories if
8109 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8110 in parent directories if
8111 `markdown-wiki-link-search-parent-directories' is non-nil."
8112 (let* ((basename (markdown-replace-regexp-in-string
8113 "[[:space:]\n]" markdown-link-space-sub-char name))
8114 (basename (if (eq major-mode 'gfm-mode)
8115 (concat (upcase (substring basename 0 1))
8116 (downcase (substring basename 1 nil)))
8117 basename))
8118 directory extension default candidates dir)
8119 (when buffer-file-name
8120 (setq directory (file-name-directory buffer-file-name)
8121 extension (file-name-extension buffer-file-name)))
8122 (setq default (concat basename
8123 (when extension (concat "." extension))))
8124 (cond
8125 ;; Look in current directory first.
8126 ((or (null buffer-file-name)
8127 (file-exists-p default))
8128 default)
8129 ;; Possibly search in subdirectories, next.
8130 ((and markdown-wiki-link-search-subdirectories
8131 (setq candidates
8132 (markdown-directory-files-recursively
8133 directory (concat "^" default "$"))))
8134 (car candidates))
8135 ;; Possibly search in parent directories as a last resort.
8136 ((and markdown-wiki-link-search-parent-directories
8137 (setq dir (locate-dominating-file directory default)))
8138 (concat dir default))
8139 ;; If nothing is found, return default in current directory.
8140 (t default))))
8142 (defun markdown-follow-wiki-link (name &optional other)
8143 "Follow the wiki link NAME.
8144 Convert the name to a file name and call `find-file'. Ensure that
8145 the new buffer remains in `markdown-mode'. Open the link in another
8146 window when OTHER is non-nil."
8147 (let ((filename (markdown-convert-wiki-link-to-filename name))
8148 (wp (when buffer-file-name
8149 (file-name-directory buffer-file-name))))
8150 (if (not wp)
8151 (user-error "Must be visiting a file")
8152 (when other (other-window 1))
8153 (let ((default-directory wp))
8154 (find-file filename)))
8155 (when (not (eq major-mode 'markdown-mode))
8156 (markdown-mode))))
8158 (defun markdown-follow-wiki-link-at-point (&optional arg)
8159 "Find Wiki Link at point.
8160 With prefix argument ARG, open the file in other window.
8161 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8162 (interactive "P")
8163 (if (markdown-wiki-link-p)
8164 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8165 (user-error "Point is not at a Wiki Link")))
8167 (defun markdown-highlight-wiki-link (from to face)
8168 "Highlight the wiki link in the region between FROM and TO using FACE."
8169 (put-text-property from to 'font-lock-face face))
8171 (defun markdown-unfontify-region-wiki-links (from to)
8172 "Remove wiki link faces from the region specified by FROM and TO."
8173 (interactive "*r")
8174 (let ((modified (buffer-modified-p)))
8175 (remove-text-properties from to '(font-lock-face markdown-link-face))
8176 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8177 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8178 ;; undo that if it wasn't originally marked modified
8179 (set-buffer-modified-p modified)))
8181 (defun markdown-fontify-region-wiki-links (from to)
8182 "Search region given by FROM and TO for wiki links and fontify them.
8183 If a wiki link is found check to see if the backing file exists
8184 and highlight accordingly."
8185 (goto-char from)
8186 (save-match-data
8187 (while (re-search-forward markdown-regex-wiki-link to t)
8188 (when (not (markdown-code-block-at-point-p))
8189 (let ((highlight-beginning (match-beginning 1))
8190 (highlight-end (match-end 1))
8191 (file-name
8192 (markdown-convert-wiki-link-to-filename
8193 (markdown-wiki-link-link))))
8194 (if (condition-case nil (file-exists-p file-name) (error nil))
8195 (markdown-highlight-wiki-link
8196 highlight-beginning highlight-end markdown-link-face)
8197 (markdown-highlight-wiki-link
8198 highlight-beginning highlight-end markdown-missing-link-face)))))))
8200 (defun markdown-extend-changed-region (from to)
8201 "Extend region given by FROM and TO so that we can fontify all links.
8202 The region is extended to the first newline before and the first
8203 newline after."
8204 ;; start looking for the first new line before 'from
8205 (goto-char from)
8206 (re-search-backward "\n" nil t)
8207 (let ((new-from (point-min))
8208 (new-to (point-max)))
8209 (if (not (= (point) from))
8210 (setq new-from (point)))
8211 ;; do the same thing for the first new line after 'to
8212 (goto-char to)
8213 (re-search-forward "\n" nil t)
8214 (if (not (= (point) to))
8215 (setq new-to (point)))
8216 (cl-values new-from new-to)))
8218 (defun markdown-check-change-for-wiki-link (from to)
8219 "Check region between FROM and TO for wiki links and re-fontify as needed."
8220 (interactive "*r")
8221 (let* ((modified (buffer-modified-p))
8222 (buffer-undo-list t)
8223 (inhibit-read-only t)
8224 (inhibit-point-motion-hooks t)
8225 deactivate-mark
8226 buffer-file-truename)
8227 (unwind-protect
8228 (save-excursion
8229 (save-match-data
8230 (save-restriction
8231 ;; Extend the region to fontify so that it starts
8232 ;; and ends at safe places.
8233 (cl-multiple-value-bind (new-from new-to)
8234 (markdown-extend-changed-region from to)
8235 (goto-char new-from)
8236 ;; Only refontify when the range contains text with a
8237 ;; wiki link face or if the wiki link regexp matches.
8238 (when (or (markdown-range-property-any
8239 new-from new-to 'font-lock-face
8240 (list markdown-link-face
8241 markdown-missing-link-face))
8242 (re-search-forward
8243 markdown-regex-wiki-link new-to t))
8244 ;; Unfontify existing fontification (start from scratch)
8245 (markdown-unfontify-region-wiki-links new-from new-to)
8246 ;; Now do the fontification.
8247 (markdown-fontify-region-wiki-links new-from new-to))))))
8248 (and (not modified)
8249 (buffer-modified-p)
8250 (set-buffer-modified-p nil)))))
8252 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8253 "Check region between FROM and TO for wiki links and re-fontify as needed.
8254 Designed to be used with the `after-change-functions' hook."
8255 (markdown-check-change-for-wiki-link from to))
8257 (defun markdown-fontify-buffer-wiki-links ()
8258 "Refontify all wiki links in the buffer."
8259 (interactive)
8260 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8263 ;;; Following & Doing =========================================================
8265 (defun markdown-follow-thing-at-point (arg)
8266 "Follow thing at point if possible, such as a reference link or wiki link.
8267 Opens inline and reference links in a browser. Opens wiki links
8268 to other files in the current window, or the another window if
8269 ARG is non-nil.
8270 See `markdown-follow-link-at-point' and
8271 `markdown-follow-wiki-link-at-point'."
8272 (interactive "P")
8273 (cond ((markdown-link-p)
8274 (markdown-follow-link-at-point))
8275 ((markdown-wiki-link-p)
8276 (markdown-follow-wiki-link-at-point arg))
8278 (user-error "Nothing to follow at point"))))
8280 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8282 (defun markdown-do ()
8283 "Do something sensible based on context at point.
8284 Jumps between reference links and definitions; between footnote
8285 markers and footnote text."
8286 (interactive)
8287 (cond
8288 ;; Footnote definition
8289 ((markdown-footnote-text-positions)
8290 (markdown-footnote-return))
8291 ;; Footnote marker
8292 ((markdown-footnote-marker-positions)
8293 (markdown-footnote-goto-text))
8294 ;; Reference link
8295 ((thing-at-point-looking-at markdown-regex-link-reference)
8296 (markdown-reference-goto-definition))
8297 ;; Reference definition
8298 ((thing-at-point-looking-at markdown-regex-reference-definition)
8299 (markdown-reference-goto-link (match-string-no-properties 2)))
8300 ;; GFM task list item
8301 ((markdown-gfm-task-list-item-at-point)
8302 (markdown-toggle-gfm-checkbox))
8303 ;; Otherwise
8305 (user-error "Nothing to do in context at point"))))
8308 ;;; Miscellaneous =============================================================
8310 (defun markdown-compress-whitespace-string (str)
8311 "Compress whitespace in STR and return result.
8312 Leading and trailing whitespace is removed. Sequences of multiple
8313 spaces, tabs, and newlines are replaced with single spaces."
8314 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8315 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8317 (defun markdown--substitute-command-keys (string)
8318 "Like `substitute-command-keys' but, but prefers control characters.
8319 First pass STRING to `substitute-command-keys' and then
8320 substitute `C-i` for `TAB` and `C-m` for `RET`."
8321 (replace-regexp-in-string
8322 "\\<TAB\\>" "C-i"
8323 (replace-regexp-in-string
8324 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8326 (defun markdown-line-number-at-pos (&optional pos)
8327 "Return (narrowed) buffer line number at position POS.
8328 If POS is nil, use current buffer location.
8329 This is an exact copy of `line-number-at-pos' for use in emacs21."
8330 (let ((opoint (or pos (point))) start)
8331 (save-excursion
8332 (goto-char (point-min))
8333 (setq start (point))
8334 (goto-char opoint)
8335 (forward-line 0)
8336 (1+ (count-lines start (point))))))
8338 (defun markdown-inside-link-p ()
8339 "Return t if point is within a link."
8340 (save-match-data
8341 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8343 (defun markdown-line-is-reference-definition-p ()
8344 "Return whether the current line is a (non-footnote) reference defition."
8345 (save-excursion
8346 (move-beginning-of-line 1)
8347 (and (looking-at-p markdown-regex-reference-definition)
8348 (not (looking-at-p "[ \t]*\\[^")))))
8350 (defun markdown-adaptive-fill-function ()
8351 "Return prefix for filling paragraph or nil if not determined."
8352 (cond
8353 ;; List item inside blockquote
8354 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8355 (markdown-replace-regexp-in-string
8356 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8357 ;; Blockquote
8358 ((looking-at markdown-regex-blockquote)
8359 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8360 ;; List items
8361 ((looking-at markdown-regex-list)
8362 (match-string-no-properties 0))
8363 ;; Footnote definition
8364 ((looking-at-p markdown-regex-footnote-definition)
8365 " ") ; four spaces
8366 ;; No match
8367 (t nil)))
8369 (defun markdown-fill-paragraph (&optional justify)
8370 "Fill paragraph at or after point.
8371 This function is like \\[fill-paragraph], but it skips Markdown
8372 code blocks. If the point is in a code block, or just before one,
8373 do not fill. Otherwise, call `fill-paragraph' as usual. If
8374 JUSTIFY is non-nil, justify text as well. Since this function
8375 handles filling itself, it always returns t so that
8376 `fill-paragraph' doesn't run."
8377 (interactive "P")
8378 (unless (or (markdown-code-block-at-point-p)
8379 (save-excursion
8380 (back-to-indentation)
8381 (skip-syntax-forward "-")
8382 (markdown-code-block-at-point-p)))
8383 (fill-paragraph justify))
8386 (make-obsolete 'markdown-fill-forward-paragraph-function
8387 'markdown-fill-forward-paragraph "v2.3")
8389 (defun markdown-fill-forward-paragraph (&optional arg)
8390 "Function used by `fill-paragraph' to move over ARG paragraphs.
8391 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8392 It is called with a single argument specifying the number of
8393 paragraphs to move. Just like `forward-paragraph', it should
8394 return the number of paragraphs left to move."
8395 (or arg (setq arg 1))
8396 (if (> arg 0)
8397 ;; With positive ARG, move across ARG non-code-block paragraphs,
8398 ;; one at a time. When passing a code block, don't decrement ARG.
8399 (while (and (not (eobp))
8400 (> arg 0)
8401 (= (forward-paragraph 1) 0)
8402 (or (markdown-code-block-at-pos (point-at-bol 0))
8403 (setq arg (1- arg)))))
8404 ;; Move backward by one paragraph with negative ARG (always -1).
8405 (let ((start (point)))
8406 (setq arg (forward-paragraph arg))
8407 (while (and (not (eobp))
8408 (progn (move-to-left-margin) (not (eobp)))
8409 (looking-at-p paragraph-separate))
8410 (forward-line 1))
8411 (cond
8412 ;; Move point past whitespace following list marker.
8413 ((looking-at markdown-regex-list)
8414 (goto-char (match-end 0)))
8415 ;; Move point past whitespace following pipe at beginning of line
8416 ;; to handle Pandoc line blocks.
8417 ((looking-at "^|\\s-*")
8418 (goto-char (match-end 0)))
8419 ;; Return point if the paragraph passed was a code block.
8420 ((markdown-code-block-at-pos (point-at-bol 2))
8421 (goto-char start)))))
8422 arg)
8424 (defun markdown--inhibit-electric-quote ()
8425 "Function added to `electric-quote-inhibit-functions'.
8426 Return non-nil if the quote has been inserted inside a code block
8427 or span."
8428 (let ((pos (1- (point))))
8429 (or (markdown-inline-code-at-pos pos)
8430 (markdown-code-block-at-pos pos))))
8433 ;;; Extension Framework =======================================================
8435 (defun markdown-reload-extensions ()
8436 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8437 (interactive)
8438 (when (member major-mode '(markdown-mode gfm-mode))
8439 ;; Update font lock keywords with extensions
8440 (setq markdown-mode-font-lock-keywords
8441 (append
8442 (markdown-mode-font-lock-keywords-math)
8443 markdown-mode-font-lock-keywords-basic
8444 (markdown-mode-font-lock-keywords-wiki-links)))
8445 ;; Update font lock defaults
8446 (setq font-lock-defaults
8447 '(markdown-mode-font-lock-keywords
8448 nil nil nil nil
8449 (font-lock-syntactic-face-function . markdown-syntactic-face)))
8450 ;; Refontify buffer
8451 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8452 (font-lock-refresh-defaults))
8454 ;; Add or remove hooks related to extensions
8455 (markdown-setup-wiki-link-hooks)))
8457 (defun markdown-handle-local-variables ()
8458 "Run in `hack-local-variables-hook' to update font lock rules.
8459 Checks to see if there is actually a ‘markdown-mode’ file local variable
8460 before regenerating font-lock rules for extensions."
8461 (when (and (boundp 'file-local-variables-alist)
8462 (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8463 (assoc 'markdown-enable-math file-local-variables-alist))
8464 (markdown-reload-extensions)))
8467 ;;; Wiki Links ================================================================
8469 (defun markdown-toggle-wiki-links (&optional arg)
8470 "Toggle support for wiki links.
8471 With a prefix argument ARG, enable wiki link support if ARG is positive,
8472 and disable it otherwise."
8473 (interactive (list (or current-prefix-arg 'toggle)))
8474 (setq markdown-enable-wiki-links
8475 (if (eq arg 'toggle)
8476 (not markdown-enable-wiki-links)
8477 (> (prefix-numeric-value arg) 0)))
8478 (if markdown-enable-wiki-links
8479 (message "markdown-mode wiki link support enabled")
8480 (message "markdown-mode wiki link support disabled"))
8481 (markdown-reload-extensions))
8483 (defun markdown-setup-wiki-link-hooks ()
8484 "Add or remove hooks for fontifying wiki links.
8485 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8486 ;; Anytime text changes make sure it gets fontified correctly
8487 (if (and markdown-enable-wiki-links
8488 markdown-wiki-link-fontify-missing)
8489 (add-hook 'after-change-functions
8490 'markdown-check-change-for-wiki-link-after-change t t)
8491 (remove-hook 'after-change-functions
8492 'markdown-check-change-for-wiki-link-after-change t))
8493 ;; If we left the buffer there is a really good chance we were
8494 ;; creating one of the wiki link documents. Make sure we get
8495 ;; refontified when we come back.
8496 (if (and markdown-enable-wiki-links
8497 markdown-wiki-link-fontify-missing)
8498 (progn
8499 (add-hook 'window-configuration-change-hook
8500 'markdown-fontify-buffer-wiki-links t t)
8501 (markdown-fontify-buffer-wiki-links))
8502 (remove-hook 'window-configuration-change-hook
8503 'markdown-fontify-buffer-wiki-links t)
8504 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8506 (defun markdown-mode-font-lock-keywords-wiki-links ()
8507 "Return wiki-link lock keywords if support is enabled.
8508 If `markdown-wiki-link-fontify-missing' is also enabled, we use
8509 hooks in `markdown-setup-wiki-link-hooks' for fontification instead."
8510 (when (and markdown-enable-wiki-links
8511 (not markdown-wiki-link-fontify-missing))
8512 (list
8513 (cons markdown-regex-wiki-link '((1 markdown-link-face prepend))))))
8516 ;;; Math Support ==============================================================
8518 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8520 (defun markdown-toggle-math (&optional arg)
8521 "Toggle support for inline and display LaTeX math expressions.
8522 With a prefix argument ARG, enable math mode if ARG is positive,
8523 and disable it otherwise. If called from Lisp, enable the mode
8524 if ARG is omitted or nil."
8525 (interactive (list (or current-prefix-arg 'toggle)))
8526 (setq markdown-enable-math
8527 (if (eq arg 'toggle)
8528 (not markdown-enable-math)
8529 (> (prefix-numeric-value arg) 0)))
8530 (if markdown-enable-math
8531 (message "markdown-mode math support enabled")
8532 (message "markdown-mode math support disabled"))
8533 (markdown-reload-extensions))
8535 (defun markdown-mode-font-lock-keywords-math ()
8536 "Return math font lock keywords if support is enabled."
8537 (when markdown-enable-math
8538 (list
8539 ;; Display mode equations with brackets: \[ \]
8540 (cons markdown-regex-math-display '((1 markdown-markup-face prepend)
8541 (2 markdown-math-face append)
8542 (3 markdown-markup-face prepend)))
8543 ;; Equation reference (eq:foo)
8544 (cons "\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" '((1 markdown-markup-face)
8545 (2 markdown-reference-face)
8546 (3 markdown-markup-face)))
8547 ;; Equation reference \eqref{foo}
8548 (cons "\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" '((1 markdown-markup-face)
8549 (2 markdown-reference-face)
8550 (3 markdown-markup-face))))))
8553 ;;; GFM Checkboxes ============================================================
8555 (define-button-type 'markdown-gfm-checkbox-button
8556 'follow-link t
8557 'face 'markdown-gfm-checkbox-face
8558 'mouse-face 'markdown-highlight-face
8559 'action #'markdown-toggle-gfm-checkbox-button)
8561 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8562 "Return non-nil if there is a GFM task list item at the point.
8563 Optionally, the list item BOUNDS may be given if available, as
8564 returned by `markdown-cur-list-item-bounds'. When a task list item
8565 is found, the return value is the same value returned by
8566 `markdown-cur-list-item-bounds'."
8567 (unless bounds
8568 (setq bounds (markdown-cur-list-item-bounds)))
8569 (> (length (nth 5 bounds)) 0))
8571 (defun markdown-toggle-gfm-checkbox ()
8572 "Toggle GFM checkbox at point.
8573 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8574 Returns nil if there is no task list item at the point."
8575 (interactive)
8576 (save-match-data
8577 (save-excursion
8578 (let ((bounds (markdown-cur-list-item-bounds)))
8579 (when bounds
8580 ;; Move to beginning of task list item
8581 (goto-char (cl-first bounds))
8582 ;; Advance to column of first non-whitespace after marker
8583 (forward-char (cl-fourth bounds))
8584 (cond ((looking-at "\\[ \\]")
8585 (replace-match
8586 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8587 nil t)
8588 (match-string-no-properties 0))
8589 ((looking-at "\\[[xX]\\]")
8590 (replace-match "[ ]" nil t)
8591 (match-string-no-properties 0))))))))
8593 (defun markdown-toggle-gfm-checkbox-button (button)
8594 "Toggle GFM checkbox BUTTON on click."
8595 (save-match-data
8596 (save-excursion
8597 (goto-char (button-start button))
8598 (markdown-toggle-gfm-checkbox))))
8600 (defun markdown-make-gfm-checkboxes-buttons (start end)
8601 "Make GFM checkboxes buttons in region between START and END."
8602 (save-excursion
8603 (goto-char start)
8604 (let ((case-fold-search t))
8605 (save-excursion
8606 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8607 (make-button (match-beginning 1) (match-end 1)
8608 :type 'markdown-gfm-checkbox-button))))))
8610 ;; Called when any modification is made to buffer text.
8611 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8612 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8613 BEG and END are the limits of scanned region."
8614 (save-excursion
8615 (save-match-data
8616 ;; Rescan between start of line from `beg' and start of line after `end'.
8617 (markdown-make-gfm-checkboxes-buttons
8618 (progn (goto-char beg) (beginning-of-line) (point))
8619 (progn (goto-char end) (forward-line 1) (point))))))
8621 (defun markdown-remove-gfm-checkbox-overlays ()
8622 "Remove all GFM checkbox overlays in buffer."
8623 (save-excursion
8624 (save-restriction
8625 (widen)
8626 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8629 ;;; Display inline image =================================================
8631 (defvar markdown-inline-image-overlays nil)
8632 (make-variable-buffer-local 'markdown-inline-image-overlays)
8634 (defun markdown-remove-inline-images ()
8635 "Remove inline image overlays from image links in the buffer.
8636 This can be toggled with `markdown-toggle-inline-images'
8637 or \\[markdown-toggle-inline-images]."
8638 (interactive)
8639 (mapc #'delete-overlay markdown-inline-image-overlays)
8640 (setq markdown-inline-image-overlays nil))
8642 (defun markdown-display-inline-images ()
8643 "Add inline image overlays to image links in the buffer.
8644 This can be toggled with `markdown-toggle-inline-images'
8645 or \\[markdown-toggle-inline-images]."
8646 (interactive)
8647 (unless (display-graphic-p)
8648 (error "Cannot show images"))
8649 (save-excursion
8650 (save-restriction
8651 (widen)
8652 (goto-char (point-min))
8653 (while (re-search-forward markdown-regex-link-inline nil t)
8654 (let ((start (match-beginning 0))
8655 (end (match-end 0))
8656 (file (match-string-no-properties 6)))
8657 (when (file-exists-p file)
8658 (let* ((abspath (if (file-name-absolute-p file)
8659 file
8660 (concat default-directory file)))
8661 (image (create-image abspath)))
8662 (when image
8663 (let ((ov (make-overlay start end)))
8664 (overlay-put ov 'display image)
8665 (overlay-put ov 'face 'default)
8666 (push ov markdown-inline-image-overlays))))))))))
8668 (defun markdown-toggle-inline-images ()
8669 "Toggle inline image overlays in the buffer."
8670 (interactive)
8671 (if markdown-inline-image-overlays
8672 (markdown-remove-inline-images)
8673 (markdown-display-inline-images)))
8676 ;;; GFM Code Block Fontification ==============================================
8678 (defcustom markdown-fontify-code-blocks-natively nil
8679 "When non-nil, fontify code in code blocks using the native major mode.
8680 This only works for fenced code blocks where the language is
8681 specified where we can automatically determine the appropriate
8682 mode to use. The language to mode mapping may be customized by
8683 setting the variable `markdown-code-lang-modes'."
8684 :group 'markdown
8685 :type 'boolean
8686 :safe 'booleanp
8687 :package-version '(markdown-mode . "2.3"))
8689 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
8690 "Toggle the native fontification of code blocks.
8691 With a prefix argument ARG, enable if ARG is positive,
8692 and disable otherwise."
8693 (interactive (list (or current-prefix-arg 'toggle)))
8694 (setq markdown-fontify-code-blocks-natively
8695 (if (eq arg 'toggle)
8696 (not markdown-fontify-code-blocks-natively)
8697 (> (prefix-numeric-value arg) 0)))
8698 (if markdown-fontify-code-blocks-natively
8699 (message "markdown-mode native code block fontification enabled")
8700 (message "markdown-mode native code block fontification disabled"))
8701 (markdown-reload-extensions))
8703 ;; This is based on `org-src-lang-modes' from org-src.el
8704 (defcustom markdown-code-lang-modes
8705 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
8706 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
8707 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
8708 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
8709 ("bash" . sh-mode))
8710 "Alist mapping languages to their major mode.
8711 The key is the language name, the value is the major mode. For
8712 many languages this is simple, but for language where this is not
8713 the case, this variable provides a way to simplify things on the
8714 user side. For example, there is no ocaml-mode in Emacs, but the
8715 mode to use is `tuareg-mode'."
8716 :group 'markdown
8717 :type '(repeat
8718 (cons
8719 (string "Language name")
8720 (symbol "Major mode")))
8721 :package-version '(markdown-mode . "2.3"))
8723 (defun markdown-get-lang-mode (lang)
8724 "Return major mode that should be used for LANG.
8725 LANG is a string, and the returned major mode is a symbol."
8726 (cl-find-if
8727 'fboundp
8728 (list (cdr (assoc lang markdown-code-lang-modes))
8729 (cdr (assoc (downcase lang) markdown-code-lang-modes))
8730 (intern (concat lang "-mode"))
8731 (intern (concat (downcase lang) "-mode")))))
8733 (defun markdown-fontify-code-blocks-generic (matcher last)
8734 "Add text properties to next code block from point to LAST.
8735 Use matching function MATCHER."
8736 (when (funcall matcher last)
8737 (save-excursion
8738 (save-match-data
8739 (let* ((start (match-beginning 0))
8740 (end (match-end 0))
8741 ;; Find positions outside opening and closing backquotes.
8742 (bol-prev (progn (goto-char start)
8743 (if (bolp) (point-at-bol 0) (point-at-bol))))
8744 (eol-next (progn (goto-char end)
8745 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
8746 lang)
8747 (if (and markdown-fontify-code-blocks-natively
8748 (setq lang (markdown-code-block-lang)))
8749 (markdown-fontify-code-block-natively lang start end)
8750 (add-text-properties start end '(face markdown-pre-face)))
8751 ;; Set background for block as well as opening and closing lines.
8752 (font-lock-append-text-property
8753 bol-prev eol-next 'face 'markdown-code-face)
8754 ;; Set invisible property for lines before and after, including newline.
8755 (add-text-properties bol-prev start '(invisible markdown-markup))
8756 (add-text-properties end eol-next '(invisible markdown-markup)))))
8759 (defun markdown-fontify-gfm-code-blocks (last)
8760 "Add text properties to next GFM code block from point to LAST."
8761 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
8763 (defun markdown-fontify-fenced-code-blocks (last)
8764 "Add text properties to next tilde fenced code block from point to LAST."
8765 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
8767 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
8768 (defun markdown-fontify-code-block-natively (lang start end)
8769 "Fontify given GFM or fenced code block.
8770 This function is called by Emacs for automatic fontification when
8771 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
8772 language used in the block. START and END specify the block
8773 position."
8774 (let ((lang-mode (markdown-get-lang-mode lang)))
8775 (when (fboundp lang-mode)
8776 (let ((string (buffer-substring-no-properties start end))
8777 (modified (buffer-modified-p))
8778 (markdown-buffer (current-buffer)) pos next)
8779 (remove-text-properties start end '(face nil))
8780 (with-current-buffer
8781 (get-buffer-create
8782 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
8783 ;; Make sure that modification hooks are not inhibited in
8784 ;; the org-src-fontification buffer in case we're called
8785 ;; from `jit-lock-function' (Bug#25132).
8786 (let ((inhibit-modification-hooks nil))
8787 (delete-region (point-min) (point-max))
8788 (insert string " ")) ;; so there's a final property change
8789 (unless (eq major-mode lang-mode) (funcall lang-mode))
8790 (markdown-font-lock-ensure)
8791 (setq pos (point-min))
8792 (while (setq next (next-single-property-change pos 'face))
8793 (let ((val (get-text-property pos 'face)))
8794 (when val
8795 (put-text-property
8796 (+ start (1- pos)) (1- (+ start next)) 'face
8797 val markdown-buffer)))
8798 (setq pos next)))
8799 (add-text-properties
8800 start end
8801 '(font-lock-fontified t fontified t font-lock-multiline t))
8802 (set-buffer-modified-p modified)))))
8804 (require 'edit-indirect nil t)
8805 (defvar edit-indirect-guess-mode-function)
8806 (defvar edit-indirect-after-commit-functions)
8808 (defun markdown--edit-indirect-after-commit-function (_beg end)
8809 "Ensure trailing newlines at the END of code blocks."
8810 (goto-char end)
8811 (unless (eq (char-before) ?\n)
8812 (insert "\n")))
8814 (defun markdown-edit-code-block ()
8815 "Edit Markdown code block in an indirect buffer."
8816 (interactive)
8817 (save-excursion
8818 (if (fboundp 'edit-indirect-region)
8819 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
8820 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
8821 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
8822 (if (and begin end)
8823 (let* ((lang (markdown-code-block-lang))
8824 (mode (and lang (markdown-get-lang-mode lang)))
8825 (edit-indirect-guess-mode-function
8826 (lambda (_parent-buffer _beg _end)
8827 (funcall mode))))
8828 (edit-indirect-region begin end 'display-buffer))
8829 (user-error "Not inside a GFM or tilde fenced code block")))
8830 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
8831 (progn (package-refresh-contents)
8832 (package-install 'edit-indirect)
8833 (markdown-edit-code-block))))))
8836 ;;; ElDoc Support
8838 (defun markdown-eldoc-function ()
8839 "Return a helpful string when appropriate based on context.
8840 * Report URL when point is at a hidden URL.
8841 * Report language name when point is a code block with hidden markup."
8842 (cond
8843 ;; Hidden URL or reference for inline link
8844 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
8845 (thing-at-point-looking-at markdown-regex-link-reference))
8846 (or markdown-hide-urls markdown-hide-markup))
8847 (let* ((imagep (string-equal (match-string 1) "!"))
8848 (edit-keys (markdown--substitute-command-keys
8849 (if imagep
8850 "\\[markdown-insert-image]"
8851 "\\[markdown-insert-link]")))
8852 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
8853 (referencep (string-equal (match-string 5) "["))
8854 (object (if referencep "reference" "URL")))
8855 (format "Hidden %s (%s to edit): %s" object edit-str
8856 (if referencep
8857 (concat
8858 (propertize "[" 'face 'markdown-markup-face)
8859 (propertize (match-string-no-properties 6)
8860 'face 'markdown-reference-face)
8861 (propertize "]" 'face 'markdown-markup-face))
8862 (propertize (match-string-no-properties 6)
8863 'face 'markdown-url-face)))))
8864 ;; Hidden language name for fenced code blocks
8865 ((and (markdown-code-block-at-point-p)
8866 (not (get-text-property (point) 'markdown-pre))
8867 markdown-hide-markup)
8868 (let ((lang (save-excursion (markdown-code-block-lang))))
8869 (unless lang (setq lang "[unspecified]"))
8870 (format "Hidden code block language: %s (%s to toggle markup)"
8871 (propertize lang 'face 'markdown-language-keyword-face)
8872 (markdown--substitute-command-keys
8873 "\\[markdown-toggle-markup-hiding]"))))))
8876 ;;; Mode Definition ==========================================================
8878 (defun markdown-show-version ()
8879 "Show the version number in the minibuffer."
8880 (interactive)
8881 (message "markdown-mode, version %s" markdown-mode-version))
8883 (defun markdown-mode-info ()
8884 "Open the `markdown-mode' homepage."
8885 (interactive)
8886 (browse-url "https://jblevins.org/projects/markdown-mode/"))
8888 ;;;###autoload
8889 (define-derived-mode markdown-mode text-mode "Markdown"
8890 "Major mode for editing Markdown files."
8891 ;; Natural Markdown tab width
8892 (setq tab-width 4)
8893 ;; Comments
8894 (setq-local comment-start "<!-- ")
8895 (setq-local comment-end " -->")
8896 (setq-local comment-start-skip "<!--[ \t]*")
8897 (setq-local comment-column 0)
8898 (setq-local comment-auto-fill-only-comments nil)
8899 (setq-local comment-use-syntax t)
8900 ;; Syntax
8901 (add-hook 'syntax-propertize-extend-region-functions
8902 #'markdown-syntax-propertize-extend-region)
8903 (add-hook 'jit-lock-after-change-extend-region-functions
8904 #'markdown-font-lock-extend-region-function t t)
8905 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
8906 ;; Font lock.
8907 (setq-local markdown-mode-font-lock-keywords nil)
8908 (setq-local font-lock-defaults nil)
8909 (setq-local font-lock-multiline t)
8910 (setq-local font-lock-extra-managed-props
8911 (append font-lock-extra-managed-props
8912 '(composition display invisible)))
8913 (if markdown-hide-markup
8914 (add-to-invisibility-spec 'markdown-markup)
8915 (remove-from-invisibility-spec 'markdown-markup))
8916 ;; Reload extensions
8917 (markdown-reload-extensions)
8918 ;; Add a buffer-local hook to reload after file-local variables are read
8919 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
8920 ;; For imenu support
8921 (setq imenu-create-index-function
8922 (if markdown-nested-imenu-heading-index
8923 #'markdown-imenu-create-nested-index
8924 #'markdown-imenu-create-flat-index))
8925 ;; For menu support in XEmacs
8926 (easy-menu-add markdown-mode-menu markdown-mode-map)
8927 ;; Defun movement
8928 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
8929 (setq-local end-of-defun-function #'markdown-end-of-defun)
8930 ;; Paragraph filling
8931 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
8932 (setq-local paragraph-start
8933 ;; Should match start of lines that start or separate paragraphs
8934 (mapconcat #'identity
8936 "\f" ; starts with a literal line-feed
8937 "[ \t\f]*$" ; space-only line
8938 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8939 "[ \t]*[*+-][ \t]+" ; unordered list item
8940 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
8941 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
8942 "[ \t]*:[ \t]+" ; definition
8943 "^|" ; table or Pandoc line block
8945 "\\|"))
8946 (setq-local paragraph-separate
8947 ;; Should match lines that separate paragraphs without being
8948 ;; part of any paragraph:
8949 (mapconcat #'identity
8950 '("[ \t\f]*$" ; space-only line
8951 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
8952 ;; The following is not ideal, but the Fill customization
8953 ;; options really only handle paragraph-starting prefixes,
8954 ;; not paragraph-ending suffixes:
8955 ".* $" ; line ending in two spaces
8956 "^#+"
8957 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
8958 "\\|"))
8959 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
8960 (setq-local adaptive-fill-regexp "\\s-*")
8961 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
8962 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
8963 ;; Outline mode
8964 (setq-local outline-regexp markdown-regex-header)
8965 (setq-local outline-level #'markdown-outline-level)
8966 ;; Cause use of ellipses for invisible text.
8967 (add-to-invisibility-spec '(outline . t))
8968 ;; ElDoc support
8969 (if (eval-when-compile (fboundp 'add-function))
8970 (add-function :before-until (local 'eldoc-documentation-function)
8971 #'markdown-eldoc-function)
8972 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
8973 ;; Inhibiting line-breaking:
8974 ;; Separating out each condition into a separate function so that users can
8975 ;; override if desired (with remove-hook)
8976 (add-hook 'fill-nobreak-predicate
8977 #'markdown-line-is-reference-definition-p nil t)
8978 (add-hook 'fill-nobreak-predicate
8979 #'markdown-pipe-at-bol-p nil t)
8981 ;; Indentation
8982 (setq-local indent-line-function markdown-indent-function)
8984 ;; Flyspell
8985 (setq-local flyspell-generic-check-word-predicate
8986 #'markdown-flyspell-check-word-p)
8988 ;; Electric quoting
8989 (add-hook 'electric-quote-inhibit-functions
8990 #'markdown--inhibit-electric-quote nil :local)
8992 ;; Backwards compatibility with markdown-css-path
8993 (when (boundp 'markdown-css-path)
8994 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
8995 (add-to-list 'markdown-css-paths markdown-css-path))
8997 ;; Prepare hooks for XEmacs compatibility
8998 (when (featurep 'xemacs)
8999 (make-local-hook 'after-change-functions)
9000 (make-local-hook 'font-lock-extend-region-functions)
9001 (make-local-hook 'window-configuration-change-hook))
9003 ;; Make checkboxes buttons
9004 (when markdown-make-gfm-checkboxes-buttons
9005 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
9006 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
9007 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
9009 ;; edit-indirect
9010 (add-hook 'edit-indirect-after-commit-functions
9011 #'markdown--edit-indirect-after-commit-function
9012 nil 'local)
9014 ;; add live preview export hook
9015 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
9016 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
9018 ;;;###autoload
9019 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
9020 ;;;###autoload
9021 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
9024 ;;; GitHub Flavored Markdown Mode ============================================
9026 (defvar gfm-mode-hook nil
9027 "Hook run when entering GFM mode.")
9029 (defvar gfm-font-lock-keywords
9030 ;; Basic Markdown features (excluding possibly overridden ones)
9031 markdown-mode-font-lock-keywords-basic
9032 "Default highlighting expressions for GitHub Flavored Markdown mode.")
9034 ;;;###autoload
9035 (define-derived-mode gfm-mode markdown-mode "GFM"
9036 "Major mode for editing GitHub Flavored Markdown files."
9037 (setq markdown-link-space-sub-char "-")
9038 (setq markdown-wiki-link-search-subdirectories t)
9039 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
9040 ;; do the initial link fontification
9041 (markdown-gfm-parse-buffer-for-languages))
9044 ;;; Live Preview Mode ============================================
9045 (define-minor-mode markdown-live-preview-mode
9046 "Toggle native previewing on save for a specific markdown file."
9047 :lighter " MD-Preview"
9048 (if markdown-live-preview-mode
9049 (if (markdown-live-preview-get-filename)
9050 (markdown-display-buffer-other-window (markdown-live-preview-export))
9051 (markdown-live-preview-mode -1)
9052 (user-error "Buffer %s does not visit a file" (current-buffer)))
9053 (markdown-live-preview-remove)))
9056 (provide 'markdown-mode)
9058 ;; Local Variables:
9059 ;; indent-tabs-mode: nil
9060 ;; coding: utf-8
9061 ;; End:
9062 ;;; markdown-mode.el ends here