Handle unspecified or unknown languages when editing code blocks
[markdown-mode.git] / markdown-mode.el
blob39f558bfd2702245a7851b74426df255b435e559
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 point
261 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
262 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
264 ;; `C-c C-s q` inserts a blockquote using the active region, if
265 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
266 ;; which always operates on the region, regardless of whether it
267 ;; is active or not (i.e., when `transient-mark-mode` is off but
268 ;; the mark is set). The appropriate amount of indentation, if
269 ;; any, is calculated automatically given the surrounding context,
270 ;; but may be adjusted later using the region indentation
271 ;; commands.
273 ;; `C-c C-s p` behaves similarly for inserting preformatted code
274 ;; blocks (with `C-c C-s P` being the region-only counterpart)
275 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
277 ;; * Headings: `C-c C-s`
279 ;; To insert or replace headings, there are two options. You can
280 ;; insert a specific level heading directly or you can have
281 ;; `markdown-mode' determine the level for you based on the previous
282 ;; heading. As with the other markup commands, the heading
283 ;; insertion commands use the text in the active region, if any,
284 ;; as the heading text. Otherwise, if the current line is not
285 ;; blank, they use the text on the current line. Finally, the
286 ;; setext commands will prompt for heading text if there is no
287 ;; active region and the current line is blank.
289 ;; `C-c C-s h` inserts a heading with automatically chosen type and
290 ;; level (both determined by the previous heading). `C-c C-s H`
291 ;; behaves similarly, but uses setext (underlined) headings when
292 ;; possible, still calculating the level automatically.
293 ;; In cases where the automatically-determined level is not what
294 ;; you intended, the level can be quickly promoted or demoted
295 ;; (as described below). Alternatively, a `C-u` prefix can be
296 ;; given to insert a heading _promoted_ (lower number) by one
297 ;; level or a `C-u C-u` prefix can be given to insert a heading
298 ;; demoted (higher number) by one level.
300 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
301 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
302 ;; `C-c C-s @` for setext headings of level one or two, respectively.
303 ;; Note that `!` is `S-1` and `@` is `S-2`.
305 ;; If the point is at a heading, these commands will replace the
306 ;; existing markup in order to update the level and/or type of the
307 ;; heading. To remove the markup of the heading at the point,
308 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
309 ;; heading text back into the buffer.
311 ;; * Horizontal Rules: `C-c C-s -`
313 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
314 ;; first string in the list `markdown-hr-strings' (the most
315 ;; prominent rule). With a `C-u` prefix, insert the last string.
316 ;; With a numeric prefix `N`, insert the string in position `N`
317 ;; (counting from 1).
319 ;; * Footnotes: `C-c C-s f`
321 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
322 ;; footnote definition below, and positions the point for
323 ;; inserting the footnote text. Note that footnotes are an
324 ;; extension to Markdown and are not supported by all processors.
326 ;; * Wiki Links: `C-c C-s w`
328 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
329 ;; there is an active region, use the region as the link text. If the
330 ;; point is at a word, use the word as the link text. If there is
331 ;; no active region and the point is not at word, simply insert
332 ;; link markup. Note that wiki links are an extension to Markdown
333 ;; and are not supported by all processors.
335 ;; * Markdown and Maintenance Commands: `C-c C-c`
337 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
338 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
339 ;; runs Markdown on the current buffer and previews, stores the
340 ;; output in a temporary file, and displays the file in a browser.
341 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
342 ;; and save the result in the file `basename.html`, where
343 ;; `basename` is the name of the Markdown file with the extension
344 ;; removed. *Export and View:* press `C-c C-c v` to export the
345 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
346 ;; the Markdown source file directly using `markdown-open-command'.
347 ;; *Live Export*: Press `C-c C-c l` to turn on
348 ;; `markdown-live-preview-mode' to view the exported output
349 ;; side-by-side with the source Markdown. **For all export commands,
350 ;; the output file will be overwritten without notice.**
351 ;; `markdown-live-preview-window-function' can be customized to open
352 ;; in a browser other than `eww'. If you want to force the
353 ;; preview window to appear at the bottom or right, you can
354 ;; customize `markdown-split-window-direction'.
356 ;; To summarize:
358 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
359 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
360 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
361 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
362 ;; - `C-c C-c w`: `markdown-command' > kill ring.
363 ;; - `C-c C-c o`: `markdown-open-command'.
364 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
366 ;; `C-c C-c c` will check for undefined references. If there are
367 ;; any, a small buffer will open with a list of undefined
368 ;; references and the line numbers on which they appear. In Emacs
369 ;; 22 and greater, selecting a reference from this list and
370 ;; pressing `RET` will insert an empty reference definition at the
371 ;; end of the buffer. Similarly, selecting the line number will
372 ;; jump to the corresponding line.
374 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
375 ;; out of sequence.
377 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
378 ;; rules in the buffer.
380 ;; * Following Links: `C-c C-o`
382 ;; Press `C-c C-o` when the point is on an inline or reference
383 ;; link to open the URL in a browser. When the point is at a
384 ;; wiki link, open it in another buffer (in the current window,
385 ;; or in the other window with the `C-u` prefix). Use `M-p` and
386 ;; `M-n` to quickly jump to the previous or next link of any type.
388 ;; * Doing Things: `C-c C-d`
390 ;; Use `C-c C-d` to do something sensible with the object at the point:
392 ;; - Jumps between reference links and reference definitions.
393 ;; If more than one link uses the same reference label, a
394 ;; window will be shown containing clickable buttons for
395 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
396 ;; between buttons in this window.
397 ;; - Jumps between footnote markers and footnote text.
398 ;; - Toggles the completion status of GFM task list items
399 ;; (checkboxes).
400 ;; - Re-aligns table columns.
402 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
404 ;; Headings, horizontal rules, and list items can be promoted and
405 ;; demoted, as well as bold and italic text. For headings,
406 ;; "promotion" means *decreasing* the level (i.e., moving from
407 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
408 ;; level. For horizontal rules, promotion and demotion means
409 ;; moving backward or forward through the list of rule strings in
410 ;; `markdown-hr-strings'. For bold and italic text, promotion and
411 ;; demotion means changing the markup from underscores to asterisks.
412 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
413 ;; if possible.
415 ;; To remember these commands, note that `-` is for decreasing the
416 ;; level (promoting), and `=` (on the same key as `+`) is for
417 ;; increasing the level (demoting). Similarly, the left and right
418 ;; arrow keys indicate the direction that the atx heading markup
419 ;; is moving in when promoting or demoting.
421 ;; * Completion: `C-c C-]`
423 ;; Complete markup is in normalized form, which means, for
424 ;; example, that the underline portion of a setext header is the
425 ;; same length as the heading text, or that the number of leading
426 ;; and trailing hash marks of an atx header are equal and that
427 ;; there is no extra whitespace in the header text. `C-c C-]`
428 ;; completes the markup at the point, if it is determined to be
429 ;; incomplete.
431 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
433 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
434 ;; command determines the appropriate marker (one of the possible
435 ;; unordered list markers or the next number in sequence for an
436 ;; ordered list) and indentation level by examining nearby list
437 ;; items. If there is no list before or after the point, start a
438 ;; new list. As with heading insertion, you may prefix this
439 ;; command by `C-u` to decrease the indentation by one level.
440 ;; Prefix this command by `C-u C-u` to increase the indentation by
441 ;; one level.
443 ;; Existing list items (and their nested sub-items) can be moved
444 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
445 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
447 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
449 ;; Entire subtrees of ATX headings can be promoted and demoted
450 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
451 ;; used for promotion and demotion of list items. If the point is in
452 ;; a list item, the operate on the list item. Otherwise, they operate
453 ;; on the current heading subtree. Similarly, subtrees can be
454 ;; moved up and down with `C-c UP` and `C-c DOWN`.
456 ;; These commands currently do not work properly if there are
457 ;; Setext headings in the affected region.
459 ;; Please note the following "boundary" behavior for promotion and
460 ;; demotion. Any level-six headings will not be demoted further
461 ;; (i.e., they remain at level six, since Markdown and HTML define
462 ;; only six levels) and any level-one headings will promoted away
463 ;; entirely (i.e., heading markup will be removed, since a
464 ;; level-zero heading is not defined).
466 ;; * Shifting the Region: `C-c <` and `C-c >`
468 ;; Text in the region can be indented or outdented as a group using
469 ;; `C-c >` to indent to the next indentation point (calculated in
470 ;; the current context), and `C-c <` to outdent to the previous
471 ;; indentation point. These keybindings are the same as those for
472 ;; similar commands in `python-mode'.
474 ;; * Killing Elements: `C-c C-k`
476 ;; Press `C-c C-k` to kill the thing at point and add important
477 ;; text, without markup, to the kill ring. Possible things to
478 ;; kill include (roughly in order of precedece): inline code,
479 ;; headings, horizonal rules, links (add link text to kill ring),
480 ;; images (add alt text to kill ring), angle URIs, email
481 ;; addresses, bold, italics, reference definitions (add URI to
482 ;; kill ring), footnote markers and text (kill both marker and
483 ;; text, add text to kill ring), and list items.
485 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
487 ;; These keys are used for hierarchical navigation in lists and
488 ;; headings. When the point is in a list, they move between list
489 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
490 ;; `C-c C-p` to move between the next and previous visible
491 ;; headings or list items of any level. Similarly, `C-c C-f` and
492 ;; `C-c C-b` move to the next and previous visible headings or
493 ;; list items at the same level as the one at the point. Finally,
494 ;; `C-c C-u` will move up to the parent heading or list item.
496 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
498 ;; Paragraphs in `markdown-mode' are regular paragraphs,
499 ;; paragraphs inside blockquotes, individual list items, headings,
500 ;; etc. These keys are usually bound to `forward-paragraph' and
501 ;; `backward-paragraph', but the built-in Emacs functions are
502 ;; based on simple regular expressions that fail in Markdown
503 ;; files. Instead, they are bound to `markdown-forward-paragraph'
504 ;; and `markdown-backward-paragraph'. To mark a paragraph,
505 ;; you can use `M-h` (`markdown-mark-paragraph').
507 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
509 ;; Markdown blocks are regular paragraphs in many cases, but
510 ;; contain many paragraphs in other cases: blocks are considered
511 ;; to be entire lists, entire code blocks, and entire blockquotes.
512 ;; To move backward one block use `C-M-{`
513 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
514 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
515 ;; (`markdown-mark-block`).
517 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
519 ;; The usual Emacs commands can be used to move by defuns
520 ;; (top-level major definitions). In markdown-mode, a defun is a
521 ;; section. As usual, `C-M-a` will move the point to the
522 ;; beginning of the current or preceding defun, `C-M-e` will move
523 ;; to the end of the current or following defun, and `C-M-h` will
524 ;; put the region around the entire defun.
526 ;; * Table Editing:
528 ;; Markdown Mode includes support for editing tables, which
529 ;; have the following basic format:
531 ;; | Right | Left | Center | Default |
532 ;; |------:|:-----|:------:|---------|
533 ;; | 12 | 12 | 12 | 12 |
534 ;; | 123 | 123 | 123 | 123 |
535 ;; | 1 | 1 | 1 | 1 |
537 ;; The first line contains column headers. The second line
538 ;; contains a separator line between the headers and the content.
539 ;; Each following line is a row in the table. Columns are always
540 ;; separated by the pipe character. The colons indicate column
541 ;; alignment.
543 ;; A table is re-aligned automatically each time you press `TAB`
544 ;; or `RET` inside the table. `TAB` also moves to the next
545 ;; field (`RET` to the next row) and creates new table rows at
546 ;; the end of the table or before horizontal separator lines. The
547 ;; indentation of the table is set by the first line. Column
548 ;; centering inside Emacs is not supported.
550 ;; Beginning pipe characters are required for proper detection of
551 ;; table borders inside Emacs. Any line starting with `|-` or `|:`
552 ;; is considered as a horizontal separator line and will be
553 ;; expanded on the next re-align to span the whole table width. No
554 ;; padding is allowed between the beginning pipe character and
555 ;; header separator symbol. So, to create the above table, you
556 ;; would only type
558 ;; |Right|Left|Center|Default|
559 ;; |-
561 ;; and then press `TAB` to align the table and start filling in
562 ;; cells.
564 ;; Then you can jump with `TAB` from one cell to the next or with
565 ;; `S-TAB` to the previous one. `RET` will jump to the to the
566 ;; next cell in the same column, and create a new row if there is
567 ;; no such cell or if the next row is beyond a separator line.
569 ;; You can also convert selected region to a table. Basic editing
570 ;; capabilities include inserting, deleting, and moving of columns
571 ;; and rows, and table re-alignment, sorting, transposition:
573 ;; - `C-c UP` or `C-c DOWN` - Move the current row up or down.
574 ;; - `C-c LEFT` or `C-c RIGHT` - Move the current column left or right.
575 ;; - `C-c S-UP` - Kill the current row.
576 ;; - `C-c S-DOWN` - Insert a row above the current row. With a
577 ;; prefix argument, row line is created below the current one.
578 ;; - `C-c S-LEFT` - Kill the current column.
579 ;; - `C-c S-RIGHT` - Insert a new column to the left of the current one.
580 ;; - `C-c C-d` - Re-align the current table (`markdown-do`).
581 ;; - `C-c C-c ^` - Sort the rows of a table by a specified column.
582 ;; This command prompts you for the column number and a sort
583 ;; method (alphabetical or numerical, optionally in reverse).
584 ;; - `C-c C-c |` - Convert the region to a table. This function
585 ;; attempts to recognize comma, tab, and space separated data
586 ;; and then splits the data into cells accordingly.
587 ;; - `C-c C-c t` - Transpose table at point.
589 ;; The table editing functions try to handle markup hiding
590 ;; correctly when calculating column widths, however, columns
591 ;; containing hidden markup may not always be aligned properly.
593 ;; * Miscellaneous Commands:
595 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
596 ;; (`markdown-edit-code-block`) can be used to edit a code block
597 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
598 ;; to commit changes and return or `C-c C-k` to cancel. You can
599 ;; also give a prefix argument to the insertion command, as in
600 ;; `C-u C-c C-s C`, to edit the code block in an indirect buffer
601 ;; upon insertion.
603 ;; As noted, many of the commands above behave differently depending
604 ;; on whether Transient Mark mode is enabled or not. When it makes
605 ;; sense, if Transient Mark mode is on and the region is active, the
606 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
607 ;; region bold). For users who prefer to work outside of Transient
608 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
609 ;; `C-SPC C-SPC`. When this is not the case, many commands then
610 ;; proceed to look work with the word or line at the point.
612 ;; When applicable, commands that specifically act on the region even
613 ;; outside of Transient Mark mode have the same keybinding as their
614 ;; standard counterpart, but the letter is uppercase. For example,
615 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
616 ;; the region in Transient Mark mode while `markdown-blockquote-region'
617 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
619 ;; Note that these region-specific functions are useful in many
620 ;; cases where it may not be obvious. For example, yanking text from
621 ;; the kill ring sets the mark at the beginning of the yanked text
622 ;; and moves the point to the end. Therefore, the (inactive) region
623 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
624 ;; yank text and turn it into a blockquote.
626 ;; markdown-mode attempts to be flexible in how it handles
627 ;; indentation. When you press `TAB` repeatedly, the point will cycle
628 ;; through several possible indentation levels corresponding to things
629 ;; you might have in mind when you press `RET` at the end of a line or
630 ;; `TAB`. For example, you may want to start a new list item,
631 ;; continue a list item with hanging indentation, indent for a nested
632 ;; pre block, and so on. Outdenting is handled similarly when backspace
633 ;; is pressed at the beginning of the non-whitespace portion of a line.
635 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
636 ;; visibility cycling for atx- or hash-style headings. There are two
637 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
638 ;; the table of contents view (headings only), outline view (top-level
639 ;; headings only), and the full document view. Pressing `TAB` while the
640 ;; point is at a heading will cycle through levels of visibility for the
641 ;; subtree: completely folded, visible children, and fully visible.
642 ;; Note that mixing hash and underline style headings will give undesired
643 ;; results.
645 ;;; Customization:
647 ;; Although no configuration is *necessary* there are a few things
648 ;; that can be customized. The `M-x customize-mode` command
649 ;; provides an interface to all of the possible customizations:
651 ;; * `markdown-command' - the command used to run Markdown (default:
652 ;; `markdown`). This variable may be customized to pass
653 ;; command-line options to your Markdown processor of choice. It can
654 ;; also be a function; in this case `markdown' will call it with three
655 ;; arguments: the beginning and end of the region to process, and
656 ;; a buffer to write the output to.
658 ;; * `markdown-command-needs-filename' - set to `t' if
659 ;; `markdown-command' does not accept standard input (default:
660 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
661 ;; content to `markdown-command' using standard input (`stdin`).
662 ;; When set to `t', `markdown-mode' will pass the name of the file
663 ;; as the final command-line argument to `markdown-command'. Note
664 ;; that in the latter case, you will only be able to run
665 ;; `markdown-command' from buffers which are visiting a file. If
666 ;; `markdown-command' is a function, `markdown-command-needs-filename'
667 ;; is ignored.
669 ;; * `markdown-open-command' - the command used for calling a standalone
670 ;; Markdown previewer which is capable of opening Markdown source files
671 ;; directly (default: `nil'). This command will be called
672 ;; with a single argument, the filename of the current buffer.
673 ;; A representative program is the Mac app [Marked 2][], a
674 ;; live-updating Markdown previewer which can be [called from a
675 ;; simple shell script](https://jblevins.org/log/marked-2-command).
676 ;; This variable can also be a function; in this case `markdown-open'
677 ;; will call it without arguments to preview the current buffer.
679 ;; * `markdown-hr-strings' - list of strings to use when inserting
680 ;; horizontal rules. Different strings will not be distinguished
681 ;; when converted to HTML--they will all be converted to
682 ;; `<hr/>`--but they may add visual distinction and style to plain
683 ;; text documents. To maintain some notion of promotion and
684 ;; demotion, keep these sorted from largest to smallest.
686 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
687 ;; underscores when inserting bold text instead of two asterisks
688 ;; (default: `nil').
690 ;; * `markdown-italic-underscore' - set to a non-nil value to use
691 ;; underscores when inserting italic text instead of asterisks
692 ;; (default: `nil').
694 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
695 ;; asymmetric header styling, placing header characters only on
696 ;; the left of headers (default: `nil').
698 ;; * `markdown-header-scaling' - set to a non-nil value to use
699 ;; a variable-pitch font for headings where the size corresponds
700 ;; to the level of the heading (default: `nil').
702 ;; * `markdown-header-scaling-values' - list of scaling values,
703 ;; relative to baseline, for headers of levels one through six,
704 ;; used when `markdown-header-scaling' is non-nil
705 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
707 ;; * `markdown-marginalize-headers' - put opening atx header markup
708 ;; in the left margin when non-nil (default: `nil').
710 ;; * `markdown-marginalize-headers-margin-width' - width of margin
711 ;; used for marginalized headers (default: 6).
713 ;; * `markdown-list-indent-width' - depth of indentation for lists
714 ;; when inserting, promoting, and demoting list items (default: 4).
716 ;; * `markdown-indent-function' - the function to use for automatic
717 ;; indentation (default: `markdown-indent-line').
719 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
720 ;; automatically indent new lines when `RET` is pressed.
721 ;; Set to `indent-and-new-item' to additionally continue lists
722 ;; when `RET` is pressed (default: `t').
724 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
725 ;; links (default: `nil'). Set this to a non-nil value to turn on
726 ;; wiki link support by default. Wiki link support can be toggled
727 ;; later using the function `markdown-toggle-wiki-links'."
729 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
730 ;; treat aliased wiki links like `[[link text|PageName]]`
731 ;; (default: `t'). When set to nil, they will be treated as
732 ;; `[[PageName|link text]]'.
734 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
735 ;; for URIs that `markdown-mode' should highlight.
737 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
738 ;; math expressions (default: `nil'). Set this to `t' to turn on
739 ;; math support by default. Math support can be toggled
740 ;; interactively later using `C-c C-x C-e`
741 ;; (`markdown-toggle-math').
743 ;; * `markdown-enable-html' - font lock for HTML tags and attributes
744 ;; (default: `t').
746 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
747 ;; (default: `nil`).
749 ;; * `markdown-content-type' - when set to a nonempty string, an
750 ;; `http-equiv` attribute will be included in the XHTML `<head>`
751 ;; block (default: `""`). If needed, the suggested values are
752 ;; `application/xhtml+xml` or `text/html`. See also:
753 ;; `markdown-coding-system'.
755 ;; * `markdown-coding-system' - used for specifying the character
756 ;; set identifier in the `http-equiv` attribute when included
757 ;; (default: `nil'). See `markdown-content-type', which must
758 ;; be set before this variable has any effect. When set to `nil',
759 ;; `buffer-file-coding-system' will be used to automatically
760 ;; determine the coding system string (falling back to
761 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
762 ;; and `iso-latin-1'.
764 ;; * `markdown-xhtml-header-content' - additional content to include
765 ;; in the XHTML `<head>` block (default: `""`).
767 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
768 ;; `markdown-mode' uses to determine whether the output of
769 ;; `markdown-command' is a standalone XHTML document or an XHTML
770 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
771 ;; this regular expression not matched in the first five lines of
772 ;; output, `markdown-mode' assumes the output is a fragment and
773 ;; adds a header and footer.
775 ;; * `markdown-link-space-sub-char' - a character to replace spaces
776 ;; when mapping wiki links to filenames (default: `"_"`).
777 ;; For example, use an underscore for compatibility with the
778 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
779 ;; set to `"-"` to conform with GitHub wiki links.
781 ;; * `markdown-reference-location' - where to insert reference
782 ;; definitions (default: `header`). The possible locations are
783 ;; the end of the document (`end`), after the current block
784 ;; (`immediately`), the end of the current subtree (`subtree'),
785 ;; or before the next header (`header`).
787 ;; * `markdown-footnote-location' - where to insert footnote text
788 ;; (default: `end`). The set of location options is the same as
789 ;; for `markdown-reference-location'.
791 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
792 ;; heading instead of a flat index (default: `t'). A nested
793 ;; index may provide more natural browsing from the menu, but a
794 ;; flat list may allow for faster keyboard navigation via tab
795 ;; completion.
797 ;; * `comment-auto-fill-only-comments' - variable is made
798 ;; buffer-local and set to `nil' by default. In programming
799 ;; language modes, when this variable is non-nil, only comments
800 ;; will be filled by auto-fill-mode. However, comments in
801 ;; Markdown documents are rare and the most users probably intend
802 ;; for the actual content of the document to be filled. Making
803 ;; this variable buffer-local allows `markdown-mode' to override
804 ;; the default behavior induced when the global variable is non-nil.
806 ;; * `markdown-gfm-additional-languages', - additional languages to
807 ;; make available, aside from those predefined in
808 ;; `markdown-gfm-recognized-languages', when inserting GFM code
809 ;; blocks (default: `nil`). Language strings must have be trimmed
810 ;; of whitespace and not contain any curly braces. They may be of
811 ;; arbitrary capitalization, though.
813 ;; * `markdown-gfm-use-electric-backquote' - use
814 ;; `markdown-electric-backquote' for interactive insertion of GFM
815 ;; code blocks when backquote is pressed three times (default: `t`).
817 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
818 ;; Flavored Markdown style task lists (checkboxes) should be
819 ;; turned into buttons that can be toggled with mouse-1 or RET. If
820 ;; non-nil (default), then buttons are enabled. This works in
821 ;; `markdown-mode' as well as `gfm-mode'.
823 ;; * `markdown-hide-urls' - Determines whether URL and reference
824 ;; labels are hidden for inline and reference links (default: `nil').
825 ;; When non-nil, inline links will appear in the buffer as
826 ;; `[link](∞)` instead of
827 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
828 ;; placeholder (composition) character used, set the variable
829 ;; `markdown-url-compose-char'. URL hiding can be toggled
830 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
831 ;; or from the Markdown | Links & Images menu.
833 ;; * `markdown-hide-markup' - Determines whether all possible markup
834 ;; is hidden or otherwise beautified (default: `nil'). The actual
835 ;; buffer text remains unchanged, but the display will be altered.
836 ;; Brackets and URLs for links will be hidden, asterisks and
837 ;; underscores for italic and bold text will be hidden, text
838 ;; bullets for unordered lists will be replaced by Unicode
839 ;; bullets, and so on. Since this includes URLs and reference
840 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
841 ;; Markup hiding can be toggled using `C-c C-x C-m`
842 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
843 ;; Hide menu.
845 ;; Unicode bullets are used to replace ASCII list item markers.
846 ;; The list of characters used, in order of list level, can be
847 ;; specified by setting the variable `markdown-list-item-bullets'.
848 ;; The placeholder characters used to replace other markup can
849 ;; be changed by customizing the corresponding variables:
850 ;; `markdown-blockquote-display-char',
851 ;; `markdown-hr-display-char', and
852 ;; `markdown-definition-display-char'.
854 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
855 ;; code in code blocks using the native major mode. This only
856 ;; works for fenced code blocks where the language is specified
857 ;; where we can automatically determine the appropriate mode to
858 ;; use. The language to mode mapping may be customized by setting
859 ;; the variable `markdown-code-lang-modes'. This can be toggled
860 ;; interactively by pressing `C-c C-x C-f`
861 ;; (`markdown-toggle-fontify-code-blocks-natively').
863 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
864 ;; task list items with `[X]` instead of `[x]` (default: `nil').
865 ;; This is useful for compatibility with `org-mode', which doesn't
866 ;; recognize the lowercase variant.
868 ;; * `markdown-translate-filename-function' - A function to be used to
869 ;; translate filenames in links.
871 ;; Additionally, the faces used for syntax highlighting can be modified to
872 ;; your liking by issuing `M-x customize-group RET markdown-faces`
873 ;; or by using the "Markdown Faces" link at the bottom of the mode
874 ;; customization screen.
876 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
878 ;;; Extensions:
880 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
881 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
882 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
883 ;; Wiki links may be followed by pressing `C-c C-o` when the point
884 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
885 ;; previous and next links (including links of other types).
886 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
887 ;; are also supported. Since some wikis reverse these components, set
888 ;; `markdown-wiki-link-alias-first' to nil to treat them as
889 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
890 ;; is also non-nil, Markdown Mode will highlight wiki links with
891 ;; missing target file in a different color. By default, Markdown
892 ;; Mode only searches for target files in the current directory.
893 ;; Search in subdirectories can be enabled by setting
894 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
895 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
896 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
897 ;; to a non-nil value.
899 ;; [Ikiwiki]: https://ikiwiki.info
901 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
902 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
903 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
904 ;; You can do this either by using `M-x customize-group markdown`
905 ;; or by placing the following in your `.emacs` file:
907 ;; ``` Lisp
908 ;; (setq markdown-command "markdown | smartypants")
909 ;; ```
911 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
913 ;; Syntax highlighting for mathematical expressions written
914 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
915 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
916 ;; either via customize or by placing `(setq markdown-enable-math t)`
917 ;; in `.emacs`, and then restarting Emacs or calling
918 ;; `markdown-reload-extensions'.
920 ;;; GitHub Flavored Markdown (GFM):
922 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
923 ;; available. The GitHub implementation differs slightly from
924 ;; standard Markdown in that it supports things like different
925 ;; behavior for underscores inside of words, automatic linking of
926 ;; URLs, strikethrough text, and fenced code blocks with an optional
927 ;; language keyword.
929 ;; The GFM-specific features above apply to `README.md` files, wiki
930 ;; pages, and other Markdown-formatted files in repositories on
931 ;; GitHub. GitHub also enables [additional features][GFM comments] for
932 ;; writing on the site (for issues, pull requests, messages, etc.)
933 ;; that are further extensions of GFM. These features include task
934 ;; lists (checkboxes), newlines corresponding to hard line breaks,
935 ;; auto-linked references to issues and commits, wiki links, and so
936 ;; on. To make matters more confusing, although task lists are not
937 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
938 ;; read-only fashion) in all Markdown documents in repositories on the
939 ;; site. These additional extensions are supported to varying degrees
940 ;; by `markdown-mode' and `gfm-mode' as described below.
942 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
943 ;; highlighting of URLs without angle brackets.
945 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
946 ;; toggle support for underscores inside of words. In this mode
947 ;; variable names such as `a_test_variable` will not trigger
948 ;; emphasis (italics).
950 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
951 ;; optional programming language keywords, are highlighted in
952 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
953 ;; `C-c C-s C`. If there is an active region, the text in the
954 ;; region will be placed inside the code block. You will be
955 ;; prompted for the name of the language, but may press enter to
956 ;; continue without naming a language.
958 ;; * **Strikethrough:** Strikethrough text is supported in both
959 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
960 ;; using `C-c C-s s`.
962 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
963 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
964 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
965 ;; (and it is set to t by default). These checkboxes can be
966 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
967 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
968 ;; in the task list item. A normal list item can be turned to a
969 ;; check list item by the same command, or more specifically
970 ;; `C-c C-s [` (`markdown-insert-gfm-checkbox`).
972 ;; * **Wiki links:** Generic wiki links are supported in
973 ;; `markdown-mode', but in `gfm-mode' specifically they will be
974 ;; treated as they are on GitHub: spaces will be replaced by hyphens
975 ;; in filenames and the first letter of the filename will be
976 ;; capitalized. For example, `[[wiki link]]' will map to a file
977 ;; named `Wiki-link` with the same extension as the current file.
978 ;; If a file with this name does not exist in the current directory,
979 ;; the first match in a subdirectory, if any, will be used instead.
981 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
982 ;; specifically with respect to newline behavior. If you use
983 ;; `gfm-mode' mostly to write text for comments or issues on the
984 ;; GitHub site--where newlines are significant and correspond to
985 ;; hard line breaks--then you may want to enable `visual-line-mode'
986 ;; for line wrapping in buffers. You can do this with a
987 ;; `gfm-mode-hook' as follows:
989 ;; ``` Lisp
990 ;; ;; Use visual-line-mode in gfm-mode
991 ;; (defun my-gfm-mode-hook ()
992 ;; (visual-line-mode 1))
993 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
994 ;; ```
996 ;; * **Preview:** GFM-specific preview can be powered by setting
997 ;; `markdown-command' to use [Docter][]. This may also be
998 ;; configured to work with [Marked 2][] for `markdown-open-command'.
1000 ;; [GFM]: http://github.github.com/github-flavored-markdown/
1001 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
1002 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
1003 ;; [Docter]: https://github.com/alampros/Docter
1005 ;;; Acknowledgments:
1007 ;; markdown-mode has benefited greatly from the efforts of the many
1008 ;; volunteers who have sent patches, test cases, bug reports,
1009 ;; suggestions, helped with packaging, etc. Thank you for your
1010 ;; contributions! See the [contributors graph][contrib] for details.
1012 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
1014 ;;; Bugs:
1016 ;; markdown-mode is developed and tested primarily for compatibility
1017 ;; with GNU Emacs 24.3 and later. If you find any bugs in
1018 ;; markdown-mode, please construct a test case or a patch and open a
1019 ;; ticket on the [GitHub issue tracker][issues]. See the
1020 ;; contributing guidelines in `CONTRIBUTING.md` for details on
1021 ;; creating pull requests.
1023 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
1025 ;;; History:
1027 ;; markdown-mode was written and is maintained by Jason Blevins. The
1028 ;; first version was released on May 24, 2007.
1030 ;; * 2007-05-24: [Version 1.1][]
1031 ;; * 2007-05-25: [Version 1.2][]
1032 ;; * 2007-06-05: [Version 1.3][]
1033 ;; * 2007-06-29: [Version 1.4][]
1034 ;; * 2007-10-11: [Version 1.5][]
1035 ;; * 2008-06-04: [Version 1.6][]
1036 ;; * 2009-10-01: [Version 1.7][]
1037 ;; * 2011-08-12: [Version 1.8][]
1038 ;; * 2011-08-15: [Version 1.8.1][]
1039 ;; * 2013-01-25: [Version 1.9][]
1040 ;; * 2013-03-24: [Version 2.0][]
1041 ;; * 2016-01-09: [Version 2.1][]
1042 ;; * 2017-05-26: [Version 2.2][]
1043 ;; * 2017-08-31: [Version 2.3][]
1045 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
1046 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
1047 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
1048 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
1049 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
1050 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
1051 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
1052 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
1053 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
1054 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
1055 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
1056 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
1057 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
1058 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
1061 ;;; Code:
1063 (require 'easymenu)
1064 (require 'outline)
1065 (require 'thingatpt)
1066 (require 'cl-lib)
1067 (require 'url-parse)
1068 (require 'button)
1069 (require 'color)
1070 (require 'rx)
1072 (defvar jit-lock-start)
1073 (defvar jit-lock-end)
1074 (defvar flyspell-generic-check-word-predicate)
1076 (declare-function eww-open-file "eww")
1077 (declare-function url-path-and-query "url-parse")
1080 ;;; Constants =================================================================
1082 (defconst markdown-mode-version "2.4-dev"
1083 "Markdown mode version number.")
1085 (defconst markdown-output-buffer-name "*markdown-output*"
1086 "Name of temporary buffer for markdown command output.")
1088 (defconst markdown-sub-superscript-display
1089 '(((raise -0.3) (height 0.7)) ; subscript
1090 ((raise 0.3) (height 0.7))) ; superscript
1091 "Parameters for sub- and superscript formatting.")
1094 ;;; Global Variables ==========================================================
1096 (defvar markdown-reference-label-history nil
1097 "History of used reference labels.")
1099 (defvar markdown-live-preview-mode nil
1100 "Sentinel variable for command `markdown-live-preview-mode'.")
1102 (defvar markdown-gfm-language-history nil
1103 "History list of languages used in the current buffer in GFM code blocks.")
1106 ;;; Customizable Variables ====================================================
1108 (defvar markdown-mode-hook nil
1109 "Hook run when entering Markdown mode.")
1111 (defvar markdown-before-export-hook nil
1112 "Hook run before running Markdown to export XHTML output.
1113 The hook may modify the buffer, which will be restored to it's
1114 original state after exporting is complete.")
1116 (defvar markdown-after-export-hook nil
1117 "Hook run after XHTML output has been saved.
1118 Any changes to the output buffer made by this hook will be saved.")
1120 (defgroup markdown nil
1121 "Major mode for editing text files in Markdown format."
1122 :prefix "markdown-"
1123 :group 'wp
1124 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1126 (defcustom markdown-command "markdown"
1127 "Command to run markdown."
1128 :group 'markdown
1129 :type '(choice (string :tag "Shell command") function))
1131 (defcustom markdown-command-needs-filename nil
1132 "Set to non-nil if `markdown-command' does not accept input from stdin.
1133 Instead, it will be passed a filename as the final command line
1134 option. As a result, you will only be able to run Markdown from
1135 buffers which are visiting a file."
1136 :group 'markdown
1137 :type 'boolean)
1139 (defcustom markdown-open-command nil
1140 "Command used for opening Markdown files directly.
1141 For example, a standalone Markdown previewer. This command will
1142 be called with a single argument: the filename of the current
1143 buffer. It can also be a function, which will be called without
1144 arguments."
1145 :group 'markdown
1146 :type '(choice file function (const :tag "None" nil)))
1148 (defcustom markdown-hr-strings
1149 '("-------------------------------------------------------------------------------"
1150 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1151 "---------------------------------------"
1152 "* * * * * * * * * * * * * * * * * * * *"
1153 "---------"
1154 "* * * * *")
1155 "Strings to use when inserting horizontal rules.
1156 The first string in the list will be the default when inserting a
1157 horizontal rule. Strings should be listed in decreasing order of
1158 prominence (as in headings from level one to six) for use with
1159 promotion and demotion functions."
1160 :group 'markdown
1161 :type '(repeat string))
1163 (defcustom markdown-bold-underscore nil
1164 "Use two underscores when inserting bold text instead of two asterisks."
1165 :group 'markdown
1166 :type 'boolean)
1168 (defcustom markdown-italic-underscore nil
1169 "Use underscores when inserting italic text instead of asterisks."
1170 :group 'markdown
1171 :type 'boolean)
1173 (defcustom markdown-marginalize-headers nil
1174 "When non-nil, put opening atx header markup in a left margin.
1176 This setting goes well with `markdown-asymmetric-header'. But
1177 sadly it conflicts with `linum-mode' since they both use the
1178 same margin."
1179 :group 'markdown
1180 :type 'boolean
1181 :safe 'booleanp
1182 :package-version '(markdown-mode . "2.4"))
1184 (defcustom markdown-marginalize-headers-margin-width 6
1185 "Character width of margin used for marginalized headers.
1186 The default value is based on there being six heading levels
1187 defined by Markdown and HTML. Increasing this produces extra
1188 whitespace on the left. Decreasing it may be preferred when
1189 fewer than six nested heading levels are used."
1190 :group 'markdown
1191 :type 'natnump
1192 :safe 'natnump
1193 :package-version '(markdown-mode . "2.4"))
1195 (defcustom markdown-asymmetric-header nil
1196 "Determines if atx header style will be asymmetric.
1197 Set to a non-nil value to use asymmetric header styling, placing
1198 header markup only at the beginning of the line. By default,
1199 balanced markup will be inserted at the beginning and end of the
1200 line around the header title."
1201 :group 'markdown
1202 :type 'boolean)
1204 (defcustom markdown-indent-function 'markdown-indent-line
1205 "Function to use to indent."
1206 :group 'markdown
1207 :type 'function)
1209 (defcustom markdown-indent-on-enter t
1210 "Determines indentation behavior when pressing \\[newline].
1211 Possible settings are nil, t, and 'indent-and-new-item.
1213 When non-nil, pressing \\[newline] will call `newline-and-indent'
1214 to indent the following line according to the context using
1215 `markdown-indent-function'. In this case, note that
1216 \\[electric-newline-and-maybe-indent] can still be used to insert
1217 a newline without indentation.
1219 When set to 'indent-and-new-item and the point is in a list item
1220 when \\[newline] is pressed, the list will be continued on the next
1221 line, where a new item will be inserted.
1223 When set to nil, simply call `newline' as usual. In this case,
1224 you can still indent lines using \\[markdown-cycle] and continue
1225 lists with \\[markdown-insert-list-item].
1227 Note that this assumes the variable `electric-indent-mode' is
1228 non-nil (enabled). When it is *disabled*, the behavior of
1229 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1230 reversed."
1231 :group 'markdown
1232 :type '(choice (const :tag "Don't automatically indent" nil)
1233 (const :tag "Automatically indent" t)
1234 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1236 (defcustom markdown-enable-wiki-links nil
1237 "Syntax highlighting for wiki links.
1238 Set this to a non-nil value to turn on wiki link support by default.
1239 Support can be toggled later using the `markdown-toggle-wiki-links'
1240 function or \\[markdown-toggle-wiki-links]."
1241 :group 'markdown
1242 :type 'boolean
1243 :safe 'booleanp
1244 :package-version '(markdown-mode . "2.2"))
1246 (defcustom markdown-wiki-link-alias-first t
1247 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1248 Otherwise, they will be treated as [[PageName|alias text]]."
1249 :group 'markdown
1250 :type 'boolean
1251 :safe 'booleanp)
1253 (defcustom markdown-wiki-link-search-subdirectories nil
1254 "When non-nil, search for wiki link targets in subdirectories.
1255 This is the default search behavior for GitHub and is
1256 automatically set to t in `gfm-mode'."
1257 :group 'markdown
1258 :type 'boolean
1259 :safe 'booleanp
1260 :package-version '(markdown-mode . "2.2"))
1262 (defcustom markdown-wiki-link-search-parent-directories nil
1263 "When non-nil, search for wiki link targets in parent directories.
1264 This is the default search behavior of Ikiwiki."
1265 :group 'markdown
1266 :type 'boolean
1267 :safe 'booleanp
1268 :package-version '(markdown-mode . "2.2"))
1270 (defcustom markdown-wiki-link-fontify-missing nil
1271 "When non-nil, change wiki link face according to existence of target files.
1272 This is expensive because it requires checking for the file each time the buffer
1273 changes or the user switches windows. It is disabled by default because it may
1274 cause lag when typing on slower machines."
1275 :group 'markdown
1276 :type 'boolean
1277 :safe 'booleanp
1278 :package-version '(markdown-mode . "2.2"))
1280 (defcustom markdown-uri-types
1281 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1282 "gopher" "http" "https" "imap" "ldap" "mailto"
1283 "mid" "message" "modem" "news" "nfs" "nntp"
1284 "pop" "prospero" "rtsp" "service" "sip" "tel"
1285 "telnet" "tip" "urn" "vemmi" "wais")
1286 "Link types for syntax highlighting of URIs."
1287 :group 'markdown
1288 :type '(repeat (string :tag "URI scheme")))
1290 (defcustom markdown-url-compose-char
1291 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
1292 "Placeholder character for hidden URLs.
1293 This may be a single character or a list of characters. In case
1294 of a list, the first one that satisfies `char-displayable-p' will
1295 be used."
1296 :type '(choice
1297 (character :tag "Single URL replacement character")
1298 (repeat :tag "List of possible URL replacement characters"
1299 character))
1300 :package-version '(markdown-mode . "2.3"))
1302 (defcustom markdown-blockquote-display-char
1303 '("▌" "┃" ">")
1304 "String to display when hiding blockquote markup.
1305 This may be a single string or a list of string. In case of a
1306 list, the first one that satisfies `char-displayable-p' will be
1307 used."
1308 :type 'string
1309 :type '(choice
1310 (string :tag "Single blockquote display string")
1311 (repeat :tag "List of possible blockquote display strings" string))
1312 :package-version '(markdown-mode . "2.3"))
1314 (defcustom markdown-hr-display-char
1315 '(?─ ?━ ?-)
1316 "Character for hiding horizontal rule markup.
1317 This may be a single character or a list of characters. In case
1318 of a list, the first one that satisfies `char-displayable-p' will
1319 be used."
1320 :group 'markdown
1321 :type '(choice
1322 (character :tag "Single HR display character")
1323 (repeat :tag "List of possible HR display characters" character))
1324 :package-version '(markdown-mode . "2.3"))
1326 (defcustom markdown-definition-display-char
1327 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
1328 "Character for replacing definition list markup.
1329 This may be a single character or a list of characters. In case
1330 of a list, the first one that satisfies `char-displayable-p' will
1331 be used."
1332 :type '(choice
1333 (character :tag "Single definition list character")
1334 (repeat :tag "List of possible definition list characters" character))
1335 :package-version '(markdown-mode . "2.3"))
1337 (defcustom markdown-enable-math nil
1338 "Syntax highlighting for inline LaTeX and itex expressions.
1339 Set this to a non-nil value to turn on math support by default.
1340 Math support can be enabled, disabled, or toggled later using
1341 `markdown-toggle-math' or \\[markdown-toggle-math]."
1342 :group 'markdown
1343 :type 'boolean
1344 :safe 'booleanp)
1345 (make-variable-buffer-local 'markdown-enable-math)
1347 (defcustom markdown-enable-html t
1348 "Enable font-lock support for HTML tags and attributes."
1349 :group 'markdown
1350 :type 'boolean
1351 :safe 'booleanp
1352 :package-version '(markdown-mode . "2.4"))
1354 (defcustom markdown-css-paths nil
1355 "URL of CSS file to link to in the output XHTML."
1356 :group 'markdown
1357 :type '(repeat (string :tag "CSS File Path")))
1359 (defcustom markdown-content-type ""
1360 "Content type string for the http-equiv header in XHTML output.
1361 When set to a non-empty string, insert the http-equiv attribute.
1362 Otherwise, this attribute is omitted."
1363 :group 'markdown
1364 :type 'string)
1366 (defcustom markdown-coding-system nil
1367 "Character set string for the http-equiv header in XHTML output.
1368 Defaults to `buffer-file-coding-system' (and falling back to
1369 `iso-8859-1' when not available). Common settings are `utf-8'
1370 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1371 :group 'markdown
1372 :type 'coding-system)
1374 (defcustom markdown-export-kill-buffer t
1375 "Kill output buffer after HTML export.
1376 When non-nil, kill the HTML output buffer after
1377 exporting with `markdown-export'."
1378 :group 'markdown
1379 :type 'boolean
1380 :safe 'booleanp
1381 :package-version '(markdown-mode . "2.4"))
1383 (defcustom markdown-xhtml-header-content ""
1384 "Additional content to include in the XHTML <head> block."
1385 :group 'markdown
1386 :type 'string)
1388 (defcustom markdown-xhtml-standalone-regexp
1389 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1390 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1391 :group 'markdown
1392 :type 'regexp)
1394 (defcustom markdown-link-space-sub-char "_"
1395 "Character to use instead of spaces when mapping wiki links to filenames."
1396 :group 'markdown
1397 :type 'string)
1399 (defcustom markdown-reference-location 'header
1400 "Position where new reference definitions are inserted in the document."
1401 :group 'markdown
1402 :type '(choice (const :tag "At the end of the document" end)
1403 (const :tag "Immediately after the current block" immediately)
1404 (const :tag "At the end of the subtree" subtree)
1405 (const :tag "Before next header" header)))
1407 (defcustom markdown-footnote-location 'end
1408 "Position where new footnotes are inserted in the document."
1409 :group 'markdown
1410 :type '(choice (const :tag "At the end of the document" end)
1411 (const :tag "Immediately after the current block" immediately)
1412 (const :tag "At the end of the subtree" subtree)
1413 (const :tag "Before next header" header)))
1415 (defcustom markdown-unordered-list-item-prefix " * "
1416 "String inserted before unordered list items."
1417 :group 'markdown
1418 :type 'string)
1420 (defcustom markdown-nested-imenu-heading-index t
1421 "Use nested or flat imenu heading index.
1422 A nested index may provide more natural browsing from the menu,
1423 but a flat list may allow for faster keyboard navigation via tab
1424 completion."
1425 :group 'markdown
1426 :type 'boolean
1427 :safe 'booleanp
1428 :package-version '(markdown-mode . "2.2"))
1430 (defcustom markdown-make-gfm-checkboxes-buttons t
1431 "When non-nil, make GFM checkboxes into buttons."
1432 :group 'markdown
1433 :type 'boolean)
1435 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1436 "When non-nil, allow YAML metadata anywhere in the document."
1437 :group 'markdown
1438 :type 'boolean)
1440 (defcustom markdown-split-window-direction 'any
1441 "Preference for splitting windows for static and live preview.
1442 The default value is 'any, which instructs Emacs to use
1443 `split-window-sensibly' to automatically choose how to split
1444 windows based on the values of `split-width-threshold' and
1445 `split-height-threshold' and the available windows. To force
1446 vertically split (left and right) windows, set this to 'vertical
1447 or 'right. To force horizontally split (top and bottom) windows,
1448 set this to 'horizontal or 'below."
1449 :group 'markdown
1450 :type '(choice (const :tag "Automatic" any)
1451 (const :tag "Right (vertical)" right)
1452 (const :tag "Below (horizontal)" below))
1453 :package-version '(markdown-mode . "2.2"))
1455 (defcustom markdown-live-preview-window-function
1456 'markdown-live-preview-window-eww
1457 "Function to display preview of Markdown output within Emacs.
1458 Function must update the buffer containing the preview and return
1459 the buffer."
1460 :group 'markdown
1461 :type 'function)
1463 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1464 "Delete exported HTML file when using `markdown-live-preview-export'.
1465 If set to 'delete-on-export, delete on every export. When set to
1466 'delete-on-destroy delete when quitting from command
1467 `markdown-live-preview-mode'. Never delete if set to nil."
1468 :group 'markdown
1469 :type '(choice
1470 (const :tag "Delete on every export" delete-on-export)
1471 (const :tag "Delete when quitting live preview" delete-on-destroy)
1472 (const :tag "Never delete" nil)))
1474 (defcustom markdown-list-indent-width 4
1475 "Depth of indentation for markdown lists.
1476 Used in `markdown-demote-list-item' and
1477 `markdown-promote-list-item'."
1478 :group 'markdown
1479 :type 'integer)
1481 (defcustom markdown-enable-prefix-prompts t
1482 "Display prompts for certain prefix commands.
1483 Set to nil to disable these prompts."
1484 :group 'markdown
1485 :type 'boolean
1486 :safe 'booleanp
1487 :package-version '(markdown-mode . "2.3"))
1489 (defcustom markdown-gfm-additional-languages nil
1490 "Extra languages made available when inserting GFM code blocks.
1491 Language strings must have be trimmed of whitespace and not
1492 contain any curly braces. They may be of arbitrary
1493 capitalization, though."
1494 :group 'markdown
1495 :type '(repeat (string :validate markdown-validate-language-string)))
1497 (defcustom markdown-gfm-use-electric-backquote t
1498 "Use `markdown-electric-backquote' when backquote is hit three times."
1499 :group 'markdown
1500 :type 'boolean)
1502 (defcustom markdown-gfm-downcase-languages t
1503 "If non-nil, downcase suggested languages.
1504 This applies to insertions done with
1505 `markdown-electric-backquote'."
1506 :group 'markdown
1507 :type 'boolean)
1509 (defcustom markdown-edit-code-block-default-mode 'normal-mode
1510 "Default mode to use for editing code blocks.
1511 This mode is used when automatic detection fails, such as for GFM
1512 code blocks with no language specified."
1513 :group 'markdown
1514 :type 'symbol
1515 :package-version '(markdown-mode . "2.4"))
1517 (defcustom markdown-gfm-uppercase-checkbox nil
1518 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1519 :group 'markdown
1520 :type 'boolean
1521 :safe 'booleanp)
1523 (defcustom markdown-hide-urls nil
1524 "Hide URLs of inline links and reference tags of reference links.
1525 Such URLs will be replaced by a single customizable
1526 character, defined by `markdown-url-compose-char', but are still part
1527 of the buffer. Links can be edited interactively with
1528 \\[markdown-insert-link] or, for example, by deleting the final
1529 parenthesis to remove the invisibility property. You can also
1530 hover your mouse pointer over the link text to see the URL.
1531 Set this to a non-nil value to turn this feature on by default.
1532 You can interactively set the value of this variable by calling
1533 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1534 or from the menu Markdown > Links & Images menu."
1535 :group 'markdown
1536 :type 'boolean
1537 :safe 'booleanp
1538 :package-version '(markdown-mode . "2.3"))
1539 (make-variable-buffer-local 'markdown-hide-urls)
1541 (defcustom markdown-translate-filename-function #'identity
1542 "Function to use to translate filenames when following links.
1543 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1544 call this function with the filename as only argument whenever
1545 they encounter a filename (instead of a URL) to be visited and
1546 use its return value instead of the filename in the link. For
1547 example, if absolute filenames are actually relative to a server
1548 root directory, you can set
1549 `markdown-translate-filename-function' to a function that
1550 prepends the root directory to the given filename."
1551 :group 'markdown
1552 :type 'function
1553 :risky t
1554 :package-version '(markdown-mode . "2.4"))
1557 ;;; Regular Expressions =======================================================
1559 (defconst markdown-regex-comment-start
1560 "<!--"
1561 "Regular expression matches HTML comment opening.")
1563 (defconst markdown-regex-comment-end
1564 "--[ \t]*>"
1565 "Regular expression matches HTML comment closing.")
1567 (defconst markdown-regex-link-inline
1568 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1569 "Regular expression for a [text](file) or an image link ![text](file).
1570 Group 1 matches the leading exclamation point (optional).
1571 Group 2 matches the opening square bracket.
1572 Group 3 matches the text inside the square brackets.
1573 Group 4 matches the closing square bracket.
1574 Group 5 matches the opening parenthesis.
1575 Group 6 matches the URL.
1576 Group 7 matches the title (optional).
1577 Group 8 matches the closing parenthesis.")
1579 (defconst markdown-regex-link-reference
1580 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1581 "Regular expression for a reference link [text][id].
1582 Group 1 matches the leading exclamation point (optional).
1583 Group 2 matches the opening square bracket for the link text.
1584 Group 3 matches the text inside the square brackets.
1585 Group 4 matches the closing square bracket for the link text.
1586 Group 5 matches the opening square bracket for the reference label.
1587 Group 6 matches the reference label.
1588 Group 7 matches the closing square bracket for the reference label.")
1590 (defconst markdown-regex-reference-definition
1591 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1592 "Regular expression for a reference definition.
1593 Group 1 matches the opening square bracket.
1594 Group 2 matches the reference label.
1595 Group 3 matches the closing square bracket.
1596 Group 4 matches the colon.
1597 Group 5 matches the URL.
1598 Group 6 matches the title attribute (optional).")
1600 (defconst markdown-regex-footnote
1601 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1602 "Regular expression for a footnote marker [^fn].
1603 Group 1 matches the opening square bracket and carat.
1604 Group 2 matches only the label, without the surrounding markup.
1605 Group 3 matches the closing square bracket.")
1607 (defconst markdown-regex-header
1608 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1609 "Regexp identifying Markdown headings.
1610 Group 1 matches the text of a setext heading.
1611 Group 2 matches the underline of a level-1 setext heading.
1612 Group 3 matches the underline of a level-2 setext heading.
1613 Group 4 matches the opening hash marks of an atx heading and whitespace.
1614 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1615 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1617 (defconst markdown-regex-header-setext
1618 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1619 "Regular expression for generic setext-style (underline) headers.")
1621 (defconst markdown-regex-header-atx
1622 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1623 "Regular expression for generic atx-style (hash mark) headers.")
1625 (defconst markdown-regex-hr
1626 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1627 "Regular expression for matching Markdown horizontal rules.")
1629 (defconst markdown-regex-code
1630 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1631 "Regular expression for matching inline code fragments.
1633 Group 1 matches the entire code fragment including the backquotes.
1634 Group 2 matches the opening backquotes.
1635 Group 3 matches the code fragment itself, without backquotes.
1636 Group 4 matches the closing backquotes.
1638 The leading, unnumbered group ensures that the leading backquote
1639 character is not escaped.
1640 The last group, also unnumbered, requires that the character
1641 following the code fragment is not a backquote.
1642 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1643 but not two newlines in a row.")
1645 (defconst markdown-regex-kbd
1646 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1647 "Regular expression for matching <kbd> tags.
1648 Groups 1 and 3 match the opening and closing tags.
1649 Group 2 matches the key sequence.")
1651 (defconst markdown-regex-gfm-code-block-open
1652 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1653 "Regular expression matching opening of GFM code blocks.
1654 Group 1 matches the opening three backquotes and any following whitespace.
1655 Group 2 matches the opening brace (optional) and surrounding whitespace.
1656 Group 3 matches the language identifier (optional).
1657 Group 4 matches the info string (optional).
1658 Group 5 matches the closing brace (optional), whitespace, and newline.
1659 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1661 (defconst markdown-regex-gfm-code-block-close
1662 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1663 "Regular expression matching closing of GFM code blocks.
1664 Group 1 matches the closing three backquotes.
1665 Group 2 matches any whitespace and the final newline.")
1667 (defconst markdown-regex-pre
1668 "^\\( \\|\t\\).*$"
1669 "Regular expression for matching preformatted text sections.")
1671 (defconst markdown-regex-list
1672 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1673 "Regular expression for matching list items.")
1675 (defconst markdown-regex-bold
1676 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1677 "Regular expression for matching bold text.
1678 Group 1 matches the character before the opening asterisk or
1679 underscore, if any, ensuring that it is not a backslash escape.
1680 Group 2 matches the entire expression, including delimiters.
1681 Groups 3 and 5 matches the opening and closing delimiters.
1682 Group 4 matches the text inside the delimiters.")
1684 (defconst markdown-regex-italic
1685 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1686 "Regular expression for matching italic text.
1687 The leading unnumbered matches the character before the opening
1688 asterisk or underscore, if any, ensuring that it is not a
1689 backslash escape.
1690 Group 1 matches the entire expression, including delimiters.
1691 Groups 2 and 4 matches the opening and closing delimiters.
1692 Group 3 matches the text inside the delimiters.")
1694 (defconst markdown-regex-strike-through
1695 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1696 "Regular expression for matching strike-through text.
1697 Group 1 matches the character before the opening tilde, if any,
1698 ensuring that it is not a backslash escape.
1699 Group 2 matches the entire expression, including delimiters.
1700 Groups 3 and 5 matches the opening and closing delimiters.
1701 Group 4 matches the text inside the delimiters.")
1703 (defconst markdown-regex-gfm-italic
1704 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1705 "Regular expression for matching italic text in GitHub Flavored Markdown.
1706 Underscores in words are not treated as special.
1707 Group 1 matches the entire expression, including delimiters.
1708 Groups 2 and 4 matches the opening and closing delimiters.
1709 Group 3 matches the text inside the delimiters.")
1711 (defconst markdown-regex-blockquote
1712 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1713 "Regular expression for matching blockquote lines.
1714 Also accounts for a potential capital letter preceding the angle
1715 bracket, for use with Leanpub blocks (asides, warnings, info
1716 blocks, etc.).
1717 Group 1 matches the leading angle bracket.
1718 Group 2 matches the separating whitespace.
1719 Group 3 matches the text.")
1721 (defconst markdown-regex-line-break
1722 "[^ \n\t][ \t]*\\( \\)$"
1723 "Regular expression for matching line breaks.")
1725 (defconst markdown-regex-wiki-link
1726 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1727 "Regular expression for matching wiki links.
1728 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1729 wiki links of the form [[PageName|link text]].
1730 The meanings of the first and second components depend
1731 on the value of `markdown-wiki-link-alias-first'.
1733 Group 1 matches the entire link.
1734 Group 2 matches the opening square brackets.
1735 Group 3 matches the first component of the wiki link.
1736 Group 4 matches the pipe separator, when present.
1737 Group 5 matches the second component of the wiki link, when present.
1738 Group 6 matches the closing square brackets.")
1740 (defconst markdown-regex-uri
1741 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1742 "Regular expression for matching inline URIs.")
1744 (defconst markdown-regex-angle-uri
1745 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1746 "Regular expression for matching inline URIs in angle brackets.")
1748 (defconst markdown-regex-email
1749 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1750 "Regular expression for matching inline email addresses.")
1752 (defsubst markdown-make-regex-link-generic ()
1753 "Make regular expression for matching any recognized link."
1754 (concat "\\(?:" markdown-regex-link-inline
1755 (when markdown-enable-wiki-links
1756 (concat "\\|" markdown-regex-wiki-link))
1757 "\\|" markdown-regex-link-reference
1758 "\\|" markdown-regex-angle-uri "\\)"))
1760 (defconst markdown-regex-gfm-checkbox
1761 " \\(\\[[ xX]\\]\\) "
1762 "Regular expression for matching GFM checkboxes.
1763 Group 1 matches the text to become a button.")
1765 (defconst markdown-regex-block-separator
1766 "\n[\n\t\f ]*\n"
1767 "Regular expression for matching block boundaries.")
1769 (defconst markdown-regex-block-separator-noindent
1770 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1771 "Regexp for block separators before lines with no indentation.")
1773 (defconst markdown-regex-math-inline-single
1774 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1775 "Regular expression for itex $..$ math mode expressions.
1776 Groups 1 and 3 match the opening and closing dollar signs.
1777 Group 2 matches the mathematical expression contained within.")
1779 (defconst markdown-regex-math-inline-double
1780 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1781 "Regular expression for itex $$..$$ math mode expressions.
1782 Groups 1 and 3 match opening and closing dollar signs.
1783 Group 2 matches the mathematical expression contained within.")
1785 (defconst markdown-regex-math-display
1786 (rx line-start
1787 (group (group (repeat 1 2 "\\")) "[")
1788 (group (*? anything))
1789 (group (backref 2) "]")
1790 line-end)
1791 "Regular expression for \[..\] or \\[..\\] display math.
1792 Groups 1 and 4 match the opening and closing markup.
1793 Group 3 matches the mathematical expression contained within.
1794 Group 2 matches the opening slashes, and is used internally to
1795 match the closing slashes.")
1797 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1798 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1799 END-OF-LINE is the regexp construct to indicate end of line; $ if
1800 missing."
1801 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1802 (or end-of-line "$")))
1804 (defconst markdown-regex-tilde-fence-begin
1805 (markdown-make-tilde-fence-regex
1806 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1807 "Regular expression for matching tilde-fenced code blocks.
1808 Group 1 matches the opening tildes.
1809 Group 2 matches (optional) opening brace and surrounding whitespace.
1810 Group 3 matches the language identifier (optional).
1811 Group 4 matches the info string (optional).
1812 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1813 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1815 (defconst markdown-regex-declarative-metadata
1816 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1817 "Regular expression for matching declarative metadata statements.
1818 This matches MultiMarkdown metadata as well as YAML and TOML
1819 assignments such as the following:
1821 variable: value
1825 variable = value")
1827 (defconst markdown-regex-pandoc-metadata
1828 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1829 "Regular expression for matching Pandoc metadata.")
1831 (defconst markdown-regex-yaml-metadata-border
1832 "\\(-\\{3\\}\\)$"
1833 "Regular expression for matching YAML metadata.")
1835 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1836 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1837 "Regular expression for matching YAML metadata end borders.")
1839 (defsubst markdown-get-yaml-metadata-start-border ()
1840 "Return YAML metadata start border depending upon whether Pandoc is used."
1841 (concat
1842 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1843 markdown-regex-yaml-metadata-border))
1845 (defsubst markdown-get-yaml-metadata-end-border (_)
1846 "Return YAML metadata end border depending upon whether Pandoc is used."
1847 (if markdown-use-pandoc-style-yaml-metadata
1848 markdown-regex-yaml-pandoc-metadata-end-border
1849 markdown-regex-yaml-metadata-border))
1851 (defconst markdown-regex-inline-attributes
1852 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1853 "Regular expression for matching inline identifiers or attribute lists.
1854 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1856 (defconst markdown-regex-leanpub-sections
1857 (concat
1858 "^\\({\\)\\("
1859 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1860 "\\)\\(}\\)[ \t]*\n")
1861 "Regular expression for Leanpub section markers and related syntax.")
1863 (defconst markdown-regex-sub-superscript
1864 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1865 "The regular expression matching a sub- or superscript.
1866 The leading un-numbered group matches the character before the
1867 opening tilde or carat, if any, ensuring that it is not a
1868 backslash escape, carat, or tilde.
1869 Group 1 matches the entire expression, including markup.
1870 Group 2 matches the opening markup--a tilde or carat.
1871 Group 3 matches the text inside the delimiters.
1872 Group 4 matches the closing markup--a tilde or carat.")
1874 (defconst markdown-regex-include
1875 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1876 "Regular expression matching common forms of include syntax.
1877 Marked 2, Leanpub, and other processors support some of these forms:
1879 <<[sections/section1.md]
1880 <<(folder/filename)
1881 <<[Code title](folder/filename)
1882 <<{folder/raw_file.html}
1884 Group 1 matches the opening two angle brackets.
1885 Groups 2-4 match the opening square bracket, the text inside,
1886 and the closing square bracket, respectively.
1887 Groups 5-7 match the opening parenthesis, the text inside, and
1888 the closing parenthesis.
1889 Groups 8-10 match the opening brace, the text inside, and the brace.")
1891 (defconst markdown-regex-pandoc-inline-footnote
1892 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1893 "Regular expression for Pandoc inline footnote^[footnote text].
1894 Group 1 matches the opening caret.
1895 Group 2 matches the opening square bracket.
1896 Group 3 matches the footnote text, without the surrounding markup.
1897 Group 4 matches the closing square bracket.")
1899 (defconst markdown-regex-html-attr
1900 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1901 "Regular expression for matching HTML attributes and values.
1902 Group 1 matches the attribute name.
1903 Group 2 matches the following whitespace, equals sign, and value, if any.
1904 Group 3 matches the equals sign, if any.
1905 Group 4 matches single-, double-, or un-quoted attribute values.")
1907 (defconst markdown-regex-html-tag
1908 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1909 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1910 "Regular expression for matching HTML tags.
1911 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1912 Group 2 matches the tag name.
1913 Group 3 matches all attributes and whitespace following the tag name.")
1915 (defconst markdown-regex-html-entity
1916 "\\(&#?[[:alnum:]]+;\\)"
1917 "Regular expression for matching HTML entities.")
1920 ;;; Syntax ====================================================================
1922 (defsubst markdown-in-comment-p (&optional pos)
1923 "Return non-nil if POS is in a comment.
1924 If POS is not given, use point instead."
1925 (nth 4 (syntax-ppss pos)))
1927 (defun markdown-syntax-propertize-extend-region (start end)
1928 "Extend START to END region to include an entire block of text.
1929 This helps improve syntax analysis for block constructs.
1930 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1931 Function is called repeatedly until it returns nil. For details, see
1932 `syntax-propertize-extend-region-functions'."
1933 (save-match-data
1934 (save-excursion
1935 (let* ((new-start (progn (goto-char start)
1936 (skip-chars-forward "\n")
1937 (if (re-search-backward "\n\n" nil t)
1938 (min start (match-end 0))
1939 (point-min))))
1940 (new-end (progn (goto-char end)
1941 (skip-chars-backward "\n")
1942 (if (re-search-forward "\n\n" nil t)
1943 (max end (match-beginning 0))
1944 (point-max))))
1945 (code-match (markdown-code-block-at-pos new-start))
1946 (new-start (or (and code-match (cl-first code-match)) new-start))
1947 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1948 (new-end (or (and code-match (cl-second code-match)) new-end)))
1949 (unless (and (eq new-start start) (eq new-end end))
1950 (cons new-start (min new-end (point-max))))))))
1952 (defun markdown-font-lock-extend-region-function (start end _)
1953 "Used in `jit-lock-after-change-extend-region-functions'.
1954 Delegates to `markdown-syntax-propertize-extend-region'. START
1955 and END are the previous region to refontify."
1956 (let ((res (markdown-syntax-propertize-extend-region start end)))
1957 (when res
1958 ;; syntax-propertize-function is not called when character at
1959 ;; (point-max) is deleted, but font-lock-extend-region-functions
1960 ;; are called. Force a syntax property update in that case.
1961 (when (= end (point-max))
1962 ;; This function is called in a buffer modification hook.
1963 ;; `markdown-syntax-propertize' doesn't save the match data,
1964 ;; so we have to do it here.
1965 (save-match-data
1966 (markdown-syntax-propertize (car res) (cdr res))))
1967 (setq jit-lock-start (car res)
1968 jit-lock-end (cdr res)))))
1970 (defun markdown-syntax-propertize-pre-blocks (start end)
1971 "Match preformatted text blocks from START to END."
1972 (save-excursion
1973 (goto-char start)
1974 (let ((levels (markdown-calculate-list-levels))
1975 indent pre-regexp close-regexp open close)
1976 (while (and (< (point) end) (not close))
1977 ;; Search for a region with sufficient indentation
1978 (if (null levels)
1979 (setq indent 1)
1980 (setq indent (1+ (length levels))))
1981 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1982 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1984 (cond
1985 ;; If not at the beginning of a line, move forward
1986 ((not (bolp)) (forward-line))
1987 ;; Move past blank lines
1988 ((markdown-cur-line-blank) (forward-line))
1989 ;; At headers and horizontal rules, reset levels
1990 ((markdown-new-baseline) (forward-line) (setq levels nil))
1991 ;; If the current line has sufficient indentation, mark out pre block
1992 ;; The opening should be preceded by a blank line.
1993 ((and (looking-at pre-regexp)
1994 (markdown-prev-line-blank-p))
1995 (setq open (match-beginning 0))
1996 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
1997 (not (eobp)))
1998 (forward-line))
1999 (skip-syntax-backward "-")
2000 (setq close (point)))
2001 ;; If current line has a list marker, update levels, move to end of block
2002 ((looking-at markdown-regex-list)
2003 (setq levels (markdown-update-list-levels
2004 (match-string 2) (current-indentation) levels))
2005 (markdown-end-of-text-block))
2006 ;; If this is the end of the indentation level, adjust levels accordingly.
2007 ;; Only match end of indentation level if levels is not the empty list.
2008 ((and (car levels) (looking-at-p close-regexp))
2009 (setq levels (markdown-update-list-levels
2010 nil (current-indentation) levels))
2011 (markdown-end-of-text-block))
2012 (t (markdown-end-of-text-block))))
2014 (when (and open close)
2015 ;; Set text property data
2016 (put-text-property open close 'markdown-pre (list open close))
2017 ;; Recursively search again
2018 (markdown-syntax-propertize-pre-blocks (point) end)))))
2020 (defconst markdown-fenced-block-pairs
2021 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
2022 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
2023 markdown-fenced-code)
2024 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
2025 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2026 markdown-yaml-metadata-section)
2027 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2028 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2029 markdown-gfm-code))
2030 "Mapping of regular expressions to \"fenced-block\" constructs.
2031 These constructs are distinguished by having a distinctive start
2032 and end pattern, both of which take up an entire line of text,
2033 but no special pattern to identify text within the fenced
2034 blocks (unlike blockquotes and indented-code sections).
2036 Each element within this list takes the form:
2038 ((START-REGEX-OR-FUN START-PROPERTY)
2039 (END-REGEX-OR-FUN END-PROPERTY)
2040 MIDDLE-PROPERTY)
2042 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2043 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2044 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2045 which is the length of the first group of the START-REGEX-OR-FUN match, which
2046 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2047 evaluate these into \"real\" regexps.
2049 The *-PROPERTY elements are the text properties applied to each part of the
2050 block construct when it is matched using
2051 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2052 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2053 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2054 `match-data' when the regexp was matched to the text. In the case of
2055 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2056 begin and end set to the edges of the \"middle\" text. This makes fontification
2057 easier.")
2059 (defun markdown-text-property-at-point (prop)
2060 (get-text-property (point) prop))
2062 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2063 (cond ((functionp object)
2064 (if arg (funcall object arg) (funcall object)))
2065 ((stringp object) object)
2066 (t (error "Object cannot be turned into regex"))))
2068 (defsubst markdown-get-start-fence-regexp ()
2069 "Return regexp to find all \"start\" sections of fenced block constructs.
2070 Which construct is actually contained in the match must be found separately."
2071 (mapconcat
2072 #'identity
2073 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2074 markdown-fenced-block-pairs)
2075 "\\|"))
2077 (defun markdown-get-fenced-block-begin-properties ()
2078 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2080 (defun markdown-get-fenced-block-end-properties ()
2081 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2083 (defun markdown-get-fenced-block-middle-properties ()
2084 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2086 (defun markdown-find-previous-prop (prop &optional lim)
2087 "Find previous place where property PROP is non-nil, up to LIM.
2088 Return a cons of (pos . property). pos is point if point contains
2089 non-nil PROP."
2090 (let ((res
2091 (if (get-text-property (point) prop) (point)
2092 (previous-single-property-change
2093 (point) prop nil (or lim (point-min))))))
2094 (when (and (not (get-text-property res prop))
2095 (> res (point-min))
2096 (get-text-property (1- res) prop))
2097 (cl-decf res))
2098 (when (and res (get-text-property res prop)) (cons res prop))))
2100 (defun markdown-find-next-prop (prop &optional lim)
2101 "Find next place where property PROP is non-nil, up to LIM.
2102 Return a cons of (POS . PROPERTY) where POS is point if point
2103 contains non-nil PROP."
2104 (let ((res
2105 (if (get-text-property (point) prop) (point)
2106 (next-single-property-change
2107 (point) prop nil (or lim (point-max))))))
2108 (when (and res (get-text-property res prop)) (cons res prop))))
2110 (defun markdown-min-of-seq (map-fn seq)
2111 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2112 (cl-loop for el in seq
2113 with min = 1.0e+INF ; infinity
2114 with min-el = nil
2115 do (let ((res (funcall map-fn el)))
2116 (when (< res min)
2117 (setq min res)
2118 (setq min-el el)))
2119 finally return min-el))
2121 (defun markdown-max-of-seq (map-fn seq)
2122 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2123 (cl-loop for el in seq
2124 with max = -1.0e+INF ; negative infinity
2125 with max-el = nil
2126 do (let ((res (funcall map-fn el)))
2127 (when (and res (> res max))
2128 (setq max res)
2129 (setq max-el el)))
2130 finally return max-el))
2132 (defun markdown-find-previous-block ()
2133 "Find previous block.
2134 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2135 unable to propertize the entire block, but was able to propertize the beginning
2136 of the block. If so, return a cons of (pos . property) where the beginning of
2137 the block was propertized."
2138 (let ((start-pt (point))
2139 (closest-open
2140 (markdown-max-of-seq
2141 #'car
2142 (cl-remove-if
2143 #'null
2144 (cl-mapcar
2145 #'markdown-find-previous-prop
2146 (markdown-get-fenced-block-begin-properties))))))
2147 (when closest-open
2148 (let* ((length-of-open-match
2149 (let ((match-d
2150 (get-text-property (car closest-open) (cdr closest-open))))
2151 (- (cl-fourth match-d) (cl-third match-d))))
2152 (end-regexp
2153 (markdown-maybe-funcall-regexp
2154 (cl-caadr
2155 (cl-find-if
2156 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2157 markdown-fenced-block-pairs))
2158 length-of-open-match))
2159 (end-prop-loc
2160 (save-excursion
2161 (save-match-data
2162 (goto-char (car closest-open))
2163 (and (re-search-forward end-regexp start-pt t)
2164 (match-beginning 0))))))
2165 (and (not end-prop-loc) closest-open)))))
2167 (defun markdown-get-fenced-block-from-start (prop)
2168 "Return limits of an enclosing fenced block from its start, using PROP.
2169 Return value is a list usable as `match-data'."
2170 (catch 'no-rest-of-block
2171 (let* ((correct-entry
2172 (cl-find-if
2173 (lambda (entry) (eq (cl-cadar entry) prop))
2174 markdown-fenced-block-pairs))
2175 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2176 (middle-prop (cl-third correct-entry))
2177 (end-prop (cl-cadadr correct-entry))
2178 (end-of-end
2179 (save-excursion
2180 (goto-char (match-end 0)) ; end of begin
2181 (unless (eobp) (forward-char))
2182 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2183 (if (not mid-prop-v) ; no middle
2184 (progn
2185 ;; try to find end by advancing one
2186 (let ((end-prop-v
2187 (markdown-text-property-at-point end-prop)))
2188 (if end-prop-v (cl-second end-prop-v)
2189 (throw 'no-rest-of-block nil))))
2190 (set-match-data mid-prop-v)
2191 (goto-char (match-end 0)) ; end of middle
2192 (beginning-of-line) ; into end
2193 (cl-second (markdown-text-property-at-point end-prop)))))))
2194 (list begin-of-begin end-of-end))))
2196 (defun markdown-get-fenced-block-from-middle (prop)
2197 "Return limits of an enclosing fenced block from its middle, using PROP.
2198 Return value is a list usable as `match-data'."
2199 (let* ((correct-entry
2200 (cl-find-if
2201 (lambda (entry) (eq (cl-third entry) prop))
2202 markdown-fenced-block-pairs))
2203 (begin-prop (cl-cadar correct-entry))
2204 (begin-of-begin
2205 (save-excursion
2206 (goto-char (match-beginning 0))
2207 (unless (bobp) (forward-line -1))
2208 (beginning-of-line)
2209 (cl-first (markdown-text-property-at-point begin-prop))))
2210 (end-prop (cl-cadadr correct-entry))
2211 (end-of-end
2212 (save-excursion
2213 (goto-char (match-end 0))
2214 (beginning-of-line)
2215 (cl-second (markdown-text-property-at-point end-prop)))))
2216 (list begin-of-begin end-of-end)))
2218 (defun markdown-get-fenced-block-from-end (prop)
2219 "Return limits of an enclosing fenced block from its end, using PROP.
2220 Return value is a list usable as `match-data'."
2221 (let* ((correct-entry
2222 (cl-find-if
2223 (lambda (entry) (eq (cl-cadadr entry) prop))
2224 markdown-fenced-block-pairs))
2225 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2226 (middle-prop (cl-third correct-entry))
2227 (begin-prop (cl-cadar correct-entry))
2228 (begin-of-begin
2229 (save-excursion
2230 (goto-char (match-beginning 0)) ; beginning of end
2231 (unless (bobp) (backward-char)) ; into middle
2232 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2233 (if (not mid-prop-v)
2234 (progn
2235 (beginning-of-line)
2236 (cl-first (markdown-text-property-at-point begin-prop)))
2237 (set-match-data mid-prop-v)
2238 (goto-char (match-beginning 0)) ; beginning of middle
2239 (unless (bobp) (forward-line -1)) ; into beginning
2240 (beginning-of-line)
2241 (cl-first (markdown-text-property-at-point begin-prop)))))))
2242 (list begin-of-begin end-of-end)))
2244 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2245 "Get \"fake\" match data for block enclosing POS.
2246 Returns fake match data which encloses the start, middle, and end
2247 of the block construct enclosing POS, if it exists. Used in
2248 `markdown-code-block-at-pos'."
2249 (save-excursion
2250 (when pos (goto-char pos))
2251 (beginning-of-line)
2252 (car
2253 (cl-remove-if
2254 #'null
2255 (cl-mapcar
2256 (lambda (fun-and-prop)
2257 (cl-destructuring-bind (fun prop) fun-and-prop
2258 (when prop
2259 (save-match-data
2260 (set-match-data (markdown-text-property-at-point prop))
2261 (funcall fun prop)))))
2262 `((markdown-get-fenced-block-from-start
2263 ,(cl-find-if
2264 #'markdown-text-property-at-point
2265 (markdown-get-fenced-block-begin-properties)))
2266 (markdown-get-fenced-block-from-middle
2267 ,(cl-find-if
2268 #'markdown-text-property-at-point
2269 (markdown-get-fenced-block-middle-properties)))
2270 (markdown-get-fenced-block-from-end
2271 ,(cl-find-if
2272 #'markdown-text-property-at-point
2273 (markdown-get-fenced-block-end-properties)))))))))
2275 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2276 "Get match for REG up to END, if exists, and propertize appropriately.
2277 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2278 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2279 (when (re-search-forward reg end t)
2280 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2281 (close-end (match-end 0)) ; End of closing line.
2282 (close-data (match-data t))) ; Match data for closing line.
2283 ;; Propertize middle section of fenced block.
2284 (put-text-property middle-begin close-begin
2285 (cl-third fence-spec)
2286 (list middle-begin close-begin))
2287 ;; Propertize closing line of fenced block.
2288 (put-text-property close-begin close-end
2289 (cl-cadadr fence-spec) close-data))))
2291 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2292 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2293 If unable to propertize an entire block (if the start of a block is within START
2294 and END, but the end of the block is not), propertize the start section of a
2295 block, then in a subsequent call propertize both middle and end by finding the
2296 start which was previously propertized."
2297 (let ((start-reg (markdown-get-start-fence-regexp)))
2298 (save-excursion
2299 (goto-char start)
2300 ;; start from previous unclosed block, if exists
2301 (let ((prev-begin-block (markdown-find-previous-block)))
2302 (when prev-begin-block
2303 (let* ((correct-entry
2304 (cl-find-if (lambda (entry)
2305 (eq (cdr prev-begin-block) (cl-cadar entry)))
2306 markdown-fenced-block-pairs))
2307 (enclosed-text-start (1+ (car prev-begin-block)))
2308 (start-length
2309 (save-excursion
2310 (goto-char (car prev-begin-block))
2311 (string-match
2312 (markdown-maybe-funcall-regexp
2313 (caar correct-entry))
2314 (buffer-substring
2315 (point-at-bol) (point-at-eol)))
2316 (- (match-end 1) (match-beginning 1))))
2317 (end-reg (markdown-maybe-funcall-regexp
2318 (cl-caadr correct-entry) start-length)))
2319 (markdown-propertize-end-match
2320 end-reg end correct-entry enclosed-text-start))))
2321 ;; find all new blocks within region
2322 (while (re-search-forward start-reg end t)
2323 ;; we assume the opening constructs take up (only) an entire line,
2324 ;; so we re-check the current line
2325 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2326 ;; find entry in `markdown-fenced-block-pairs' corresponding
2327 ;; to regex which was matched
2328 (correct-entry
2329 (cl-find-if
2330 (lambda (fenced-pair)
2331 (string-match-p
2332 (markdown-maybe-funcall-regexp (caar fenced-pair))
2333 cur-line))
2334 markdown-fenced-block-pairs))
2335 (enclosed-text-start
2336 (save-excursion (1+ (point-at-eol))))
2337 (end-reg
2338 (markdown-maybe-funcall-regexp
2339 (cl-caadr correct-entry)
2340 (if (and (match-beginning 1) (match-end 1))
2341 (- (match-end 1) (match-beginning 1))
2342 0))))
2343 ;; get correct match data
2344 (save-excursion
2345 (beginning-of-line)
2346 (re-search-forward
2347 (markdown-maybe-funcall-regexp (caar correct-entry))
2348 (point-at-eol)))
2349 ;; mark starting, even if ending is outside of region
2350 (put-text-property (match-beginning 0) (match-end 0)
2351 (cl-cadar correct-entry) (match-data t))
2352 (markdown-propertize-end-match
2353 end-reg end correct-entry enclosed-text-start))))))
2355 (defun markdown-syntax-propertize-blockquotes (start end)
2356 "Match blockquotes from START to END."
2357 (save-excursion
2358 (goto-char start)
2359 (while (and (re-search-forward markdown-regex-blockquote end t)
2360 (not (markdown-code-block-at-pos (match-beginning 0))))
2361 (put-text-property (match-beginning 0) (match-end 0)
2362 'markdown-blockquote
2363 (match-data t)))))
2365 (defun markdown-syntax-propertize-hrs (start end)
2366 "Match horizontal rules from START to END."
2367 (save-excursion
2368 (goto-char start)
2369 (while (re-search-forward markdown-regex-hr end t)
2370 (unless (or (markdown-on-heading-p)
2371 (markdown-code-block-at-point-p))
2372 (put-text-property (match-beginning 0) (match-end 0)
2373 'markdown-hr
2374 (match-data t))))))
2376 (defun markdown-syntax-propertize-yaml-metadata (start end)
2377 (save-excursion
2378 (goto-char start)
2379 (cl-loop
2380 while (re-search-forward markdown-regex-declarative-metadata end t)
2381 do (when (get-text-property (match-beginning 0)
2382 'markdown-yaml-metadata-section)
2383 (put-text-property (match-beginning 1) (match-end 1)
2384 'markdown-metadata-key (match-data t))
2385 (put-text-property (match-beginning 2) (match-end 2)
2386 'markdown-metadata-markup (match-data t))
2387 (put-text-property (match-beginning 3) (match-end 3)
2388 'markdown-metadata-value (match-data t))))))
2390 (defun markdown-syntax-propertize-headings (start end)
2391 "Match headings of type SYMBOL with REGEX from START to END."
2392 (goto-char start)
2393 (while (re-search-forward markdown-regex-header end t)
2394 (unless (markdown-code-block-at-pos (match-beginning 0))
2395 (put-text-property
2396 (match-beginning 0) (match-end 0) 'markdown-heading
2397 (match-data t))
2398 (put-text-property
2399 (match-beginning 0) (match-end 0)
2400 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2401 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2402 (t (let ((atx-level (length (markdown-trim-whitespace
2403 (match-string-no-properties 4)))))
2404 (intern (format "markdown-heading-%d-atx" atx-level)))))
2405 (match-data t)))))
2407 (defun markdown-syntax-propertize-comments (start end)
2408 "Match HTML comments from the START to END."
2409 (let* ((in-comment (markdown-in-comment-p)))
2410 (goto-char start)
2411 (cond
2412 ;; Comment start
2413 ((and (not in-comment)
2414 (re-search-forward markdown-regex-comment-start end t)
2415 (not (markdown-inline-code-at-point-p))
2416 (not (markdown-code-block-at-point-p)))
2417 (let ((open-beg (match-beginning 0)))
2418 (put-text-property open-beg (1+ open-beg)
2419 'syntax-table (string-to-syntax "<"))
2420 (markdown-syntax-propertize-comments
2421 (min (1+ (match-end 0)) end (point-max)) end)))
2422 ;; Comment end
2423 ((and in-comment
2424 (re-search-forward markdown-regex-comment-end end t))
2425 (put-text-property (1- (match-end 0)) (match-end 0)
2426 'syntax-table (string-to-syntax ">"))
2427 (markdown-syntax-propertize-comments
2428 (min (1+ (match-end 0)) end (point-max)) end))
2429 ;; Nothing found
2430 (t nil))))
2432 (defvar markdown--syntax-properties
2433 (list 'markdown-tilde-fence-begin nil
2434 'markdown-tilde-fence-end nil
2435 'markdown-fenced-code nil
2436 'markdown-yaml-metadata-begin nil
2437 'markdown-yaml-metadata-end nil
2438 'markdown-yaml-metadata-section nil
2439 'markdown-gfm-block-begin nil
2440 'markdown-gfm-block-end nil
2441 'markdown-gfm-code nil
2442 'markdown-pre nil
2443 'markdown-blockquote nil
2444 'markdown-hr nil
2445 'markdown-heading nil
2446 'markdown-heading-1-setext nil
2447 'markdown-heading-2-setext nil
2448 'markdown-heading-1-atx nil
2449 'markdown-heading-2-atx nil
2450 'markdown-heading-3-atx nil
2451 'markdown-heading-4-atx nil
2452 'markdown-heading-5-atx nil
2453 'markdown-heading-6-atx nil
2454 'markdown-metadata-key nil
2455 'markdown-metadata-value nil
2456 'markdown-metadata-markup nil)
2457 "Property list of all Markdown syntactic properties.")
2459 (defun markdown-syntax-propertize (start end)
2460 "Function used as `syntax-propertize-function'.
2461 START and END delimit region to propertize."
2462 (with-silent-modifications
2463 (save-excursion
2464 (remove-text-properties start end markdown--syntax-properties)
2465 (markdown-syntax-propertize-fenced-block-constructs start end)
2466 (markdown-syntax-propertize-yaml-metadata start end)
2467 (markdown-syntax-propertize-pre-blocks start end)
2468 (markdown-syntax-propertize-blockquotes start end)
2469 (markdown-syntax-propertize-headings start end)
2470 (markdown-syntax-propertize-hrs start end)
2471 (markdown-syntax-propertize-comments start end))))
2474 ;;; Markup Hiding
2476 (defconst markdown-markup-properties
2477 '(face markdown-markup-face invisible markdown-markup)
2478 "List of properties and values to apply to markup.")
2480 (defconst markdown-language-keyword-properties
2481 '(face markdown-language-keyword-face invisible markdown-markup)
2482 "List of properties and values to apply to code block language names.")
2484 (defconst markdown-language-info-properties
2485 '(face markdown-language-info-face invisible markdown-markup)
2486 "List of properties and values to apply to code block language info strings.")
2488 (defconst markdown-include-title-properties
2489 '(face markdown-link-title-face invisible markdown-markup)
2490 "List of properties and values to apply to included code titles.")
2492 (defconst markdown-inline-footnote-properties
2493 '(face nil display ((raise 0.2) (height 0.8)))
2494 "Properties to apply to footnote markers and inline footnotes.")
2496 (defcustom markdown-hide-markup nil
2497 "Determines whether markup in the buffer will be hidden.
2498 When set to nil, all markup is displayed in the buffer as it
2499 appears in the file. An exception is when `markdown-hide-urls'
2500 is non-nil.
2501 Set this to a non-nil value to turn this feature on by default.
2502 You can interactively toggle the value of this variable with
2503 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2504 or from the Markdown > Show & Hide menu.
2506 Markup hiding works by adding text properties to positions in the
2507 buffer---either the `invisible' property or the `display' property
2508 in cases where alternative glyphs are used (e.g., list bullets).
2509 This does not, however, affect printing or other output.
2510 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2511 not honor these text properties. For printing, it would be better
2512 to first convert to HTML or PDF (e.g,. using Pandoc)."
2513 :group 'markdown
2514 :type 'boolean
2515 :safe 'booleanp
2516 :package-version '(markdown-mode . "2.3"))
2517 (make-variable-buffer-local 'markdown-hide-markup)
2519 (defun markdown-toggle-markup-hiding (&optional arg)
2520 "Toggle the display or hiding of markup.
2521 With a prefix argument ARG, enable markup hiding if ARG is positive,
2522 and disable it otherwise.
2523 See `markdown-hide-markup' for additional details."
2524 (interactive (list (or current-prefix-arg 'toggle)))
2525 (setq markdown-hide-markup
2526 (if (eq arg 'toggle)
2527 (not markdown-hide-markup)
2528 (> (prefix-numeric-value arg) 0)))
2529 (if markdown-hide-markup
2530 (progn (add-to-invisibility-spec 'markdown-markup)
2531 (message "markdown-mode markup hiding enabled"))
2532 (progn (remove-from-invisibility-spec 'markdown-markup)
2533 (message "markdown-mode markup hiding disabled")))
2534 (markdown-reload-extensions))
2537 ;;; Font Lock =================================================================
2539 (require 'font-lock)
2541 (defvar markdown-italic-face 'markdown-italic-face
2542 "Face name to use for italic text.")
2544 (defvar markdown-bold-face 'markdown-bold-face
2545 "Face name to use for bold text.")
2547 (defvar markdown-strike-through-face 'markdown-strike-through-face
2548 "Face name to use for strike-through text.")
2550 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2551 "Face name to use as a base for header delimiters.")
2553 (defvar markdown-header-rule-face 'markdown-header-rule-face
2554 "Face name to use as a base for header rules.")
2556 (defvar markdown-header-face 'markdown-header-face
2557 "Face name to use as a base for headers.")
2559 (defvar markdown-header-face-1 'markdown-header-face-1
2560 "Face name to use for level-1 headers.")
2562 (defvar markdown-header-face-2 'markdown-header-face-2
2563 "Face name to use for level-2 headers.")
2565 (defvar markdown-header-face-3 'markdown-header-face-3
2566 "Face name to use for level-3 headers.")
2568 (defvar markdown-header-face-4 'markdown-header-face-4
2569 "Face name to use for level-4 headers.")
2571 (defvar markdown-header-face-5 'markdown-header-face-5
2572 "Face name to use for level-5 headers.")
2574 (defvar markdown-header-face-6 'markdown-header-face-6
2575 "Face name to use for level-6 headers.")
2577 (defvar markdown-inline-code-face 'markdown-inline-code-face
2578 "Face name to use for inline code.")
2580 (defvar markdown-list-face 'markdown-list-face
2581 "Face name to use for list markers.")
2583 (defvar markdown-blockquote-face 'markdown-blockquote-face
2584 "Face name to use for blockquote.")
2586 (defvar markdown-pre-face 'markdown-pre-face
2587 "Face name to use for preformatted text.")
2589 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2590 "Face name to use for programming language identifiers.")
2592 (defvar markdown-language-info-face 'markdown-language-info-face
2593 "Face name to use for programming info strings.")
2595 (defvar markdown-link-face 'markdown-link-face
2596 "Face name to use for links.")
2598 (defvar markdown-missing-link-face 'markdown-missing-link-face
2599 "Face name to use for links where the linked file does not exist.")
2601 (defvar markdown-reference-face 'markdown-reference-face
2602 "Face name to use for reference.")
2604 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2605 "Face name to use for footnote markers.")
2607 (defvar markdown-url-face 'markdown-url-face
2608 "Face name to use for URLs.")
2610 (defvar markdown-link-title-face 'markdown-link-title-face
2611 "Face name to use for reference link titles.")
2613 (defvar markdown-line-break-face 'markdown-line-break-face
2614 "Face name to use for hard line breaks.")
2616 (defvar markdown-comment-face 'markdown-comment-face
2617 "Face name to use for HTML comments.")
2619 (defvar markdown-math-face 'markdown-math-face
2620 "Face name to use for LaTeX expressions.")
2622 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2623 "Face name to use for metadata keys.")
2625 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2626 "Face name to use for metadata values.")
2628 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2629 "Face name to use for GFM checkboxes.")
2631 (defvar markdown-highlight-face 'markdown-highlight-face
2632 "Face name to use for mouse highlighting.")
2634 (defvar markdown-markup-face 'markdown-markup-face
2635 "Face name to use for markup elements.")
2637 (defgroup markdown-faces nil
2638 "Faces used in Markdown Mode"
2639 :group 'markdown
2640 :group 'faces)
2642 (defface markdown-italic-face
2643 '((t (:inherit italic)))
2644 "Face for italic text."
2645 :group 'markdown-faces)
2647 (defface markdown-bold-face
2648 '((t (:inherit bold)))
2649 "Face for bold text."
2650 :group 'markdown-faces)
2652 (defface markdown-strike-through-face
2653 '((t (:strike-through t)))
2654 "Face for strike-through text."
2655 :group 'markdown-faces)
2657 (defface markdown-markup-face
2658 '((t (:inherit shadow :slant normal :weight normal)))
2659 "Face for markup elements."
2660 :group 'markdown-faces)
2662 (defface markdown-header-rule-face
2663 '((t (:inherit markdown-markup-face)))
2664 "Base face for headers rules."
2665 :group 'markdown-faces)
2667 (defface markdown-header-delimiter-face
2668 '((t (:inherit markdown-markup-face)))
2669 "Base face for headers hash delimiter."
2670 :group 'markdown-faces)
2672 (defface markdown-list-face
2673 '((t (:inherit markdown-markup-face)))
2674 "Face for list item markers."
2675 :group 'markdown-faces)
2677 (defface markdown-blockquote-face
2678 '((t (:inherit font-lock-doc-face)))
2679 "Face for blockquote sections."
2680 :group 'markdown-faces)
2682 (defface markdown-code-face
2683 '((t (:inherit fixed-pitch)))
2684 "Face for inline code, pre blocks, and fenced code blocks.
2685 This may be used, for example, to add a contrasting background to
2686 inline code fragments and code blocks."
2687 :group 'markdown-faces)
2689 (defface markdown-inline-code-face
2690 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2691 "Face for inline code."
2692 :group 'markdown-faces)
2694 (defface markdown-pre-face
2695 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2696 "Face for preformatted text."
2697 :group 'markdown-faces)
2699 (defface markdown-language-keyword-face
2700 '((t (:inherit font-lock-type-face)))
2701 "Face for programming language identifiers."
2702 :group 'markdown-faces)
2704 (defface markdown-language-info-face
2705 '((t (:inherit font-lock-string-face)))
2706 "Face for programming language info strings."
2707 :group 'markdown-faces)
2709 (defface markdown-link-face
2710 '((t (:inherit link)))
2711 "Face for links."
2712 :group 'markdown-faces)
2714 (defface markdown-missing-link-face
2715 '((t (:inherit font-lock-warning-face)))
2716 "Face for missing links."
2717 :group 'markdown-faces)
2719 (defface markdown-reference-face
2720 '((t (:inherit markdown-markup-face)))
2721 "Face for link references."
2722 :group 'markdown-faces)
2724 (define-obsolete-face-alias 'markdown-footnote-face
2725 'markdown-footnote-marker-face "v2.3")
2727 (defface markdown-footnote-marker-face
2728 '((t (:inherit markdown-markup-face)))
2729 "Face for footnote markers."
2730 :group 'markdown-faces)
2732 (defface markdown-footnote-text-face
2733 '((t (:inherit font-lock-comment-face)))
2734 "Face for footnote text."
2735 :group 'markdown-faces)
2737 (defface markdown-url-face
2738 '((t (:inherit font-lock-string-face)))
2739 "Face for URLs that are part of markup.
2740 For example, this applies to URLs in inline links:
2741 [link text](http://example.com/)."
2742 :group 'markdown-faces)
2744 (defface markdown-plain-url-face
2745 '((t (:inherit markdown-link-face)))
2746 "Face for URLs that are also links.
2747 For example, this applies to plain angle bracket URLs:
2748 <http://example.com/>."
2749 :group 'markdown-faces)
2751 (defface markdown-link-title-face
2752 '((t (:inherit font-lock-comment-face)))
2753 "Face for reference link titles."
2754 :group 'markdown-faces)
2756 (defface markdown-line-break-face
2757 '((t (:inherit font-lock-constant-face :underline t)))
2758 "Face for hard line breaks."
2759 :group 'markdown-faces)
2761 (defface markdown-comment-face
2762 '((t (:inherit font-lock-comment-face)))
2763 "Face for HTML comments."
2764 :group 'markdown-faces)
2766 (defface markdown-math-face
2767 '((t (:inherit font-lock-string-face)))
2768 "Face for LaTeX expressions."
2769 :group 'markdown-faces)
2771 (defface markdown-metadata-key-face
2772 '((t (:inherit font-lock-variable-name-face)))
2773 "Face for metadata keys."
2774 :group 'markdown-faces)
2776 (defface markdown-metadata-value-face
2777 '((t (:inherit font-lock-string-face)))
2778 "Face for metadata values."
2779 :group 'markdown-faces)
2781 (defface markdown-gfm-checkbox-face
2782 '((t (:inherit font-lock-builtin-face)))
2783 "Face for GFM checkboxes."
2784 :group 'markdown-faces)
2786 (defface markdown-highlight-face
2787 '((t (:inherit highlight)))
2788 "Face for mouse highlighting."
2789 :group 'markdown-faces)
2791 (defface markdown-hr-face
2792 '((t (:inherit markdown-markup-face)))
2793 "Face for horizontal rules."
2794 :group 'markdown-faces)
2796 (defface markdown-html-tag-name-face
2797 '((t (:inherit font-lock-type-face)))
2798 "Face for HTML tag names."
2799 :group 'markdown-faces)
2801 (defface markdown-html-tag-delimiter-face
2802 '((t (:inherit markdown-markup-face)))
2803 "Face for HTML tag delimiters."
2804 :group 'markdown-faces)
2806 (defface markdown-html-attr-name-face
2807 '((t (:inherit font-lock-variable-name-face)))
2808 "Face for HTML attribute names."
2809 :group 'markdown-faces)
2811 (defface markdown-html-attr-value-face
2812 '((t (:inherit font-lock-string-face)))
2813 "Face for HTML attribute values."
2814 :group 'markdown-faces)
2816 (defface markdown-html-entity-face
2817 '((t (:inherit font-lock-variable-name-face)))
2818 "Face for HTML entities."
2819 :group 'markdown-faces)
2821 (defcustom markdown-header-scaling nil
2822 "Whether to use variable-height faces for headers.
2823 When non-nil, `markdown-header-face' will inherit from
2824 `variable-pitch' and the scaling values in
2825 `markdown-header-scaling-values' will be applied to
2826 headers of levels one through six respectively."
2827 :type 'boolean
2828 :initialize 'custom-initialize-default
2829 :set (lambda (symbol value)
2830 (set-default symbol value)
2831 (markdown-update-header-faces value))
2832 :group 'markdown-faces
2833 :package-version '(markdown-mode . "2.2"))
2835 (defcustom markdown-header-scaling-values
2836 '(2.0 1.7 1.4 1.1 1.0 1.0)
2837 "List of scaling values for headers of level one through six.
2838 Used when `markdown-header-scaling' is non-nil."
2839 :type 'list
2840 :initialize 'custom-initialize-default
2841 :set (lambda (symbol value)
2842 (set-default symbol value)
2843 (markdown-update-header-faces markdown-header-scaling value))
2844 :group 'markdown-faces)
2846 (defun markdown-make-header-faces ()
2847 "Build the faces used for Markdown headers."
2848 (let ((inherit-faces '(font-lock-function-name-face)))
2849 (when markdown-header-scaling
2850 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2851 (defface markdown-header-face
2852 `((t (:inherit ,inherit-faces :weight bold)))
2853 "Base face for headers."
2854 :group 'markdown-faces))
2855 (dotimes (num 6)
2856 (let* ((num1 (1+ num))
2857 (face-name (intern (format "markdown-header-face-%s" num1)))
2858 (scale (if markdown-header-scaling
2859 (float (nth num markdown-header-scaling-values))
2860 1.0)))
2861 (eval
2862 `(defface ,face-name
2863 '((t (:inherit markdown-header-face :height ,scale)))
2864 (format "Face for level %s headers.
2865 You probably don't want to customize this face directly. Instead
2866 you can customize the base face `markdown-header-face' or the
2867 variable-height variable `markdown-header-scaling'." ,num1)
2868 :group 'markdown-faces)))))
2870 (markdown-make-header-faces)
2872 (defun markdown-update-header-faces (&optional scaling scaling-values)
2873 "Update header faces, depending on if header SCALING is desired.
2874 If so, use given list of SCALING-VALUES relative to the baseline
2875 size of `markdown-header-face'."
2876 (dotimes (num 6)
2877 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2878 (scale (cond ((not scaling) 1.0)
2879 (scaling-values (float (nth num scaling-values)))
2880 (t (float (nth num markdown-header-scaling-values))))))
2881 (unless (get face-name 'saved-face) ; Don't update customized faces
2882 (set-face-attribute face-name nil :height scale)))))
2884 (defun markdown-syntactic-face (state)
2885 "Return font-lock face for characters with given STATE.
2886 See `font-lock-syntactic-face-function' for details."
2887 (let ((in-comment (nth 4 state)))
2888 (cond
2889 (in-comment 'markdown-comment-face)
2890 (t nil))))
2892 (defcustom markdown-list-item-bullets
2893 '("●" "◎" "○" "◆" "◇" "►" "•")
2894 "List of bullets to use for unordered lists.
2895 It can contain any number of symbols, which will be repeated.
2896 Depending on your font, some reasonable choices are:
2897 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2898 :group 'markdown
2899 :type '(repeat (string :tag "Bullet character"))
2900 :package-version '(markdown-mode . "2.3"))
2902 (defvar markdown-mode-font-lock-keywords-basic
2903 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2904 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2905 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2906 (2 markdown-markup-face)
2907 (3 markdown-metadata-value-face)))
2908 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2909 (2 markdown-markup-properties nil t)
2910 (3 markdown-language-keyword-properties nil t)
2911 (4 markdown-language-info-properties nil t)
2912 (5 markdown-markup-properties nil t)))
2913 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2914 (markdown-fontify-gfm-code-blocks)
2915 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2916 (2 markdown-markup-properties nil t)
2917 (3 markdown-language-keyword-properties nil t)
2918 (4 markdown-language-info-properties nil t)
2919 (5 markdown-markup-properties nil t)))
2920 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2921 (markdown-fontify-fenced-code-blocks)
2922 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2923 (markdown-fontify-headings)
2924 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2925 (2 markdown-markup-face)
2926 (3 markdown-metadata-value-face)))
2927 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2928 (2 markdown-markup-face)
2929 (3 markdown-metadata-value-face)))
2930 (markdown-fontify-hrs)
2931 (markdown-match-code . ((1 markdown-markup-properties prepend)
2932 (2 markdown-inline-code-face prepend)
2933 (3 markdown-markup-properties prepend)))
2934 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2935 (2 markdown-inline-code-face)
2936 (3 markdown-markup-properties)))
2937 (markdown-fontify-angle-uris)
2938 (,markdown-regex-email . 'markdown-plain-url-face)
2939 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2940 (2 'markdown-html-tag-name-face t)
2941 (3 'markdown-html-tag-delimiter-face t)
2942 ;; Anchored matcher for HTML tag attributes
2943 (,markdown-regex-html-attr
2944 ;; Before searching, move past tag
2945 ;; name; set limit at tag close.
2946 (progn
2947 (goto-char (match-end 2)) (match-end 3))
2949 . ((1 'markdown-html-attr-name-face)
2950 (3 'markdown-html-tag-delimiter-face nil t)
2951 (4 'markdown-html-attr-value-face nil t)))))
2952 (,markdown-regex-html-entity . 'markdown-html-entity-face)
2953 (markdown-fontify-list-items)
2954 (,markdown-regex-footnote . ((0 markdown-inline-footnote-properties)
2955 (1 markdown-markup-properties) ; [^
2956 (2 markdown-footnote-marker-face) ; label
2957 (3 markdown-markup-properties))) ; ]
2958 (,markdown-regex-pandoc-inline-footnote . ((0 markdown-inline-footnote-properties)
2959 (1 markdown-markup-properties) ; ^
2960 (2 markdown-markup-properties) ; [
2961 (3 'markdown-footnote-text-face) ; text
2962 (4 markdown-markup-properties))) ; ]
2963 (markdown-match-includes . ((1 markdown-markup-properties)
2964 (2 markdown-markup-properties nil t)
2965 (3 markdown-include-title-properties nil t)
2966 (4 markdown-markup-properties nil t)
2967 (5 markdown-markup-properties)
2968 (6 'markdown-url-face)
2969 (7 markdown-markup-properties)))
2970 (markdown-fontify-inline-links)
2971 (markdown-fontify-reference-links)
2972 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
2973 (2 markdown-reference-face) ; label
2974 (3 markdown-markup-face) ; ]
2975 (4 markdown-markup-face) ; :
2976 (5 markdown-url-face) ; url
2977 (6 markdown-link-title-face))) ; "title" (optional)
2978 (markdown-fontify-plain-uris)
2979 ;; Math mode $..$
2980 (markdown-match-math-single . ((1 markdown-markup-face prepend)
2981 (2 markdown-math-face append)
2982 (3 markdown-markup-face prepend)))
2983 ;; Math mode $$..$$
2984 (markdown-match-math-double . ((1 markdown-markup-face prepend)
2985 (2 markdown-math-face append)
2986 (3 markdown-markup-face prepend)))
2987 ;; Math mode \[..\] and \\[..\\]
2988 (markdown-match-math-display . ((1 markdown-markup-face prepend)
2989 (3 markdown-math-face append)
2990 (4 markdown-markup-face prepend)))
2991 (markdown-match-bold . ((1 markdown-markup-properties prepend)
2992 (2 markdown-bold-face append)
2993 (3 markdown-markup-properties prepend)))
2994 (markdown-match-italic . ((1 markdown-markup-properties prepend)
2995 (2 markdown-italic-face append)
2996 (3 markdown-markup-properties prepend)))
2997 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
2998 (4 markdown-strike-through-face)
2999 (5 markdown-markup-properties)))
3000 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
3001 (markdown-fontify-sub-superscripts)
3002 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
3003 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
3004 (markdown-fontify-blockquotes)
3005 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
3006 "Syntax highlighting for Markdown files.")
3008 ;; Footnotes
3009 (defvar markdown-footnote-counter 0
3010 "Counter for footnote numbers.")
3011 (make-variable-buffer-local 'markdown-footnote-counter)
3013 (defconst markdown-footnote-chars
3014 "[[:alnum:]-]"
3015 "Regular expression matching any character that is allowed in a footnote identifier.")
3017 (defconst markdown-regex-footnote-definition
3018 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
3019 "Regular expression matching a footnote definition, capturing the label.")
3022 ;;; Compatibility =============================================================
3024 (defun markdown-replace-regexp-in-string (regexp rep string)
3025 "Replace ocurrences of REGEXP with REP in STRING.
3026 This is a compatibility wrapper to provide `replace-regexp-in-string'
3027 in XEmacs 21."
3028 (if (featurep 'xemacs)
3029 (replace-in-string string regexp rep)
3030 (replace-regexp-in-string regexp rep string)))
3032 ;; `markdown-use-region-p' is a compatibility function which checks
3033 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
3034 (eval-and-compile
3035 (cond
3036 ;; Emacs 24 and newer
3037 ((fboundp 'use-region-p)
3038 (defalias 'markdown-use-region-p 'use-region-p))
3039 ;; XEmacs
3040 ((fboundp 'region-active-p)
3041 (defalias 'markdown-use-region-p 'region-active-p))))
3043 ;; Use new names for outline-mode functions in Emacs 25 and later.
3044 (eval-and-compile
3045 (defalias 'markdown-hide-sublevels
3046 (if (fboundp 'outline-hide-sublevels)
3047 'outline-hide-sublevels
3048 'hide-sublevels))
3049 (defalias 'markdown-show-all
3050 (if (fboundp 'outline-show-all)
3051 'outline-show-all
3052 'show-all))
3053 (defalias 'markdown-hide-body
3054 (if (fboundp 'outline-hide-body)
3055 'outline-hide-body
3056 'hide-body))
3057 (defalias 'markdown-show-children
3058 (if (fboundp 'outline-show-children)
3059 'outline-show-children
3060 'show-children))
3061 (defalias 'markdown-show-subtree
3062 (if (fboundp 'outline-show-subtree)
3063 'outline-show-subtree
3064 'show-subtree))
3065 (defalias 'markdown-hide-subtree
3066 (if (fboundp 'outline-hide-subtree)
3067 'outline-hide-subtree
3068 'hide-subtree)))
3070 ;; Provide directory-name-p to Emacs 24
3071 (defsubst markdown-directory-name-p (name)
3072 "Return non-nil if NAME ends with a directory separator character.
3073 Taken from `directory-name-p' from Emacs 25 and provided here for
3074 backwards compatibility."
3075 (let ((len (length name))
3076 (lastc ?.))
3077 (if (> len 0)
3078 (setq lastc (aref name (1- len))))
3079 (or (= lastc ?/)
3080 (and (memq system-type '(windows-nt ms-dos))
3081 (= lastc ?\\)))))
3083 ;; Provide a function to find files recursively in Emacs 24.
3084 (defalias 'markdown-directory-files-recursively
3085 (if (fboundp 'directory-files-recursively)
3086 'directory-files-recursively
3087 (lambda (dir regexp)
3088 "Return list of all files under DIR that have file names matching REGEXP.
3089 This function works recursively. Files are returned in \"depth first\"
3090 order, and files from each directory are sorted in alphabetical order.
3091 Each file name appears in the returned list in its absolute form.
3092 Based on `directory-files-recursively' from Emacs 25 and provided
3093 here for backwards compatibility."
3094 (let ((result nil)
3095 (files nil)
3096 ;; When DIR is "/", remote file names like "/method:" could
3097 ;; also be offered. We shall suppress them.
3098 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3099 (dolist (file (sort (file-name-all-completions "" dir)
3100 'string<))
3101 (unless (member file '("./" "../"))
3102 (if (markdown-directory-name-p file)
3103 (let* ((leaf (substring file 0 (1- (length file))))
3104 (full-file (expand-file-name leaf dir)))
3105 (setq result
3106 (nconc result (markdown-directory-files-recursively
3107 full-file regexp))))
3108 (when (string-match-p regexp file)
3109 (push (expand-file-name file dir) files)))))
3110 (nconc result (nreverse files))))))
3112 (defun markdown-flyspell-check-word-p ()
3113 "Return t if `flyspell' should check word just before point.
3114 Used for `flyspell-generic-check-word-predicate'."
3115 (save-excursion
3116 (goto-char (1- (point)))
3117 (not (or (markdown-code-block-at-point-p)
3118 (markdown-inline-code-at-point-p)
3119 (markdown-in-comment-p)
3120 (let ((faces (get-text-property (point) 'face)))
3121 (if (listp faces)
3122 (or (memq 'markdown-reference-face faces)
3123 (memq 'markdown-markup-face faces)
3124 (memq 'markdown-plain-url-face faces)
3125 (memq 'markdown-inline-code-face faces)
3126 (memq 'markdown-url-face faces))
3127 (memq faces '(markdown-reference-face
3128 markdown-markup-face
3129 markdown-plain-url-face
3130 markdown-inline-code-face
3131 markdown-url-face))))))))
3133 (defun markdown-font-lock-ensure ()
3134 "Provide `font-lock-ensure' in Emacs 24."
3135 (if (fboundp 'font-lock-ensure)
3136 (font-lock-ensure)
3137 (with-no-warnings
3138 ;; Suppress warning about non-interactive use of
3139 ;; `font-lock-fontify-buffer' in Emacs 25.
3140 (font-lock-fontify-buffer))))
3143 ;;; Markdown Parsing Functions ================================================
3145 (defun markdown-cur-line-blank (&optional predicate)
3146 "Return t if the current line is blank and nil otherwise.
3147 When PREDICATE is non-nil, don't modify the match data."
3148 (save-excursion
3149 (beginning-of-line)
3150 (let ((regexp "^\\s *$"))
3151 (if predicate
3152 (looking-at-p regexp)
3153 (looking-at regexp)))))
3155 (defun markdown-cur-line-blank-p ()
3156 "Same as `markdown-cur-line-blank', but does not change the match data."
3157 (markdown-cur-line-blank t))
3159 (defun markdown-prev-line-blank (&optional predicate)
3160 "Return t if the previous line is blank and nil otherwise.
3161 If we are at the first line, then consider the previous line to be blank.
3162 When PREDICATE is non-nil, don't modify the match data."
3163 (or (= (line-beginning-position) (point-min))
3164 (save-excursion
3165 (forward-line -1)
3166 (markdown-cur-line-blank predicate))))
3168 (defun markdown-prev-line-blank-p ()
3169 "Same as `markdown-prev-line-blank', but does not change the match data."
3170 (markdown-prev-line-blank t))
3172 (defun markdown-next-line-blank (&optional predicate)
3173 "Return t if the next line is blank and nil otherwise.
3174 If we are at the last line, then consider the next line to be blank.
3175 When PREDICATE is non-nil, don't modify the match data."
3176 (or (= (line-end-position) (point-max))
3177 (save-excursion
3178 (forward-line 1)
3179 (markdown-cur-line-blank predicate))))
3181 (defun markdown-next-line-blank-p ()
3182 "Same as `markdown-next-line-blank', but does not change the match data."
3183 (markdown-next-line-blank t))
3185 (defun markdown-prev-line-indent ()
3186 "Return the number of leading whitespace characters in the previous line.
3187 Return 0 if the current line is the first line in the buffer."
3188 (save-excursion
3189 (if (= (line-beginning-position) (point-min))
3191 (forward-line -1)
3192 (current-indentation))))
3194 (defun markdown-next-line-indent ()
3195 "Return the number of leading whitespace characters in the next line.
3196 Return 0 if line is the last line in the buffer."
3197 (save-excursion
3198 (if (= (line-end-position) (point-max))
3200 (forward-line 1)
3201 (current-indentation))))
3203 (defun markdown-cur-non-list-indent ()
3204 "Return beginning position of list item text (not including the list marker).
3205 Return nil if the current line is not the beginning of a list item."
3206 (save-match-data
3207 (save-excursion
3208 (beginning-of-line)
3209 (when (re-search-forward markdown-regex-list (line-end-position) t)
3210 (current-column)))))
3212 (defun markdown-prev-non-list-indent ()
3213 "Return position of the first non-list-marker on the previous line."
3214 (save-excursion
3215 (forward-line -1)
3216 (markdown-cur-non-list-indent)))
3218 (defun markdown-new-baseline ()
3219 "Determine if the current line begins a new baseline level."
3220 (save-excursion
3221 (beginning-of-line)
3222 (or (looking-at markdown-regex-header)
3223 (looking-at markdown-regex-hr)
3224 (and (null (markdown-cur-non-list-indent))
3225 (= (current-indentation) 0)
3226 (markdown-prev-line-blank)))))
3228 (defun markdown-search-backward-baseline ()
3229 "Search backward baseline point with no indentation and not a list item."
3230 (end-of-line)
3231 (let (stop)
3232 (while (not (or stop (bobp)))
3233 (re-search-backward markdown-regex-block-separator-noindent nil t)
3234 (when (match-end 2)
3235 (goto-char (match-end 2))
3236 (cond
3237 ((markdown-new-baseline)
3238 (setq stop t))
3239 ((looking-at-p markdown-regex-list)
3240 (setq stop nil))
3241 (t (setq stop t)))))))
3243 (defun markdown-update-list-levels (marker indent levels)
3244 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3245 Here, MARKER is a string representing the type of list, INDENT is an integer
3246 giving the indentation, in spaces, of the current block, and LEVELS is a
3247 list of the indentation levels of parent list items. When LEVELS is nil,
3248 it means we are at baseline (not inside of a nested list)."
3249 (cond
3250 ;; New list item at baseline.
3251 ((and marker (null levels))
3252 (setq levels (list indent)))
3253 ;; List item with greater indentation (four or more spaces).
3254 ;; Increase list level.
3255 ((and marker (>= indent (+ (car levels) 4)))
3256 (setq levels (cons indent levels)))
3257 ;; List item with greater or equal indentation (less than four spaces).
3258 ;; Do not increase list level.
3259 ((and marker (>= indent (car levels)))
3260 levels)
3261 ;; Lesser indentation level.
3262 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3263 ;; indentation could move back more than one list level). Note
3264 ;; that this block need not be the beginning of list item.
3265 ((< indent (car levels))
3266 (while (and (> (length levels) 1)
3267 (< indent (+ (cadr levels) 4)))
3268 (setq levels (cdr levels)))
3269 levels)
3270 ;; Otherwise, do nothing.
3271 (t levels)))
3273 (defun markdown-calculate-list-levels ()
3274 "Calculate list levels at point.
3275 Return a list of the form (n1 n2 n3 ...) where n1 is the
3276 indentation of the deepest nested list item in the branch of
3277 the list at the point, n2 is the indentation of the parent
3278 list item, and so on. The depth of the list item is therefore
3279 the length of the returned list. If the point is not at or
3280 immediately after a list item, return nil."
3281 (save-excursion
3282 (let ((first (point)) levels indent pre-regexp)
3283 ;; Find a baseline point with zero list indentation
3284 (markdown-search-backward-baseline)
3285 ;; Search for all list items between baseline and LOC
3286 (while (and (< (point) first)
3287 (re-search-forward markdown-regex-list first t))
3288 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3289 (beginning-of-line)
3290 (cond
3291 ;; Make sure this is not a header or hr
3292 ((markdown-new-baseline) (setq levels nil))
3293 ;; Make sure this is not a line from a pre block
3294 ((looking-at-p pre-regexp))
3295 ;; If not, then update levels
3297 (setq indent (current-indentation))
3298 (setq levels (markdown-update-list-levels (match-string 2)
3299 indent levels))))
3300 (end-of-line))
3301 levels)))
3303 (defun markdown-prev-list-item (level)
3304 "Search backward from point for a list item with indentation LEVEL.
3305 Set point to the beginning of the item, and return point, or nil
3306 upon failure."
3307 (let (bounds indent prev)
3308 (setq prev (point))
3309 (forward-line -1)
3310 (setq indent (current-indentation))
3311 (while
3312 (cond
3313 ;; List item
3314 ((and (looking-at-p markdown-regex-list)
3315 (setq bounds (markdown-cur-list-item-bounds)))
3316 (cond
3317 ;; Stop and return point at item of equal indentation
3318 ((= (nth 3 bounds) level)
3319 (setq prev (point))
3320 nil)
3321 ;; Stop and return nil at item with lesser indentation
3322 ((< (nth 3 bounds) level)
3323 (setq prev nil)
3324 nil)
3325 ;; Stop at beginning of buffer
3326 ((bobp) (setq prev nil))
3327 ;; Continue at item with greater indentation
3328 ((> (nth 3 bounds) level) t)))
3329 ;; Stop at beginning of buffer
3330 ((bobp) (setq prev nil))
3331 ;; Continue if current line is blank
3332 ((markdown-cur-line-blank-p) t)
3333 ;; Continue while indentation is the same or greater
3334 ((>= indent level) t)
3335 ;; Stop if current indentation is less than list item
3336 ;; and the next is blank
3337 ((and (< indent level)
3338 (markdown-next-line-blank-p))
3339 (setq prev nil))
3340 ;; Stop at a header
3341 ((looking-at-p markdown-regex-header) (setq prev nil))
3342 ;; Stop at a horizontal rule
3343 ((looking-at-p markdown-regex-hr) (setq prev nil))
3344 ;; Otherwise, continue.
3345 (t t))
3346 (forward-line -1)
3347 (setq indent (current-indentation)))
3348 prev))
3350 (defun markdown-next-list-item (level)
3351 "Search forward from point for the next list item with indentation LEVEL.
3352 Set point to the beginning of the item, and return point, or nil
3353 upon failure."
3354 (let (bounds indent next)
3355 (setq next (point))
3356 (if (looking-at markdown-regex-header-setext)
3357 (goto-char (match-end 0)))
3358 (forward-line)
3359 (setq indent (current-indentation))
3360 (while
3361 (cond
3362 ;; Stop at end of the buffer.
3363 ((eobp) nil)
3364 ;; Continue if the current line is blank
3365 ((markdown-cur-line-blank-p) t)
3366 ;; List item
3367 ((and (looking-at-p markdown-regex-list)
3368 (setq bounds (markdown-cur-list-item-bounds)))
3369 (cond
3370 ;; Continue at item with greater indentation
3371 ((> (nth 3 bounds) level) t)
3372 ;; Stop and return point at item of equal indentation
3373 ((= (nth 3 bounds) level)
3374 (setq next (point))
3375 nil)
3376 ;; Stop and return nil at item with lesser indentation
3377 ((< (nth 3 bounds) level)
3378 (setq next nil)
3379 nil)))
3380 ;; Continue while indentation is the same or greater
3381 ((>= indent level) t)
3382 ;; Stop if current indentation is less than list item
3383 ;; and the previous line was blank.
3384 ((and (< indent level)
3385 (markdown-prev-line-blank-p))
3386 (setq next nil))
3387 ;; Stop at a header
3388 ((looking-at-p markdown-regex-header) (setq next nil))
3389 ;; Stop at a horizontal rule
3390 ((looking-at-p markdown-regex-hr) (setq next nil))
3391 ;; Otherwise, continue.
3392 (t t))
3393 (forward-line)
3394 (setq indent (current-indentation)))
3395 next))
3397 (defun markdown-cur-list-item-end (level)
3398 "Move to the end of the current list item with nonlist indentation LEVEL.
3399 If the point is not in a list item, do nothing."
3400 (let (indent)
3401 (forward-line)
3402 (setq indent (current-indentation))
3403 (while
3404 (cond
3405 ;; Stop at end of the buffer.
3406 ((eobp) nil)
3407 ;; Continue if the current line is blank
3408 ((markdown-cur-line-blank-p) t)
3409 ;; Continue while indentation is the same or greater
3410 ((>= indent level) t)
3411 ;; Stop if current indentation is less than list item
3412 ;; and the previous line was blank.
3413 ((and (< indent level)
3414 (markdown-prev-line-blank-p))
3415 nil)
3416 ;; Stop at a new list item of the same or lesser indentation
3417 ((looking-at-p markdown-regex-list) nil)
3418 ;; Stop at a header
3419 ((looking-at-p markdown-regex-header) nil)
3420 ;; Stop at a horizontal rule
3421 ((looking-at-p markdown-regex-hr) nil)
3422 ;; Otherwise, continue.
3423 (t t))
3424 (forward-line)
3425 (setq indent (current-indentation)))
3426 ;; Don't skip over whitespace for empty list items (marker and
3427 ;; whitespace only), just move to end of whitespace.
3428 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3429 (goto-char (match-end 3))
3430 (skip-syntax-backward "-"))))
3432 (defun markdown-cur-list-item-bounds ()
3433 "Return bounds and indentation of the current list item.
3434 Return a list of the following form:
3436 (begin end indent nonlist-indent marker checkbox)
3438 The named components are:
3440 - begin: Position of beginning of list item, including leading indentation.
3441 - end: Position of the end of the list item, including list item text.
3442 - indent: Number of characters of indentation before list marker (an integer).
3443 - nonlist-indent: Number characters of indentation, list
3444 marker, and whitespace following list marker (an integer).
3445 - marker: String containing the list marker and following whitespace
3446 (e.g., \"- \" or \"* \").
3447 - checkbox: String containing the GFM checkbox portion, if any,
3448 including any trailing whitespace before the text
3449 begins (e.g., \"[x] \").
3451 As an example, for the following unordered list item
3453 - item
3455 the returned list would be
3457 (1 14 3 5 \"- \" nil)
3459 If the point is not inside a list item, return nil.
3460 Leave match data intact for `markdown-regex-list'."
3461 (save-excursion
3462 (let ((cur (point)))
3463 (end-of-line)
3464 (when (re-search-backward markdown-regex-list nil t)
3465 (let* ((begin (match-beginning 0))
3466 (indent (length (match-string-no-properties 1)))
3467 (nonlist-indent (length (match-string 0)))
3468 (marker (concat (match-string-no-properties 2)
3469 (match-string-no-properties 3)))
3470 (checkbox (progn (goto-char (match-end 0))
3471 (when (looking-at "\\[[xX ]\\]\\s-*")
3472 (match-string-no-properties 0))))
3473 (end (save-match-data
3474 (markdown-cur-list-item-end nonlist-indent)
3475 (point))))
3476 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3477 (list begin end indent nonlist-indent marker checkbox)))))))
3479 (defun markdown-list-item-at-point-p ()
3480 "Return t if there is a list item at the point and nil otherwise."
3481 (save-match-data (markdown-cur-list-item-bounds)))
3483 (defun markdown-prev-list-item-bounds ()
3484 "Return bounds of previous item in the same list of any level.
3485 The return value has the same form as that of
3486 `markdown-cur-list-item-bounds'."
3487 (save-excursion
3488 (let ((cur-bounds (markdown-cur-list-item-bounds))
3489 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3490 stop)
3491 (when cur-bounds
3492 (goto-char (nth 0 cur-bounds))
3493 (while (and (not stop) (not (bobp))
3494 (re-search-backward markdown-regex-list
3495 beginning-of-list t))
3496 (unless (or (looking-at markdown-regex-hr)
3497 (markdown-code-block-at-point-p))
3498 (setq stop (point))))
3499 (markdown-cur-list-item-bounds)))))
3501 (defun markdown-next-list-item-bounds ()
3502 "Return bounds of next item in the same list of any level.
3503 The return value has the same form as that of
3504 `markdown-cur-list-item-bounds'."
3505 (save-excursion
3506 (let ((cur-bounds (markdown-cur-list-item-bounds))
3507 (end-of-list (save-excursion (markdown-end-of-list)))
3508 stop)
3509 (when cur-bounds
3510 (goto-char (nth 0 cur-bounds))
3511 (end-of-line)
3512 (while (and (not stop) (not (eobp))
3513 (re-search-forward markdown-regex-list
3514 end-of-list t))
3515 (unless (or (looking-at markdown-regex-hr)
3516 (markdown-code-block-at-point-p))
3517 (setq stop (point))))
3518 (when stop
3519 (markdown-cur-list-item-bounds))))))
3521 (defun markdown-beginning-of-list ()
3522 "Move point to beginning of list at point, if any."
3523 (interactive)
3524 (let ((orig-point (point))
3525 (list-begin (save-excursion
3526 (markdown-search-backward-baseline)
3527 ;; Stop at next list item, regardless of the indentation.
3528 (markdown-next-list-item (point-max))
3529 (when (looking-at markdown-regex-list)
3530 (point)))))
3531 (when (and list-begin (<= list-begin orig-point))
3532 (goto-char list-begin))))
3534 (defun markdown-end-of-list ()
3535 "Move point to end of list at point, if any."
3536 (interactive)
3537 (let ((start (point))
3538 (end (save-excursion
3539 (when (markdown-beginning-of-list)
3540 ;; Items can't have nonlist-indent <= 1, so this
3541 ;; moves past all list items.
3542 (markdown-next-list-item 1)
3543 (skip-syntax-backward "-")
3544 (unless (eobp) (forward-char 1))
3545 (point)))))
3546 (when (and end (>= end start))
3547 (goto-char end))))
3549 (defun markdown-up-list ()
3550 "Move point to beginning of parent list item."
3551 (interactive)
3552 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3553 (when cur-bounds
3554 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3555 (let ((up-bounds (markdown-cur-list-item-bounds)))
3556 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3557 (point))))))
3559 (defun markdown-bounds-of-thing-at-point (thing)
3560 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3561 Does not include trailing newlines when THING is 'line. Handles the
3562 end of buffer case by setting both endpoints equal to the value of
3563 `point-max', since an empty region will trigger empty markup insertion.
3564 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3565 (let* ((bounds (bounds-of-thing-at-point thing))
3566 (a (car bounds))
3567 (b (cdr bounds)))
3568 (when bounds
3569 (when (eq thing 'line)
3570 (cond ((and (eobp) (markdown-cur-line-blank-p))
3571 (setq a b))
3572 ((char-equal (char-before b) ?\^J)
3573 (setq b (1- b)))))
3574 (cons a b))))
3576 (defun markdown-reference-definition (reference)
3577 "Find out whether Markdown REFERENCE is defined.
3578 REFERENCE should not include the square brackets.
3579 When REFERENCE is defined, return a list of the form (text start end)
3580 containing the definition text itself followed by the start and end
3581 locations of the text. Otherwise, return nil.
3582 Leave match data for `markdown-regex-reference-definition'
3583 intact additional processing."
3584 (let ((reference (downcase reference)))
3585 (save-excursion
3586 (goto-char (point-min))
3587 (catch 'found
3588 (while (re-search-forward markdown-regex-reference-definition nil t)
3589 (when (string= reference (downcase (match-string-no-properties 2)))
3590 (throw 'found
3591 (list (match-string-no-properties 5)
3592 (match-beginning 5) (match-end 5)))))))))
3594 (defun markdown-get-defined-references ()
3595 "Return a list of all defined reference labels (not including square brackets)."
3596 (save-excursion
3597 (goto-char (point-min))
3598 (let (refs)
3599 (while (re-search-forward markdown-regex-reference-definition nil t)
3600 (let ((target (match-string-no-properties 2)))
3601 (cl-pushnew target refs :test #'equal)))
3602 (reverse refs))))
3604 (defun markdown-get-used-uris ()
3605 "Return a list of all used URIs in the buffer."
3606 (save-excursion
3607 (goto-char (point-min))
3608 (let (uris)
3609 (while (re-search-forward
3610 (concat "\\(?:" markdown-regex-link-inline
3611 "\\|" markdown-regex-angle-uri
3612 "\\|" markdown-regex-uri
3613 "\\|" markdown-regex-email
3614 "\\)")
3615 nil t)
3616 (unless (or (markdown-inline-code-at-point-p)
3617 (markdown-code-block-at-point-p))
3618 (cl-pushnew (or (match-string-no-properties 6)
3619 (match-string-no-properties 10)
3620 (match-string-no-properties 12)
3621 (match-string-no-properties 13))
3622 uris :test #'equal)))
3623 (reverse uris))))
3625 (defun markdown-inline-code-at-pos (pos)
3626 "Return non-nil if there is an inline code fragment at POS.
3627 Return nil otherwise. Set match data according to
3628 `markdown-match-code' upon success.
3629 This function searches the block for a code fragment that
3630 contains the point using `markdown-match-code'. We do this
3631 because `thing-at-point-looking-at' does not work reliably with
3632 `markdown-regex-code'.
3634 The match data is set as follows:
3635 Group 1 matches the opening backquotes.
3636 Group 2 matches the code fragment itself, without backquotes.
3637 Group 3 matches the closing backquotes."
3638 (save-excursion
3639 (goto-char pos)
3640 (let ((old-point (point))
3641 (end-of-block (progn (markdown-end-of-text-block) (point)))
3642 found)
3643 (markdown-beginning-of-text-block)
3644 (while (and (markdown-match-code end-of-block)
3645 (setq found t)
3646 (< (match-end 0) old-point)))
3647 (and found ; matched something
3648 (<= (match-beginning 0) old-point) ; match contains old-point
3649 (>= (match-end 0) old-point)))))
3651 (defun markdown-inline-code-at-pos-p (pos)
3652 "Return non-nil if there is an inline code fragment at POS.
3653 Like `markdown-inline-code-at-pos`, but preserves match data."
3654 (save-match-data (markdown-inline-code-at-pos pos)))
3656 (defun markdown-inline-code-at-point ()
3657 "Return non-nil if the point is at an inline code fragment.
3658 See `markdown-inline-code-at-pos' for details."
3659 (markdown-inline-code-at-pos (point)))
3661 (defun markdown-inline-code-at-point-p ()
3662 "Return non-nil if there is inline code at the point.
3663 This is a predicate function counterpart to
3664 `markdown-inline-code-at-point' which does not modify the match
3665 data. See `markdown-code-block-at-point-p' for code blocks."
3666 (save-match-data (markdown-inline-code-at-pos (point))))
3668 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3670 (defun markdown-code-block-at-pos (pos)
3671 "Return match data list if there is a code block at POS.
3672 Uses text properties at the beginning of the line position.
3673 This includes pre blocks, tilde-fenced code blocks, and GFM
3674 quoted code blocks. Return nil otherwise."
3675 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3676 (or (get-text-property pos 'markdown-pre)
3677 (markdown-get-enclosing-fenced-block-construct pos)
3678 ;; polymode removes text properties set by markdown-mode, so
3679 ;; check if `poly-markdown-mode' is active and whether the
3680 ;; `chunkmode' property is non-nil at POS.
3681 (and (bound-and-true-p poly-markdown-mode)
3682 (get-text-property pos 'chunkmode))))
3684 ;; Function was renamed to emphasize that it does not modify match-data.
3685 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3687 (defun markdown-code-block-at-point-p ()
3688 "Return non-nil if there is a code block at the point.
3689 This includes pre blocks, tilde-fenced code blocks, and GFM
3690 quoted code blocks. This function does not modify the match
3691 data. See `markdown-inline-code-at-point-p' for inline code."
3692 (save-match-data (markdown-code-block-at-pos (point))))
3694 (defun markdown-heading-at-point ()
3695 "Return non-nil if there is a heading at the point.
3696 Set match data for `markdown-regex-header'."
3697 (let ((match-data (get-text-property (point) 'markdown-heading)))
3698 (when match-data
3699 (set-match-data match-data)
3700 t)))
3702 (defun markdown-pipe-at-bol-p ()
3703 "Return non-nil if the line begins with a pipe symbol.
3704 This may be useful for tables and Pandoc's line_blocks extension."
3705 (char-equal (char-after (point-at-bol)) ?|))
3708 ;;; Markdown Font Lock Matching Functions =====================================
3710 (defun markdown-range-property-any (begin end prop prop-values)
3711 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3712 Also returns t if PROP is a list containing one of the PROP-VALUES.
3713 Return nil otherwise."
3714 (let (props)
3715 (catch 'found
3716 (dolist (loc (number-sequence begin end))
3717 (when (setq props (get-text-property loc prop))
3718 (cond ((listp props)
3719 ;; props is a list, check for membership
3720 (dolist (val prop-values)
3721 (when (memq val props) (throw 'found loc))))
3723 ;; props is a scalar, check for equality
3724 (dolist (val prop-values)
3725 (when (eq val props) (throw 'found loc))))))))))
3727 (defun markdown-range-properties-exist (begin end props)
3728 (cl-loop
3729 for loc in (number-sequence begin end)
3730 with result = nil
3731 while (not
3732 (setq result
3733 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3734 finally return result))
3736 (defun markdown-match-inline-generic (regex last &optional faceless)
3737 "Match inline REGEX from the point to LAST.
3738 When FACELESS is non-nil, do not return matches where faces have been applied."
3739 (when (re-search-forward regex last t)
3740 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3741 (face (and faceless (text-property-not-all
3742 (match-beginning 0) (match-end 0) 'face nil))))
3743 (cond
3744 ;; In code block: move past it and recursively search again
3745 (bounds
3746 (when (< (goto-char (cl-second bounds)) last)
3747 (markdown-match-inline-generic regex last faceless)))
3748 ;; When faces are found in the match range, skip over the match and
3749 ;; recursively search again.
3750 (face
3751 (when (< (goto-char (match-end 0)) last)
3752 (markdown-match-inline-generic regex last faceless)))
3753 ;; Keep match data and return t when in bounds.
3755 (<= (match-end 0) last))))))
3757 (defun markdown-match-code (last)
3758 "Match inline code fragments from point to LAST."
3759 (unless (bobp)
3760 (backward-char 1))
3761 (when (markdown-match-inline-generic markdown-regex-code last)
3762 (let ((begin (match-beginning 1))
3763 (end (match-end 1))
3764 (open-begin (match-beginning 2))
3765 (open-end (match-end 2))
3766 (code-begin (match-beginning 3))
3767 (code-end (match-end 3))
3768 (close-begin (match-beginning 4))
3769 (close-end (match-end 4)))
3770 (if (or (markdown-in-comment-p begin)
3771 (markdown-in-comment-p end)
3772 (markdown-code-block-at-pos begin))
3773 (progn (goto-char (min (1+ begin) last))
3774 (when (< (point) last)
3775 (markdown-match-code last)))
3776 (set-match-data (list begin end
3777 open-begin open-end
3778 code-begin code-end
3779 close-begin close-end))
3780 t))))
3782 (defun markdown-match-bold (last)
3783 "Match inline bold from the point to LAST."
3784 (when (markdown-match-inline-generic markdown-regex-bold last)
3785 (let ((begin (match-beginning 2))
3786 (end (match-end 2)))
3787 (if (or (markdown-inline-code-at-pos-p begin)
3788 (markdown-inline-code-at-pos-p end)
3789 (markdown-in-comment-p)
3790 (markdown-range-property-any
3791 begin begin 'face '(markdown-url-face
3792 markdown-plain-url-face))
3793 (markdown-range-property-any
3794 begin end 'face '(markdown-math-face)))
3795 (progn (goto-char (min (1+ begin) last))
3796 (when (< (point) last)
3797 (markdown-match-italic last)))
3798 (set-match-data (list (match-beginning 2) (match-end 2)
3799 (match-beginning 3) (match-end 3)
3800 (match-beginning 4) (match-end 4)
3801 (match-beginning 5) (match-end 5)))
3802 t))))
3804 (defun markdown-match-italic (last)
3805 "Match inline italics from the point to LAST."
3806 (let ((regex (if (eq major-mode 'gfm-mode)
3807 markdown-regex-gfm-italic markdown-regex-italic)))
3808 (when (markdown-match-inline-generic regex last)
3809 (let ((begin (match-beginning 1))
3810 (end (match-end 1)))
3811 (if (or (markdown-inline-code-at-pos-p begin)
3812 (markdown-inline-code-at-pos-p end)
3813 (markdown-in-comment-p)
3814 (markdown-range-property-any
3815 begin begin 'face '(markdown-url-face
3816 markdown-plain-url-face))
3817 (markdown-range-property-any
3818 begin end 'face '(markdown-bold-face
3819 markdown-list-face
3820 markdown-math-face)))
3821 (progn (goto-char (min (1+ begin) last))
3822 (when (< (point) last)
3823 (markdown-match-italic last)))
3824 (set-match-data (list (match-beginning 1) (match-end 1)
3825 (match-beginning 2) (match-end 2)
3826 (match-beginning 3) (match-end 3)
3827 (match-beginning 4) (match-end 4)))
3828 t)))))
3830 (defun markdown-match-math-generic (regex last)
3831 "Match REGEX from point to LAST.
3832 REGEX is either `markdown-regex-math-inline-single' for matching
3833 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3834 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3835 (let ((begin (match-beginning 1)) (end (match-end 1)))
3836 (prog1
3837 (if (or (markdown-range-property-any
3838 begin end 'face (list markdown-inline-code-face
3839 markdown-bold-face))
3840 (markdown-range-properties-exist
3841 begin end
3842 (markdown-get-fenced-block-middle-properties)))
3843 (markdown-match-math-generic regex last)
3845 (goto-char (1+ (match-end 0)))))))
3847 (defun markdown-match-list-items (last)
3848 "Match list items from point to LAST."
3849 (when (markdown-match-inline-generic markdown-regex-list last)
3850 (let ((begin (match-beginning 2))
3851 (end (match-end 2)))
3852 (if (or (markdown-range-property-any
3853 begin end 'face (list markdown-inline-code-face
3854 markdown-bold-face
3855 markdown-math-face))
3856 (markdown-range-properties-exist begin end '(markdown-hr))
3857 (markdown-in-comment-p))
3858 (progn (goto-char (min (1+ (match-end 0)) last))
3859 (markdown-match-list-items last))
3860 (set-match-data (list (match-beginning 0) (match-end 0)
3861 (match-beginning 1) (match-end 1)
3862 (match-beginning 2) (match-end 2)))
3863 (goto-char (1+ (match-end 0)))))))
3865 (defun markdown-match-math-single (last)
3866 "Match single quoted $..$ math from point to LAST."
3867 (markdown-match-math-generic markdown-regex-math-inline-single last))
3869 (defun markdown-match-math-double (last)
3870 "Match double quoted $$..$$ math from point to LAST."
3871 (markdown-match-math-generic markdown-regex-math-inline-double last))
3873 (defun markdown-match-math-display (last)
3874 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3875 (markdown-match-math-generic markdown-regex-math-display last))
3877 (defun markdown-match-propertized-text (property last)
3878 "Match text with PROPERTY from point to LAST.
3879 Restore match data previously stored in PROPERTY."
3880 (let ((saved (get-text-property (point) property))
3881 pos)
3882 (unless saved
3883 (setq pos (next-single-char-property-change (point) property nil last))
3884 (setq saved (get-text-property pos property)))
3885 (when saved
3886 (set-match-data saved)
3887 ;; Step at least one character beyond point. Otherwise
3888 ;; `font-lock-fontify-keywords-region' infloops.
3889 (goto-char (min (1+ (max (match-end 0) (point)))
3890 (point-max)))
3891 saved)))
3893 (defun markdown-match-pre-blocks (last)
3894 "Match preformatted blocks from point to LAST.
3895 Use data stored in 'markdown-pre text property during syntax
3896 analysis."
3897 (markdown-match-propertized-text 'markdown-pre last))
3899 (defun markdown-match-gfm-code-blocks (last)
3900 "Match GFM quoted code blocks from point to LAST.
3901 Use data stored in 'markdown-gfm-code text property during syntax
3902 analysis."
3903 (markdown-match-propertized-text 'markdown-gfm-code last))
3905 (defun markdown-match-gfm-open-code-blocks (last)
3906 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3908 (defun markdown-match-gfm-close-code-blocks (last)
3909 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3911 (defun markdown-match-fenced-code-blocks (last)
3912 "Match fenced code blocks from the point to LAST."
3913 (markdown-match-propertized-text 'markdown-fenced-code last))
3915 (defun markdown-match-fenced-start-code-block (last)
3916 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3918 (defun markdown-match-fenced-end-code-block (last)
3919 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3921 (defun markdown-match-blockquotes (last)
3922 "Match blockquotes from point to LAST.
3923 Use data stored in 'markdown-blockquote text property during syntax
3924 analysis."
3925 (markdown-match-propertized-text 'markdown-blockquote last))
3927 (defun markdown-match-hr (last)
3928 "Match horizontal rules comments from the point to LAST."
3929 (markdown-match-propertized-text 'markdown-hr last))
3931 (defun markdown-match-comments (last)
3932 "Match HTML comments from the point to LAST."
3933 (when (and (skip-syntax-forward "^<" last))
3934 (let ((beg (point)))
3935 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3936 (forward-char)
3937 (set-match-data (list beg (point)))
3938 t))))
3940 (defun markdown-match-generic-links (last ref)
3941 "Match inline links from point to LAST.
3942 When REF is non-nil, match reference links instead of standard
3943 links with URLs."
3944 ;; Search for the next potential link (not in a code block).
3945 (while (and (progn
3946 ;; Clear match data to test for a match after functions returns.
3947 (set-match-data nil)
3948 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
3949 ;; Keep searching if this is in a code block, inline
3950 ;; code, or a comment, or if it is include syntax.
3951 (or (markdown-code-block-at-point-p)
3952 (markdown-inline-code-at-pos-p (match-beginning 0))
3953 (markdown-inline-code-at-pos-p (match-end 0))
3954 (markdown-in-comment-p)
3955 (and (char-equal (char-after (point-at-bol)) ?<)
3956 (char-equal (char-after (1+ (point-at-bol))) ?<)))
3957 (< (point) last)))
3958 ;; Match opening exclamation point (optional) and left bracket.
3959 (when (match-beginning 2)
3960 (let* ((bang (match-beginning 1))
3961 (first-begin (match-beginning 2))
3962 ;; Find end of block to prevent matching across blocks.
3963 (end-of-block (save-excursion
3964 (progn
3965 (goto-char (match-beginning 2))
3966 (markdown-end-of-text-block)
3967 (point))))
3968 ;; Move over balanced expressions to closing right bracket.
3969 ;; Catch unbalanced expression errors and return nil.
3970 (first-end (condition-case nil
3971 (and (goto-char first-begin)
3972 (scan-sexps (point) 1))
3973 (error nil)))
3974 ;; Continue with point at CONT-POINT upon failure.
3975 (cont-point (min (1+ first-begin) last))
3976 second-begin second-end url-begin url-end
3977 title-begin title-end)
3978 ;; When bracket found, in range, and followed by a left paren/bracket...
3979 (when (and first-end (< first-end end-of-block) (goto-char first-end)
3980 (char-equal (char-after (point)) (if ref ?\[ ?\()))
3981 ;; Scan across balanced expressions for closing parenthesis/bracket.
3982 (setq second-begin (point)
3983 second-end (condition-case nil
3984 (scan-sexps (point) 1)
3985 (error nil)))
3986 ;; Check that closing parenthesis/bracket is in range.
3987 (if (and second-end (<= second-end end-of-block) (<= second-end last))
3988 (progn
3989 ;; Search for (optional) title inside closing parenthesis
3990 (when (and (not ref) (search-forward "\"" second-end t))
3991 (setq title-begin (1- (point))
3992 title-end (and (goto-char second-end)
3993 (search-backward "\"" (1+ title-begin) t))
3994 title-end (and title-end (1+ title-end))))
3995 ;; Store URL/reference range
3996 (setq url-begin (1+ second-begin)
3997 url-end (1- (or title-begin second-end)))
3998 ;; Set match data, move point beyond link, and return
3999 (set-match-data
4000 (list (or bang first-begin) second-end ; 0 - all
4001 bang (and bang (1+ bang)) ; 1 - bang
4002 first-begin (1+ first-begin) ; 2 - markup
4003 (1+ first-begin) (1- first-end) ; 3 - link text
4004 (1- first-end) first-end ; 4 - markup
4005 second-begin (1+ second-begin) ; 5 - markup
4006 url-begin url-end ; 6 - url/reference
4007 title-begin title-end ; 7 - title
4008 (1- second-end) second-end)) ; 8 - markup
4009 ;; Nullify cont-point and leave point at end and
4010 (setq cont-point nil)
4011 (goto-char second-end))
4012 ;; If no closing parenthesis in range, update continuation point
4013 (setq cont-point (min end-of-block second-begin))))
4014 (cond
4015 ;; On failure, continue searching at cont-point
4016 ((and cont-point (< cont-point last))
4017 (goto-char cont-point)
4018 (markdown-match-generic-links last ref))
4019 ;; No more text, return nil
4020 ((and cont-point (= cont-point last))
4021 nil)
4022 ;; Return t if a match occurred
4023 (t t)))))
4025 (defun markdown-match-inline-links (last)
4026 "Match standard inline links from point to LAST."
4027 (markdown-match-generic-links last nil))
4029 (defun markdown-match-reference-links (last)
4030 "Match inline reference links from point to LAST."
4031 (markdown-match-generic-links last t))
4033 (defun markdown-match-angle-uris (last)
4034 "Match angle bracket URIs from point to LAST."
4035 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
4036 (goto-char (1+ (match-end 0)))))
4038 (defun markdown-match-plain-uris (last)
4039 "Match plain URIs from point to LAST."
4040 (when (markdown-match-inline-generic markdown-regex-uri last t)
4041 (goto-char (1+ (match-end 0)))))
4043 (defvar markdown-conditional-search-function #'re-search-forward
4044 "Conditional search function used in `markdown-search-until-condition'.
4045 Made into a variable to allow for dynamic let-binding.")
4047 (defun markdown-search-until-condition (condition &rest args)
4048 (let (ret)
4049 (while (and (not ret) (apply markdown-conditional-search-function args))
4050 (setq ret (funcall condition)))
4051 ret))
4053 (defun markdown-match-generic-metadata
4054 (regexp last &optional block-begin-re block-end-re)
4055 "Match metadata declarations specified by REGEXP from point to LAST.
4056 These declarations must appear inside a metadata block specified
4057 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
4058 expression denoting the beginning of a metadata block. If it is
4059 nil, we assume metadata can only appear at the beginning of the
4060 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
4061 the end of a metadata block. If it is nil, assume blocks end with
4062 a blank line or the end of the buffer. There may be at most one such
4063 block in a file. Subsequent blocks will be ignored."
4064 (let* ((first (point))
4065 (begin-re (or block-begin-re "\\`"))
4066 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
4068 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4069 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4070 ;; (block-begin (or prev-block-begin next-block-begin))
4072 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4073 (re-search-forward begin-re last t))
4074 (match-end 0)))
4076 (block-end (and block-begin (goto-char block-begin)
4077 (re-search-forward end-re nil t))))
4078 (cond
4079 ;; Don't match declarations if there is no metadata block or if
4080 ;; the point is beyond the block. Move point to point-max to
4081 ;; prevent additional searches and return return nil since nothing
4082 ;; was found.
4083 ((or (null block-begin) (and block-end (> first block-end)))
4084 (goto-char (point-max))
4085 nil)
4086 ;; No declarations to match if a block was found but not in
4087 ;; range. Move point to LAST, to resume there, and return nil.
4088 ((> block-begin last)
4089 (goto-char last)
4090 nil)
4091 ;; If a block was found that begins before LAST and ends after
4092 ;; point, search for declarations inside it.
4094 ;; If the starting is before the beginning of the block, start
4095 ;; there. Otherwise, move back to FIRST.
4096 (goto-char (if (< first block-begin) block-begin first))
4097 (if (re-search-forward regexp (min last block-end) t)
4098 ;; If a metadata declaration is found, set match-data and return t.
4099 (let ((key-beginning (match-beginning 1))
4100 (key-end (match-end 1))
4101 (markup-begin (match-beginning 2))
4102 (markup-end (match-end 2))
4103 (value-beginning (match-beginning 3)))
4104 (set-match-data (list key-beginning (point) ; complete metadata
4105 key-beginning key-end ; key
4106 markup-begin markup-end ; markup
4107 value-beginning (point))) ; value
4109 ;; Otherwise, move the point to last and return nil
4110 (goto-char last)
4111 nil)))))
4113 (defun markdown-match-declarative-metadata (last)
4114 "Match declarative metadata from the point to LAST."
4115 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4117 (defun markdown-match-pandoc-metadata (last)
4118 "Match Pandoc metadata from the point to LAST."
4119 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4121 (defun markdown-match-yaml-metadata-begin (last)
4122 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4124 (defun markdown-match-yaml-metadata-end (last)
4125 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4127 (defun markdown-match-yaml-metadata-key (last)
4128 (markdown-match-propertized-text 'markdown-metadata-key last))
4130 (defun markdown-match-wiki-link (last)
4131 "Match wiki links from point to LAST."
4132 (when (and markdown-enable-wiki-links
4133 (not markdown-wiki-link-fontify-missing)
4134 (markdown-match-inline-generic markdown-regex-wiki-link last))
4135 (let ((begin (match-beginning 1)) (end (match-end 1)))
4136 (if (or (markdown-in-comment-p begin)
4137 (markdown-in-comment-p end)
4138 (markdown-inline-code-at-pos-p begin)
4139 (markdown-inline-code-at-pos-p end)
4140 (markdown-code-block-at-pos begin))
4141 (progn (goto-char (min (1+ begin) last))
4142 (when (< (point) last)
4143 (markdown-match-wiki-link last)))
4144 (set-match-data (list begin end))
4145 t))))
4147 (defun markdown-match-inline-attributes (last)
4148 "Match inline attributes from point to LAST."
4149 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4150 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4151 (markdown-inline-code-at-pos-p (match-end 0))
4152 (markdown-in-comment-p))
4153 t)))
4155 (defun markdown-match-leanpub-sections (last)
4156 "Match Leanpub section markers from point to LAST."
4157 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4158 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4159 (markdown-inline-code-at-pos-p (match-end 0))
4160 (markdown-in-comment-p))
4161 t)))
4163 (defun markdown-match-includes (last)
4164 "Match include statements from point to LAST.
4165 Sets match data for the following seven groups:
4166 Group 1: opening two angle brackets
4167 Group 2: opening title delimiter (optional)
4168 Group 3: title text (optional)
4169 Group 4: closing title delimiter (optional)
4170 Group 5: opening filename delimiter
4171 Group 6: filename
4172 Group 7: closing filename delimiter"
4173 (when (markdown-match-inline-generic markdown-regex-include last)
4174 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4175 (markdown-in-comment-p (match-end 0))
4176 (markdown-code-block-at-pos (match-beginning 0))))))
4177 (cond
4178 ;; Parentheses and maybe square brackets, but no curly braces:
4179 ;; match optional title in square brackets and file in parentheses.
4180 ((and valid (match-beginning 5)
4181 (not (match-beginning 8)))
4182 (set-match-data (list (match-beginning 1) (match-end 7)
4183 (match-beginning 1) (match-end 1)
4184 (match-beginning 2) (match-end 2)
4185 (match-beginning 3) (match-end 3)
4186 (match-beginning 4) (match-end 4)
4187 (match-beginning 5) (match-end 5)
4188 (match-beginning 6) (match-end 6)
4189 (match-beginning 7) (match-end 7))))
4190 ;; Only square brackets present: match file in square brackets.
4191 ((and valid (match-beginning 2)
4192 (not (match-beginning 5))
4193 (not (match-beginning 7)))
4194 (set-match-data (list (match-beginning 1) (match-end 4)
4195 (match-beginning 1) (match-end 1)
4196 nil nil
4197 nil nil
4198 nil nil
4199 (match-beginning 2) (match-end 2)
4200 (match-beginning 3) (match-end 3)
4201 (match-beginning 4) (match-end 4))))
4202 ;; Only curly braces present: match file in curly braces.
4203 ((and valid (match-beginning 8)
4204 (not (match-beginning 2))
4205 (not (match-beginning 5)))
4206 (set-match-data (list (match-beginning 1) (match-end 10)
4207 (match-beginning 1) (match-end 1)
4208 nil nil
4209 nil nil
4210 nil nil
4211 (match-beginning 8) (match-end 8)
4212 (match-beginning 9) (match-end 9)
4213 (match-beginning 10) (match-end 10))))
4215 ;; Not a valid match, move to next line and search again.
4216 (forward-line)
4217 (when (< (point) last)
4218 (setq valid (markdown-match-includes last)))))
4219 valid)))
4221 (defun markdown-match-html-tag (last)
4222 "Match HTML tags from point to LAST."
4223 (when (and markdown-enable-html
4224 (markdown-match-inline-generic markdown-regex-html-tag last t))
4225 (set-match-data (list (match-beginning 0) (match-end 0)
4226 (match-beginning 1) (match-end 1)
4227 (match-beginning 2) (match-end 2)
4228 (match-beginning 9) (match-end 9)))
4232 ;;; Markdown Font Fontification Functions =====================================
4234 (defun markdown--first-displayable (seq)
4235 "Return the first displayable character or string in SEQ.
4236 SEQ may be an atom or a sequence."
4237 (let ((seq (if (listp seq) seq (list seq))))
4238 (cond ((stringp (car seq))
4239 (cl-find-if
4240 (lambda (str)
4241 (and (mapcar #'char-displayable-p (string-to-list str))))
4242 seq))
4243 ((characterp (car seq))
4244 (cl-find-if #'char-displayable-p seq)))))
4246 (defun markdown--marginalize-string (level)
4247 "Generate atx markup string of given LEVEL for left margin."
4248 (let ((margin-left-space-count
4249 (- markdown-marginalize-headers-margin-width level)))
4250 (concat (make-string margin-left-space-count ? )
4251 (make-string level ?#))))
4253 (defun markdown-marginalize-update-current ()
4254 "Update the window configuration to create a left margin."
4255 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4256 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4257 (let* ((header-delimiter-font-width
4258 (window-font-width nil 'markdown-header-delimiter-face))
4259 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4260 header-delimiter-font-width))
4261 (margin-char-width (/ margin-pixel-width (default-font-width))))
4262 (set-window-margins nil margin-char-width))
4263 ;; As a fallback, simply set margin based on character count.
4264 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4266 (defun markdown-fontify-headings (last)
4267 "Add text properties to headings from point to LAST."
4268 (when (markdown-match-propertized-text 'markdown-heading last)
4269 (let* ((level (markdown-outline-level))
4270 (heading-face
4271 (intern (format "markdown-header-face-%d" level)))
4272 (heading-props `(face ,heading-face))
4273 (left-markup-props
4274 `(face markdown-header-delimiter-face
4275 ,@(cond
4276 (markdown-hide-markup
4277 `(display ""))
4278 (markdown-marginalize-headers
4279 `(display ((margin left-margin)
4280 ,(markdown--marginalize-string level)))))))
4281 (right-markup-props
4282 `(face markdown-header-delimiter-face
4283 ,@(when markdown-hide-markup `(display ""))))
4284 (rule-props `(face markdown-header-rule-face
4285 ,@(when markdown-hide-markup `(display "")))))
4286 (if (match-end 1)
4287 ;; Setext heading
4288 (progn (add-text-properties
4289 (match-beginning 1) (match-end 1) heading-props)
4290 (if (= level 1)
4291 (add-text-properties
4292 (match-beginning 2) (match-end 2) rule-props)
4293 (add-text-properties
4294 (match-beginning 3) (match-end 3) rule-props)))
4295 ;; atx heading
4296 (add-text-properties
4297 (match-beginning 4) (match-end 4) left-markup-props)
4298 (add-text-properties
4299 (match-beginning 5) (match-end 5) heading-props)
4300 (when (match-end 6)
4301 (add-text-properties
4302 (match-beginning 6) (match-end 6) right-markup-props))))
4305 (defun markdown-fontify-blockquotes (last)
4306 "Apply font-lock properties to blockquotes from point to LAST."
4307 (when (markdown-match-blockquotes last)
4308 (let ((display-string
4309 (markdown--first-displayable markdown-blockquote-display-char)))
4310 (add-text-properties
4311 (match-beginning 1) (match-end 1)
4312 (if markdown-hide-markup
4313 `(face markdown-blockquote-face display ,display-string)
4314 `(face markdown-markup-face)))
4315 (font-lock-append-text-property
4316 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4317 t)))
4319 (defun markdown-fontify-list-items (last)
4320 "Apply font-lock properties to list markers from point to LAST."
4321 (when (markdown-match-list-items last)
4322 (let* ((indent (length (match-string-no-properties 1)))
4323 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4324 (bullet (nth (mod level (length markdown-list-item-bullets))
4325 markdown-list-item-bullets)))
4326 (add-text-properties
4327 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4328 (when markdown-hide-markup
4329 (cond
4330 ;; Unordered lists
4331 ((string-match-p "[\\*\\+-]" (match-string 2))
4332 (add-text-properties
4333 (match-beginning 2) (match-end 2) `(display ,bullet)))
4334 ;; Definition lists
4335 ((string-equal ":" (match-string 2))
4336 (let ((display-string
4337 (char-to-string (markdown--first-displayable
4338 markdown-definition-display-char))))
4339 (add-text-properties (match-beginning 2) (match-end 2)
4340 `(display ,display-string)))))))
4343 (defun markdown-fontify-hrs (last)
4344 "Add text properties to horizontal rules from point to LAST."
4345 (when (markdown-match-hr last)
4346 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4347 (add-text-properties
4348 (match-beginning 0) (match-end 0)
4349 `(face markdown-hr-face
4350 font-lock-multiline t
4351 ,@(when (and markdown-hide-markup hr-char)
4352 `(display ,(make-string
4353 (window-body-width) hr-char)))))
4354 t)))
4356 (defun markdown-fontify-sub-superscripts (last)
4357 "Apply text properties to sub- and superscripts from point to LAST."
4358 (when (markdown-search-until-condition
4359 (lambda () (and (not (markdown-code-block-at-point-p))
4360 (not (markdown-inline-code-at-point-p))
4361 (not (markdown-in-comment-p))))
4362 markdown-regex-sub-superscript last t)
4363 (let* ((subscript-p (string= (match-string 2) "~"))
4364 (index (if subscript-p 0 1))
4365 (mp (list 'face 'markdown-markup-face
4366 'invisible 'markdown-markup)))
4367 (when markdown-hide-markup
4368 (put-text-property (match-beginning 3) (match-end 3)
4369 'display
4370 (nth index markdown-sub-superscript-display)))
4371 (add-text-properties (match-beginning 2) (match-end 2) mp)
4372 (add-text-properties (match-beginning 4) (match-end 4) mp)
4373 t)))
4376 ;;; Syntax Table ==============================================================
4378 (defvar markdown-mode-syntax-table
4379 (let ((tab (make-syntax-table text-mode-syntax-table)))
4380 (modify-syntax-entry ?\" "." tab)
4381 tab)
4382 "Syntax table for `markdown-mode'.")
4385 ;;; Element Insertion =========================================================
4387 (defun markdown-ensure-blank-line-before ()
4388 "If previous line is not already blank, insert a blank line before point."
4389 (unless (bolp) (insert "\n"))
4390 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4392 (defun markdown-ensure-blank-line-after ()
4393 "If following line is not already blank, insert a blank line after point.
4394 Return the point where it was originally."
4395 (save-excursion
4396 (unless (eolp) (insert "\n"))
4397 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4399 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4400 "Insert the strings S1 and S2, wrapping around region or THING.
4401 If a region is specified by the optional BEG and END arguments,
4402 wrap the strings S1 and S2 around that region.
4403 If there is an active region, wrap the strings S1 and S2 around
4404 the region. If there is not an active region but the point is at
4405 THING, wrap that thing (which defaults to word). Otherwise, just
4406 insert S1 and S2 and place the point in between. Return the
4407 bounds of the entire wrapped string, or nil if nothing was wrapped
4408 and S1 and S2 were only inserted."
4409 (let (a b bounds new-point)
4410 (cond
4411 ;; Given region
4412 ((and beg end)
4413 (setq a beg
4414 b end
4415 new-point (+ (point) (length s1))))
4416 ;; Active region
4417 ((markdown-use-region-p)
4418 (setq a (region-beginning)
4419 b (region-end)
4420 new-point (+ (point) (length s1))))
4421 ;; Thing (word) at point
4422 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4423 (setq a (car bounds)
4424 b (cdr bounds)
4425 new-point (+ (point) (length s1))))
4426 ;; No active region and no word
4428 (setq a (point)
4429 b (point))))
4430 (goto-char b)
4431 (insert s2)
4432 (goto-char a)
4433 (insert s1)
4434 (when new-point (goto-char new-point))
4435 (if (= a b)
4437 (setq b (+ b (length s1) (length s2)))
4438 (cons a b))))
4440 (defun markdown-point-after-unwrap (cur prefix suffix)
4441 "Return desired position of point after an unwrapping operation.
4442 CUR gives the position of the point before the operation.
4443 Additionally, two cons cells must be provided. PREFIX gives the
4444 bounds of the prefix string and SUFFIX gives the bounds of the
4445 suffix string."
4446 (cond ((< cur (cdr prefix)) (car prefix))
4447 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4448 ((<= cur (cdr suffix))
4449 (- cur (+ (- (cdr prefix) (car prefix))
4450 (- cur (car suffix)))))
4451 (t cur)))
4453 (defun markdown-unwrap-thing-at-point (regexp all text)
4454 "Remove prefix and suffix of thing at point and reposition the point.
4455 When the thing at point matches REGEXP, replace the subexpression
4456 ALL with the string in subexpression TEXT. Reposition the point
4457 in an appropriate location accounting for the removal of prefix
4458 and suffix strings. Return new bounds of string from group TEXT.
4459 When REGEXP is nil, assumes match data is already set."
4460 (when (or (null regexp)
4461 (thing-at-point-looking-at regexp))
4462 (let ((cur (point))
4463 (prefix (cons (match-beginning all) (match-beginning text)))
4464 (suffix (cons (match-end text) (match-end all)))
4465 (bounds (cons (match-beginning text) (match-end text))))
4466 ;; Replace the thing at point
4467 (replace-match (match-string text) t t nil all)
4468 ;; Reposition the point
4469 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4470 ;; Adjust bounds
4471 (setq bounds (cons (car prefix)
4472 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4474 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4475 "Remove prefix and suffix of all things in region from BEG to END.
4476 When a thing in the region matches REGEXP, replace the
4477 subexpression ALL with the string in subexpression TEXT.
4478 Return a cons cell containing updated bounds for the region."
4479 (save-excursion
4480 (goto-char beg)
4481 (let ((removed 0) len-all len-text)
4482 (while (re-search-forward regexp (- end removed) t)
4483 (setq len-all (length (match-string-no-properties all)))
4484 (setq len-text (length (match-string-no-properties text)))
4485 (setq removed (+ removed (- len-all len-text)))
4486 (replace-match (match-string text) t t nil all))
4487 (cons beg (- end removed)))))
4489 (defun markdown-insert-hr (arg)
4490 "Insert or replace a horizonal rule.
4491 By default, use the first element of `markdown-hr-strings'. When
4492 ARG is non-nil, as when given a prefix, select a different
4493 element as follows. When prefixed with \\[universal-argument],
4494 use the last element of `markdown-hr-strings' instead. When
4495 prefixed with an integer from 1 to the length of
4496 `markdown-hr-strings', use the element in that position instead."
4497 (interactive "*P")
4498 (when (thing-at-point-looking-at markdown-regex-hr)
4499 (delete-region (match-beginning 0) (match-end 0)))
4500 (markdown-ensure-blank-line-before)
4501 (cond ((equal arg '(4))
4502 (insert (car (reverse markdown-hr-strings))))
4503 ((and (integerp arg) (> arg 0)
4504 (<= arg (length markdown-hr-strings)))
4505 (insert (nth (1- arg) markdown-hr-strings)))
4507 (insert (car markdown-hr-strings))))
4508 (markdown-ensure-blank-line-after))
4510 (defun markdown-insert-bold ()
4511 "Insert markup to make a region or word bold.
4512 If there is an active region, make the region bold. If the point
4513 is at a non-bold word, make the word bold. If the point is at a
4514 bold word or phrase, remove the bold markup. Otherwise, simply
4515 insert bold delimiters and place the point in between them."
4516 (interactive)
4517 (let ((delim (if markdown-bold-underscore "__" "**")))
4518 (if (markdown-use-region-p)
4519 ;; Active region
4520 (let ((bounds (markdown-unwrap-things-in-region
4521 (region-beginning) (region-end)
4522 markdown-regex-bold 2 4)))
4523 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4524 ;; Bold markup removal, bold word at point, or empty markup insertion
4525 (if (thing-at-point-looking-at markdown-regex-bold)
4526 (markdown-unwrap-thing-at-point nil 2 4)
4527 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4529 (defun markdown-insert-italic ()
4530 "Insert markup to make a region or word italic.
4531 If there is an active region, make the region italic. If the point
4532 is at a non-italic word, make the word italic. If the point is at an
4533 italic word or phrase, remove the italic markup. Otherwise, simply
4534 insert italic delimiters and place the point in between them."
4535 (interactive)
4536 (let ((delim (if markdown-italic-underscore "_" "*")))
4537 (if (markdown-use-region-p)
4538 ;; Active region
4539 (let ((bounds (markdown-unwrap-things-in-region
4540 (region-beginning) (region-end)
4541 markdown-regex-italic 1 3)))
4542 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4543 ;; Italic markup removal, italic word at point, or empty markup insertion
4544 (if (thing-at-point-looking-at markdown-regex-italic)
4545 (markdown-unwrap-thing-at-point nil 1 3)
4546 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4548 (defun markdown-insert-strike-through ()
4549 "Insert markup to make a region or word strikethrough.
4550 If there is an active region, make the region strikethrough. If the point
4551 is at a non-bold word, make the word strikethrough. If the point is at a
4552 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4553 simply insert bold delimiters and place the point in between them."
4554 (interactive)
4555 (let ((delim "~~"))
4556 (if (markdown-use-region-p)
4557 ;; Active region
4558 (let ((bounds (markdown-unwrap-things-in-region
4559 (region-beginning) (region-end)
4560 markdown-regex-strike-through 2 4)))
4561 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4562 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4563 (if (thing-at-point-looking-at markdown-regex-strike-through)
4564 (markdown-unwrap-thing-at-point nil 2 4)
4565 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4567 (defun markdown-insert-code ()
4568 "Insert markup to make a region or word an inline code fragment.
4569 If there is an active region, make the region an inline code
4570 fragment. If the point is at a word, make the word an inline
4571 code fragment. Otherwise, simply insert code delimiters and
4572 place the point in between them."
4573 (interactive)
4574 (if (markdown-use-region-p)
4575 ;; Active region
4576 (let ((bounds (markdown-unwrap-things-in-region
4577 (region-beginning) (region-end)
4578 markdown-regex-code 1 3)))
4579 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4580 ;; Code markup removal, code markup for word, or empty markup insertion
4581 (if (markdown-inline-code-at-point)
4582 (markdown-unwrap-thing-at-point nil 0 2)
4583 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4585 (defun markdown-insert-kbd ()
4586 "Insert markup to wrap region or word in <kbd> tags.
4587 If there is an active region, use the region. If the point is at
4588 a word, use the word. Otherwise, simply insert <kbd> tags and
4589 place the point in between them."
4590 (interactive)
4591 (if (markdown-use-region-p)
4592 ;; Active region
4593 (let ((bounds (markdown-unwrap-things-in-region
4594 (region-beginning) (region-end)
4595 markdown-regex-kbd 0 2)))
4596 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4597 ;; Markup removal, markup for word, or empty markup insertion
4598 (if (thing-at-point-looking-at markdown-regex-kbd)
4599 (markdown-unwrap-thing-at-point nil 0 2)
4600 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4602 (defun markdown-insert-inline-link (text url &optional title)
4603 "Insert an inline link with TEXT pointing to URL.
4604 Optionally, the user can provide a TITLE."
4605 (let ((cur (point)))
4606 (setq title (and title (concat " \"" title "\"")))
4607 (insert (concat "[" text "](" url title ")"))
4608 (cond ((not text) (goto-char (+ 1 cur)))
4609 ((not url) (goto-char (+ 3 (length text) cur))))))
4611 (defun markdown-insert-inline-image (text url &optional title)
4612 "Insert an inline link with alt TEXT pointing to URL.
4613 Optionally, also provide a TITLE."
4614 (let ((cur (point)))
4615 (setq title (and title (concat " \"" title "\"")))
4616 (insert (concat "![" text "](" url title ")"))
4617 (cond ((not text) (goto-char (+ 2 cur)))
4618 ((not url) (goto-char (+ 4 (length text) cur))))))
4620 (defun markdown-insert-reference-link (text label &optional url title)
4621 "Insert a reference link and, optionally, a reference definition.
4622 The link TEXT will be inserted followed by the optional LABEL.
4623 If a URL is given, also insert a definition for the reference
4624 LABEL according to `markdown-reference-location'. If a TITLE is
4625 given, it will be added to the end of the reference definition
4626 and will be used to populate the title attribute when converted
4627 to XHTML. If URL is nil, insert only the link portion (for
4628 example, when a reference label is already defined)."
4629 (insert (concat "[" text "][" label "]"))
4630 (when url
4631 (markdown-insert-reference-definition
4632 (if (string-equal label "") text label)
4633 url title)))
4635 (defun markdown-insert-reference-image (text label &optional url title)
4636 "Insert a reference image and, optionally, a reference definition.
4637 The alt TEXT will be inserted followed by the optional LABEL.
4638 If a URL is given, also insert a definition for the reference
4639 LABEL according to `markdown-reference-location'. If a TITLE is
4640 given, it will be added to the end of the reference definition
4641 and will be used to populate the title attribute when converted
4642 to XHTML. If URL is nil, insert only the link portion (for
4643 example, when a reference label is already defined)."
4644 (insert (concat "![" text "][" label "]"))
4645 (when url
4646 (markdown-insert-reference-definition
4647 (if (string-equal label "") text label)
4648 url title)))
4650 (defun markdown-insert-reference-definition (label &optional url title)
4651 "Add definition for reference LABEL with URL and TITLE.
4652 LABEL is a Markdown reference label without square brackets.
4653 URL and TITLE are optional. When given, the TITLE will
4654 be used to populate the title attribute when converted to XHTML."
4655 ;; END specifies where to leave the point upon return
4656 (let ((end (point)))
4657 (cl-case markdown-reference-location
4658 (end (goto-char (point-max)))
4659 (immediately (markdown-end-of-text-block))
4660 (subtree (markdown-end-of-subtree))
4661 (header (markdown-end-of-defun)))
4662 ;; Skip backwards over local variables. This logic is similar to the one
4663 ;; used in ‘hack-local-variables’.
4664 (when (and enable-local-variables (eobp))
4665 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4666 (when (let ((case-fold-search t))
4667 (search-forward "Local Variables:" nil :move))
4668 (beginning-of-line 0)
4669 (when (eq (char-before) ?\n) (backward-char))))
4670 (unless (or (markdown-cur-line-blank-p)
4671 (thing-at-point-looking-at markdown-regex-reference-definition))
4672 (insert "\n"))
4673 (insert "\n[" label "]: ")
4674 (if url
4675 (insert url)
4676 ;; When no URL is given, leave point at END following the colon
4677 (setq end (point)))
4678 (when (> (length title) 0)
4679 (insert " \"" title "\""))
4680 (unless (looking-at-p "\n")
4681 (insert "\n"))
4682 (goto-char end)
4683 (when url
4684 (message
4685 (markdown--substitute-command-keys
4686 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4687 label))))
4689 (define-obsolete-function-alias
4690 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4691 (define-obsolete-function-alias
4692 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4694 (defun markdown--insert-link-or-image (image)
4695 "Interactively insert new or update an existing link or image.
4696 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4697 This is an internal function called by
4698 `markdown-insert-link' and `markdown-insert-image'."
4699 (cl-multiple-value-bind (begin end text uri ref title)
4700 (if (markdown-use-region-p)
4701 ;; Use region as either link text or URL as appropriate.
4702 (let ((region (buffer-substring-no-properties
4703 (region-beginning) (region-end))))
4704 (if (string-match markdown-regex-uri region)
4705 ;; Region contains a URL; use it as such.
4706 (list (region-beginning) (region-end)
4707 nil (match-string 0 region) nil nil)
4708 ;; Region doesn't contain a URL, so use it as text.
4709 (list (region-beginning) (region-end)
4710 region nil nil nil)))
4711 ;; Extract and use properties of existing link, if any.
4712 (markdown-link-at-pos (point)))
4713 (let* ((ref (when ref (concat "[" ref "]")))
4714 (defined-refs (append
4715 (mapcar (lambda (ref) (concat "[" ref "]"))
4716 (markdown-get-defined-references))))
4717 (used-uris (markdown-get-used-uris))
4718 (uri-or-ref (completing-read
4719 "URL or [reference]: "
4720 (append defined-refs used-uris)
4721 nil nil (or uri ref)))
4722 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4723 (match-string 1 uri-or-ref))
4724 ((string-equal "" uri-or-ref)
4725 "")))
4726 (uri (unless ref uri-or-ref))
4727 (text-prompt (if image
4728 "Alt text: "
4729 (if ref
4730 "Link text: "
4731 "Link text (blank for plain URL): ")))
4732 (text (read-string text-prompt text))
4733 (text (if (= (length text) 0) nil text))
4734 (plainp (and uri (not text)))
4735 (implicitp (string-equal ref ""))
4736 (ref (if implicitp text ref))
4737 (definedp (and ref (markdown-reference-definition ref)))
4738 (ref-url (unless (or uri definedp)
4739 (completing-read "Reference URL: " used-uris)))
4740 (title (unless (or plainp definedp)
4741 (read-string "Title (tooltip text, optional): " title)))
4742 (title (if (= (length title) 0) nil title)))
4743 (when (and image implicitp)
4744 (user-error "Reference required: implicit image references are invalid"))
4745 (when (and begin end)
4746 (delete-region begin end))
4747 (cond
4748 ((and (not image) uri text)
4749 (markdown-insert-inline-link text uri title))
4750 ((and image uri text)
4751 (markdown-insert-inline-image text uri title))
4752 ((and ref text)
4753 (if image
4754 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4755 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4756 (unless definedp
4757 (markdown-insert-reference-definition ref ref-url title)))
4758 ((and (not image) uri)
4759 (markdown-insert-uri uri))))))
4761 (defun markdown-insert-link ()
4762 "Insert new or update an existing link, with interactive prompts.
4763 If the point is at an existing link or URL, update the link text,
4764 URL, reference label, and/or title. Otherwise, insert a new link.
4765 The type of link inserted (inline, reference, or plain URL)
4766 depends on which values are provided:
4768 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4769 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4770 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4771 * If only a URL is given, insert a plain link: <URL>.
4773 In other words, to create an implicit reference link, leave the
4774 URL prompt empty and to create a plain URL link, leave the link
4775 text empty.
4777 If there is an active region, use the text as the default URL, if
4778 it seems to be a URL, or link text value otherwise.
4780 If a given reference is not defined, this function will
4781 additionally prompt for the URL and optional title. In this case,
4782 the reference definition is placed at the location determined by
4783 `markdown-reference-location'.
4785 Through updating the link, this function can be used to convert a
4786 link of one type (inline, reference, or plain) to another type by
4787 selectively adding or removing information via the prompts."
4788 (interactive)
4789 (markdown--insert-link-or-image nil))
4791 (defun markdown-insert-image ()
4792 "Insert new or update an existing image, with interactive prompts.
4793 If the point is at an existing image, update the alt text, URL,
4794 reference label, and/or title. Otherwise, insert a new image.
4795 The type of image inserted (inline or reference) depends on which
4796 values are provided:
4798 * If a URL and ALT-TEXT are given, insert an inline image:
4799 ![ALT-TEXT](URL).
4800 * If [REF] and ALT-TEXT are given, insert a reference image:
4801 ![ALT-TEXT][REF].
4803 If there is an active region, use the text as the default URL, if
4804 it seems to be a URL, or alt text value otherwise.
4806 If a given reference is not defined, this function will
4807 additionally prompt for the URL and optional title. In this case,
4808 the reference definition is placed at the location determined by
4809 `markdown-reference-location'.
4811 Through updating the image, this function can be used to convert an
4812 image of one type (inline or reference) to another type by
4813 selectively adding or removing information via the prompts."
4814 (interactive)
4815 (markdown--insert-link-or-image t))
4817 (defun markdown-insert-uri (&optional uri)
4818 "Insert markup for an inline URI.
4819 If there is an active region, use it as the URI. If the point is
4820 at a URI, wrap it with angle brackets. If the point is at an
4821 inline URI, remove the angle brackets. Otherwise, simply insert
4822 angle brackets place the point between them."
4823 (interactive)
4824 (if (markdown-use-region-p)
4825 ;; Active region
4826 (let ((bounds (markdown-unwrap-things-in-region
4827 (region-beginning) (region-end)
4828 markdown-regex-angle-uri 0 2)))
4829 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4830 ;; Markup removal, URI at point, new URI, or empty markup insertion
4831 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4832 (markdown-unwrap-thing-at-point nil 0 2)
4833 (if uri
4834 (insert "<" uri ">")
4835 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4837 (defun markdown-insert-wiki-link ()
4838 "Insert a wiki link of the form [[WikiLink]].
4839 If there is an active region, use the region as the link text.
4840 If the point is at a word, use the word as the link text. If
4841 there is no active region and the point is not at word, simply
4842 insert link markup."
4843 (interactive)
4844 (if (markdown-use-region-p)
4845 ;; Active region
4846 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4847 ;; Markup removal, wiki link at at point, or empty markup insertion
4848 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4849 (if (or markdown-wiki-link-alias-first
4850 (null (match-string 5)))
4851 (markdown-unwrap-thing-at-point nil 1 3)
4852 (markdown-unwrap-thing-at-point nil 1 5))
4853 (markdown-wrap-or-insert "[[" "]]"))))
4855 (defun markdown-remove-header ()
4856 "Remove header markup if point is at a header.
4857 Return bounds of remaining header text if a header was removed
4858 and nil otherwise."
4859 (interactive "*")
4860 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4861 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4863 (defun markdown-insert-header (&optional level text setext)
4864 "Insert or replace header markup.
4865 The level of the header is specified by LEVEL and header text is
4866 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4867 default value is 1.
4868 When TEXT is nil, the header text is obtained as follows.
4869 If there is an active region, it is used as the header text.
4870 Otherwise, the current line will be used as the header text.
4871 If there is not an active region and the point is at a header,
4872 remove the header markup and replace with level N header.
4873 Otherwise, insert empty header markup and place the point in
4874 between.
4875 The style of the header will be atx (hash marks) unless
4876 SETEXT is non-nil, in which case a setext-style (underlined)
4877 header will be inserted."
4878 (interactive "p\nsHeader text: ")
4879 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4880 ;; Determine header text if not given
4881 (when (null text)
4882 (if (markdown-use-region-p)
4883 ;; Active region
4884 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4885 ;; No active region
4886 (markdown-remove-header)
4887 (setq text (delete-and-extract-region
4888 (line-beginning-position) (line-end-position)))
4889 (when (and setext (string-match-p "^[ \t]*$" text))
4890 (setq text (read-string "Header text: "))))
4891 (setq text (markdown-compress-whitespace-string text)))
4892 ;; Insertion with given text
4893 (markdown-ensure-blank-line-before)
4894 (let (hdr)
4895 (cond (setext
4896 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4897 (insert text "\n" hdr))
4899 (setq hdr (make-string level ?#))
4900 (insert hdr " " text)
4901 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4902 (markdown-ensure-blank-line-after)
4903 ;; Leave point at end of text
4904 (cond (setext
4905 (backward-char (1+ (string-width text))))
4906 ((null markdown-asymmetric-header)
4907 (backward-char (1+ level)))))
4909 (defun markdown-insert-header-dwim (&optional arg setext)
4910 "Insert or replace header markup.
4911 The level and type of the header are determined automatically by
4912 the type and level of the previous header, unless a prefix
4913 argument is given via ARG.
4914 With a numeric prefix valued 1 to 6, insert a header of the given
4915 level, with the type being determined automatically (note that
4916 only level 1 or 2 setext headers are possible).
4918 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4919 promote the heading by one level.
4920 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4921 demote the heading by one level.
4922 When SETEXT is non-nil, prefer setext-style headers when
4923 possible (levels one and two).
4925 When there is an active region, use it for the header text. When
4926 the point is at an existing header, change the type and level
4927 according to the rules above.
4928 Otherwise, if the line is not empty, create a header using the
4929 text on the current line as the header text.
4930 Finally, if the point is on a blank line, insert empty header
4931 markup (atx) or prompt for text (setext).
4932 See `markdown-insert-header' for more details about how the
4933 header text is determined."
4934 (interactive "*P")
4935 (let (level)
4936 (save-excursion
4937 (when (or (thing-at-point-looking-at markdown-regex-header)
4938 (re-search-backward markdown-regex-header nil t))
4939 ;; level of current or previous header
4940 (setq level (markdown-outline-level))
4941 ;; match group 1 indicates a setext header
4942 (setq setext (match-end 1))))
4943 ;; check prefix argument
4944 (cond
4945 ((and (equal arg '(4)) level (> level 1)) ;; C-u
4946 (cl-decf level))
4947 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
4948 (cl-incf level))
4949 (arg ;; numeric prefix
4950 (setq level (prefix-numeric-value arg))))
4951 ;; setext headers must be level one or two
4952 (and level (setq setext (and setext (<= level 2))))
4953 ;; insert the heading
4954 (markdown-insert-header level nil setext)))
4956 (defun markdown-insert-header-setext-dwim (&optional arg)
4957 "Insert or replace header markup, with preference for setext.
4958 See `markdown-insert-header-dwim' for details, including how ARG is handled."
4959 (interactive "*P")
4960 (markdown-insert-header-dwim arg t))
4962 (defun markdown-insert-header-atx-1 ()
4963 "Insert a first level atx-style (hash mark) header.
4964 See `markdown-insert-header'."
4965 (interactive "*")
4966 (markdown-insert-header 1 nil nil))
4968 (defun markdown-insert-header-atx-2 ()
4969 "Insert a level two atx-style (hash mark) header.
4970 See `markdown-insert-header'."
4971 (interactive "*")
4972 (markdown-insert-header 2 nil nil))
4974 (defun markdown-insert-header-atx-3 ()
4975 "Insert a level three atx-style (hash mark) header.
4976 See `markdown-insert-header'."
4977 (interactive "*")
4978 (markdown-insert-header 3 nil nil))
4980 (defun markdown-insert-header-atx-4 ()
4981 "Insert a level four atx-style (hash mark) header.
4982 See `markdown-insert-header'."
4983 (interactive "*")
4984 (markdown-insert-header 4 nil nil))
4986 (defun markdown-insert-header-atx-5 ()
4987 "Insert a level five atx-style (hash mark) header.
4988 See `markdown-insert-header'."
4989 (interactive "*")
4990 (markdown-insert-header 5 nil nil))
4992 (defun markdown-insert-header-atx-6 ()
4993 "Insert a sixth level atx-style (hash mark) header.
4994 See `markdown-insert-header'."
4995 (interactive "*")
4996 (markdown-insert-header 6 nil nil))
4998 (defun markdown-insert-header-setext-1 ()
4999 "Insert a setext-style (underlined) first-level header.
5000 See `markdown-insert-header'."
5001 (interactive "*")
5002 (markdown-insert-header 1 nil t))
5004 (defun markdown-insert-header-setext-2 ()
5005 "Insert a setext-style (underlined) second-level header.
5006 See `markdown-insert-header'."
5007 (interactive "*")
5008 (markdown-insert-header 2 nil t))
5010 (defun markdown-blockquote-indentation (loc)
5011 "Return string containing necessary indentation for a blockquote at LOC.
5012 Also see `markdown-pre-indentation'."
5013 (save-excursion
5014 (goto-char loc)
5015 (let* ((list-level (length (markdown-calculate-list-levels)))
5016 (indent ""))
5017 (dotimes (_ list-level indent)
5018 (setq indent (concat indent " "))))))
5020 (defun markdown-insert-blockquote ()
5021 "Start a blockquote section (or blockquote the region).
5022 If Transient Mark mode is on and a region is active, it is used as
5023 the blockquote text."
5024 (interactive)
5025 (if (markdown-use-region-p)
5026 (markdown-blockquote-region (region-beginning) (region-end))
5027 (markdown-ensure-blank-line-before)
5028 (insert (markdown-blockquote-indentation (point)) "> ")
5029 (markdown-ensure-blank-line-after)))
5031 (defun markdown-block-region (beg end prefix)
5032 "Format the region using a block prefix.
5033 Arguments BEG and END specify the beginning and end of the
5034 region. The characters PREFIX will appear at the beginning
5035 of each line."
5036 (save-excursion
5037 (let* ((end-marker (make-marker))
5038 (beg-marker (make-marker))
5039 (prefix-without-trailing-whitespace
5040 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
5041 ;; Ensure blank line after and remove extra whitespace
5042 (goto-char end)
5043 (skip-syntax-backward "-")
5044 (set-marker end-marker (point))
5045 (delete-horizontal-space)
5046 (markdown-ensure-blank-line-after)
5047 ;; Ensure blank line before and remove extra whitespace
5048 (goto-char beg)
5049 (skip-syntax-forward "-")
5050 (delete-horizontal-space)
5051 (markdown-ensure-blank-line-before)
5052 (set-marker beg-marker (point))
5053 ;; Insert PREFIX before each line
5054 (goto-char beg-marker)
5055 (while (and (< (line-beginning-position) end-marker)
5056 (not (eobp)))
5057 ;; Don’t insert trailing whitespace.
5058 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
5059 (forward-line)))))
5061 (defun markdown-blockquote-region (beg end)
5062 "Blockquote the region.
5063 Arguments BEG and END specify the beginning and end of the region."
5064 (interactive "*r")
5065 (markdown-block-region
5066 beg end (concat (markdown-blockquote-indentation
5067 (max (point-min) (1- beg))) "> ")))
5069 (defun markdown-pre-indentation (loc)
5070 "Return string containing necessary whitespace for a pre block at LOC.
5071 Also see `markdown-blockquote-indentation'."
5072 (save-excursion
5073 (goto-char loc)
5074 (let* ((list-level (length (markdown-calculate-list-levels)))
5075 indent)
5076 (dotimes (_ (1+ list-level) indent)
5077 (setq indent (concat indent " "))))))
5079 (defun markdown-insert-pre ()
5080 "Start a preformatted section (or apply to the region).
5081 If Transient Mark mode is on and a region is active, it is marked
5082 as preformatted text."
5083 (interactive)
5084 (if (markdown-use-region-p)
5085 (markdown-pre-region (region-beginning) (region-end))
5086 (markdown-ensure-blank-line-before)
5087 (insert (markdown-pre-indentation (point)))
5088 (markdown-ensure-blank-line-after)))
5090 (defun markdown-pre-region (beg end)
5091 "Format the region as preformatted text.
5092 Arguments BEG and END specify the beginning and end of the region."
5093 (interactive "*r")
5094 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5095 (markdown-block-region beg end indent)))
5097 (defun markdown-electric-backquote (arg)
5098 "Insert a backquote.
5099 The numeric prefix argument ARG says how many times to repeat the insertion.
5100 Call `markdown-insert-gfm-code-block' interactively
5101 if three backquotes inserted at the beginning of line."
5102 (interactive "*P")
5103 (self-insert-command (prefix-numeric-value arg))
5104 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5105 (replace-match "")
5106 (call-interactively #'markdown-insert-gfm-code-block)))
5108 (defconst markdown-gfm-recognized-languages
5109 ;; To reproduce/update, evaluate the let-form in
5110 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5111 ;; but with appropriate use of a keyboard macro, indenting and filling it
5112 ;; properly is pretty fast.
5113 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5114 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5115 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5116 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5117 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5118 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5119 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5120 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5121 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5122 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5123 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5124 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5125 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5126 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5127 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5128 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5129 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5130 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5131 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5132 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5133 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5134 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5135 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5136 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5137 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5138 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5139 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5140 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5141 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5142 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5143 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5144 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5145 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5146 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5147 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5148 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5149 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5150 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5151 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5152 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5153 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5154 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5155 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5156 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5157 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5158 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5159 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5160 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5161 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5162 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5163 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5164 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5165 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5166 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5167 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5168 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5169 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5170 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5171 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5172 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5173 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5174 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5175 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5176 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5177 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5178 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5179 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5180 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5181 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5182 "Language specifiers recognized by GitHub's syntax highlighting features.")
5184 (defvar markdown-gfm-used-languages nil
5185 "Language names used in GFM code blocks.")
5186 (make-variable-buffer-local 'markdown-gfm-used-languages)
5188 (defun markdown-trim-whitespace (str)
5189 (markdown-replace-regexp-in-string
5190 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5192 (defun markdown-clean-language-string (str)
5193 (markdown-replace-regexp-in-string
5194 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5196 (defun markdown-validate-language-string (widget)
5197 (let ((str (widget-value widget)))
5198 (unless (string= str (markdown-clean-language-string str))
5199 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5200 widget)))
5202 (defun markdown-gfm-get-corpus ()
5203 "Create corpus of recognized GFM code block languages for the given buffer."
5204 (let ((given-corpus (append markdown-gfm-additional-languages
5205 markdown-gfm-recognized-languages)))
5206 (append
5207 markdown-gfm-used-languages
5208 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5209 given-corpus))))
5211 (defun markdown-gfm-add-used-language (lang)
5212 "Clean LANG and add to list of used languages."
5213 (setq markdown-gfm-used-languages
5214 (cons lang (remove lang markdown-gfm-used-languages))))
5216 (defcustom markdown-spaces-after-code-fence 1
5217 "Number of space characters to insert after a code fence.
5218 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5219 opening code fence and an info string."
5220 :group 'markdown
5221 :type 'integer
5222 :safe #'natnump
5223 :package-version '(markdown-mode . "2.3"))
5225 (defun markdown-insert-gfm-code-block (&optional lang edit)
5226 "Insert GFM code block for language LANG.
5227 If LANG is nil, the language will be queried from user. If a
5228 region is active, wrap this region with the markup instead. If
5229 the region boundaries are not on empty lines, these are added
5230 automatically in order to have the correct markup. When EDIT is
5231 non-nil (e.g., when \\[universal-argument] is given), edit the
5232 code block in an indirect buffer after insertion."
5233 (interactive
5234 (list (let ((completion-ignore-case nil))
5235 (condition-case nil
5236 (markdown-clean-language-string
5237 (completing-read
5238 "Programming language: "
5239 (markdown-gfm-get-corpus)
5240 nil 'confirm (car markdown-gfm-used-languages)
5241 'markdown-gfm-language-history))
5242 (quit "")))
5243 current-prefix-arg))
5244 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5245 (when (> (length lang) 0)
5246 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5247 lang)))
5248 (if (markdown-use-region-p)
5249 (let* ((b (region-beginning)) (e (region-end)) end
5250 (indent (progn (goto-char b) (current-indentation))))
5251 (goto-char e)
5252 ;; if we're on a blank line, don't newline, otherwise the ```
5253 ;; should go on its own line
5254 (unless (looking-back "\n" nil)
5255 (newline))
5256 (indent-to indent)
5257 (insert "```")
5258 (markdown-ensure-blank-line-after)
5259 (setq end (point))
5260 (goto-char b)
5261 ;; if we're on a blank line, insert the quotes here, otherwise
5262 ;; add a new line first
5263 (unless (looking-at-p "\n")
5264 (newline)
5265 (forward-line -1))
5266 (markdown-ensure-blank-line-before)
5267 (indent-to indent)
5268 (insert "```" lang)
5269 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5270 (let ((indent (current-indentation)) start)
5271 (delete-horizontal-space :backward-only)
5272 (markdown-ensure-blank-line-before)
5273 (indent-to indent)
5274 (setq start (point))
5275 (insert "```" lang "\n")
5276 (indent-to indent)
5277 (unless edit (insert ?\n))
5278 (indent-to indent)
5279 (insert "```")
5280 (markdown-ensure-blank-line-after)
5281 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5282 (end-of-line 0)
5283 (when edit (markdown-edit-code-block))))
5285 (defun markdown-code-block-lang (&optional pos-prop)
5286 "Return the language name for a GFM or tilde fenced code block.
5287 The beginning of the block may be described by POS-PROP,
5288 a cons of (pos . prop) giving the position and property
5289 at the beginning of the block."
5290 (or pos-prop
5291 (setq pos-prop
5292 (markdown-max-of-seq
5293 #'car
5294 (cl-remove-if
5295 #'null
5296 (cl-mapcar
5297 #'markdown-find-previous-prop
5298 (markdown-get-fenced-block-begin-properties))))))
5299 (when pos-prop
5300 (goto-char (car pos-prop))
5301 (set-match-data (get-text-property (point) (cdr pos-prop)))
5302 ;; Note: Hard-coded group number assumes tilde
5303 ;; and GFM fenced code regexp groups agree.
5304 (let ((begin (match-beginning 3))
5305 (end (match-end 3)))
5306 (when (and begin end)
5307 ;; Fix language strings beginning with periods, like ".ruby".
5308 (when (eq (char-after begin) ?.)
5309 (setq begin (1+ begin)))
5310 (buffer-substring-no-properties begin end)))))
5312 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5313 (with-current-buffer (or buffer (current-buffer))
5314 (save-excursion
5315 (goto-char (point-min))
5316 (cl-loop
5317 with prop = 'markdown-gfm-block-begin
5318 for pos-prop = (markdown-find-next-prop prop)
5319 while pos-prop
5320 for lang = (markdown-code-block-lang pos-prop)
5321 do (progn (when lang (markdown-gfm-add-used-language lang))
5322 (goto-char (next-single-property-change (point) prop)))))))
5325 ;;; Footnotes ==================================================================
5327 (defun markdown-footnote-counter-inc ()
5328 "Increment `markdown-footnote-counter' and return the new value."
5329 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5330 (save-excursion
5331 (goto-char (point-min))
5332 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5333 (point-max) t)
5334 (let ((fn (string-to-number (match-string 1))))
5335 (when (> fn markdown-footnote-counter)
5336 (setq markdown-footnote-counter fn))))))
5337 (cl-incf markdown-footnote-counter))
5339 (defun markdown-insert-footnote ()
5340 "Insert footnote with a new number and move point to footnote definition."
5341 (interactive)
5342 (let ((fn (markdown-footnote-counter-inc)))
5343 (insert (format "[^%d]" fn))
5344 (markdown-footnote-text-find-new-location)
5345 (markdown-ensure-blank-line-before)
5346 (unless (markdown-cur-line-blank-p)
5347 (insert "\n"))
5348 (insert (format "[^%d]: " fn))
5349 (markdown-ensure-blank-line-after)))
5351 (defun markdown-footnote-text-find-new-location ()
5352 "Position the point at the proper location for a new footnote text."
5353 (cond
5354 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5355 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5356 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5357 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5359 (defun markdown-footnote-kill ()
5360 "Kill the footnote at point.
5361 The footnote text is killed (and added to the kill ring), the
5362 footnote marker is deleted. Point has to be either at the
5363 footnote marker or in the footnote text."
5364 (interactive)
5365 (let ((marker-pos nil)
5366 (skip-deleting-marker nil)
5367 (starting-footnote-text-positions
5368 (markdown-footnote-text-positions)))
5369 (when starting-footnote-text-positions
5370 ;; We're starting in footnote text, so mark our return position and jump
5371 ;; to the marker if possible.
5372 (let ((marker-pos (markdown-footnote-find-marker
5373 (cl-first starting-footnote-text-positions))))
5374 (if marker-pos
5375 (goto-char (1- marker-pos))
5376 ;; If there isn't a marker, we still want to kill the text.
5377 (setq skip-deleting-marker t))))
5378 ;; Either we didn't start in the text, or we started in the text and jumped
5379 ;; to the marker. We want to assume we're at the marker now and error if
5380 ;; we're not.
5381 (unless skip-deleting-marker
5382 (let ((marker (markdown-footnote-delete-marker)))
5383 (unless marker
5384 (error "Not at a footnote"))
5385 ;; Even if we knew the text position before, it changed when we deleted
5386 ;; the label.
5387 (setq marker-pos (cl-second marker))
5388 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5389 (unless new-text-pos
5390 (error "No text for footnote `%s'" (cl-first marker)))
5391 (goto-char new-text-pos))))
5392 (let ((pos (markdown-footnote-kill-text)))
5393 (goto-char (if starting-footnote-text-positions
5395 marker-pos)))))
5397 (defun markdown-footnote-delete-marker ()
5398 "Delete a footnote marker at point.
5399 Returns a list (ID START) containing the footnote ID and the
5400 start position of the marker before deletion. If no footnote
5401 marker was deleted, this function returns NIL."
5402 (let ((marker (markdown-footnote-marker-positions)))
5403 (when marker
5404 (delete-region (cl-second marker) (cl-third marker))
5405 (butlast marker))))
5407 (defun markdown-footnote-kill-text ()
5408 "Kill footnote text at point.
5409 Returns the start position of the footnote text before deletion,
5410 or NIL if point was not inside a footnote text.
5412 The killed text is placed in the kill ring (without the footnote
5413 number)."
5414 (let ((fn (markdown-footnote-text-positions)))
5415 (when fn
5416 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5417 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5418 (kill-new (match-string 1 text))
5419 (when (and (markdown-cur-line-blank-p)
5420 (markdown-prev-line-blank-p)
5421 (not (bobp)))
5422 (delete-region (1- (point)) (point)))
5423 (cl-second fn)))))
5425 (defun markdown-footnote-goto-text ()
5426 "Jump to the text of the footnote at point."
5427 (interactive)
5428 (let ((fn (car (markdown-footnote-marker-positions))))
5429 (unless fn
5430 (user-error "Not at a footnote marker"))
5431 (let ((new-pos (markdown-footnote-find-text fn)))
5432 (unless new-pos
5433 (error "No definition found for footnote `%s'" fn))
5434 (goto-char new-pos))))
5436 (defun markdown-footnote-return ()
5437 "Return from a footnote to its footnote number in the main text."
5438 (interactive)
5439 (let ((fn (save-excursion
5440 (car (markdown-footnote-text-positions)))))
5441 (unless fn
5442 (user-error "Not in a footnote"))
5443 (let ((new-pos (markdown-footnote-find-marker fn)))
5444 (unless new-pos
5445 (error "Footnote marker `%s' not found" fn))
5446 (goto-char new-pos))))
5448 (defun markdown-footnote-find-marker (id)
5449 "Find the location of the footnote marker with ID.
5450 The actual buffer position returned is the position directly
5451 following the marker's closing bracket. If no marker is found,
5452 NIL is returned."
5453 (save-excursion
5454 (goto-char (point-min))
5455 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5456 (skip-chars-backward "^]")
5457 (point))))
5459 (defun markdown-footnote-find-text (id)
5460 "Find the location of the text of footnote ID.
5461 The actual buffer position returned is the position of the first
5462 character of the text, after the footnote's identifier. If no
5463 footnote text is found, NIL is returned."
5464 (save-excursion
5465 (goto-char (point-min))
5466 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5467 (skip-chars-forward "[ \t]")
5468 (point))))
5470 (defun markdown-footnote-marker-positions ()
5471 "Return the position and ID of the footnote marker point is on.
5472 The return value is a list (ID START END). If point is not on a
5473 footnote, NIL is returned."
5474 ;; first make sure we're at a footnote marker
5475 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5476 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5477 (save-excursion
5478 ;; move point between [ and ^:
5479 (if (looking-at-p "\\[")
5480 (forward-char 1)
5481 (skip-chars-backward "^["))
5482 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5483 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5485 (defun markdown-footnote-text-positions ()
5486 "Return the start and end positions of the footnote text point is in.
5487 The exact return value is a list of three elements: (ID START END).
5488 The start position is the position of the opening bracket
5489 of the footnote id. The end position is directly after the
5490 newline that ends the footnote. If point is not in a footnote,
5491 NIL is returned instead."
5492 (save-excursion
5493 (let (result)
5494 (move-beginning-of-line 1)
5495 ;; Try to find the label. If we haven't found the label and we're at a blank
5496 ;; or indented line, back up if possible.
5497 (while (and
5498 (not (and (looking-at markdown-regex-footnote-definition)
5499 (setq result (list (match-string 1) (point)))))
5500 (and (not (bobp))
5501 (or (markdown-cur-line-blank-p)
5502 (>= (current-indentation) 4))))
5503 (forward-line -1))
5504 (when result
5505 ;; Advance if there is a next line that is either blank or indented.
5506 ;; (Need to check if we're on the last line, because
5507 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5508 (while (and (/= (line-end-position) (point-max))
5509 (or (markdown-next-line-blank-p)
5510 (>= (markdown-next-line-indent) 4)))
5511 (forward-line))
5512 ;; Move back while the current line is blank.
5513 (while (markdown-cur-line-blank-p)
5514 (forward-line -1))
5515 ;; Advance to capture this line and a single trailing newline (if there
5516 ;; is one).
5517 (forward-line)
5518 (append result (list (point)))))))
5521 ;;; Element Removal ===========================================================
5523 (defun markdown-kill-thing-at-point ()
5524 "Kill thing at point and add important text, without markup, to kill ring.
5525 Possible things to kill include (roughly in order of precedence):
5526 inline code, headers, horizonal rules, links (add link text to
5527 kill ring), images (add alt text to kill ring), angle uri, email
5528 addresses, bold, italics, reference definition (add URI to kill
5529 ring), footnote markers and text (kill both marker and text, add
5530 text to kill ring), and list items."
5531 (interactive "*")
5532 (let (val)
5533 (cond
5534 ;; Inline code
5535 ((markdown-inline-code-at-point)
5536 (kill-new (match-string 2))
5537 (delete-region (match-beginning 0) (match-end 0)))
5538 ;; ATX header
5539 ((thing-at-point-looking-at markdown-regex-header-atx)
5540 (kill-new (match-string 2))
5541 (delete-region (match-beginning 0) (match-end 0)))
5542 ;; Setext header
5543 ((thing-at-point-looking-at markdown-regex-header-setext)
5544 (kill-new (match-string 1))
5545 (delete-region (match-beginning 0) (match-end 0)))
5546 ;; Horizonal rule
5547 ((thing-at-point-looking-at markdown-regex-hr)
5548 (kill-new (match-string 0))
5549 (delete-region (match-beginning 0) (match-end 0)))
5550 ;; Inline link or image (add link or alt text to kill ring)
5551 ((thing-at-point-looking-at markdown-regex-link-inline)
5552 (kill-new (match-string 3))
5553 (delete-region (match-beginning 0) (match-end 0)))
5554 ;; Reference link or image (add link or alt text to kill ring)
5555 ((thing-at-point-looking-at markdown-regex-link-reference)
5556 (kill-new (match-string 3))
5557 (delete-region (match-beginning 0) (match-end 0)))
5558 ;; Angle URI (add URL to kill ring)
5559 ((thing-at-point-looking-at markdown-regex-angle-uri)
5560 (kill-new (match-string 2))
5561 (delete-region (match-beginning 0) (match-end 0)))
5562 ;; Email address in angle brackets (add email address to kill ring)
5563 ((thing-at-point-looking-at markdown-regex-email)
5564 (kill-new (match-string 1))
5565 (delete-region (match-beginning 0) (match-end 0)))
5566 ;; Wiki link (add alias text to kill ring)
5567 ((and markdown-enable-wiki-links
5568 (thing-at-point-looking-at markdown-regex-wiki-link))
5569 (kill-new (markdown-wiki-link-alias))
5570 (delete-region (match-beginning 1) (match-end 1)))
5571 ;; Bold
5572 ((thing-at-point-looking-at markdown-regex-bold)
5573 (kill-new (match-string 4))
5574 (delete-region (match-beginning 2) (match-end 2)))
5575 ;; Italics
5576 ((thing-at-point-looking-at markdown-regex-italic)
5577 (kill-new (match-string 3))
5578 (delete-region (match-beginning 1) (match-end 1)))
5579 ;; Strikethrough
5580 ((thing-at-point-looking-at markdown-regex-strike-through)
5581 (kill-new (match-string 4))
5582 (delete-region (match-beginning 2) (match-end 2)))
5583 ;; Footnote marker (add footnote text to kill ring)
5584 ((thing-at-point-looking-at markdown-regex-footnote)
5585 (markdown-footnote-kill))
5586 ;; Footnote text (add footnote text to kill ring)
5587 ((setq val (markdown-footnote-text-positions))
5588 (markdown-footnote-kill))
5589 ;; Reference definition (add URL to kill ring)
5590 ((thing-at-point-looking-at markdown-regex-reference-definition)
5591 (kill-new (match-string 5))
5592 (delete-region (match-beginning 0) (match-end 0)))
5593 ;; List item
5594 ((setq val (markdown-cur-list-item-bounds))
5595 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5597 (user-error "Nothing found at point to kill")))))
5600 ;;; Indentation ====================================================================
5602 (defun markdown-indent-find-next-position (cur-pos positions)
5603 "Return the position after the index of CUR-POS in POSITIONS.
5604 Positions are calculated by `markdown-calc-indents'."
5605 (while (and positions
5606 (not (equal cur-pos (car positions))))
5607 (setq positions (cdr positions)))
5608 (or (cadr positions) 0))
5610 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5611 'markdown-outdent-find-next-position "v2.3")
5613 (defun markdown-outdent-find-next-position (cur-pos positions)
5614 "Return the maximal element that precedes CUR-POS from POSITIONS.
5615 Positions are calculated by `markdown-calc-indents'."
5616 (let ((result 0))
5617 (dolist (i positions)
5618 (when (< i cur-pos)
5619 (setq result (max result i))))
5620 result))
5622 (defun markdown-indent-line ()
5623 "Indent the current line using some heuristics.
5624 If the _previous_ command was either `markdown-enter-key' or
5625 `markdown-cycle', then we should cycle to the next
5626 reasonable indentation position. Otherwise, we could have been
5627 called directly by `markdown-enter-key', by an initial call of
5628 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5629 these cases, indent to the default position.
5630 Positions are calculated by `markdown-calc-indents'."
5631 (interactive)
5632 (let ((positions (markdown-calc-indents))
5633 (point-pos (current-column))
5634 (_ (back-to-indentation))
5635 (cur-pos (current-column)))
5636 (if (not (equal this-command 'markdown-cycle))
5637 (indent-line-to (car positions))
5638 (setq positions (sort (delete-dups positions) '<))
5639 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5640 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5641 (indent-line-to next-pos)
5642 (move-to-column new-point-pos)))))
5644 (defun markdown-calc-indents ()
5645 "Return a list of indentation columns to cycle through.
5646 The first element in the returned list should be considered the
5647 default indentation level. This function does not worry about
5648 duplicate positions, which are handled up by calling functions."
5649 (let (pos prev-line-pos positions)
5651 ;; Indentation of previous line
5652 (setq prev-line-pos (markdown-prev-line-indent))
5653 (setq positions (cons prev-line-pos positions))
5655 ;; Indentation of previous non-list-marker text
5656 (when (setq pos (markdown-prev-non-list-indent))
5657 (setq positions (cons pos positions)))
5659 ;; Indentation required for a pre block in current context
5660 (setq pos (length (markdown-pre-indentation (point))))
5661 (setq positions (cons pos positions))
5663 ;; Indentation of the previous line + tab-width
5664 (if prev-line-pos
5665 (setq positions (cons (+ prev-line-pos tab-width) positions))
5666 (setq positions (cons tab-width positions)))
5668 ;; Indentation of the previous line - tab-width
5669 (if (and prev-line-pos (> prev-line-pos tab-width))
5670 (setq positions (cons (- prev-line-pos tab-width) positions)))
5672 ;; Indentation of all preceeding list markers (when in a list)
5673 (when (setq pos (markdown-calculate-list-levels))
5674 (setq positions (append pos positions)))
5676 ;; First column
5677 (setq positions (cons 0 positions))
5679 ;; Return reversed list
5680 (reverse positions)))
5682 (defun markdown-enter-key ()
5683 "Handle RET depending on the context.
5684 If the point is at a table, move to the next row. Otherwise,
5685 indent according to value of `markdown-indent-on-enter'.
5686 When it is nil, simply call `newline'. Otherwise, indent the next line
5687 following RET using `markdown-indent-line'. Furthermore, when it
5688 is set to 'indent-and-new-item and the point is in a list item,
5689 start a new item with the same indentation. If the point is in an
5690 empty list item, remove it (so that pressing RET twice when in a
5691 list simply adds a blank line)."
5692 (interactive)
5693 (cond
5694 ;; Table
5695 ((markdown-table-at-point-p)
5696 (call-interactively #'markdown-table-next-row))
5697 ;; Indent non-table text
5698 (markdown-indent-on-enter
5699 (let (bounds)
5700 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5701 (setq bounds (markdown-cur-list-item-bounds)))
5702 (let ((beg (cl-first bounds))
5703 (end (cl-second bounds))
5704 (length (cl-fourth bounds)))
5705 ;; Point is in a list item
5706 (if (= (- end beg) length)
5707 ;; Delete blank list
5708 (progn
5709 (delete-region beg end)
5710 (newline)
5711 (markdown-indent-line))
5712 (call-interactively #'markdown-insert-list-item)))
5713 ;; Point is not in a list
5714 (newline)
5715 (markdown-indent-line))))
5716 ;; Insert a raw newline
5717 (t (newline))))
5719 (define-obsolete-function-alias 'markdown-exdent-or-delete
5720 'markdown-outdent-or-delete "v2.3")
5722 (defun markdown-outdent-or-delete (arg)
5723 "Handle BACKSPACE by cycling through indentation points.
5724 When BACKSPACE is pressed, if there is only whitespace
5725 before the current point, then outdent the line one level.
5726 Otherwise, do normal delete by repeating
5727 `backward-delete-char-untabify' ARG times."
5728 (interactive "*p")
5729 (if (use-region-p)
5730 (backward-delete-char-untabify arg)
5731 (let ((cur-pos (current-column))
5732 (start-of-indention (save-excursion
5733 (back-to-indentation)
5734 (current-column)))
5735 (positions (markdown-calc-indents)))
5736 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5737 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5738 (backward-delete-char-untabify arg)))))
5740 (defun markdown-find-leftmost-column (beg end)
5741 "Find the leftmost column in the region from BEG to END."
5742 (let ((mincol 1000))
5743 (save-excursion
5744 (goto-char beg)
5745 (while (< (point) end)
5746 (back-to-indentation)
5747 (unless (looking-at-p "[ \t]*$")
5748 (setq mincol (min mincol (current-column))))
5749 (forward-line 1)
5751 mincol))
5753 (defun markdown-indent-region (beg end arg)
5754 "Indent the region from BEG to END using some heuristics.
5755 When ARG is non-nil, outdent the region instead.
5756 See `markdown-indent-line' and `markdown-indent-line'."
5757 (interactive "*r\nP")
5758 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5759 (leftmostcol (markdown-find-leftmost-column beg end))
5760 (next-pos (if arg
5761 (markdown-outdent-find-next-position leftmostcol positions)
5762 (markdown-indent-find-next-position leftmostcol positions))))
5763 (indent-rigidly beg end (- next-pos leftmostcol))
5764 (setq deactivate-mark nil)))
5766 (define-obsolete-function-alias 'markdown-exdent-region
5767 'markdown-outdent-region "v2.3")
5769 (defun markdown-outdent-region (beg end)
5770 "Call `markdown-indent-region' on region from BEG to END with prefix."
5771 (interactive "*r")
5772 (markdown-indent-region beg end t))
5775 ;;; Markup Completion =========================================================
5777 (defconst markdown-complete-alist
5778 '((markdown-regex-header-atx . markdown-complete-atx)
5779 (markdown-regex-header-setext . markdown-complete-setext)
5780 (markdown-regex-hr . markdown-complete-hr))
5781 "Association list of form (regexp . function) for markup completion.")
5783 (defun markdown-incomplete-atx-p ()
5784 "Return t if ATX header markup is incomplete and nil otherwise.
5785 Assumes match data is available for `markdown-regex-header-atx'.
5786 Checks that the number of trailing hash marks equals the number of leading
5787 hash marks, that there is only a single space before and after the text,
5788 and that there is no extraneous whitespace in the text."
5790 ;; Number of starting and ending hash marks differs
5791 (not (= (length (match-string 1)) (length (match-string 3))))
5792 ;; When the header text is not empty...
5793 (and (> (length (match-string 2)) 0)
5794 ;; ...if there are extra leading, trailing, or interior spaces
5795 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5796 (not (= (match-beginning 3) (1+ (match-end 2))))
5797 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5798 ;; When the header text is empty...
5799 (and (= (length (match-string 2)) 0)
5800 ;; ...if there are too many or too few spaces
5801 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5803 (defun markdown-complete-atx ()
5804 "Complete and normalize ATX headers.
5805 Add or remove hash marks to the end of the header to match the
5806 beginning. Ensure that there is only a single space between hash
5807 marks and header text. Removes extraneous whitespace from header text.
5808 Assumes match data is available for `markdown-regex-header-atx'.
5809 Return nil if markup was complete and non-nil if markup was completed."
5810 (when (markdown-incomplete-atx-p)
5811 (let* ((new-marker (make-marker))
5812 (new-marker (set-marker new-marker (match-end 2))))
5813 ;; Hash marks and spacing at end
5814 (goto-char (match-end 2))
5815 (delete-region (match-end 2) (match-end 3))
5816 (insert " " (match-string 1))
5817 ;; Remove extraneous whitespace from title
5818 (replace-match (markdown-compress-whitespace-string (match-string 2))
5819 t t nil 2)
5820 ;; Spacing at beginning
5821 (goto-char (match-end 1))
5822 (delete-region (match-end 1) (match-beginning 2))
5823 (insert " ")
5824 ;; Leave point at end of text
5825 (goto-char new-marker))))
5827 (defun markdown-incomplete-setext-p ()
5828 "Return t if setext header markup is incomplete and nil otherwise.
5829 Assumes match data is available for `markdown-regex-header-setext'.
5830 Checks that length of underline matches text and that there is no
5831 extraneous whitespace in the text."
5832 (or (not (= (length (match-string 1)) (length (match-string 2))))
5833 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5835 (defun markdown-complete-setext ()
5836 "Complete and normalize setext headers.
5837 Add or remove underline characters to match length of header
5838 text. Removes extraneous whitespace from header text. Assumes
5839 match data is available for `markdown-regex-header-setext'.
5840 Return nil if markup was complete and non-nil if markup was completed."
5841 (when (markdown-incomplete-setext-p)
5842 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5843 (char (char-after (match-beginning 2)))
5844 (level (if (char-equal char ?-) 2 1)))
5845 (goto-char (match-beginning 0))
5846 (delete-region (match-beginning 0) (match-end 0))
5847 (markdown-insert-header level text t)
5848 t)))
5850 (defun markdown-incomplete-hr-p ()
5851 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5852 Assumes match data is available for `markdown-regex-hr'."
5853 (not (member (match-string 0) markdown-hr-strings)))
5855 (defun markdown-complete-hr ()
5856 "Complete horizontal rules.
5857 If horizontal rule string is a member of `markdown-hr-strings',
5858 do nothing. Otherwise, replace with the car of
5859 `markdown-hr-strings'.
5860 Assumes match data is available for `markdown-regex-hr'.
5861 Return nil if markup was complete and non-nil if markup was completed."
5862 (when (markdown-incomplete-hr-p)
5863 (replace-match (car markdown-hr-strings))
5866 (defun markdown-complete ()
5867 "Complete markup of object near point or in region when active.
5868 Handle all objects in `markdown-complete-alist', in order.
5869 See `markdown-complete-at-point' and `markdown-complete-region'."
5870 (interactive "*")
5871 (if (markdown-use-region-p)
5872 (markdown-complete-region (region-beginning) (region-end))
5873 (markdown-complete-at-point)))
5875 (defun markdown-complete-at-point ()
5876 "Complete markup of object near point.
5877 Handle all elements of `markdown-complete-alist' in order."
5878 (interactive "*")
5879 (let ((list markdown-complete-alist) found changed)
5880 (while list
5881 (let ((regexp (eval (caar list)))
5882 (function (cdar list)))
5883 (setq list (cdr list))
5884 (when (thing-at-point-looking-at regexp)
5885 (setq found t)
5886 (setq changed (funcall function))
5887 (setq list nil))))
5888 (if found
5889 (or changed (user-error "Markup at point is complete"))
5890 (user-error "Nothing to complete at point"))))
5892 (defun markdown-complete-region (beg end)
5893 "Complete markup of objects in region from BEG to END.
5894 Handle all objects in `markdown-complete-alist', in order. Each
5895 match is checked to ensure that a previous regexp does not also
5896 match."
5897 (interactive "*r")
5898 (let ((end-marker (set-marker (make-marker) end))
5899 previous)
5900 (dolist (element markdown-complete-alist)
5901 (let ((regexp (eval (car element)))
5902 (function (cdr element)))
5903 (goto-char beg)
5904 (while (re-search-forward regexp end-marker 'limit)
5905 (when (match-string 0)
5906 ;; Make sure this is not a match for any of the preceding regexps.
5907 ;; This prevents mistaking an HR for a Setext subheading.
5908 (let (match)
5909 (save-match-data
5910 (dolist (prev-regexp previous)
5911 (or match (setq match (looking-back prev-regexp nil)))))
5912 (unless match
5913 (save-excursion (funcall function))))))
5914 (cl-pushnew regexp previous :test #'equal)))
5915 previous))
5917 (defun markdown-complete-buffer ()
5918 "Complete markup for all objects in the current buffer."
5919 (interactive "*")
5920 (markdown-complete-region (point-min) (point-max)))
5923 ;;; Markup Cycling ============================================================
5925 (defun markdown-cycle-atx (arg &optional remove)
5926 "Cycle ATX header markup.
5927 Promote header (decrease level) when ARG is 1 and demote
5928 header (increase level) if arg is -1. When REMOVE is non-nil,
5929 remove the header when the level reaches zero and stop cycling
5930 when it reaches six. Otherwise, perform a proper cycling through
5931 levels one through six. Assumes match data is available for
5932 `markdown-regex-header-atx'."
5933 (let* ((old-level (length (match-string 1)))
5934 (new-level (+ old-level arg))
5935 (text (match-string 2)))
5936 (when (not remove)
5937 (setq new-level (% new-level 6))
5938 (setq new-level (cond ((= new-level 0) 6)
5939 ((< new-level 0) (+ new-level 6))
5940 (t new-level))))
5941 (cond
5942 ((= new-level 0)
5943 (markdown-unwrap-thing-at-point nil 0 2))
5944 ((<= new-level 6)
5945 (goto-char (match-beginning 0))
5946 (delete-region (match-beginning 0) (match-end 0))
5947 (markdown-insert-header new-level text nil)))))
5949 (defun markdown-cycle-setext (arg &optional remove)
5950 "Cycle setext header markup.
5951 Promote header (increase level) when ARG is 1 and demote
5952 header (decrease level or remove) if arg is -1. When demoting a
5953 level-two setext header, replace with a level-three atx header.
5954 When REMOVE is non-nil, remove the header when the level reaches
5955 zero. Otherwise, cycle back to a level six atx header. Assumes
5956 match data is available for `markdown-regex-header-setext'."
5957 (let* ((char (char-after (match-beginning 2)))
5958 (old-level (if (char-equal char ?=) 1 2))
5959 (new-level (+ old-level arg)))
5960 (when (and (not remove) (= new-level 0))
5961 (setq new-level 6))
5962 (cond
5963 ((= new-level 0)
5964 (markdown-unwrap-thing-at-point nil 0 1))
5965 ((<= new-level 2)
5966 (markdown-insert-header new-level nil t))
5967 ((<= new-level 6)
5968 (markdown-insert-header new-level nil nil)))))
5970 (defun markdown-cycle-hr (arg &optional remove)
5971 "Cycle string used for horizontal rule from `markdown-hr-strings'.
5972 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
5973 backwards (promote). When REMOVE is non-nil, remove the hr instead
5974 of cycling when the end of the list is reached.
5975 Assumes match data is available for `markdown-regex-hr'."
5976 (let* ((strings (if (= arg -1)
5977 (reverse markdown-hr-strings)
5978 markdown-hr-strings))
5979 (tail (member (match-string 0) strings))
5980 (new (or (cadr tail)
5981 (if remove
5982 (if (= arg 1)
5984 (car tail))
5985 (car strings)))))
5986 (replace-match new)))
5988 (defun markdown-cycle-bold ()
5989 "Cycle bold markup between underscores and asterisks.
5990 Assumes match data is available for `markdown-regex-bold'."
5991 (save-excursion
5992 (let* ((old-delim (match-string 3))
5993 (new-delim (if (string-equal old-delim "**") "__" "**")))
5994 (replace-match new-delim t t nil 3)
5995 (replace-match new-delim t t nil 5))))
5997 (defun markdown-cycle-italic ()
5998 "Cycle italic markup between underscores and asterisks.
5999 Assumes match data is available for `markdown-regex-italic'."
6000 (save-excursion
6001 (let* ((old-delim (match-string 2))
6002 (new-delim (if (string-equal old-delim "*") "_" "*")))
6003 (replace-match new-delim t t nil 2)
6004 (replace-match new-delim t t nil 4))))
6007 ;;; Keymap ====================================================================
6009 (defun markdown--style-map-prompt ()
6010 "Return a formatted prompt for Markdown markup insertion."
6011 (when markdown-enable-prefix-prompts
6012 (concat
6013 "Markdown: "
6014 (propertize "bold" 'face 'markdown-bold-face) ", "
6015 (propertize "italic" 'face 'markdown-italic-face) ", "
6016 (propertize "code" 'face 'markdown-inline-code-face) ", "
6017 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
6018 (propertize "pre" 'face 'markdown-pre-face) ", "
6019 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
6020 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
6021 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
6022 (propertize "- = hr" 'face 'markdown-hr-face) ", "
6023 "C-h = more")))
6025 (defun markdown--command-map-prompt ()
6026 "Return prompt for Markdown buffer-wide commands."
6027 (when markdown-enable-prefix-prompts
6028 (concat
6029 "Command: "
6030 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
6031 (propertize "p" 'face 'markdown-bold-face) "review, "
6032 (propertize "o" 'face 'markdown-bold-face) "pen, "
6033 (propertize "e" 'face 'markdown-bold-face) "xport, "
6034 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
6035 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
6036 "C-h = more")))
6038 (defvar markdown-mode-style-map
6039 (let ((map (make-keymap (markdown--style-map-prompt))))
6040 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
6041 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
6042 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
6043 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
6044 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
6045 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
6046 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
6047 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
6048 (define-key map (kbd "b") 'markdown-insert-bold)
6049 (define-key map (kbd "c") 'markdown-insert-code)
6050 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
6051 (define-key map (kbd "f") 'markdown-insert-footnote)
6052 (define-key map (kbd "h") 'markdown-insert-header-dwim)
6053 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
6054 (define-key map (kbd "i") 'markdown-insert-italic)
6055 (define-key map (kbd "k") 'markdown-insert-kbd)
6056 (define-key map (kbd "l") 'markdown-insert-link)
6057 (define-key map (kbd "p") 'markdown-insert-pre)
6058 (define-key map (kbd "P") 'markdown-pre-region)
6059 (define-key map (kbd "q") 'markdown-insert-blockquote)
6060 (define-key map (kbd "s") 'markdown-insert-strike-through)
6061 (define-key map (kbd "Q") 'markdown-blockquote-region)
6062 (define-key map (kbd "w") 'markdown-insert-wiki-link)
6063 (define-key map (kbd "-") 'markdown-insert-hr)
6064 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
6065 ;; Deprecated keys that may be removed in a future version
6066 (define-key map (kbd "e") 'markdown-insert-italic)
6067 map)
6068 "Keymap for Markdown text styling commands.")
6070 (defvar markdown-mode-command-map
6071 (let ((map (make-keymap (markdown--command-map-prompt))))
6072 (define-key map (kbd "m") 'markdown-other-window)
6073 (define-key map (kbd "p") 'markdown-preview)
6074 (define-key map (kbd "e") 'markdown-export)
6075 (define-key map (kbd "v") 'markdown-export-and-preview)
6076 (define-key map (kbd "o") 'markdown-open)
6077 (define-key map (kbd "l") 'markdown-live-preview-mode)
6078 (define-key map (kbd "w") 'markdown-kill-ring-save)
6079 (define-key map (kbd "c") 'markdown-check-refs)
6080 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6081 (define-key map (kbd "]") 'markdown-complete-buffer)
6082 (define-key map (kbd "^") 'markdown-table-sort-lines)
6083 (define-key map (kbd "|") 'markdown-table-convert-region)
6084 (define-key map (kbd "t") 'markdown-table-transpose)
6085 map)
6086 "Keymap for Markdown buffer-wide commands.")
6088 (defvar markdown-mode-map
6089 (let ((map (make-keymap)))
6090 ;; Markup insertion & removal
6091 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6092 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6093 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6094 ;; Promotion, demotion, and cycling
6095 (define-key map (kbd "C-c C--") 'markdown-promote)
6096 (define-key map (kbd "C-c C-=") 'markdown-demote)
6097 (define-key map (kbd "C-c C-]") 'markdown-complete)
6098 ;; Following and doing things
6099 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6100 (define-key map (kbd "C-c C-d") 'markdown-do)
6101 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6102 ;; Indentation
6103 (define-key map (kbd "C-m") 'markdown-enter-key)
6104 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6105 (define-key map (kbd "C-c >") 'markdown-indent-region)
6106 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6107 ;; Visibility cycling
6108 (define-key map (kbd "TAB") 'markdown-cycle)
6109 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6110 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6111 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6112 ;; Heading and list navigation
6113 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6114 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6115 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6116 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6117 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6118 ;; Buffer-wide commands
6119 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6120 ;; Subtree, list, and table editing
6121 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6122 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6123 (define-key map (kbd "C-c <left>") 'markdown-promote)
6124 (define-key map (kbd "C-c <right>") 'markdown-demote)
6125 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6126 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6127 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6128 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6129 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6130 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6131 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6132 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6133 ;; Paragraphs (Markdown context aware)
6134 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6135 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6136 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6137 ;; Blocks (one or more paragraphs)
6138 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6139 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6140 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6141 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6142 ;; Pages (top-level sections)
6143 (define-key map [remap backward-page] 'markdown-backward-page)
6144 (define-key map [remap forward-page] 'markdown-forward-page)
6145 (define-key map [remap mark-page] 'markdown-mark-page)
6146 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6147 ;; Link Movement
6148 (define-key map (kbd "M-n") 'markdown-next-link)
6149 (define-key map (kbd "M-p") 'markdown-previous-link)
6150 ;; Toggling functionality
6151 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6152 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6153 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6154 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6155 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6156 ;; Alternative keys (in case of problems with the arrow keys)
6157 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6158 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6159 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6160 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6161 ;; Deprecated keys that may be removed in a future version
6162 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6163 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6164 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6165 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6166 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6167 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6168 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6169 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6170 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6171 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6172 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6173 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6174 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6175 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6176 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6177 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6178 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6179 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6180 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6181 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6182 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6183 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6184 map)
6185 "Keymap for Markdown major mode.")
6187 (defvar markdown-mode-mouse-map
6188 (let ((map (make-sparse-keymap)))
6189 (define-key map [follow-link] 'mouse-face)
6190 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6191 map)
6192 "Keymap for following links with mouse.")
6194 (defvar gfm-mode-map
6195 (let ((map (make-sparse-keymap)))
6196 (set-keymap-parent map markdown-mode-map)
6197 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6198 (define-key map "`" 'markdown-electric-backquote)
6199 map)
6200 "Keymap for `gfm-mode'.
6201 See also `markdown-mode-map'.")
6204 ;;; Menu ==================================================================
6206 (easy-menu-define markdown-mode-menu markdown-mode-map
6207 "Menu for Markdown mode"
6208 '("Markdown"
6209 "---"
6210 ("Movement"
6211 ["Jump" markdown-do]
6212 ["Follow Link" markdown-follow-thing-at-point]
6213 ["Next Link" markdown-next-link]
6214 ["Previous Link" markdown-previous-link]
6215 "---"
6216 ["Next Heading or List Item" markdown-outline-next]
6217 ["Previous Heading or List Item" markdown-outline-previous]
6218 ["Next at Same Level" markdown-outline-next-same-level]
6219 ["Previous at Same Level" markdown-outline-previous-same-level]
6220 ["Up to Parent" markdown-outline-up]
6221 "---"
6222 ["Forward Paragraph" markdown-forward-paragraph]
6223 ["Backward Paragraph" markdown-backward-paragraph]
6224 ["Forward Block" markdown-forward-block]
6225 ["Backward Block" markdown-backward-block])
6226 ("Show & Hide"
6227 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6228 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6229 "---"
6230 ["Narrow to Region" narrow-to-region]
6231 ["Narrow to Block" markdown-narrow-to-block]
6232 ["Narrow to Section" narrow-to-defun]
6233 ["Narrow to Subtree" markdown-narrow-to-subtree]
6234 ["Widen" widen (buffer-narrowed-p)]
6235 "---"
6236 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6237 :keys "C-c C-x C-m"
6238 :style radio
6239 :selected markdown-hide-markup])
6240 "---"
6241 ("Headings & Structure"
6242 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6243 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6244 ("Specific Heading (atx)"
6245 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6246 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6247 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6248 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6249 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6250 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6251 ("Specific Heading (Setext)"
6252 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6253 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6254 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6255 "---"
6256 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6257 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6258 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6259 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6260 ("Region & Mark"
6261 ["Indent Region" markdown-indent-region]
6262 ["Outdent Region" markdown-outdent-region]
6263 "--"
6264 ["Mark Paragraph" mark-paragraph]
6265 ["Mark Block" markdown-mark-block]
6266 ["Mark Section" mark-defun]
6267 ["Mark Subtree" markdown-mark-subtree])
6268 ("Lists"
6269 ["Insert List Item" markdown-insert-list-item]
6270 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6271 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6272 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6273 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6274 ["Renumber List" markdown-cleanup-list-numbers]
6275 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6276 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6277 ("Links & Images"
6278 ["Insert Link" markdown-insert-link]
6279 ["Insert Image" markdown-insert-image]
6280 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6281 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6282 "---"
6283 ["Check References" markdown-check-refs]
6284 ["Toggle URL Hiding" markdown-toggle-url-hiding
6285 :style radio
6286 :selected markdown-hide-urls]
6287 ["Toggle Inline Images" markdown-toggle-inline-images
6288 :keys "C-c C-x C-i"
6289 :style radio
6290 :selected markdown-inline-image-overlays]
6291 ["Toggle Wiki Links" markdown-toggle-wiki-links
6292 :style radio
6293 :selected markdown-enable-wiki-links])
6294 ("Styles"
6295 ["Bold" markdown-insert-bold]
6296 ["Italic" markdown-insert-italic]
6297 ["Code" markdown-insert-code]
6298 ["Strikethrough" markdown-insert-strike-through]
6299 ["Keyboard" markdown-insert-kbd]
6300 "---"
6301 ["Blockquote" markdown-insert-blockquote]
6302 ["Preformatted" markdown-insert-pre]
6303 ["GFM Code Block" markdown-insert-gfm-code-block]
6304 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6305 "---"
6306 ["Blockquote Region" markdown-blockquote-region]
6307 ["Preformatted Region" markdown-pre-region]
6308 "---"
6309 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6310 :style radio
6311 :selected markdown-fontify-code-blocks-natively]
6312 ["LaTeX Math Support" markdown-toggle-math
6313 :style radio
6314 :selected markdown-enable-math])
6315 "---"
6316 ("Preview & Export"
6317 ["Compile" markdown-other-window]
6318 ["Preview" markdown-preview]
6319 ["Export" markdown-export]
6320 ["Export & View" markdown-export-and-preview]
6321 ["Open" markdown-open]
6322 ["Live Export" markdown-live-preview-mode
6323 :style radio
6324 :selected markdown-live-preview-mode]
6325 ["Kill ring save" markdown-kill-ring-save])
6326 ("Markup Completion and Cycling"
6327 ["Complete Markup" markdown-complete]
6328 ["Promote Element" markdown-promote :keys "C-c C--"]
6329 ["Demote Element" markdown-demote :keys "C-c C-="])
6330 "---"
6331 ["Kill Element" markdown-kill-thing-at-point]
6332 "---"
6333 ("Documentation"
6334 ["Version" markdown-show-version]
6335 ["Homepage" markdown-mode-info]
6336 ["Describe Mode" (describe-function 'markdown-mode)]
6337 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6340 ;;; imenu =====================================================================
6342 (defun markdown-imenu-create-nested-index ()
6343 "Create and return a nested imenu index alist for the current buffer.
6344 See `imenu-create-index-function' and `imenu--index-alist' for details."
6345 (let* ((root '(nil . nil))
6346 cur-alist
6347 (cur-level 0)
6348 (empty-heading "-")
6349 (self-heading ".")
6350 hashes pos level heading)
6351 (save-excursion
6352 (goto-char (point-min))
6353 (while (re-search-forward markdown-regex-header (point-max) t)
6354 (unless (markdown-code-block-at-point-p)
6355 (cond
6356 ((match-string-no-properties 2) ;; level 1 setext
6357 (setq heading (match-string-no-properties 1))
6358 (setq pos (match-beginning 1)
6359 level 1))
6360 ((match-string-no-properties 3) ;; level 2 setext
6361 (setq heading (match-string-no-properties 1))
6362 (setq pos (match-beginning 1)
6363 level 2))
6364 ((setq hashes (markdown-trim-whitespace
6365 (match-string-no-properties 4)))
6366 (setq heading (match-string-no-properties 5)
6367 pos (match-beginning 4)
6368 level (length hashes))))
6369 (let ((alist (list (cons heading pos))))
6370 (cond
6371 ((= cur-level level) ; new sibling
6372 (setcdr cur-alist alist)
6373 (setq cur-alist alist))
6374 ((< cur-level level) ; first child
6375 (dotimes (_ (- level cur-level 1))
6376 (setq alist (list (cons empty-heading alist))))
6377 (if cur-alist
6378 (let* ((parent (car cur-alist))
6379 (self-pos (cdr parent)))
6380 (setcdr parent (cons (cons self-heading self-pos) alist)))
6381 (setcdr root alist)) ; primogenitor
6382 (setq cur-alist alist)
6383 (setq cur-level level))
6384 (t ; new sibling of an ancestor
6385 (let ((sibling-alist (last (cdr root))))
6386 (dotimes (_ (1- level))
6387 (setq sibling-alist (last (cdar sibling-alist))))
6388 (setcdr sibling-alist alist)
6389 (setq cur-alist alist))
6390 (setq cur-level level))))))
6391 (cdr root))))
6393 (defun markdown-imenu-create-flat-index ()
6394 "Create and return a flat imenu index alist for the current buffer.
6395 See `imenu-create-index-function' and `imenu--index-alist' for details."
6396 (let* ((empty-heading "-") index heading pos)
6397 (save-excursion
6398 (goto-char (point-min))
6399 (while (re-search-forward markdown-regex-header (point-max) t)
6400 (when (and (not (markdown-code-block-at-point-p))
6401 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6402 (cond
6403 ((setq heading (match-string-no-properties 1))
6404 (setq pos (match-beginning 1)))
6405 ((setq heading (match-string-no-properties 5))
6406 (setq pos (match-beginning 4))))
6407 (or (> (length heading) 0)
6408 (setq heading empty-heading))
6409 (setq index (append index (list (cons heading pos))))))
6410 index)))
6413 ;;; References ================================================================
6415 (defun markdown-reference-goto-definition ()
6416 "Jump to the definition of the reference at point or create it."
6417 (interactive)
6418 (when (thing-at-point-looking-at markdown-regex-link-reference)
6419 (let* ((text (match-string-no-properties 3))
6420 (reference (match-string-no-properties 6))
6421 (target (downcase (if (string= reference "") text reference)))
6422 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6423 (if loc
6424 (goto-char loc)
6425 (goto-char (match-beginning 0))
6426 (markdown-insert-reference-definition target)))))
6428 (defun markdown-reference-find-links (reference)
6429 "Return a list of all links for REFERENCE.
6430 REFERENCE should not include the surrounding square brackets.
6431 Elements of the list have the form (text start line), where
6432 text is the link text, start is the location at the beginning of
6433 the link, and line is the line number on which the link appears."
6434 (let* ((ref-quote (regexp-quote reference))
6435 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6436 ref-quote ref-quote))
6437 links)
6438 (save-excursion
6439 (goto-char (point-min))
6440 (while (re-search-forward regexp nil t)
6441 (let* ((text (or (match-string-no-properties 1)
6442 (match-string-no-properties 2)))
6443 (start (match-beginning 0))
6444 (line (markdown-line-number-at-pos)))
6445 (cl-pushnew (list text start line) links :test #'equal))))
6446 links))
6448 (defun markdown-get-undefined-refs ()
6449 "Return a list of undefined Markdown references.
6450 Result is an alist of pairs (reference . occurrences), where
6451 occurrences is itself another alist of pairs (label . line-number).
6452 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6453 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6454 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6455 (let ((missing))
6456 (save-excursion
6457 (goto-char (point-min))
6458 (while
6459 (re-search-forward markdown-regex-link-reference nil t)
6460 (let* ((text (match-string-no-properties 3))
6461 (reference (match-string-no-properties 6))
6462 (target (downcase (if (string= reference "") text reference))))
6463 (unless (markdown-reference-definition target)
6464 (let ((entry (assoc target missing)))
6465 (if (not entry)
6466 (cl-pushnew
6467 (cons target (list (cons text (markdown-line-number-at-pos))))
6468 missing :test #'equal)
6469 (setcdr entry
6470 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6471 (reverse missing))))
6473 (defconst markdown-reference-check-buffer
6474 "*Undefined references for %buffer%*"
6475 "Pattern for name of buffer for listing undefined references.
6476 The string %buffer% will be replaced by the corresponding
6477 `markdown-mode' buffer name.")
6479 (defun markdown-reference-check-buffer (&optional buffer-name)
6480 "Name and return buffer for reference checking.
6481 BUFFER-NAME is the name of the main buffer being visited."
6482 (or buffer-name (setq buffer-name (buffer-name)))
6483 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6484 "%buffer%" buffer-name
6485 markdown-reference-check-buffer))))
6486 (with-current-buffer refbuf
6487 (when view-mode
6488 (View-exit-and-edit))
6489 (use-local-map button-buffer-map)
6490 (erase-buffer))
6491 refbuf))
6493 (defconst markdown-reference-links-buffer
6494 "*Reference links for %buffer%*"
6495 "Pattern for name of buffer for listing references.
6496 The string %buffer% will be replaced by the corresponding buffer name.")
6498 (defun markdown-reference-links-buffer (&optional buffer-name)
6499 "Name, setup, and return a buffer for listing links.
6500 BUFFER-NAME is the name of the main buffer being visited."
6501 (or buffer-name (setq buffer-name (buffer-name)))
6502 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6503 "%buffer%" buffer-name
6504 markdown-reference-links-buffer))))
6505 (with-current-buffer linkbuf
6506 (when view-mode
6507 (View-exit-and-edit))
6508 (use-local-map button-buffer-map)
6509 (erase-buffer))
6510 linkbuf))
6512 ;; Add an empty Markdown reference definition to buffer
6513 ;; specified in the 'target-buffer property. The reference name is
6514 ;; the button's label.
6515 (define-button-type 'markdown-undefined-reference-button
6516 'help-echo "mouse-1, RET: create definition for undefined reference"
6517 'follow-link t
6518 'face 'bold
6519 'action (lambda (b)
6520 (let ((buffer (button-get b 'target-buffer))
6521 (line (button-get b 'target-line))
6522 (label (button-label b)))
6523 (switch-to-buffer-other-window buffer)
6524 (goto-char (point-min))
6525 (forward-line line)
6526 (markdown-insert-reference-definition label)
6527 (markdown-check-refs t))))
6529 ;; Jump to line in buffer specified by 'target-buffer property.
6530 ;; Line number is button's 'line property.
6531 (define-button-type 'markdown-goto-line-button
6532 'help-echo "mouse-1, RET: go to line"
6533 'follow-link t
6534 'face 'italic
6535 'action (lambda (b)
6536 (message (button-get b 'buffer))
6537 (switch-to-buffer-other-window (button-get b 'target-buffer))
6538 ;; use call-interactively to silence compiler
6539 (let ((current-prefix-arg (button-get b 'target-line)))
6540 (call-interactively 'goto-line))))
6542 ;; Jumps to a particular link at location given by 'target-char
6543 ;; property in buffer given by 'target-buffer property.
6544 (define-button-type 'markdown-location-button
6545 'help-echo "mouse-1, RET: jump to location of link"
6546 'follow-link t
6547 'face 'bold
6548 'action (lambda (b)
6549 (let ((target (button-get b 'target-buffer))
6550 (loc (button-get b 'target-char)))
6551 (kill-buffer-and-window)
6552 (switch-to-buffer target)
6553 (goto-char loc))))
6555 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6556 "Insert a button for creating REFERENCE in buffer OLDBUF.
6557 REFERENCE should be a list of the form (reference . occurrences),
6558 as by `markdown-get-undefined-refs'."
6559 (let ((label (car reference)))
6560 ;; Create a reference button
6561 (insert-button label
6562 :type 'markdown-undefined-reference-button
6563 'target-buffer oldbuf
6564 'target-line (cdr (car (cdr reference))))
6565 (insert " (")
6566 (dolist (occurrence (cdr reference))
6567 (let ((line (cdr occurrence)))
6568 ;; Create a line number button
6569 (insert-button (number-to-string line)
6570 :type 'markdown-goto-line-button
6571 'target-buffer oldbuf
6572 'target-line line)
6573 (insert " ")))
6574 (delete-char -1)
6575 (insert ")")
6576 (newline)))
6578 (defun markdown-insert-link-button (link oldbuf)
6579 "Insert a button for jumping to LINK in buffer OLDBUF.
6580 LINK should be a list of the form (text char line) containing
6581 the link text, location, and line number."
6582 (let ((label (cl-first link))
6583 (char (cl-second link))
6584 (line (cl-third link)))
6585 ;; Create a reference button
6586 (insert-button label
6587 :type 'markdown-location-button
6588 'target-buffer oldbuf
6589 'target-char char)
6590 (insert (format " (line %d)\n" line))))
6592 (defun markdown-reference-goto-link (&optional reference)
6593 "Jump to the location of the first use of REFERENCE."
6594 (interactive)
6595 (unless reference
6596 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6597 (setq reference (match-string-no-properties 2))
6598 (user-error "No reference definition at point")))
6599 (let ((links (markdown-reference-find-links reference)))
6600 (cond ((= (length links) 1)
6601 (goto-char (cadr (car links))))
6602 ((> (length links) 1)
6603 (let ((oldbuf (current-buffer))
6604 (linkbuf (markdown-reference-links-buffer)))
6605 (with-current-buffer linkbuf
6606 (insert "Links using reference " reference ":\n\n")
6607 (dolist (link (reverse links))
6608 (markdown-insert-link-button link oldbuf)))
6609 (view-buffer-other-window linkbuf)
6610 (goto-char (point-min))
6611 (forward-line 2)))
6613 (error "No links for reference %s" reference)))))
6615 (defun markdown-check-refs (&optional silent)
6616 "Show all undefined Markdown references in current `markdown-mode' buffer.
6617 If SILENT is non-nil, do not message anything when no undefined
6618 references found.
6619 Links which have empty reference definitions are considered to be
6620 defined."
6621 (interactive "P")
6622 (when (not (eq major-mode 'markdown-mode))
6623 (user-error "Not available in current mode"))
6624 (let ((oldbuf (current-buffer))
6625 (refs (markdown-get-undefined-refs))
6626 (refbuf (markdown-reference-check-buffer)))
6627 (if (null refs)
6628 (progn
6629 (when (not silent)
6630 (message "No undefined references found"))
6631 (kill-buffer refbuf))
6632 (with-current-buffer refbuf
6633 (insert "The following references are undefined:\n\n")
6634 (dolist (ref refs)
6635 (markdown-insert-undefined-reference-button ref oldbuf))
6636 (view-buffer-other-window refbuf)
6637 (goto-char (point-min))
6638 (forward-line 2)))))
6641 ;;; Lists =====================================================================
6643 (defun markdown-insert-list-item (&optional arg)
6644 "Insert a new list item.
6645 If the point is inside unordered list, insert a bullet mark. If
6646 the point is inside ordered list, insert the next number followed
6647 by a period. Use the previous list item to determine the amount
6648 of whitespace to place before and after list markers.
6650 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6651 decrease the indentation by one level.
6653 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6654 increase the indentation by one level."
6655 (interactive "p")
6656 (let (bounds cur-indent marker indent new-indent new-loc)
6657 (save-match-data
6658 ;; Look for a list item on current or previous non-blank line
6659 (save-excursion
6660 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6661 (not (bobp))
6662 (markdown-cur-line-blank-p))
6663 (forward-line -1)))
6664 (when bounds
6665 (cond ((save-excursion
6666 (skip-chars-backward " \t")
6667 (looking-at-p markdown-regex-list))
6668 (beginning-of-line)
6669 (insert "\n")
6670 (forward-line -1))
6671 ((not (markdown-cur-line-blank-p))
6672 (newline)))
6673 (setq new-loc (point)))
6674 ;; Look ahead for a list item on next non-blank line
6675 (unless bounds
6676 (save-excursion
6677 (while (and (null bounds)
6678 (not (eobp))
6679 (markdown-cur-line-blank-p))
6680 (forward-line)
6681 (setq bounds (markdown-cur-list-item-bounds))))
6682 (when bounds
6683 (setq new-loc (point))
6684 (unless (markdown-cur-line-blank-p)
6685 (newline))))
6686 (if (not bounds)
6687 ;; When not in a list, start a new unordered one
6688 (progn
6689 (unless (markdown-cur-line-blank-p)
6690 (insert "\n"))
6691 (insert markdown-unordered-list-item-prefix))
6692 ;; Compute indentation and marker for new list item
6693 (setq cur-indent (nth 2 bounds))
6694 (setq marker (nth 4 bounds))
6695 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6696 (when (nth 5 bounds)
6697 (setq marker
6698 (concat marker
6699 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6700 (cond
6701 ;; Dedent: decrement indentation, find previous marker.
6702 ((= arg 4)
6703 (setq indent (max (- cur-indent 4) 0))
6704 (let ((prev-bounds
6705 (save-excursion
6706 (goto-char (nth 0 bounds))
6707 (when (markdown-up-list)
6708 (markdown-cur-list-item-bounds)))))
6709 (when prev-bounds
6710 (setq marker (nth 4 prev-bounds)))))
6711 ;; Indent: increment indentation by 4, use same marker.
6712 ((= arg 16) (setq indent (+ cur-indent 4)))
6713 ;; Same level: keep current indentation and marker.
6714 (t (setq indent cur-indent)))
6715 (setq new-indent (make-string indent 32))
6716 (goto-char new-loc)
6717 (cond
6718 ;; Ordered list
6719 ((string-match-p "[0-9]" marker)
6720 (if (= arg 16) ;; starting a new column indented one more level
6721 (insert (concat new-indent "1. "))
6722 ;; Don't use previous match-data
6723 (set-match-data nil)
6724 ;; travel up to the last item and pick the correct number. If
6725 ;; the argument was nil, "new-indent = cur-indent" is the same,
6726 ;; so we don't need special treatment. Neat.
6727 (save-excursion
6728 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6729 (>= (forward-line -1) 0))))
6730 (let* ((old-prefix (match-string 1))
6731 (old-spacing (match-string 2))
6732 (new-prefix (if old-prefix
6733 (int-to-string (1+ (string-to-number old-prefix)))
6734 "1"))
6735 (space-adjust (- (length old-prefix) (length new-prefix)))
6736 (new-spacing (if (and (match-string 2)
6737 (not (string-match-p "\t" old-spacing))
6738 (< space-adjust 0)
6739 (> space-adjust (- 1 (length (match-string 2)))))
6740 (substring (match-string 2) 0 space-adjust)
6741 (or old-spacing ". "))))
6742 (insert (concat new-indent new-prefix new-spacing)))))
6743 ;; Unordered list, GFM task list, or ordered list with hash mark
6744 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6745 (insert new-indent marker)))))))
6747 (defun markdown-move-list-item-up ()
6748 "Move the current list item up in the list when possible.
6749 In nested lists, move child items with the parent item."
6750 (interactive)
6751 (let (cur prev old)
6752 (when (setq cur (markdown-cur-list-item-bounds))
6753 (setq old (point))
6754 (goto-char (nth 0 cur))
6755 (if (markdown-prev-list-item (nth 3 cur))
6756 (progn
6757 (setq prev (markdown-cur-list-item-bounds))
6758 (condition-case nil
6759 (progn
6760 (transpose-regions (nth 0 prev) (nth 1 prev)
6761 (nth 0 cur) (nth 1 cur) t)
6762 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6763 ;; Catch error in case regions overlap.
6764 (error (goto-char old))))
6765 (goto-char old)))))
6767 (defun markdown-move-list-item-down ()
6768 "Move the current list item down in the list when possible.
6769 In nested lists, move child items with the parent item."
6770 (interactive)
6771 (let (cur next old)
6772 (when (setq cur (markdown-cur-list-item-bounds))
6773 (setq old (point))
6774 (if (markdown-next-list-item (nth 3 cur))
6775 (progn
6776 (setq next (markdown-cur-list-item-bounds))
6777 (condition-case nil
6778 (progn
6779 (transpose-regions (nth 0 cur) (nth 1 cur)
6780 (nth 0 next) (nth 1 next) nil)
6781 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6782 ;; Catch error in case regions overlap.
6783 (error (goto-char old))))
6784 (goto-char old)))))
6786 (defun markdown-demote-list-item (&optional bounds)
6787 "Indent (or demote) the current list item.
6788 Optionally, BOUNDS of the current list item may be provided if available.
6789 In nested lists, demote child items as well."
6790 (interactive)
6791 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6792 (save-excursion
6793 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6794 (goto-char (nth 0 bounds))
6795 (while (< (point) end-marker)
6796 (unless (markdown-cur-line-blank-p)
6797 (insert (make-string markdown-list-indent-width ? )))
6798 (forward-line))))))
6800 (defun markdown-promote-list-item (&optional bounds)
6801 "Unindent (or promote) the current list item.
6802 Optionally, BOUNDS of the current list item may be provided if available.
6803 In nested lists, demote child items as well."
6804 (interactive)
6805 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6806 (save-excursion
6807 (save-match-data
6808 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6809 num regexp)
6810 (goto-char (nth 0 bounds))
6811 (when (looking-at (format "^[ ]\\{1,%d\\}"
6812 markdown-list-indent-width))
6813 (setq num (- (match-end 0) (match-beginning 0)))
6814 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6815 (while (and (< (point) end-marker)
6816 (re-search-forward regexp end-marker t))
6817 (replace-match "" nil nil)
6818 (forward-line))))))))
6820 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6821 "Update the numbering for level PFX (as a string of spaces).
6823 Assume that the previously found match was for a numbered item in
6824 a list."
6825 (let ((cpfx pfx)
6826 (idx 0)
6827 (continue t)
6828 (step t)
6829 (sep nil))
6830 (while (and continue (not (eobp)))
6831 (setq step t)
6832 (cond
6833 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6834 (setq cpfx (match-string-no-properties 1))
6835 (cond
6836 ((string= cpfx pfx)
6837 (save-excursion
6838 (replace-match
6839 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6840 (setq sep nil))
6841 ;; indented a level
6842 ((string< pfx cpfx)
6843 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6844 (setq step nil))
6845 ;; exit the loop
6847 (setq step nil)
6848 (setq continue nil))))
6850 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6851 (setq cpfx (match-string-no-properties 1))
6852 (cond
6853 ;; reset if separated before
6854 ((string= cpfx pfx) (when sep (setq idx 0)))
6855 ((string< cpfx pfx)
6856 (setq step nil)
6857 (setq continue nil))))
6858 (t (setq sep t)))
6860 (when step
6861 (beginning-of-line)
6862 (setq continue (= (forward-line) 0))))
6863 sep))
6865 (defun markdown-cleanup-list-numbers ()
6866 "Update the numbering of ordered lists."
6867 (interactive)
6868 (save-excursion
6869 (goto-char (point-min))
6870 (markdown-cleanup-list-numbers-level "")))
6873 ;;; Movement ==================================================================
6875 (defun markdown-beginning-of-defun (&optional arg)
6876 "`beginning-of-defun-function' for Markdown.
6877 This is used to find the beginning of the defun and should behave
6878 like ‘beginning-of-defun’, returning non-nil if it found the
6879 beginning of a defun. It moves the point backward, right before a
6880 heading which defines a defun. When ARG is non-nil, repeat that
6881 many times. When ARG is negative, move forward to the ARG-th
6882 following section."
6883 (or arg (setq arg 1))
6884 (when (< arg 0) (end-of-line))
6885 ;; Adjust position for setext headings.
6886 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6887 (not (= (point) (match-beginning 0)))
6888 (not (markdown-code-block-at-point-p)))
6889 (goto-char (match-end 0)))
6890 (let (found)
6891 ;; Move backward with positive argument.
6892 (while (and (not (bobp)) (> arg 0))
6893 (setq found nil)
6894 (while (and (not found)
6895 (not (bobp))
6896 (re-search-backward markdown-regex-header nil 'move))
6897 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6898 (setq found (match-beginning 0)))
6899 (setq arg (1- arg)))
6900 ;; Move forward with negative argument.
6901 (while (and (not (eobp)) (< arg 0))
6902 (setq found nil)
6903 (while (and (not found)
6904 (not (eobp))
6905 (re-search-forward markdown-regex-header nil 'move))
6906 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6907 (setq found (match-beginning 0)))
6908 (setq arg (1+ arg)))
6909 (when found
6910 (beginning-of-line)
6911 t)))
6913 (defun markdown-end-of-defun ()
6914 "`end-of-defun-function’ for Markdown.
6915 This is used to find the end of the defun at point.
6916 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6917 so it can assume that point is at the beginning of the defun body.
6918 It should move point to the first position after the defun."
6919 (or (eobp) (forward-char 1))
6920 (let (found)
6921 (while (and (not found)
6922 (not (eobp))
6923 (re-search-forward markdown-regex-header nil 'move))
6924 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6925 (setq found (match-beginning 0))))
6926 (when found
6927 (goto-char found)
6928 (skip-syntax-backward "-"))))
6930 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6932 (defun markdown-beginning-of-text-block ()
6933 "Move backward to previous beginning of a plain text block.
6934 This function simply looks for blank lines without considering
6935 the surrounding context in light of Markdown syntax. For that, see
6936 `markdown-backward-block'."
6937 (interactive)
6938 (let ((start (point)))
6939 (if (re-search-backward markdown-regex-block-separator nil t)
6940 (goto-char (match-end 0))
6941 (goto-char (point-min)))
6942 (when (and (= start (point)) (not (bobp)))
6943 (forward-line -1)
6944 (if (re-search-backward markdown-regex-block-separator nil t)
6945 (goto-char (match-end 0))
6946 (goto-char (point-min))))))
6948 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
6950 (defun markdown-end-of-text-block ()
6951 "Move forward to next beginning of a plain text block.
6952 This function simply looks for blank lines without considering
6953 the surrounding context in light of Markdown syntax. For that, see
6954 `markdown-forward-block'."
6955 (interactive)
6956 (beginning-of-line)
6957 (skip-syntax-forward "-")
6958 (when (= (point) (point-min))
6959 (forward-char))
6960 (if (re-search-forward markdown-regex-block-separator nil t)
6961 (goto-char (match-end 0))
6962 (goto-char (point-max)))
6963 (skip-syntax-backward "-")
6964 (forward-line))
6966 (defun markdown-backward-paragraph (&optional arg)
6967 "Move the point to the start of the current paragraph.
6968 With argument ARG, do it ARG times; a negative argument ARG = -N
6969 means move forward N blocks."
6970 (interactive "^p")
6971 (or arg (setq arg 1))
6972 (if (< arg 0)
6973 (markdown-forward-paragraph (- arg))
6974 (dotimes (_ arg)
6975 ;; Skip over whitespace in between paragraphs when moving backward.
6976 (skip-syntax-backward "-")
6977 (beginning-of-line)
6978 ;; Skip over code block endings.
6979 (when (markdown-range-properties-exist
6980 (point-at-bol) (point-at-eol)
6981 '(markdown-gfm-block-end
6982 markdown-tilde-fence-end))
6983 (forward-line -1))
6984 ;; Skip over blank lines inside blockquotes.
6985 (while (and (not (eobp))
6986 (looking-at markdown-regex-blockquote)
6987 (= (length (match-string 3)) 0))
6988 (forward-line -1))
6989 ;; Proceed forward based on the type of block of paragraph.
6990 (let (bounds skip)
6991 (cond
6992 ;; Blockquotes
6993 ((looking-at markdown-regex-blockquote)
6994 (while (and (not (bobp))
6995 (looking-at markdown-regex-blockquote)
6996 (> (length (match-string 3)) 0)) ;; not blank
6997 (forward-line -1))
6998 (forward-line))
6999 ;; List items
7000 ((setq bounds (markdown-cur-list-item-bounds))
7001 (goto-char (nth 0 bounds)))
7002 ;; Other
7004 (while (and (not (bobp))
7005 (not skip)
7006 (not (markdown-cur-line-blank-p))
7007 (not (looking-at markdown-regex-blockquote))
7008 (not (markdown-range-properties-exist
7009 (point-at-bol) (point-at-eol)
7010 '(markdown-gfm-block-end
7011 markdown-tilde-fence-end))))
7012 (setq skip (markdown-range-properties-exist
7013 (point-at-bol) (point-at-eol)
7014 '(markdown-gfm-block-begin
7015 markdown-tilde-fence-begin)))
7016 (forward-line -1))
7017 (unless (bobp)
7018 (forward-line 1))))))))
7020 (defun markdown-forward-paragraph (&optional arg)
7021 "Move forward to the next end of a paragraph.
7022 With argument ARG, do it ARG times; a negative argument ARG = -N
7023 means move backward N blocks."
7024 (interactive "^p")
7025 (or arg (setq arg 1))
7026 (if (< arg 0)
7027 (markdown-backward-paragraph (- arg))
7028 (dotimes (_ arg)
7029 ;; Skip whitespace in between paragraphs.
7030 (when (markdown-cur-line-blank-p)
7031 (skip-syntax-forward "-")
7032 (beginning-of-line))
7033 ;; Proceed forward based on the type of block.
7034 (let (bounds skip)
7035 (cond
7036 ;; Blockquotes
7037 ((looking-at markdown-regex-blockquote)
7038 ;; Skip over blank lines inside blockquotes.
7039 (while (and (not (eobp))
7040 (looking-at markdown-regex-blockquote)
7041 (= (length (match-string 3)) 0))
7042 (forward-line))
7043 ;; Move to end of quoted text block
7044 (while (and (not (eobp))
7045 (looking-at markdown-regex-blockquote)
7046 (> (length (match-string 3)) 0)) ;; not blank
7047 (forward-line)))
7048 ;; List items
7049 ((and (markdown-cur-list-item-bounds)
7050 (setq bounds (markdown-next-list-item-bounds)))
7051 (goto-char (nth 0 bounds)))
7052 ;; Other
7054 (forward-line)
7055 (while (and (not (eobp))
7056 (not skip)
7057 (not (markdown-cur-line-blank-p))
7058 (not (looking-at markdown-regex-blockquote))
7059 (not (markdown-range-properties-exist
7060 (point-at-bol) (point-at-eol)
7061 '(markdown-gfm-block-begin
7062 markdown-tilde-fence-begin))))
7063 (setq skip (markdown-range-properties-exist
7064 (point-at-bol) (point-at-eol)
7065 '(markdown-gfm-block-end
7066 markdown-tilde-fence-end)))
7067 (forward-line))))))))
7069 (defun markdown-backward-block (&optional arg)
7070 "Move the point to the start of the current Markdown block.
7071 Moves across complete code blocks, list items, and blockquotes,
7072 but otherwise stops at blank lines, headers, and horizontal
7073 rules. With argument ARG, do it ARG times; a negative argument
7074 ARG = -N means move forward N blocks."
7075 (interactive "^p")
7076 (or arg (setq arg 1))
7077 (if (< arg 0)
7078 (markdown-forward-block (- arg))
7079 (dotimes (_ arg)
7080 ;; Skip over whitespace in between blocks when moving backward,
7081 ;; unless at a block boundary with no whitespace.
7082 (skip-syntax-backward "-")
7083 (beginning-of-line)
7084 ;; Proceed forward based on the type of block.
7085 (cond
7086 ;; Code blocks
7087 ((and (markdown-code-block-at-pos (point)) ;; this line
7088 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7089 (forward-line -1)
7090 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7091 (forward-line -1))
7092 (forward-line))
7093 ;; Headings
7094 ((markdown-heading-at-point)
7095 (goto-char (match-beginning 0)))
7096 ;; Horizontal rules
7097 ((looking-at markdown-regex-hr))
7098 ;; Blockquotes
7099 ((looking-at markdown-regex-blockquote)
7100 (forward-line -1)
7101 (while (and (looking-at markdown-regex-blockquote)
7102 (not (bobp)))
7103 (forward-line -1))
7104 (forward-line))
7105 ;; List items
7106 ((markdown-cur-list-item-bounds)
7107 (markdown-beginning-of-list))
7108 ;; Other
7110 ;; Move forward in case it is a one line regular paragraph.
7111 (unless (markdown-next-line-blank-p)
7112 (forward-line))
7113 (unless (markdown-prev-line-blank-p)
7114 (markdown-backward-paragraph)))))))
7116 (defun markdown-forward-block (&optional arg)
7117 "Move forward to the next end of a Markdown block.
7118 Moves across complete code blocks, list items, and blockquotes,
7119 but otherwise stops at blank lines, headers, and horizontal
7120 rules. With argument ARG, do it ARG times; a negative argument
7121 ARG = -N means move backward N blocks."
7122 (interactive "^p")
7123 (or arg (setq arg 1))
7124 (if (< arg 0)
7125 (markdown-backward-block (- arg))
7126 (dotimes (_ arg)
7127 ;; Skip over whitespace in between blocks when moving forward.
7128 (if (markdown-cur-line-blank-p)
7129 (skip-syntax-forward "-")
7130 (beginning-of-line))
7131 ;; Proceed forward based on the type of block.
7132 (cond
7133 ;; Code blocks
7134 ((markdown-code-block-at-point-p)
7135 (forward-line)
7136 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7137 (forward-line)))
7138 ;; Headings
7139 ((looking-at markdown-regex-header)
7140 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7141 (forward-line))
7142 ;; Horizontal rules
7143 ((looking-at markdown-regex-hr)
7144 (forward-line))
7145 ;; Blockquotes
7146 ((looking-at markdown-regex-blockquote)
7147 (forward-line)
7148 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7149 (forward-line)))
7150 ;; List items
7151 ((markdown-cur-list-item-bounds)
7152 (markdown-end-of-list)
7153 (forward-line))
7154 ;; Other
7155 (t (markdown-forward-paragraph))))
7156 (skip-syntax-backward "-")
7157 (unless (eobp)
7158 (forward-char 1))))
7160 (defun markdown-backward-page (&optional count)
7161 "Move backward to boundary of the current toplevel section.
7162 With COUNT, repeat, or go forward if negative."
7163 (interactive "p")
7164 (or count (setq count 1))
7165 (if (< count 0)
7166 (markdown-forward-page (- count))
7167 (skip-syntax-backward "-")
7168 (or (markdown-back-to-heading-over-code-block t t)
7169 (goto-char (point-min)))
7170 (when (looking-at markdown-regex-header)
7171 (let ((level (markdown-outline-level)))
7172 (when (> level 1) (markdown-up-heading level))
7173 (when (> count 1)
7174 (condition-case nil
7175 (markdown-backward-same-level (1- count))
7176 (error (goto-char (point-min)))))))))
7178 (defun markdown-forward-page (&optional count)
7179 "Move forward to boundary of the current toplevel section.
7180 With COUNT, repeat, or go backward if negative."
7181 (interactive "p")
7182 (or count (setq count 1))
7183 (if (< count 0)
7184 (markdown-backward-page (- count))
7185 (if (markdown-back-to-heading-over-code-block t t)
7186 (let ((level (markdown-outline-level)))
7187 (when (> level 1) (markdown-up-heading level))
7188 (condition-case nil
7189 (markdown-forward-same-level count)
7190 (error (goto-char (point-max)))))
7191 (markdown-next-visible-heading 1))))
7193 (defun markdown-next-link ()
7194 "Jump to next inline, reference, or wiki link.
7195 If successful, return point. Otherwise, return nil.
7196 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7197 (interactive)
7198 (let ((opoint (point)))
7199 (when (or (markdown-link-p) (markdown-wiki-link-p))
7200 ;; At a link already, move past it.
7201 (goto-char (+ (match-end 0) 1)))
7202 ;; Search for the next wiki link and move to the beginning.
7203 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7204 (markdown-code-block-at-point-p)
7205 (< (point) (point-max))))
7206 (if (and (not (eq (point) opoint))
7207 (or (markdown-link-p) (markdown-wiki-link-p)))
7208 ;; Group 1 will move past non-escape character in wiki link regexp.
7209 ;; Go to beginning of group zero for all other link types.
7210 (goto-char (or (match-beginning 1) (match-beginning 0)))
7211 (goto-char opoint)
7212 nil)))
7214 (defun markdown-previous-link ()
7215 "Jump to previous wiki link.
7216 If successful, return point. Otherwise, return nil.
7217 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7218 (interactive)
7219 (let ((opoint (point)))
7220 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7221 (markdown-code-block-at-point-p)
7222 (> (point) (point-min))))
7223 (if (and (not (eq (point) opoint))
7224 (or (markdown-link-p) (markdown-wiki-link-p)))
7225 (goto-char (or (match-beginning 1) (match-beginning 0)))
7226 (goto-char opoint)
7227 nil)))
7230 ;;; Outline ===================================================================
7232 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7233 "Wrapper for `outline-mode' functions to skip false positives.
7234 MOVE-FN is a function and ARG is its argument. For example,
7235 headings inside preformatted code blocks may match
7236 `outline-regexp' but should not be considered as headings.
7237 When ADJUST is non-nil, adjust the point for interactive calls
7238 to avoid leaving the point at invisible markup. This adjustment
7239 generally should only be done for interactive calls, since other
7240 functions may expect the point to be at the beginning of the
7241 regular expression."
7242 (let ((prev -1) (start (point)))
7243 (if arg (funcall move-fn arg) (funcall move-fn))
7244 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7245 (setq prev (point))
7246 (if arg (funcall move-fn arg) (funcall move-fn)))
7247 ;; Adjust point for setext headings and invisible text.
7248 (save-match-data
7249 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7250 (if markdown-hide-markup
7251 ;; Move to beginning of heading text if markup is hidden.
7252 (goto-char (or (match-beginning 1) (match-beginning 5)))
7253 ;; Move to beginning of markup otherwise.
7254 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7255 (if (= (point) start) nil (point))))
7257 (defun markdown-next-visible-heading (arg)
7258 "Move to the next visible heading line of any level.
7259 With argument, repeats or can move backward if negative. ARG is
7260 passed to `outline-next-visible-heading'."
7261 (interactive "p")
7262 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7264 (defun markdown-previous-visible-heading (arg)
7265 "Move to the previous visible heading line of any level.
7266 With argument, repeats or can move backward if negative. ARG is
7267 passed to `outline-previous-visible-heading'."
7268 (interactive "p")
7269 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7271 (defun markdown-next-heading ()
7272 "Move to the next heading line of any level."
7273 (markdown-move-heading-common #'outline-next-heading))
7275 (defun markdown-previous-heading ()
7276 "Move to the previous heading line of any level."
7277 (markdown-move-heading-common #'outline-previous-heading))
7279 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7280 "Move back to the beginning of the previous heading.
7281 Returns t if the point is at a heading, the location if a heading
7282 was found, and nil otherwise.
7283 Only visible heading lines are considered, unless INVISIBLE-OK is
7284 non-nil. Throw an error if there is no previous heading unless
7285 NO-ERROR is non-nil.
7286 Leaves match data intact for `markdown-regex-header'."
7287 (beginning-of-line)
7288 (or (and (markdown-heading-at-point)
7289 (not (markdown-code-block-at-point-p)))
7290 (let (found)
7291 (save-excursion
7292 (while (and (not found)
7293 (re-search-backward markdown-regex-header nil t))
7294 (when (and (or invisible-ok (not (outline-invisible-p)))
7295 (not (markdown-code-block-at-point-p)))
7296 (setq found (point))))
7297 (if (not found)
7298 (unless no-error (user-error "Before first heading"))
7299 (setq found (point))))
7300 (when found (goto-char found)))))
7302 (defun markdown-forward-same-level (arg)
7303 "Move forward to the ARG'th heading at same level as this one.
7304 Stop at the first and last headings of a superior heading."
7305 (interactive "p")
7306 (markdown-back-to-heading-over-code-block)
7307 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7309 (defun markdown-backward-same-level (arg)
7310 "Move backward to the ARG'th heading at same level as this one.
7311 Stop at the first and last headings of a superior heading."
7312 (interactive "p")
7313 (markdown-back-to-heading-over-code-block)
7314 (while (> arg 0)
7315 (let ((point-to-move-to
7316 (save-excursion
7317 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7318 (if point-to-move-to
7319 (progn
7320 (goto-char point-to-move-to)
7321 (setq arg (1- arg)))
7322 (user-error "No previous same-level heading")))))
7324 (defun markdown-up-heading (arg)
7325 "Move to the visible heading line of which the present line is a subheading.
7326 With argument, move up ARG levels."
7327 (interactive "p")
7328 (and (called-interactively-p 'any)
7329 (not (eq last-command 'markdown-up-heading)) (push-mark))
7330 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7332 (defun markdown-back-to-heading (&optional invisible-ok)
7333 "Move to previous heading line, or beg of this line if it's a heading.
7334 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7335 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7337 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7339 (defun markdown-on-heading-p ()
7340 "Return non-nil if point is on a heading line."
7341 (get-text-property (point-at-bol) 'markdown-heading))
7343 (defun markdown-end-of-subtree (&optional invisible-OK)
7344 "Move to the end of the current subtree.
7345 Only visible heading lines are considered, unless INVISIBLE-OK is
7346 non-nil.
7347 Derived from `org-end-of-subtree'."
7348 (markdown-back-to-heading invisible-OK)
7349 (let ((first t)
7350 (level (markdown-outline-level)))
7351 (while (and (not (eobp))
7352 (or first (> (markdown-outline-level) level)))
7353 (setq first nil)
7354 (markdown-next-heading))
7355 (if (memq (preceding-char) '(?\n ?\^M))
7356 (progn
7357 ;; Go to end of line before heading
7358 (forward-char -1)
7359 (if (memq (preceding-char) '(?\n ?\^M))
7360 ;; leave blank line before heading
7361 (forward-char -1)))))
7362 (point))
7364 (defun markdown-outline-fix-visibility ()
7365 "Hide any false positive headings that should not be shown.
7366 For example, headings inside preformatted code blocks may match
7367 `outline-regexp' but should not be shown as headings when cycling.
7368 Also, the ending --- line in metadata blocks appears to be a
7369 setext header, but should not be folded."
7370 (save-excursion
7371 (goto-char (point-min))
7372 ;; Unhide any false positives in metadata blocks
7373 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7374 (let ((body (progn (forward-line)
7375 (markdown-text-property-at-point
7376 'markdown-yaml-metadata-section))))
7377 (when body
7378 (let ((end (progn (goto-char (cl-second body))
7379 (markdown-text-property-at-point
7380 'markdown-yaml-metadata-end))))
7381 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7382 ;; Hide any false positives in code blocks
7383 (unless (outline-on-heading-p)
7384 (outline-next-visible-heading 1))
7385 (while (< (point) (point-max))
7386 (when (markdown-code-block-at-point-p)
7387 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7388 (outline-next-visible-heading 1))))
7390 (defvar markdown-cycle-global-status 1)
7391 (defvar markdown-cycle-subtree-status nil)
7393 (defun markdown-next-preface ()
7394 (let (finish)
7395 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7396 nil 'move))
7397 (unless (markdown-code-block-at-point-p)
7398 (goto-char (match-beginning 0))
7399 (setq finish t))))
7400 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7401 (forward-char -1)))
7403 (defun markdown-show-entry ()
7404 (save-excursion
7405 (outline-back-to-heading t)
7406 (outline-flag-region (1- (point))
7407 (progn
7408 (markdown-next-preface)
7409 (if (= 1 (- (point-max) (point)))
7410 (point-max)
7411 (point)))
7412 nil)))
7414 ;; This function was originally derived from `org-cycle' from org.el.
7415 (defun markdown-cycle (&optional arg)
7416 "Visibility cycling for Markdown mode.
7417 If ARG is t, perform global visibility cycling. If the point is
7418 at an atx-style header, cycle visibility of the corresponding
7419 subtree. Otherwise, indent the current line or insert a tab,
7420 as appropriate, by calling `indent-for-tab-command'."
7421 (interactive "P")
7422 (cond
7424 ;; Global cycling
7425 ((eq arg t)
7426 (cond
7427 ;; Move from overview to contents
7428 ((and (eq last-command this-command)
7429 (eq markdown-cycle-global-status 2))
7430 (markdown-hide-sublevels 1)
7431 (message "CONTENTS")
7432 (setq markdown-cycle-global-status 3)
7433 (markdown-outline-fix-visibility))
7434 ;; Move from contents to all
7435 ((and (eq last-command this-command)
7436 (eq markdown-cycle-global-status 3))
7437 (markdown-show-all)
7438 (message "SHOW ALL")
7439 (setq markdown-cycle-global-status 1))
7440 ;; Defaults to overview
7442 (markdown-hide-body)
7443 (message "OVERVIEW")
7444 (setq markdown-cycle-global-status 2)
7445 (markdown-outline-fix-visibility))))
7447 ;; At a heading: rotate between three different views
7448 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7449 (markdown-back-to-heading)
7450 (let ((goal-column 0) eoh eol eos)
7451 ;; Determine boundaries
7452 (save-excursion
7453 (markdown-back-to-heading)
7454 (save-excursion
7455 (beginning-of-line 2)
7456 (while (and (not (eobp)) ;; this is like `next-line'
7457 (get-char-property (1- (point)) 'invisible))
7458 (beginning-of-line 2)) (setq eol (point)))
7459 (markdown-end-of-heading) (setq eoh (point))
7460 (markdown-end-of-subtree t)
7461 (skip-chars-forward " \t\n")
7462 (beginning-of-line 1) ; in case this is an item
7463 (setq eos (1- (point))))
7464 ;; Find out what to do next and set `this-command'
7465 (cond
7466 ;; Nothing is hidden behind this heading
7467 ((= eos eoh)
7468 (message "EMPTY ENTRY")
7469 (setq markdown-cycle-subtree-status nil))
7470 ;; Entire subtree is hidden in one line: open it
7471 ((>= eol eos)
7472 (markdown-show-entry)
7473 (markdown-show-children)
7474 (message "CHILDREN")
7475 (setq markdown-cycle-subtree-status 'children))
7476 ;; We just showed the children, now show everything.
7477 ((and (eq last-command this-command)
7478 (eq markdown-cycle-subtree-status 'children))
7479 (markdown-show-subtree)
7480 (message "SUBTREE")
7481 (setq markdown-cycle-subtree-status 'subtree))
7482 ;; Default action: hide the subtree.
7484 (markdown-hide-subtree)
7485 (message "FOLDED")
7486 (setq markdown-cycle-subtree-status 'folded)))))
7488 ;; In a table, move forward by one cell
7489 ((markdown-table-at-point-p)
7490 (call-interactively #'markdown-table-forward-cell))
7492 ;; Otherwise, indent as appropriate
7494 (indent-for-tab-command))))
7496 (defun markdown-shifttab ()
7497 "Handle S-TAB keybinding based on context.
7498 When in a table, move backward one cell.
7499 Otherwise, cycle global heading visibility by calling
7500 `markdown-cycle' with argument t."
7501 (interactive)
7502 (cond ((markdown-table-at-point-p)
7503 (call-interactively #'markdown-table-backward-cell))
7504 (t (markdown-cycle t))))
7506 (defun markdown-outline-level ()
7507 "Return the depth to which a statement is nested in the outline."
7508 (cond
7509 ((and (match-beginning 0)
7510 (markdown-code-block-at-pos (match-beginning 0)))
7511 7) ;; Only 6 header levels are defined.
7512 ((match-end 2) 1)
7513 ((match-end 3) 2)
7514 ((match-end 4)
7515 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7517 (defun markdown-promote-subtree (&optional arg)
7518 "Promote the current subtree of ATX headings.
7519 Note that Markdown does not support heading levels higher than
7520 six and therefore level-six headings will not be promoted
7521 further. If ARG is non-nil promote the heading, otherwise
7522 demote."
7523 (interactive "*P")
7524 (save-excursion
7525 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7526 (re-search-backward markdown-regex-header-atx nil t))
7527 (not (markdown-code-block-at-point-p)))
7528 (let ((level (length (match-string 1)))
7529 (promote-or-demote (if arg 1 -1))
7530 (remove 't))
7531 (markdown-cycle-atx promote-or-demote remove)
7532 (catch 'end-of-subtree
7533 (while (and (markdown-next-heading)
7534 (looking-at markdown-regex-header-atx))
7535 ;; Exit if this not a higher level heading; promote otherwise.
7536 (if (and (looking-at markdown-regex-header-atx)
7537 (<= (length (match-string-no-properties 1)) level))
7538 (throw 'end-of-subtree nil)
7539 (markdown-cycle-atx promote-or-demote remove))))))))
7541 (defun markdown-demote-subtree ()
7542 "Demote the current subtree of ATX headings."
7543 (interactive)
7544 (markdown-promote-subtree t))
7546 (defun markdown-move-subtree-up ()
7547 "Move the current subtree of ATX headings up."
7548 (interactive)
7549 (outline-move-subtree-up 1))
7551 (defun markdown-move-subtree-down ()
7552 "Move the current subtree of ATX headings down."
7553 (interactive)
7554 (outline-move-subtree-down 1))
7556 (defun markdown-outline-next ()
7557 "Move to next list item, when in a list, or next visible heading."
7558 (interactive)
7559 (let ((bounds (markdown-next-list-item-bounds)))
7560 (if bounds
7561 (goto-char (nth 0 bounds))
7562 (markdown-next-visible-heading 1))))
7564 (defun markdown-outline-previous ()
7565 "Move to previous list item, when in a list, or previous visible heading."
7566 (interactive)
7567 (let ((bounds (markdown-prev-list-item-bounds)))
7568 (if bounds
7569 (goto-char (nth 0 bounds))
7570 (markdown-previous-visible-heading 1))))
7572 (defun markdown-outline-next-same-level ()
7573 "Move to next list item or heading of same level."
7574 (interactive)
7575 (let ((bounds (markdown-cur-list-item-bounds)))
7576 (if bounds
7577 (markdown-next-list-item (nth 3 bounds))
7578 (markdown-forward-same-level 1))))
7580 (defun markdown-outline-previous-same-level ()
7581 "Move to previous list item or heading of same level."
7582 (interactive)
7583 (let ((bounds (markdown-cur-list-item-bounds)))
7584 (if bounds
7585 (markdown-prev-list-item (nth 3 bounds))
7586 (markdown-backward-same-level 1))))
7588 (defun markdown-outline-up ()
7589 "Move to previous list item, when in a list, or next heading."
7590 (interactive)
7591 (unless (markdown-up-list)
7592 (markdown-up-heading 1)))
7595 ;;; Marking and Narrowing =====================================================
7597 (defun markdown-mark-paragraph ()
7598 "Put mark at end of this block, point at beginning.
7599 The block marked is the one that contains point or follows point.
7601 Interactively, if this command is repeated or (in Transient Mark
7602 mode) if the mark is active, it marks the next block after the
7603 ones already marked."
7604 (interactive)
7605 (if (or (and (eq last-command this-command) (mark t))
7606 (and transient-mark-mode mark-active))
7607 (set-mark
7608 (save-excursion
7609 (goto-char (mark))
7610 (markdown-forward-paragraph)
7611 (point)))
7612 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7613 (end-of-defun-function 'markdown-forward-paragraph))
7614 (mark-defun))))
7616 (defun markdown-mark-block ()
7617 "Put mark at end of this block, point at beginning.
7618 The block marked is the one that contains point or follows point.
7620 Interactively, if this command is repeated or (in Transient Mark
7621 mode) if the mark is active, it marks the next block after the
7622 ones already marked."
7623 (interactive)
7624 (if (or (and (eq last-command this-command) (mark t))
7625 (and transient-mark-mode mark-active))
7626 (set-mark
7627 (save-excursion
7628 (goto-char (mark))
7629 (markdown-forward-block)
7630 (point)))
7631 (let ((beginning-of-defun-function 'markdown-backward-block)
7632 (end-of-defun-function 'markdown-forward-block))
7633 (mark-defun))))
7635 (defun markdown-narrow-to-block ()
7636 "Make text outside current block invisible.
7637 The current block is the one that contains point or follows point."
7638 (interactive)
7639 (let ((beginning-of-defun-function 'markdown-backward-block)
7640 (end-of-defun-function 'markdown-forward-block))
7641 (narrow-to-defun)))
7643 (defun markdown-mark-text-block ()
7644 "Put mark at end of this plain text block, point at beginning.
7645 The block marked is the one that contains point or follows point.
7647 Interactively, if this command is repeated or (in Transient Mark
7648 mode) if the mark is active, it marks the next block after the
7649 ones already marked."
7650 (interactive)
7651 (if (or (and (eq last-command this-command) (mark t))
7652 (and transient-mark-mode mark-active))
7653 (set-mark
7654 (save-excursion
7655 (goto-char (mark))
7656 (markdown-end-of-text-block)
7657 (point)))
7658 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7659 (end-of-defun-function 'markdown-end-of-text-block))
7660 (mark-defun))))
7662 (defun markdown-mark-page ()
7663 "Put mark at end of this top level section, point at beginning.
7664 The top level section marked is the one that contains point or
7665 follows point.
7667 Interactively, if this command is repeated or (in Transient Mark
7668 mode) if the mark is active, it marks the next page after the
7669 ones already marked."
7670 (interactive)
7671 (if (or (and (eq last-command this-command) (mark t))
7672 (and transient-mark-mode mark-active))
7673 (set-mark
7674 (save-excursion
7675 (goto-char (mark))
7676 (markdown-forward-page)
7677 (point)))
7678 (let ((beginning-of-defun-function 'markdown-backward-page)
7679 (end-of-defun-function 'markdown-forward-page))
7680 (mark-defun))))
7682 (defun markdown-narrow-to-page ()
7683 "Make text outside current top level section invisible.
7684 The current section is the one that contains point or follows point."
7685 (interactive)
7686 (let ((beginning-of-defun-function 'markdown-backward-page)
7687 (end-of-defun-function 'markdown-forward-page))
7688 (narrow-to-defun)))
7690 (defun markdown-mark-subtree ()
7691 "Mark the current subtree.
7692 This puts point at the start of the current subtree, and mark at the end."
7693 (interactive)
7694 (let ((beg))
7695 (if (markdown-heading-at-point)
7696 (beginning-of-line)
7697 (markdown-previous-visible-heading 1))
7698 (setq beg (point))
7699 (markdown-end-of-subtree)
7700 (push-mark (point) nil t)
7701 (goto-char beg)))
7703 (defun markdown-narrow-to-subtree ()
7704 "Narrow buffer to the current subtree."
7705 (interactive)
7706 (save-excursion
7707 (save-match-data
7708 (narrow-to-region
7709 (progn (markdown-back-to-heading-over-code-block t) (point))
7710 (progn (markdown-end-of-subtree)
7711 (if (and (markdown-heading-at-point) (not (eobp)))
7712 (backward-char 1))
7713 (point))))))
7716 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7718 (defun markdown-move-up ()
7719 "Move thing at point up.
7720 When in a list item, call `markdown-move-list-item-up'.
7721 When in a table, call `markdown-table-move-row-up'.
7722 Otherwise, move the current heading subtree up with
7723 `markdown-move-subtree-up'."
7724 (interactive)
7725 (cond
7726 ((markdown-list-item-at-point-p)
7727 (call-interactively #'markdown-move-list-item-up))
7728 ((markdown-table-at-point-p)
7729 (call-interactively #'markdown-table-move-row-up))
7731 (call-interactively #'markdown-move-subtree-up))))
7733 (defun markdown-move-down ()
7734 "Move thing at point down.
7735 When in a list item, call `markdown-move-list-item-down'.
7736 Otherwise, move the current heading subtree up with
7737 `markdown-move-subtree-down'."
7738 (interactive)
7739 (cond
7740 ((markdown-list-item-at-point-p)
7741 (call-interactively #'markdown-move-list-item-down))
7742 ((markdown-table-at-point-p)
7743 (call-interactively #'markdown-table-move-row-down))
7745 (call-interactively #'markdown-move-subtree-down))))
7747 (defun markdown-promote ()
7748 "Promote or move element at point to the left.
7749 Depending on the context, this function will promote a heading or
7750 list item at the point, move a table column to the left, or cycle
7751 markup."
7752 (interactive)
7753 (let (bounds)
7754 (cond
7755 ;; Promote atx heading subtree
7756 ((thing-at-point-looking-at markdown-regex-header-atx)
7757 (markdown-promote-subtree))
7758 ;; Promote setext heading
7759 ((thing-at-point-looking-at markdown-regex-header-setext)
7760 (markdown-cycle-setext -1))
7761 ;; Promote horizonal rule
7762 ((thing-at-point-looking-at markdown-regex-hr)
7763 (markdown-cycle-hr -1))
7764 ;; Promote list item
7765 ((setq bounds (markdown-cur-list-item-bounds))
7766 (markdown-promote-list-item bounds))
7767 ;; Move table column to the left
7768 ((markdown-table-at-point-p)
7769 (call-interactively #'markdown-table-move-column-left))
7770 ;; Promote bold
7771 ((thing-at-point-looking-at markdown-regex-bold)
7772 (markdown-cycle-bold))
7773 ;; Promote italic
7774 ((thing-at-point-looking-at markdown-regex-italic)
7775 (markdown-cycle-italic))
7777 (user-error "Nothing to promote at point")))))
7779 (defun markdown-demote ()
7780 "Demote or move element at point to the right.
7781 Depending on the context, this function will demote a heading or
7782 list item at the point, move a table column to the right, or cycle
7783 or remove markup."
7784 (interactive)
7785 (let (bounds)
7786 (cond
7787 ;; Demote atx heading subtree
7788 ((thing-at-point-looking-at markdown-regex-header-atx)
7789 (markdown-demote-subtree))
7790 ;; Demote setext heading
7791 ((thing-at-point-looking-at markdown-regex-header-setext)
7792 (markdown-cycle-setext 1))
7793 ;; Demote horizonal rule
7794 ((thing-at-point-looking-at markdown-regex-hr)
7795 (markdown-cycle-hr 1))
7796 ;; Demote list item
7797 ((setq bounds (markdown-cur-list-item-bounds))
7798 (markdown-demote-list-item bounds))
7799 ;; Move table column to the right
7800 ((markdown-table-at-point-p)
7801 (call-interactively #'markdown-table-move-column-right))
7802 ;; Demote bold
7803 ((thing-at-point-looking-at markdown-regex-bold)
7804 (markdown-cycle-bold))
7805 ;; Demote italic
7806 ((thing-at-point-looking-at markdown-regex-italic)
7807 (markdown-cycle-italic))
7809 (user-error "Nothing to demote at point")))))
7812 ;;; Commands ==================================================================
7814 (defun markdown (&optional output-buffer-name)
7815 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7816 The output buffer name defaults to `markdown-output-buffer-name'.
7817 Return the name of the output buffer used."
7818 (interactive)
7819 (save-window-excursion
7820 (let ((begin-region)
7821 (end-region))
7822 (if (markdown-use-region-p)
7823 (setq begin-region (region-beginning)
7824 end-region (region-end))
7825 (setq begin-region (point-min)
7826 end-region (point-max)))
7828 (unless output-buffer-name
7829 (setq output-buffer-name markdown-output-buffer-name))
7830 (cond
7831 ;; Handle case when `markdown-command' does not read from stdin
7832 ((and (stringp markdown-command) markdown-command-needs-filename)
7833 (if (not buffer-file-name)
7834 (user-error "Must be visiting a file")
7835 (shell-command (concat markdown-command " "
7836 (shell-quote-argument buffer-file-name))
7837 output-buffer-name)))
7838 ;; Pass region to `markdown-command' via stdin
7840 (let ((buf (get-buffer-create output-buffer-name)))
7841 (with-current-buffer buf
7842 (setq buffer-read-only nil)
7843 (erase-buffer))
7844 (if (stringp markdown-command)
7845 (call-process-region begin-region end-region
7846 shell-file-name nil buf nil
7847 shell-command-switch markdown-command)
7848 (funcall markdown-command begin-region end-region buf))))))
7849 output-buffer-name))
7851 (defun markdown-standalone (&optional output-buffer-name)
7852 "Special function to provide standalone HTML output.
7853 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7854 (interactive)
7855 (setq output-buffer-name (markdown output-buffer-name))
7856 (with-current-buffer output-buffer-name
7857 (set-buffer output-buffer-name)
7858 (unless (markdown-output-standalone-p)
7859 (markdown-add-xhtml-header-and-footer output-buffer-name))
7860 (goto-char (point-min))
7861 (html-mode))
7862 output-buffer-name)
7864 (defun markdown-other-window (&optional output-buffer-name)
7865 "Run `markdown-command' on current buffer and display in other window.
7866 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7867 that name."
7868 (interactive)
7869 (markdown-display-buffer-other-window
7870 (markdown-standalone output-buffer-name)))
7872 (defun markdown-output-standalone-p ()
7873 "Determine whether `markdown-command' output is standalone XHTML.
7874 Standalone XHTML output is identified by an occurrence of
7875 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7876 (save-excursion
7877 (goto-char (point-min))
7878 (save-match-data
7879 (re-search-forward
7880 markdown-xhtml-standalone-regexp
7881 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7882 t))))
7884 (defun markdown-stylesheet-link-string (stylesheet-path)
7885 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7886 stylesheet-path
7887 "\" />"))
7889 (defun markdown-add-xhtml-header-and-footer (title)
7890 "Wrap XHTML header and footer with given TITLE around current buffer."
7891 (goto-char (point-min))
7892 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7893 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7894 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7895 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7896 "<head>\n<title>")
7897 (insert title)
7898 (insert "</title>\n")
7899 (when (> (length markdown-content-type) 0)
7900 (insert
7901 (format
7902 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7903 markdown-content-type
7904 (or (and markdown-coding-system
7905 (fboundp 'coding-system-get)
7906 (coding-system-get markdown-coding-system
7907 'mime-charset))
7908 (and (fboundp 'coding-system-get)
7909 (coding-system-get buffer-file-coding-system
7910 'mime-charset))
7911 "iso-8859-1"))))
7912 (if (> (length markdown-css-paths) 0)
7913 (insert (mapconcat #'markdown-stylesheet-link-string
7914 markdown-css-paths "\n")))
7915 (when (> (length markdown-xhtml-header-content) 0)
7916 (insert markdown-xhtml-header-content))
7917 (insert "\n</head>\n\n"
7918 "<body>\n\n")
7919 (goto-char (point-max))
7920 (insert "\n"
7921 "</body>\n"
7922 "</html>\n"))
7924 (defun markdown-preview (&optional output-buffer-name)
7925 "Run `markdown-command' on the current buffer and view output in browser.
7926 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7927 that name."
7928 (interactive)
7929 (browse-url-of-buffer
7930 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7932 (defun markdown-export-file-name (&optional extension)
7933 "Attempt to generate a filename for Markdown output.
7934 The file extension will be EXTENSION if given, or .html by default.
7935 If the current buffer is visiting a file, we construct a new
7936 output filename based on that filename. Otherwise, return nil."
7937 (when (buffer-file-name)
7938 (unless extension
7939 (setq extension ".html"))
7940 (let ((candidate
7941 (concat
7942 (cond
7943 ((buffer-file-name)
7944 (file-name-sans-extension (buffer-file-name)))
7945 (t (buffer-name)))
7946 extension)))
7947 (cond
7948 ((equal candidate (buffer-file-name))
7949 (concat candidate extension))
7951 candidate)))))
7953 (defun markdown-export (&optional output-file)
7954 "Run Markdown on the current buffer, save to file, and return the filename.
7955 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
7956 generated by `markdown-export-file-name', which will be constructed using the
7957 current filename, but with the extension removed and replaced with .html."
7958 (interactive)
7959 (unless output-file
7960 (setq output-file (markdown-export-file-name ".html")))
7961 (when output-file
7962 (let* ((init-buf (current-buffer))
7963 (init-point (point))
7964 (init-buf-string (buffer-string))
7965 (output-buffer (find-file-noselect output-file))
7966 (output-buffer-name (buffer-name output-buffer)))
7967 (run-hooks 'markdown-before-export-hook)
7968 (markdown-standalone output-buffer-name)
7969 (with-current-buffer output-buffer
7970 (run-hooks 'markdown-after-export-hook)
7971 (save-buffer)
7972 (when markdown-export-kill-buffer (kill-buffer)))
7973 ;; if modified, restore initial buffer
7974 (when (buffer-modified-p init-buf)
7975 (erase-buffer)
7976 (insert init-buf-string)
7977 (save-buffer)
7978 (goto-char init-point))
7979 output-file)))
7981 (defun markdown-export-and-preview ()
7982 "Export to XHTML using `markdown-export' and browse the resulting file."
7983 (interactive)
7984 (browse-url-of-file (markdown-export)))
7986 (defvar markdown-live-preview-buffer nil
7987 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
7988 (make-variable-buffer-local 'markdown-live-preview-buffer)
7990 (defvar markdown-live-preview-source-buffer nil
7991 "Source buffer from which current buffer was generated.
7992 This is the inverse of `markdown-live-preview-buffer'.")
7993 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
7995 (defvar markdown-live-preview-currently-exporting nil)
7997 (defun markdown-live-preview-get-filename ()
7998 "Standardize the filename exported by `markdown-live-preview-export'."
7999 (markdown-export-file-name ".html"))
8001 (defun markdown-live-preview-window-eww (file)
8002 "Preview FILE with eww.
8003 To be used with `markdown-live-preview-window-function'."
8004 (if (require 'eww nil t)
8005 (progn
8006 (eww-open-file file)
8007 (get-buffer "*eww*"))
8008 (error "EWW is not present or not loaded on this version of Emacs")))
8010 (defun markdown-visual-lines-between-points (beg end)
8011 (save-excursion
8012 (goto-char beg)
8013 (cl-loop with count = 0
8014 while (progn (end-of-visual-line)
8015 (and (< (point) end) (line-move-visual 1 t)))
8016 do (cl-incf count)
8017 finally return count)))
8019 (defun markdown-live-preview-window-serialize (buf)
8020 "Get window point and scroll data for all windows displaying BUF."
8021 (when (buffer-live-p buf)
8022 (with-current-buffer buf
8023 (mapcar
8024 (lambda (win)
8025 (with-selected-window win
8026 (let* ((start (window-start))
8027 (pt (window-point))
8028 (pt-or-sym (cond ((= pt (point-min)) 'min)
8029 ((= pt (point-max)) 'max)
8030 (t pt)))
8031 (diff (markdown-visual-lines-between-points
8032 start pt)))
8033 (list win pt-or-sym diff))))
8034 (get-buffer-window-list buf)))))
8036 (defun markdown-get-point-back-lines (pt num-lines)
8037 (save-excursion
8038 (goto-char pt)
8039 (line-move-visual (- num-lines) t)
8040 ;; in testing, can occasionally overshoot the number of lines to traverse
8041 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
8042 (when (> actual-num-lines num-lines)
8043 (line-move-visual (- actual-num-lines num-lines) t)))
8044 (point)))
8046 (defun markdown-live-preview-window-deserialize (window-posns)
8047 "Apply window point and scroll data from WINDOW-POSNS.
8048 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
8049 (cl-destructuring-bind (win pt-or-sym diff) window-posns
8050 (when (window-live-p win)
8051 (with-current-buffer markdown-live-preview-buffer
8052 (set-window-buffer win (current-buffer))
8053 (cl-destructuring-bind (actual-pt actual-diff)
8054 (cl-case pt-or-sym
8055 (min (list (point-min) 0))
8056 (max (list (point-max) diff))
8057 (t (list pt-or-sym diff)))
8058 (set-window-start
8059 win (markdown-get-point-back-lines actual-pt actual-diff))
8060 (set-window-point win actual-pt))))))
8062 (defun markdown-live-preview-export ()
8063 "Export to XHTML using `markdown-export'.
8064 Browse the resulting file within Emacs using
8065 `markdown-live-preview-window-function' Return the buffer
8066 displaying the rendered output."
8067 (interactive)
8068 (let ((filename (markdown-live-preview-get-filename)))
8069 (when filename
8070 (let* ((markdown-live-preview-currently-exporting t)
8071 (cur-buf (current-buffer))
8072 (export-file (markdown-export filename))
8073 ;; get positions in all windows currently displaying output buffer
8074 (window-data
8075 (markdown-live-preview-window-serialize
8076 markdown-live-preview-buffer)))
8077 (save-window-excursion
8078 (let ((output-buffer
8079 (funcall markdown-live-preview-window-function export-file)))
8080 (with-current-buffer output-buffer
8081 (setq markdown-live-preview-source-buffer cur-buf)
8082 (add-hook 'kill-buffer-hook
8083 #'markdown-live-preview-remove-on-kill t t))
8084 (with-current-buffer cur-buf
8085 (setq markdown-live-preview-buffer output-buffer))))
8086 (with-current-buffer cur-buf
8087 ;; reset all windows displaying output buffer to where they were,
8088 ;; now with the new output
8089 (mapc #'markdown-live-preview-window-deserialize window-data)
8090 ;; delete html editing buffer
8091 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8092 (when (and export-file (file-exists-p export-file)
8093 (eq markdown-live-preview-delete-export
8094 'delete-on-export))
8095 (delete-file export-file))
8096 markdown-live-preview-buffer)))))
8098 (defun markdown-live-preview-remove ()
8099 (when (buffer-live-p markdown-live-preview-buffer)
8100 (kill-buffer markdown-live-preview-buffer))
8101 (setq markdown-live-preview-buffer nil)
8102 ;; if set to 'delete-on-export, the output has already been deleted
8103 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8104 (let ((outfile-name (markdown-live-preview-get-filename)))
8105 (when (and outfile-name (file-exists-p outfile-name))
8106 (delete-file outfile-name)))))
8108 (defun markdown-get-other-window ()
8109 "Find another window to display preview or output content."
8110 (cond
8111 ((memq markdown-split-window-direction '(vertical below))
8112 (or (window-in-direction 'below) (split-window-vertically)))
8113 ((memq markdown-split-window-direction '(horizontal right))
8114 (or (window-in-direction 'right) (split-window-horizontally)))
8115 (t (split-window-sensibly (get-buffer-window)))))
8117 (defun markdown-display-buffer-other-window (buf)
8118 "Display preview or output buffer BUF in another window."
8119 (let ((cur-buf (current-buffer))
8120 (window (markdown-get-other-window)))
8121 (set-window-buffer window buf)
8122 (set-buffer cur-buf)))
8124 (defun markdown-live-preview-if-markdown ()
8125 (when (and (derived-mode-p 'markdown-mode)
8126 markdown-live-preview-mode)
8127 (unless markdown-live-preview-currently-exporting
8128 (if (buffer-live-p markdown-live-preview-buffer)
8129 (markdown-live-preview-export)
8130 (markdown-display-buffer-other-window
8131 (markdown-live-preview-export))))))
8133 (defun markdown-live-preview-remove-on-kill ()
8134 (cond ((and (derived-mode-p 'markdown-mode)
8135 markdown-live-preview-mode)
8136 (markdown-live-preview-remove))
8137 (markdown-live-preview-source-buffer
8138 (with-current-buffer markdown-live-preview-source-buffer
8139 (setq markdown-live-preview-buffer nil))
8140 (setq markdown-live-preview-source-buffer nil))))
8142 (defun markdown-live-preview-switch-to-output ()
8143 "Switch to output buffer."
8144 (interactive)
8145 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8146 output buffer in another window."
8147 (if markdown-live-preview-mode
8148 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8149 (markdown-live-preview-mode))
8151 (defun markdown-live-preview-re-export ()
8152 "Re export source buffer."
8153 (interactive)
8154 "If the current buffer is a buffer displaying the exported version of a
8155 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8156 update this buffer's contents."
8157 (when markdown-live-preview-source-buffer
8158 (with-current-buffer markdown-live-preview-source-buffer
8159 (markdown-live-preview-export))))
8161 (defun markdown-open ()
8162 "Open file for the current buffer with `markdown-open-command'."
8163 (interactive)
8164 (unless markdown-open-command
8165 (user-error "Variable `markdown-open-command' must be set"))
8166 (if (stringp markdown-open-command)
8167 (if (not buffer-file-name)
8168 (user-error "Must be visiting a file")
8169 (save-buffer)
8170 (call-process markdown-open-command nil 0 nil buffer-file-name))
8171 (funcall markdown-open-command))
8172 nil)
8174 (defun markdown-kill-ring-save ()
8175 "Run Markdown on file and store output in the kill ring."
8176 (interactive)
8177 (save-window-excursion
8178 (markdown)
8179 (with-current-buffer markdown-output-buffer-name
8180 (kill-ring-save (point-min) (point-max)))))
8183 ;;; Links =====================================================================
8185 (defun markdown-link-p ()
8186 "Return non-nil when `point' is at a non-wiki link.
8187 See `markdown-wiki-link-p' for more information."
8188 (let ((case-fold-search nil))
8189 (and (not (markdown-wiki-link-p))
8190 (not (markdown-code-block-at-point-p))
8191 (or (thing-at-point-looking-at markdown-regex-link-inline)
8192 (thing-at-point-looking-at markdown-regex-link-reference)
8193 (thing-at-point-looking-at markdown-regex-uri)
8194 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8196 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8198 (defun markdown-link-at-pos (pos)
8199 "Return properties of link or image at position POS.
8200 Value is a list of elements describing the link:
8201 0. beginning position
8202 1. end position
8203 2. link text
8204 3. URL
8205 4. reference label
8206 5. title text
8207 6. bang (nil or \"!\")"
8208 (save-excursion
8209 (goto-char pos)
8210 (let (begin end text url reference title bang)
8211 (cond
8212 ;; Inline or reference image or link at point.
8213 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8214 (thing-at-point-looking-at markdown-regex-link-reference))
8215 (setq bang (match-string-no-properties 1)
8216 begin (match-beginning 0)
8217 end (match-end 0)
8218 text (match-string-no-properties 3))
8219 (if (char-equal (char-after (match-beginning 5)) ?\[)
8220 ;; Reference link
8221 (setq reference (match-string-no-properties 6))
8222 ;; Inline link
8223 (setq url (match-string-no-properties 6))
8224 (when (match-end 7)
8225 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8226 ;; Angle bracket URI at point.
8227 ((thing-at-point-looking-at markdown-regex-angle-uri)
8228 (setq begin (match-beginning 0)
8229 end (match-end 0)
8230 url (match-string-no-properties 2)))
8231 ;; Plain URI at point.
8232 ((thing-at-point-looking-at markdown-regex-uri)
8233 (setq begin (match-beginning 0)
8234 end (match-end 0)
8235 url (match-string-no-properties 1))))
8236 (list begin end text url reference title bang))))
8238 (defun markdown-link-url ()
8239 "Return the URL part of the regular (non-wiki) link at point.
8240 Works with both inline and reference style links, and with images.
8241 If point is not at a link or the link reference is not defined
8242 returns nil."
8243 (let* ((values (markdown-link-at-pos (point)))
8244 (text (nth 2 values))
8245 (url (nth 3 values))
8246 (ref (nth 4 values)))
8247 (or url (and ref (car (markdown-reference-definition
8248 (downcase (if (string= ref "") text ref))))))))
8250 (defun markdown-follow-link-at-point ()
8251 "Open the current non-wiki link.
8252 If the link is a complete URL, open in browser with `browse-url'.
8253 Otherwise, open with `find-file' after stripping anchor and/or query string.
8254 Translate filenames using `markdown-filename-translate-function'."
8255 (interactive)
8256 (if (markdown-link-p)
8257 (let* ((url (markdown-link-url))
8258 (struct (url-generic-parse-url url))
8259 (full (url-fullness struct))
8260 (file url))
8261 ;; Parse URL, determine fullness, strip query string
8262 (if (fboundp 'url-path-and-query)
8263 (setq file (car (url-path-and-query struct)))
8264 (when (and (setq file (url-filename struct))
8265 (string-match "\\?" file))
8266 (setq file (substring file 0 (match-beginning 0)))))
8267 ;; Open full URLs in browser, files in Emacs
8268 (if full
8269 (browse-url url)
8270 (when (and file (> (length file) 0))
8271 (find-file (funcall markdown-translate-filename-function file)))))
8272 (user-error "Point is not at a Markdown link or URL")))
8274 (defun markdown-fontify-inline-links (last)
8275 "Add text properties to next inline link from point to LAST."
8276 (when (markdown-match-generic-links last nil)
8277 (let* ((link-start (match-beginning 3))
8278 (link-end (match-end 3))
8279 (url-start (match-beginning 6))
8280 (url-end (match-end 6))
8281 (url (match-string-no-properties 6))
8282 (title-start (match-beginning 7))
8283 (title-end (match-end 7))
8284 (title (match-string-no-properties 7))
8285 ;; Markup part
8286 (mp (list 'face 'markdown-markup-face
8287 'invisible 'markdown-markup
8288 'rear-nonsticky t
8289 'font-lock-multiline t))
8290 ;; Link part
8291 (lp (list 'keymap markdown-mode-mouse-map
8292 'face markdown-link-face
8293 'mouse-face 'markdown-highlight-face
8294 'font-lock-multiline t
8295 'help-echo (if title (concat title "\n" url) url)))
8296 ;; URL part
8297 (up (list 'keymap markdown-mode-mouse-map
8298 'face 'markdown-url-face
8299 'invisible 'markdown-markup
8300 'mouse-face 'markdown-highlight-face
8301 'font-lock-multiline t))
8302 ;; URL composition character
8303 (url-char (markdown--first-displayable markdown-url-compose-char))
8304 ;; Title part
8305 (tp (list 'face 'markdown-link-title-face
8306 'invisible 'markdown-markup
8307 'font-lock-multiline t)))
8308 (dolist (g '(1 2 4 5 8))
8309 (when (match-end g)
8310 (add-text-properties (match-beginning g) (match-end g) mp)))
8311 (when link-start (add-text-properties link-start link-end lp))
8312 (when url-start (add-text-properties url-start url-end up))
8313 (when title-start (add-text-properties url-end title-end tp))
8314 (when (and markdown-hide-urls url-start)
8315 (compose-region url-start (or title-end url-end) url-char))
8316 t)))
8318 (defun markdown-fontify-reference-links (last)
8319 "Add text properties to next reference link from point to LAST."
8320 (when (markdown-match-generic-links last t)
8321 (let* ((link-start (match-beginning 3))
8322 (link-end (match-end 3))
8323 (ref-start (match-beginning 6))
8324 (ref-end (match-end 6))
8325 ;; Markup part
8326 (mp (list 'face 'markdown-markup-face
8327 'invisible 'markdown-markup
8328 'rear-nonsticky t
8329 'font-lock-multiline t))
8330 ;; Link part
8331 (lp (list 'keymap markdown-mode-mouse-map
8332 'face markdown-link-face
8333 'mouse-face 'markdown-highlight-face
8334 'font-lock-multiline t
8335 'help-echo (lambda (_ __ pos)
8336 (save-match-data
8337 (save-excursion
8338 (goto-char pos)
8339 (or (markdown-link-url)
8340 "Undefined reference"))))))
8341 ;; URL composition character
8342 (url-char (markdown--first-displayable markdown-url-compose-char))
8343 ;; Reference part
8344 (rp (list 'face 'markdown-reference-face
8345 'invisible 'markdown-markup
8346 'font-lock-multiline t)))
8347 (dolist (g '(1 2 4 5 8))
8348 (when (match-end g)
8349 (add-text-properties (match-beginning g) (match-end g) mp)))
8350 (when link-start (add-text-properties link-start link-end lp))
8351 (when ref-start (add-text-properties ref-start ref-end rp)
8352 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8353 (compose-region ref-start ref-end url-char)))
8354 t)))
8356 (defun markdown-fontify-angle-uris (last)
8357 "Add text properties to angle URIs from point to LAST."
8358 (when (markdown-match-angle-uris last)
8359 (let* ((url-start (match-beginning 2))
8360 (url-end (match-end 2))
8361 ;; Markup part
8362 (mp (list 'face 'markdown-markup-face
8363 'invisible 'markdown-markup
8364 'rear-nonsticky t
8365 'font-lock-multiline t))
8366 ;; URI part
8367 (up (list 'keymap markdown-mode-mouse-map
8368 'face 'markdown-plain-url-face
8369 'mouse-face 'markdown-highlight-face
8370 'font-lock-multiline t)))
8371 (dolist (g '(1 3))
8372 (add-text-properties (match-beginning g) (match-end g) mp))
8373 (add-text-properties url-start url-end up)
8374 t)))
8376 (defun markdown-fontify-plain-uris (last)
8377 "Add text properties to plain URLs from point to LAST."
8378 (when (markdown-match-plain-uris last)
8379 (let* ((start (match-beginning 0))
8380 (end (match-end 0))
8381 (props (list 'keymap markdown-mode-mouse-map
8382 'face 'markdown-plain-url-face
8383 'mouse-face 'markdown-highlight-face
8384 'rear-nonsticky t
8385 'font-lock-multiline t)))
8386 (add-text-properties start end props)
8387 t)))
8389 (defun markdown-toggle-url-hiding (&optional arg)
8390 "Toggle the display or hiding of URLs.
8391 With a prefix argument ARG, enable URL hiding if ARG is positive,
8392 and disable it otherwise."
8393 (interactive (list (or current-prefix-arg 'toggle)))
8394 (setq markdown-hide-urls
8395 (if (eq arg 'toggle)
8396 (not markdown-hide-urls)
8397 (> (prefix-numeric-value arg) 0)))
8398 (if markdown-hide-urls
8399 (message "markdown-mode URL hiding enabled")
8400 (message "markdown-mode URL hiding disabled"))
8401 (markdown-reload-extensions))
8404 ;;; WikiLink Following/Markup =================================================
8406 (defun markdown-wiki-link-p ()
8407 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8408 A true wiki link name matches `markdown-regex-wiki-link' but does
8409 not match the current file name after conversion. This modifies
8410 the data returned by `match-data'. Note that the potential wiki
8411 link name must be available via `match-string'."
8412 (when markdown-enable-wiki-links
8413 (let ((case-fold-search nil))
8414 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8415 (not (markdown-code-block-at-point-p))
8416 (or (not buffer-file-name)
8417 (not (string-equal (buffer-file-name)
8418 (markdown-convert-wiki-link-to-filename
8419 (markdown-wiki-link-link)))))))))
8421 (defun markdown-wiki-link-link ()
8422 "Return the link part of the wiki link using current match data.
8423 The location of the link component depends on the value of
8424 `markdown-wiki-link-alias-first'."
8425 (if markdown-wiki-link-alias-first
8426 (or (match-string-no-properties 5) (match-string-no-properties 3))
8427 (match-string-no-properties 3)))
8429 (defun markdown-wiki-link-alias ()
8430 "Return the alias or text part of the wiki link using current match data.
8431 The location of the alias component depends on the value of
8432 `markdown-wiki-link-alias-first'."
8433 (if markdown-wiki-link-alias-first
8434 (match-string-no-properties 3)
8435 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8437 (defun markdown-convert-wiki-link-to-filename (name)
8438 "Generate a filename from the wiki link NAME.
8439 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8440 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8441 and [[test test]] both map to Test-test.ext. Look in the current
8442 directory first, then in subdirectories if
8443 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8444 in parent directories if
8445 `markdown-wiki-link-search-parent-directories' is non-nil."
8446 (let* ((basename (markdown-replace-regexp-in-string
8447 "[[:space:]\n]" markdown-link-space-sub-char name))
8448 (basename (if (eq major-mode 'gfm-mode)
8449 (concat (upcase (substring basename 0 1))
8450 (downcase (substring basename 1 nil)))
8451 basename))
8452 directory extension default candidates dir)
8453 (when buffer-file-name
8454 (setq directory (file-name-directory buffer-file-name)
8455 extension (file-name-extension buffer-file-name)))
8456 (setq default (concat basename
8457 (when extension (concat "." extension))))
8458 (cond
8459 ;; Look in current directory first.
8460 ((or (null buffer-file-name)
8461 (file-exists-p default))
8462 default)
8463 ;; Possibly search in subdirectories, next.
8464 ((and markdown-wiki-link-search-subdirectories
8465 (setq candidates
8466 (markdown-directory-files-recursively
8467 directory (concat "^" default "$"))))
8468 (car candidates))
8469 ;; Possibly search in parent directories as a last resort.
8470 ((and markdown-wiki-link-search-parent-directories
8471 (setq dir (locate-dominating-file directory default)))
8472 (concat dir default))
8473 ;; If nothing is found, return default in current directory.
8474 (t default))))
8476 (defun markdown-follow-wiki-link (name &optional other)
8477 "Follow the wiki link NAME.
8478 Convert the name to a file name and call `find-file'. Ensure that
8479 the new buffer remains in `markdown-mode'. Open the link in another
8480 window when OTHER is non-nil."
8481 (let ((filename (markdown-convert-wiki-link-to-filename name))
8482 (wp (when buffer-file-name
8483 (file-name-directory buffer-file-name))))
8484 (if (not wp)
8485 (user-error "Must be visiting a file")
8486 (when other (other-window 1))
8487 (let ((default-directory wp))
8488 (find-file filename)))
8489 (when (not (eq major-mode 'markdown-mode))
8490 (markdown-mode))))
8492 (defun markdown-follow-wiki-link-at-point (&optional arg)
8493 "Find Wiki Link at point.
8494 With prefix argument ARG, open the file in other window.
8495 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8496 (interactive "P")
8497 (if (markdown-wiki-link-p)
8498 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8499 (user-error "Point is not at a Wiki Link")))
8501 (defun markdown-highlight-wiki-link (from to face)
8502 "Highlight the wiki link in the region between FROM and TO using FACE."
8503 (put-text-property from to 'font-lock-face face))
8505 (defun markdown-unfontify-region-wiki-links (from to)
8506 "Remove wiki link faces from the region specified by FROM and TO."
8507 (interactive "*r")
8508 (let ((modified (buffer-modified-p)))
8509 (remove-text-properties from to '(font-lock-face markdown-link-face))
8510 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8511 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8512 ;; undo that if it wasn't originally marked modified
8513 (set-buffer-modified-p modified)))
8515 (defun markdown-fontify-region-wiki-links (from to)
8516 "Search region given by FROM and TO for wiki links and fontify them.
8517 If a wiki link is found check to see if the backing file exists
8518 and highlight accordingly."
8519 (goto-char from)
8520 (save-match-data
8521 (while (re-search-forward markdown-regex-wiki-link to t)
8522 (when (not (markdown-code-block-at-point-p))
8523 (let ((highlight-beginning (match-beginning 1))
8524 (highlight-end (match-end 1))
8525 (file-name
8526 (markdown-convert-wiki-link-to-filename
8527 (markdown-wiki-link-link))))
8528 (if (condition-case nil (file-exists-p file-name) (error nil))
8529 (markdown-highlight-wiki-link
8530 highlight-beginning highlight-end markdown-link-face)
8531 (markdown-highlight-wiki-link
8532 highlight-beginning highlight-end markdown-missing-link-face)))))))
8534 (defun markdown-extend-changed-region (from to)
8535 "Extend region given by FROM and TO so that we can fontify all links.
8536 The region is extended to the first newline before and the first
8537 newline after."
8538 ;; start looking for the first new line before 'from
8539 (goto-char from)
8540 (re-search-backward "\n" nil t)
8541 (let ((new-from (point-min))
8542 (new-to (point-max)))
8543 (if (not (= (point) from))
8544 (setq new-from (point)))
8545 ;; do the same thing for the first new line after 'to
8546 (goto-char to)
8547 (re-search-forward "\n" nil t)
8548 (if (not (= (point) to))
8549 (setq new-to (point)))
8550 (cl-values new-from new-to)))
8552 (defun markdown-check-change-for-wiki-link (from to)
8553 "Check region between FROM and TO for wiki links and re-fontify as needed."
8554 (interactive "*r")
8555 (let* ((modified (buffer-modified-p))
8556 (buffer-undo-list t)
8557 (inhibit-read-only t)
8558 (inhibit-point-motion-hooks t)
8559 deactivate-mark
8560 buffer-file-truename)
8561 (unwind-protect
8562 (save-excursion
8563 (save-match-data
8564 (save-restriction
8565 ;; Extend the region to fontify so that it starts
8566 ;; and ends at safe places.
8567 (cl-multiple-value-bind (new-from new-to)
8568 (markdown-extend-changed-region from to)
8569 (goto-char new-from)
8570 ;; Only refontify when the range contains text with a
8571 ;; wiki link face or if the wiki link regexp matches.
8572 (when (or (markdown-range-property-any
8573 new-from new-to 'font-lock-face
8574 (list markdown-link-face
8575 markdown-missing-link-face))
8576 (re-search-forward
8577 markdown-regex-wiki-link new-to t))
8578 ;; Unfontify existing fontification (start from scratch)
8579 (markdown-unfontify-region-wiki-links new-from new-to)
8580 ;; Now do the fontification.
8581 (markdown-fontify-region-wiki-links new-from new-to))))))
8582 (and (not modified)
8583 (buffer-modified-p)
8584 (set-buffer-modified-p nil)))))
8586 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8587 "Check region between FROM and TO for wiki links and re-fontify as needed.
8588 Designed to be used with the `after-change-functions' hook."
8589 (markdown-check-change-for-wiki-link from to))
8591 (defun markdown-fontify-buffer-wiki-links ()
8592 "Refontify all wiki links in the buffer."
8593 (interactive)
8594 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8597 ;;; Following & Doing =========================================================
8599 (defun markdown-follow-thing-at-point (arg)
8600 "Follow thing at point if possible, such as a reference link or wiki link.
8601 Opens inline and reference links in a browser. Opens wiki links
8602 to other files in the current window, or the another window if
8603 ARG is non-nil.
8604 See `markdown-follow-link-at-point' and
8605 `markdown-follow-wiki-link-at-point'."
8606 (interactive "P")
8607 (cond ((markdown-link-p)
8608 (markdown-follow-link-at-point))
8609 ((markdown-wiki-link-p)
8610 (markdown-follow-wiki-link-at-point arg))
8612 (user-error "Nothing to follow at point"))))
8614 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8616 (defun markdown-do ()
8617 "Do something sensible based on context at point.
8618 Jumps between reference links and definitions; between footnote
8619 markers and footnote text."
8620 (interactive)
8621 (cond
8622 ;; Footnote definition
8623 ((markdown-footnote-text-positions)
8624 (markdown-footnote-return))
8625 ;; Footnote marker
8626 ((markdown-footnote-marker-positions)
8627 (markdown-footnote-goto-text))
8628 ;; Reference link
8629 ((thing-at-point-looking-at markdown-regex-link-reference)
8630 (markdown-reference-goto-definition))
8631 ;; Reference definition
8632 ((thing-at-point-looking-at markdown-regex-reference-definition)
8633 (markdown-reference-goto-link (match-string-no-properties 2)))
8634 ;; GFM task list item
8635 ((markdown-gfm-task-list-item-at-point)
8636 (markdown-toggle-gfm-checkbox))
8637 ;; Align table
8638 ((markdown-table-at-point-p)
8639 (call-interactively #'markdown-table-align))
8640 ;; Otherwise
8642 (markdown-insert-gfm-checkbox))))
8645 ;;; Miscellaneous =============================================================
8647 (defun markdown-compress-whitespace-string (str)
8648 "Compress whitespace in STR and return result.
8649 Leading and trailing whitespace is removed. Sequences of multiple
8650 spaces, tabs, and newlines are replaced with single spaces."
8651 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8652 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8654 (defun markdown--substitute-command-keys (string)
8655 "Like `substitute-command-keys' but, but prefers control characters.
8656 First pass STRING to `substitute-command-keys' and then
8657 substitute `C-i` for `TAB` and `C-m` for `RET`."
8658 (replace-regexp-in-string
8659 "\\<TAB\\>" "C-i"
8660 (replace-regexp-in-string
8661 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8663 (defun markdown-line-number-at-pos (&optional pos)
8664 "Return (narrowed) buffer line number at position POS.
8665 If POS is nil, use current buffer location.
8666 This is an exact copy of `line-number-at-pos' for use in emacs21."
8667 (let ((opoint (or pos (point))) start)
8668 (save-excursion
8669 (goto-char (point-min))
8670 (setq start (point))
8671 (goto-char opoint)
8672 (forward-line 0)
8673 (1+ (count-lines start (point))))))
8675 (defun markdown-inside-link-p ()
8676 "Return t if point is within a link."
8677 (save-match-data
8678 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8680 (defun markdown-line-is-reference-definition-p ()
8681 "Return whether the current line is a (non-footnote) reference defition."
8682 (save-excursion
8683 (move-beginning-of-line 1)
8684 (and (looking-at-p markdown-regex-reference-definition)
8685 (not (looking-at-p "[ \t]*\\[^")))))
8687 (defun markdown-adaptive-fill-function ()
8688 "Return prefix for filling paragraph or nil if not determined."
8689 (cond
8690 ;; List item inside blockquote
8691 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8692 (markdown-replace-regexp-in-string
8693 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8694 ;; Blockquote
8695 ((looking-at markdown-regex-blockquote)
8696 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8697 ;; List items
8698 ((looking-at markdown-regex-list)
8699 (match-string-no-properties 0))
8700 ;; Footnote definition
8701 ((looking-at-p markdown-regex-footnote-definition)
8702 " ") ; four spaces
8703 ;; No match
8704 (t nil)))
8706 (defun markdown-fill-paragraph (&optional justify)
8707 "Fill paragraph at or after point.
8708 This function is like \\[fill-paragraph], but it skips Markdown
8709 code blocks. If the point is in a code block, or just before one,
8710 do not fill. Otherwise, call `fill-paragraph' as usual. If
8711 JUSTIFY is non-nil, justify text as well. Since this function
8712 handles filling itself, it always returns t so that
8713 `fill-paragraph' doesn't run."
8714 (interactive "P")
8715 (unless (or (markdown-code-block-at-point-p)
8716 (save-excursion
8717 (back-to-indentation)
8718 (skip-syntax-forward "-")
8719 (markdown-code-block-at-point-p)))
8720 (fill-paragraph justify))
8723 (make-obsolete 'markdown-fill-forward-paragraph-function
8724 'markdown-fill-forward-paragraph "v2.3")
8726 (defun markdown-fill-forward-paragraph (&optional arg)
8727 "Function used by `fill-paragraph' to move over ARG paragraphs.
8728 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8729 It is called with a single argument specifying the number of
8730 paragraphs to move. Just like `forward-paragraph', it should
8731 return the number of paragraphs left to move."
8732 (or arg (setq arg 1))
8733 (if (> arg 0)
8734 ;; With positive ARG, move across ARG non-code-block paragraphs,
8735 ;; one at a time. When passing a code block, don't decrement ARG.
8736 (while (and (not (eobp))
8737 (> arg 0)
8738 (= (forward-paragraph 1) 0)
8739 (or (markdown-code-block-at-pos (point-at-bol 0))
8740 (setq arg (1- arg)))))
8741 ;; Move backward by one paragraph with negative ARG (always -1).
8742 (let ((start (point)))
8743 (setq arg (forward-paragraph arg))
8744 (while (and (not (eobp))
8745 (progn (move-to-left-margin) (not (eobp)))
8746 (looking-at-p paragraph-separate))
8747 (forward-line 1))
8748 (cond
8749 ;; Move point past whitespace following list marker.
8750 ((looking-at markdown-regex-list)
8751 (goto-char (match-end 0)))
8752 ;; Move point past whitespace following pipe at beginning of line
8753 ;; to handle Pandoc line blocks.
8754 ((looking-at "^|\\s-*")
8755 (goto-char (match-end 0)))
8756 ;; Return point if the paragraph passed was a code block.
8757 ((markdown-code-block-at-pos (point-at-bol 2))
8758 (goto-char start)))))
8759 arg)
8761 (defun markdown--inhibit-electric-quote ()
8762 "Function added to `electric-quote-inhibit-functions'.
8763 Return non-nil if the quote has been inserted inside a code block
8764 or span."
8765 (let ((pos (1- (point))))
8766 (or (markdown-inline-code-at-pos pos)
8767 (markdown-code-block-at-pos pos))))
8770 ;;; Extension Framework =======================================================
8772 (defun markdown-reload-extensions ()
8773 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8774 (interactive)
8775 (when (member major-mode '(markdown-mode gfm-mode))
8776 ;; Refontify buffer
8777 (if (eval-when-compile (fboundp 'font-lock-flush))
8778 ;; Use font-lock-flush in Emacs >= 25.1
8779 (font-lock-flush)
8780 ;; Backwards compatibility for Emacs 24.3-24.5
8781 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8782 (font-lock-refresh-defaults)))
8783 ;; Add or remove hooks related to extensions
8784 (markdown-setup-wiki-link-hooks)))
8786 (defun markdown-handle-local-variables ()
8787 "Run in `hack-local-variables-hook' to update font lock rules.
8788 Checks to see if there is actually a ‘markdown-mode’ file local variable
8789 before regenerating font-lock rules for extensions."
8790 (when (and (boundp 'file-local-variables-alist)
8791 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8792 (assoc 'markdown-enable-math file-local-variables-alist)))
8793 (when (assoc 'markdown-enable-math file-local-variables-alist)
8794 (markdown-toggle-math markdown-enable-math))
8795 (markdown-reload-extensions)))
8798 ;;; Wiki Links ================================================================
8800 (defun markdown-toggle-wiki-links (&optional arg)
8801 "Toggle support for wiki links.
8802 With a prefix argument ARG, enable wiki link support if ARG is positive,
8803 and disable it otherwise."
8804 (interactive (list (or current-prefix-arg 'toggle)))
8805 (setq markdown-enable-wiki-links
8806 (if (eq arg 'toggle)
8807 (not markdown-enable-wiki-links)
8808 (> (prefix-numeric-value arg) 0)))
8809 (if markdown-enable-wiki-links
8810 (message "markdown-mode wiki link support enabled")
8811 (message "markdown-mode wiki link support disabled"))
8812 (markdown-reload-extensions))
8814 (defun markdown-setup-wiki-link-hooks ()
8815 "Add or remove hooks for fontifying wiki links.
8816 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8817 ;; Anytime text changes make sure it gets fontified correctly
8818 (if (and markdown-enable-wiki-links
8819 markdown-wiki-link-fontify-missing)
8820 (add-hook 'after-change-functions
8821 'markdown-check-change-for-wiki-link-after-change t t)
8822 (remove-hook 'after-change-functions
8823 'markdown-check-change-for-wiki-link-after-change t))
8824 ;; If we left the buffer there is a really good chance we were
8825 ;; creating one of the wiki link documents. Make sure we get
8826 ;; refontified when we come back.
8827 (if (and markdown-enable-wiki-links
8828 markdown-wiki-link-fontify-missing)
8829 (progn
8830 (add-hook 'window-configuration-change-hook
8831 'markdown-fontify-buffer-wiki-links t t)
8832 (markdown-fontify-buffer-wiki-links))
8833 (remove-hook 'window-configuration-change-hook
8834 'markdown-fontify-buffer-wiki-links t)
8835 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8838 ;;; Math Support ==============================================================
8840 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8842 (defconst markdown-mode-font-lock-keywords-math
8843 (list
8844 ;; Equation reference (eq:foo)
8845 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8846 (2 markdown-reference-face)
8847 (3 markdown-markup-face)))
8848 ;; Equation reference \eqref{foo}
8849 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8850 (2 markdown-reference-face)
8851 (3 markdown-markup-face))))
8852 "Font lock keywords to add and remove when toggling math support.")
8854 (defun markdown-toggle-math (&optional arg)
8855 "Toggle support for inline and display LaTeX math expressions.
8856 With a prefix argument ARG, enable math mode if ARG is positive,
8857 and disable it otherwise. If called from Lisp, enable the mode
8858 if ARG is omitted or nil."
8859 (interactive (list (or current-prefix-arg 'toggle)))
8860 (setq markdown-enable-math
8861 (if (eq arg 'toggle)
8862 (not markdown-enable-math)
8863 (> (prefix-numeric-value arg) 0)))
8864 (if markdown-enable-math
8865 (progn
8866 (font-lock-add-keywords
8867 'markdown-mode markdown-mode-font-lock-keywords-math)
8868 (message "markdown-mode math support enabled"))
8869 (font-lock-remove-keywords
8870 'markdown-mode markdown-mode-font-lock-keywords-math)
8871 (message "markdown-mode math support disabled"))
8872 (markdown-reload-extensions))
8875 ;;; GFM Checkboxes ============================================================
8877 (define-button-type 'markdown-gfm-checkbox-button
8878 'follow-link t
8879 'face 'markdown-gfm-checkbox-face
8880 'mouse-face 'markdown-highlight-face
8881 'action #'markdown-toggle-gfm-checkbox-button)
8883 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8884 "Return non-nil if there is a GFM task list item at the point.
8885 Optionally, the list item BOUNDS may be given if available, as
8886 returned by `markdown-cur-list-item-bounds'. When a task list item
8887 is found, the return value is the same value returned by
8888 `markdown-cur-list-item-bounds'."
8889 (unless bounds
8890 (setq bounds (markdown-cur-list-item-bounds)))
8891 (> (length (nth 5 bounds)) 0))
8893 (defun markdown-insert-gfm-checkbox ()
8894 "Add GFM checkbox at point.
8895 Returns t if added.
8896 Returns nil if non-applicable."
8897 (interactive)
8898 (let ((bounds (markdown-cur-list-item-bounds)))
8899 (if bounds
8900 (unless (cl-sixth bounds)
8901 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8902 (markup "[ ] "))
8903 (if (< pos (point))
8904 (save-excursion
8905 (goto-char pos)
8906 (insert markup))
8907 (goto-char pos)
8908 (insert markup))
8910 (unless (save-excursion
8911 (back-to-indentation)
8912 (or (markdown-list-item-at-point-p)
8913 (markdown-heading-at-point)
8914 (markdown-in-comment-p)
8915 (markdown-code-block-at-point-p)))
8916 (let ((pos (save-excursion
8917 (back-to-indentation)
8918 (point)))
8919 (markup (concat (or (save-excursion
8920 (beginning-of-line 0)
8921 (cl-fifth (markdown-cur-list-item-bounds)))
8922 markdown-unordered-list-item-prefix)
8923 "[ ] ")))
8924 (if (< pos (point))
8925 (save-excursion
8926 (goto-char pos)
8927 (insert markup))
8928 (goto-char pos)
8929 (insert markup))
8930 t)))))
8932 (defun markdown-toggle-gfm-checkbox ()
8933 "Toggle GFM checkbox at point.
8934 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
8935 Returns nil if there is no task list item at the point."
8936 (interactive)
8937 (save-match-data
8938 (save-excursion
8939 (let ((bounds (markdown-cur-list-item-bounds)))
8940 (when bounds
8941 ;; Move to beginning of task list item
8942 (goto-char (cl-first bounds))
8943 ;; Advance to column of first non-whitespace after marker
8944 (forward-char (cl-fourth bounds))
8945 (cond ((looking-at "\\[ \\]")
8946 (replace-match
8947 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
8948 nil t)
8949 (match-string-no-properties 0))
8950 ((looking-at "\\[[xX]\\]")
8951 (replace-match "[ ]" nil t)
8952 (match-string-no-properties 0))))))))
8954 (defun markdown-toggle-gfm-checkbox-button (button)
8955 "Toggle GFM checkbox BUTTON on click."
8956 (save-match-data
8957 (save-excursion
8958 (goto-char (button-start button))
8959 (markdown-toggle-gfm-checkbox))))
8961 (defun markdown-make-gfm-checkboxes-buttons (start end)
8962 "Make GFM checkboxes buttons in region between START and END."
8963 (save-excursion
8964 (goto-char start)
8965 (let ((case-fold-search t))
8966 (save-excursion
8967 (while (re-search-forward markdown-regex-gfm-checkbox end t)
8968 (make-button (match-beginning 1) (match-end 1)
8969 :type 'markdown-gfm-checkbox-button))))))
8971 ;; Called when any modification is made to buffer text.
8972 (defun markdown-gfm-checkbox-after-change-function (beg end _)
8973 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
8974 BEG and END are the limits of scanned region."
8975 (save-excursion
8976 (save-match-data
8977 ;; Rescan between start of line from `beg' and start of line after `end'.
8978 (markdown-make-gfm-checkboxes-buttons
8979 (progn (goto-char beg) (beginning-of-line) (point))
8980 (progn (goto-char end) (forward-line 1) (point))))))
8982 (defun markdown-remove-gfm-checkbox-overlays ()
8983 "Remove all GFM checkbox overlays in buffer."
8984 (save-excursion
8985 (save-restriction
8986 (widen)
8987 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
8990 ;;; Display inline image =================================================
8992 (defvar markdown-inline-image-overlays nil)
8993 (make-variable-buffer-local 'markdown-inline-image-overlays)
8995 (defun markdown-remove-inline-images ()
8996 "Remove inline image overlays from image links in the buffer.
8997 This can be toggled with `markdown-toggle-inline-images'
8998 or \\[markdown-toggle-inline-images]."
8999 (interactive)
9000 (mapc #'delete-overlay markdown-inline-image-overlays)
9001 (setq markdown-inline-image-overlays nil))
9003 (defun markdown-display-inline-images ()
9004 "Add inline image overlays to image links in the buffer.
9005 This can be toggled with `markdown-toggle-inline-images'
9006 or \\[markdown-toggle-inline-images]."
9007 (interactive)
9008 (unless (display-graphic-p)
9009 (error "Cannot show images"))
9010 (save-excursion
9011 (save-restriction
9012 (widen)
9013 (goto-char (point-min))
9014 (while (re-search-forward markdown-regex-link-inline nil t)
9015 (let ((start (match-beginning 0))
9016 (end (match-end 0))
9017 (file (match-string-no-properties 6)))
9018 (when (file-exists-p file)
9019 (let* ((abspath (if (file-name-absolute-p file)
9020 file
9021 (concat default-directory file)))
9022 (image (create-image abspath)))
9023 (when image
9024 (let ((ov (make-overlay start end)))
9025 (overlay-put ov 'display image)
9026 (overlay-put ov 'face 'default)
9027 (push ov markdown-inline-image-overlays))))))))))
9029 (defun markdown-toggle-inline-images ()
9030 "Toggle inline image overlays in the buffer."
9031 (interactive)
9032 (if markdown-inline-image-overlays
9033 (markdown-remove-inline-images)
9034 (markdown-display-inline-images)))
9037 ;;; GFM Code Block Fontification ==============================================
9039 (defcustom markdown-fontify-code-blocks-natively nil
9040 "When non-nil, fontify code in code blocks using the native major mode.
9041 This only works for fenced code blocks where the language is
9042 specified where we can automatically determine the appropriate
9043 mode to use. The language to mode mapping may be customized by
9044 setting the variable `markdown-code-lang-modes'."
9045 :group 'markdown
9046 :type 'boolean
9047 :safe 'booleanp
9048 :package-version '(markdown-mode . "2.3"))
9050 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
9051 "Toggle the native fontification of code blocks.
9052 With a prefix argument ARG, enable if ARG is positive,
9053 and disable otherwise."
9054 (interactive (list (or current-prefix-arg 'toggle)))
9055 (setq markdown-fontify-code-blocks-natively
9056 (if (eq arg 'toggle)
9057 (not markdown-fontify-code-blocks-natively)
9058 (> (prefix-numeric-value arg) 0)))
9059 (if markdown-fontify-code-blocks-natively
9060 (message "markdown-mode native code block fontification enabled")
9061 (message "markdown-mode native code block fontification disabled"))
9062 (markdown-reload-extensions))
9064 ;; This is based on `org-src-lang-modes' from org-src.el
9065 (defcustom markdown-code-lang-modes
9066 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
9067 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
9068 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
9069 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9070 ("bash" . sh-mode))
9071 "Alist mapping languages to their major mode.
9072 The key is the language name, the value is the major mode. For
9073 many languages this is simple, but for language where this is not
9074 the case, this variable provides a way to simplify things on the
9075 user side. For example, there is no ocaml-mode in Emacs, but the
9076 mode to use is `tuareg-mode'."
9077 :group 'markdown
9078 :type '(repeat
9079 (cons
9080 (string "Language name")
9081 (symbol "Major mode")))
9082 :package-version '(markdown-mode . "2.3"))
9084 (defun markdown-get-lang-mode (lang)
9085 "Return major mode that should be used for LANG.
9086 LANG is a string, and the returned major mode is a symbol."
9087 (cl-find-if
9088 'fboundp
9089 (list (cdr (assoc lang markdown-code-lang-modes))
9090 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9091 (intern (concat lang "-mode"))
9092 (intern (concat (downcase lang) "-mode")))))
9094 (defun markdown-fontify-code-blocks-generic (matcher last)
9095 "Add text properties to next code block from point to LAST.
9096 Use matching function MATCHER."
9097 (when (funcall matcher last)
9098 (save-excursion
9099 (save-match-data
9100 (let* ((start (match-beginning 0))
9101 (end (match-end 0))
9102 ;; Find positions outside opening and closing backquotes.
9103 (bol-prev (progn (goto-char start)
9104 (if (bolp) (point-at-bol 0) (point-at-bol))))
9105 (eol-next (progn (goto-char end)
9106 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9107 lang)
9108 (if (and markdown-fontify-code-blocks-natively
9109 (setq lang (markdown-code-block-lang)))
9110 (markdown-fontify-code-block-natively lang start end)
9111 (add-text-properties start end '(face markdown-pre-face)))
9112 ;; Set background for block as well as opening and closing lines.
9113 (font-lock-append-text-property
9114 bol-prev eol-next 'face 'markdown-code-face)
9115 ;; Set invisible property for lines before and after, including newline.
9116 (add-text-properties bol-prev start '(invisible markdown-markup))
9117 (add-text-properties end eol-next '(invisible markdown-markup)))))
9120 (defun markdown-fontify-gfm-code-blocks (last)
9121 "Add text properties to next GFM code block from point to LAST."
9122 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9124 (defun markdown-fontify-fenced-code-blocks (last)
9125 "Add text properties to next tilde fenced code block from point to LAST."
9126 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9128 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9129 (defun markdown-fontify-code-block-natively (lang start end)
9130 "Fontify given GFM or fenced code block.
9131 This function is called by Emacs for automatic fontification when
9132 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9133 language used in the block. START and END specify the block
9134 position."
9135 (let ((lang-mode (markdown-get-lang-mode lang)))
9136 (when (fboundp lang-mode)
9137 (let ((string (buffer-substring-no-properties start end))
9138 (modified (buffer-modified-p))
9139 (markdown-buffer (current-buffer)) pos next)
9140 (remove-text-properties start end '(face nil))
9141 (with-current-buffer
9142 (get-buffer-create
9143 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9144 ;; Make sure that modification hooks are not inhibited in
9145 ;; the org-src-fontification buffer in case we're called
9146 ;; from `jit-lock-function' (Bug#25132).
9147 (let ((inhibit-modification-hooks nil))
9148 (delete-region (point-min) (point-max))
9149 (insert string " ")) ;; so there's a final property change
9150 (unless (eq major-mode lang-mode) (funcall lang-mode))
9151 (markdown-font-lock-ensure)
9152 (setq pos (point-min))
9153 (while (setq next (next-single-property-change pos 'face))
9154 (let ((val (get-text-property pos 'face)))
9155 (when val
9156 (put-text-property
9157 (+ start (1- pos)) (1- (+ start next)) 'face
9158 val markdown-buffer)))
9159 (setq pos next)))
9160 (add-text-properties
9161 start end
9162 '(font-lock-fontified t fontified t font-lock-multiline t))
9163 (set-buffer-modified-p modified)))))
9165 (require 'edit-indirect nil t)
9166 (defvar edit-indirect-guess-mode-function)
9167 (defvar edit-indirect-after-commit-functions)
9169 (defun markdown--edit-indirect-after-commit-function (_beg end)
9170 "Ensure trailing newlines at the END of code blocks."
9171 (goto-char end)
9172 (unless (eq (char-before) ?\n)
9173 (insert "\n")))
9175 (defun markdown-edit-code-block ()
9176 "Edit Markdown code block in an indirect buffer."
9177 (interactive)
9178 (save-excursion
9179 (if (fboundp 'edit-indirect-region)
9180 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9181 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9182 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9183 (if (and begin end)
9184 (let* ((lang (markdown-code-block-lang))
9185 (mode (or (and lang (markdown-get-lang-mode lang))
9186 markdown-edit-code-block-default-mode))
9187 (edit-indirect-guess-mode-function
9188 (lambda (_parent-buffer _beg _end)
9189 (funcall mode))))
9190 (edit-indirect-region begin end 'display-buffer))
9191 (user-error "Not inside a GFM or tilde fenced code block")))
9192 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9193 (progn (package-refresh-contents)
9194 (package-install 'edit-indirect)
9195 (markdown-edit-code-block))))))
9198 ;;; Table Editing
9200 ;; These functions were originally adapted from `org-table.el'.
9202 ;; General helper functions
9204 (defmacro markdown--with-gensyms (symbols &rest body)
9205 (declare (debug (sexp body)) (indent 1))
9206 `(let ,(mapcar (lambda (s)
9207 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9208 symbols)
9209 ,@body))
9211 (defun markdown--split-string (string &optional separators)
9212 "Splits STRING into substrings at SEPARATORS.
9213 SEPARATORS is a regular expression. If nil it defaults to
9214 `split-string-default-separators'. This version returns no empty
9215 strings if there are matches at the beginning and end of string."
9216 (let ((start 0) notfirst list)
9217 (while (and (string-match
9218 (or separators split-string-default-separators)
9219 string
9220 (if (and notfirst
9221 (= start (match-beginning 0))
9222 (< start (length string)))
9223 (1+ start) start))
9224 (< (match-beginning 0) (length string)))
9225 (setq notfirst t)
9226 (or (eq (match-beginning 0) 0)
9227 (and (eq (match-beginning 0) (match-end 0))
9228 (eq (match-beginning 0) start))
9229 (push (substring string start (match-beginning 0)) list))
9230 (setq start (match-end 0)))
9231 (or (eq start (length string))
9232 (push (substring string start) list))
9233 (nreverse list)))
9235 (defun markdown--string-width (s)
9236 "Return width of string S.
9237 This version ignores characters with invisibility property
9238 `markdown-markup'."
9239 (let (b)
9240 (when (or (eq t buffer-invisibility-spec)
9241 (member 'markdown-markup buffer-invisibility-spec))
9242 (while (setq b (text-property-any
9243 0 (length s)
9244 'invisible 'markdown-markup s))
9245 (setq s (concat
9246 (substring s 0 b)
9247 (substring s (or (next-single-property-change
9248 b 'invisible s)
9249 (length s))))))))
9250 (string-width s))
9252 (defun markdown--remove-invisible-markup (s)
9253 "Remove Markdown markup from string S.
9254 This version removes characters with invisibility property
9255 `markdown-markup'."
9256 (let (b)
9257 (while (setq b (text-property-any
9258 0 (length s)
9259 'invisible 'markdown-markup s))
9260 (setq s (concat
9261 (substring s 0 b)
9262 (substring s (or (next-single-property-change
9263 b 'invisible s)
9264 (length s)))))))
9267 ;; Functions for maintaining tables
9269 (defconst markdown-table-line-regexp "^[ \t]*|"
9270 "Regexp matching any line inside a table.")
9272 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9273 "Regexp matching hline inside a table.")
9275 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9276 "Regexp matching dline inside a table.")
9278 (defconst markdown-table-border-regexp "^[ \t]*[^| \t]"
9279 "Regexp matching any line outside a table.")
9281 (defun markdown-table-at-point-p ()
9282 "Return non-nil when point is inside a table."
9283 (save-excursion
9284 (beginning-of-line)
9285 (and (looking-at-p markdown-table-line-regexp)
9286 (not (markdown-code-block-at-point-p)))))
9288 (defun markdown-table-hline-at-point-p ()
9289 "Return non-nil when point is on a hline in a table.
9290 This function assumes point is on a table."
9291 (save-excursion
9292 (beginning-of-line)
9293 (looking-at-p markdown-table-hline-regexp)))
9295 (defun markdown-table-begin ()
9296 "Find the beginning of the table and return its position.
9297 This function assumes point is on a table."
9298 (cond
9299 ((save-excursion
9300 (and (re-search-backward markdown-table-border-regexp nil t)
9301 (line-beginning-position 2))))
9302 (t (point-min))))
9304 (defun markdown-table-end ()
9305 "Find the end of the table and return its position.
9306 This function assumes point is on a table."
9307 (save-excursion
9308 (cond
9309 ((re-search-forward markdown-table-border-regexp nil t)
9310 (match-beginning 0))
9311 (t (goto-char (point-max))
9312 (skip-chars-backward " \t")
9313 (if (bolp) (point) (line-end-position))))))
9315 (defun markdown-table-get-dline ()
9316 "Return index of the table data line at point.
9317 This function assumes point is on a table."
9318 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9319 (save-excursion
9320 (goto-char (markdown-table-begin))
9321 (while (and (re-search-forward
9322 markdown-table-dline-regexp end t)
9323 (setq cnt (1+ cnt))
9324 (< (point-at-eol) pos))))
9325 cnt))
9327 (defun markdown-table-get-column ()
9328 "Return table column at point.
9329 This function assumes point is on a table."
9330 (let ((pos (point)) (cnt 0))
9331 (save-excursion
9332 (beginning-of-line)
9333 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9334 cnt))
9336 (defun markdown-table-get-cell (&optional n)
9337 "Return the content of the cell in column N of current row.
9338 N defaults to column at point. This function assumes point is on
9339 a table."
9340 (and n (markdown-table-goto-column n))
9341 (skip-chars-backward "^|\n") (backward-char 1)
9342 (if (looking-at "|[^|\r\n]*")
9343 (let* ((pos (match-beginning 0))
9344 (val (buffer-substring (1+ pos) (match-end 0))))
9345 (goto-char (min (point-at-eol) (+ 2 pos)))
9346 ;; Trim whitespaces
9347 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9348 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9349 (forward-char 1) ""))
9351 (defun markdown-table-goto-dline (n)
9352 "Go to the Nth data line in the table at point.
9353 Return t when the line exists, nil otherwise. This function
9354 assumes point is on a table."
9355 (goto-char (markdown-table-begin))
9356 (let ((end (markdown-table-end)) (cnt 0))
9357 (while (and (re-search-forward
9358 markdown-table-dline-regexp end t)
9359 (< (setq cnt (1+ cnt)) n)))
9360 (= cnt n)))
9362 (defun markdown-table-goto-column (n &optional on-delim)
9363 "Go to the Nth column in the table line at point.
9364 With optional argument ON-DELIM, stop with point before the left
9365 delimiter of the cell. If there are less than N cells, just go
9366 beyond the last delimiter. This function assumes point is on a
9367 table."
9368 (beginning-of-line 1)
9369 (when (> n 0)
9370 (while (and (> (setq n (1- n)) -1)
9371 (search-forward "|" (point-at-eol) t)))
9372 (if on-delim
9373 (backward-char 1)
9374 (when (looking-at " ") (forward-char 1)))))
9376 (defmacro markdown-table-save-cell (&rest body)
9377 "Save cell at point, execute BODY and restore cell.
9378 This function assumes point is on a table."
9379 (declare (debug (body)))
9380 (markdown--with-gensyms (line column)
9381 `(let ((,line (copy-marker (line-beginning-position)))
9382 (,column (markdown-table-get-column)))
9383 (unwind-protect
9384 (progn ,@body)
9385 (goto-char ,line)
9386 (markdown-table-goto-column ,column)
9387 (set-marker ,line nil)))))
9389 (defun markdown-table-blank-line (s)
9390 "Convert a table line S into a line with blank cells."
9391 (if (string-match "^[ \t]*|-" s)
9392 (setq s (mapconcat
9393 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9394 s ""))
9395 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9396 (setq s (replace-match
9397 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9398 t t s)))
9401 (defun markdown-table-colfmt (fmtspec)
9402 "Process column alignment specifier FMTSPEC for tables."
9403 (when (stringp fmtspec)
9404 (mapcar (lambda (x)
9405 (cond ((string-match-p "^:.*:$" x) 'c)
9406 ((string-match-p "^:" x) 'l)
9407 ((string-match-p ":$" x) 'r)
9408 (t 'd)))
9409 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9411 (defun markdown-table-align ()
9412 "Align table at point.
9413 This function assumes point is on a table."
9414 (interactive)
9415 (let ((begin (markdown-table-begin))
9416 (end (copy-marker (markdown-table-end))))
9417 (markdown-table-save-cell
9418 (goto-char begin)
9419 (let* (fmtspec
9420 ;; Store table indent
9421 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9422 ;; Split table in lines and save column format specifier
9423 (lines (mapcar (lambda (l)
9424 (if (string-match-p "\\`[ \t]*|[-:]" l)
9425 (progn (setq fmtspec (or fmtspec l)) nil) l))
9426 (markdown--split-string (buffer-substring begin end) "\n")))
9427 ;; Split lines in cells
9428 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9429 (remq nil lines)))
9430 ;; Calculate maximum number of cells in a line
9431 (maxcells (if cells
9432 (apply #'max (mapcar #'length cells))
9433 (user-error "Empty table")))
9434 ;; Empty cells to fill short lines
9435 (emptycells (make-list maxcells "")) maxwidths)
9436 ;; Calculate maximum width for each column
9437 (dotimes (i maxcells)
9438 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9439 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9440 maxwidths)))
9441 (setq maxwidths (nreverse maxwidths))
9442 ;; Process column format specifier
9443 (setq fmtspec (markdown-table-colfmt fmtspec))
9444 ;; Compute formats needed for output of table lines
9445 (let ((hfmt (concat indent "|"))
9446 (rfmt (concat indent "|"))
9447 hfmt1 rfmt1 fmt)
9448 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9449 (setq fmt (pop fmtspec))
9450 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9451 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9452 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9453 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9454 (setq rfmt (concat rfmt (format rfmt1 width)))
9455 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9456 ;; Replace modified lines only
9457 (dolist (line lines)
9458 (let ((line (if line
9459 (apply #'format rfmt (append (pop cells) emptycells))
9460 hfmt))
9461 (previous (buffer-substring (point) (line-end-position))))
9462 (if (equal previous line)
9463 (forward-line)
9464 (insert line "\n")
9465 (delete-region (point) (line-beginning-position 2))))))
9466 (set-marker end nil)))))
9468 (defun markdown-table-insert-row (&optional arg)
9469 "Insert a new row above the row at point into the table.
9470 With optional argument ARG, insert below the current row."
9471 (interactive "P")
9472 (unless (markdown-table-at-point-p)
9473 (user-error "Not at a table"))
9474 (let* ((line (buffer-substring
9475 (line-beginning-position) (line-end-position)))
9476 (new (markdown-table-blank-line line)))
9477 (beginning-of-line (if arg 2 1))
9478 (unless (bolp) (insert "\n"))
9479 (insert-before-markers new "\n")
9480 (beginning-of-line 0)
9481 (re-search-forward "| ?" (line-end-position) t)))
9483 (defun markdown-table-delete-row ()
9484 "Delete row or horizontal line at point from the table."
9485 (interactive)
9486 (unless (markdown-table-at-point-p)
9487 (user-error "Not at a table"))
9488 (let ((col (current-column)))
9489 (kill-region (point-at-bol)
9490 (min (1+ (point-at-eol)) (point-max)))
9491 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9492 (move-to-column col)))
9494 (defun markdown-table-move-row (&optional up)
9495 "Move table line at point down.
9496 With optional argument UP, move it up."
9497 (interactive "P")
9498 (unless (markdown-table-at-point-p)
9499 (user-error "Not at a table"))
9500 (let* ((col (current-column)) (pos (point))
9501 (tonew (if up 0 2)) txt)
9502 (beginning-of-line tonew)
9503 (unless (markdown-table-at-point-p)
9504 (goto-char pos) (user-error "Cannot move row further"))
9505 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9506 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9507 (delete-region (point) (1+ (point-at-eol)))
9508 (beginning-of-line tonew)
9509 (insert txt) (beginning-of-line 0)
9510 (move-to-column col)))
9512 (defun markdown-table-move-row-up ()
9513 "Move table row at point up."
9514 (interactive)
9515 (markdown-table-move-row 'up))
9517 (defun markdown-table-move-row-down ()
9518 "Move table row at point down."
9519 (interactive)
9520 (markdown-table-move-row nil))
9522 (defun markdown-table-insert-column ()
9523 "Insert a new table column."
9524 (interactive)
9525 (unless (markdown-table-at-point-p)
9526 (user-error "Not at a table"))
9527 (let* ((col (max 1 (markdown-table-get-column)))
9528 (begin (markdown-table-begin))
9529 (end (copy-marker (markdown-table-end))))
9530 (markdown-table-save-cell
9531 (goto-char begin)
9532 (while (< (point) end)
9533 (markdown-table-goto-column col t)
9534 (if (markdown-table-hline-at-point-p)
9535 (insert "|---")
9536 (insert "| "))
9537 (forward-line)))
9538 (set-marker end nil)
9539 (markdown-table-align)))
9541 (defun markdown-table-delete-column ()
9542 "Delete column at point from table."
9543 (interactive)
9544 (unless (markdown-table-at-point-p)
9545 (user-error "Not at a table"))
9546 (let ((col (markdown-table-get-column))
9547 (begin (markdown-table-begin))
9548 (end (copy-marker (markdown-table-end))))
9549 (markdown-table-save-cell
9550 (goto-char begin)
9551 (while (< (point) end)
9552 (markdown-table-goto-column col t)
9553 (and (looking-at "|[^|\n]+|")
9554 (replace-match "|"))
9555 (forward-line)))
9556 (set-marker end nil)
9557 (markdown-table-goto-column (max 1 (1- col)))
9558 (markdown-table-align)))
9560 (defun markdown-table-move-column (&optional left)
9561 "Move table column at point to the right.
9562 With optional argument LEFT, move it to the left."
9563 (interactive "P")
9564 (unless (markdown-table-at-point-p)
9565 (user-error "Not at a table"))
9566 (let* ((col (markdown-table-get-column))
9567 (col1 (if left (1- col) col))
9568 (colpos (if left (1- col) (1+ col)))
9569 (begin (markdown-table-begin))
9570 (end (copy-marker (markdown-table-end))))
9571 (when (and left (= col 1))
9572 (user-error "Cannot move column further left"))
9573 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9574 (user-error "Cannot move column further right"))
9575 (markdown-table-save-cell
9576 (goto-char begin)
9577 (while (< (point) end)
9578 (markdown-table-goto-column col1 t)
9579 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9580 (replace-match "|\\2|\\1|"))
9581 (forward-line)))
9582 (set-marker end nil)
9583 (markdown-table-goto-column colpos)
9584 (markdown-table-align)))
9586 (defun markdown-table-move-column-left ()
9587 "Move table column at point to the left."
9588 (interactive)
9589 (markdown-table-move-column 'left))
9591 (defun markdown-table-move-column-right ()
9592 "Move table column at point to the right."
9593 (interactive)
9594 (markdown-table-move-column nil))
9596 (defun markdown-table-next-row ()
9597 "Go to the next row (same column) in the table.
9598 Create new table lines if required."
9599 (interactive)
9600 (unless (markdown-table-at-point-p)
9601 (user-error "Not at a table"))
9602 (if (or (looking-at "[ \t]*$")
9603 (save-excursion (skip-chars-backward " \t") (bolp)))
9604 (newline)
9605 (markdown-table-align)
9606 (let ((col (markdown-table-get-column)))
9607 (beginning-of-line 2)
9608 (if (or (not (markdown-table-at-point-p))
9609 (markdown-table-hline-at-point-p))
9610 (progn
9611 (beginning-of-line 0)
9612 (markdown-table-insert-row 'below)))
9613 (markdown-table-goto-column col)
9614 (skip-chars-backward "^|\n\r")
9615 (when (looking-at " ") (forward-char 1)))))
9617 (defun markdown-table-forward-cell ()
9618 "Go to the next cell in the table.
9619 Create new table lines if required."
9620 (interactive)
9621 (unless (markdown-table-at-point-p)
9622 (user-error "Not at a table"))
9623 (markdown-table-align)
9624 (let ((end (markdown-table-end)))
9625 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9626 (condition-case nil
9627 (progn
9628 (re-search-forward "|" end)
9629 (if (looking-at "[ \t]*$")
9630 (re-search-forward "|" end))
9631 (if (and (looking-at "[-:]")
9632 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9633 (goto-char (match-beginning 1)))
9634 (if (looking-at "[-:]")
9635 (progn
9636 (beginning-of-line 0)
9637 (markdown-table-insert-row 'below))
9638 (when (looking-at " ") (forward-char 1))))
9639 (error (markdown-table-insert-row 'below)))))
9641 (defun markdown-table-backward-cell ()
9642 "Go to the previous cell in the table."
9643 (interactive)
9644 (unless (markdown-table-at-point-p)
9645 (user-error "Not at a table"))
9646 (markdown-table-align)
9647 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9648 (condition-case nil
9649 (progn
9650 (re-search-backward "|" (markdown-table-begin))
9651 (re-search-backward "|" (markdown-table-begin)))
9652 (error (user-error "Cannot move to previous table cell")))
9653 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9654 (re-search-backward "|" (markdown-table-begin)))
9655 (when (looking-at "| ?") (goto-char (match-end 0))))
9657 (defun markdown-table-transpose ()
9658 "Transpose table at point.
9659 Horizontal separator lines will be eliminated."
9660 (interactive)
9661 (unless (markdown-table-at-point-p)
9662 (user-error "Not at a table"))
9663 (let* ((table (buffer-substring-no-properties
9664 (markdown-table-begin) (markdown-table-end)))
9665 ;; Convert table to a Lisp structure
9666 (table (delq nil
9667 (mapcar
9668 (lambda (x)
9669 (unless (string-match-p
9670 markdown-table-hline-regexp x)
9671 (markdown--split-string x "\\s-*|\\s-*")))
9672 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9673 (dline_old (markdown-table-get-dline))
9674 (col_old (markdown-table-get-column))
9675 (contents (mapcar (lambda (_)
9676 (let ((tp table))
9677 (mapcar
9678 (lambda (_)
9679 (prog1
9680 (pop (car tp))
9681 (setq tp (cdr tp))))
9682 table)))
9683 (car table))))
9684 (goto-char (markdown-table-begin))
9685 (re-search-forward "|") (backward-char)
9686 (delete-region (point) (markdown-table-end))
9687 (insert (mapconcat
9688 (lambda(x)
9689 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9690 contents ""))
9691 (markdown-table-goto-dline col_old)
9692 (markdown-table-goto-column dline_old))
9693 (markdown-table-align))
9695 (defun markdown-table-sort-lines (&optional sorting-type)
9696 "Sort table lines according to the column at point.
9698 The position of point indicates the column to be used for
9699 sorting, and the range of lines is the range between the nearest
9700 horizontal separator lines, or the entire table of no such lines
9701 exist. If point is before the first column, user will be prompted
9702 for the sorting column. If there is an active region, the mark
9703 specifies the first line and the sorting column, while point
9704 should be in the last line to be included into the sorting.
9706 The command then prompts for the sorting type which can be
9707 alphabetically or numerically. Sorting in reverse order is also
9708 possible.
9710 If SORTING-TYPE is specified when this function is called from a
9711 Lisp program, no prompting will take place. SORTING-TYPE must be
9712 a character, any of (?a ?A ?n ?N) where the capital letters
9713 indicate that sorting should be done in reverse order."
9714 (interactive)
9715 (unless (markdown-table-at-point-p)
9716 (user-error "Not at a table"))
9717 ;; Set sorting type and column used for sorting
9718 (let ((column (let ((c (markdown-table-get-column)))
9719 (cond ((> c 0) c)
9720 ((called-interactively-p 'any)
9721 (read-number "Use column N for sorting: "))
9722 (t 1))))
9723 (sorting-type
9724 (or sorting-type
9725 (read-char-exclusive
9726 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9727 (save-restriction
9728 ;; Narrow buffer to appropriate sorting area
9729 (if (region-active-p)
9730 (narrow-to-region
9731 (save-excursion
9732 (progn
9733 (goto-char (region-beginning)) (line-beginning-position)))
9734 (save-excursion
9735 (progn
9736 (goto-char (region-end)) (line-end-position))))
9737 (let ((start (markdown-table-begin))
9738 (end (markdown-table-end)))
9739 (narrow-to-region
9740 (save-excursion
9741 (if (re-search-backward
9742 markdown-table-hline-regexp start t)
9743 (line-beginning-position 2)
9744 start))
9745 (if (save-excursion (re-search-forward
9746 markdown-table-hline-regexp end t))
9747 (match-beginning 0)
9748 end))))
9749 ;; Determine arguments for `sort-subr'
9750 (let* ((extract-key-from-cell
9751 (cl-case sorting-type
9752 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9753 ((?n ?N) #'string-to-number)
9754 (t (user-error "Invalid sorting type: %c" sorting-type))))
9755 (predicate
9756 (cl-case sorting-type
9757 ((?n ?N) #'<)
9758 ((?a ?A) #'string<))))
9759 ;; Sort selected area
9760 (goto-char (point-min))
9761 (sort-subr (memq sorting-type '(?A ?N))
9762 (lambda ()
9763 (forward-line)
9764 (while (and (not (eobp))
9765 (not (looking-at
9766 markdown-table-dline-regexp)))
9767 (forward-line)))
9768 #'end-of-line
9769 (lambda ()
9770 (funcall extract-key-from-cell
9771 (markdown-table-get-cell column)))
9773 predicate)
9774 (goto-char (point-min))))))
9776 (defun markdown-table-convert-region (begin end &optional separator)
9777 "Convert region from BEGIN to END to table with SEPARATOR.
9779 If every line contains at least one TAB character, the function
9780 assumes that the material is tab separated (TSV). If every line
9781 contains a comma, comma-separated values (CSV) are assumed. If
9782 not, lines are split at whitespace into cells.
9784 You can use a prefix argument to force a specific separator:
9785 \\[universal-argument] once forces CSV, \\[universal-argument]
9786 twice forces TAB, and \\[universal-argument] three times will
9787 prompt for a regular expression to match the separator, and a
9788 numeric argument N indicates that at least N consecutive
9789 spaces, or alternatively a TAB should be used as the separator."
9791 (interactive "r\nP")
9792 (let* ((begin (min begin end)) (end (max begin end)) re)
9793 (goto-char begin) (beginning-of-line 1)
9794 (setq begin (point-marker))
9795 (goto-char end)
9796 (if (bolp) (backward-char 1) (end-of-line 1))
9797 (setq end (point-marker))
9798 (when (equal separator '(64))
9799 (setq separator (read-regexp "Regexp for cell separator: ")))
9800 (unless separator
9801 ;; Get the right cell separator
9802 (goto-char begin)
9803 (setq separator
9804 (cond
9805 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9806 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9807 (t 1))))
9808 (goto-char begin)
9809 (if (equal separator '(4))
9810 ;; Parse CSV
9811 (while (< (point) end)
9812 (cond
9813 ((looking-at "^") (insert "| "))
9814 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9815 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9816 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9817 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9818 ((looking-at "[ \t]*,") (replace-match " | "))
9819 (t (beginning-of-line 2))))
9820 (setq re
9821 (cond
9822 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9823 ((equal separator '(16)) "^\\|\t")
9824 ((integerp separator)
9825 (if (< separator 1)
9826 (user-error "Cell separator must contain one or more spaces")
9827 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9828 ((stringp separator) (format "^ *\\|%s" separator))
9829 (t (error "Invalid cell separator"))))
9830 (while (re-search-forward re end t) (replace-match "| " t t)))
9831 (goto-char begin)
9832 (markdown-table-align)))
9835 ;;; ElDoc Support
9837 (defun markdown-eldoc-function ()
9838 "Return a helpful string when appropriate based on context.
9839 * Report URL when point is at a hidden URL.
9840 * Report language name when point is a code block with hidden markup."
9841 (cond
9842 ;; Hidden URL or reference for inline link
9843 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9844 (thing-at-point-looking-at markdown-regex-link-reference))
9845 (or markdown-hide-urls markdown-hide-markup))
9846 (let* ((imagep (string-equal (match-string 1) "!"))
9847 (edit-keys (markdown--substitute-command-keys
9848 (if imagep
9849 "\\[markdown-insert-image]"
9850 "\\[markdown-insert-link]")))
9851 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9852 (referencep (string-equal (match-string 5) "["))
9853 (object (if referencep "reference" "URL")))
9854 (format "Hidden %s (%s to edit): %s" object edit-str
9855 (if referencep
9856 (concat
9857 (propertize "[" 'face 'markdown-markup-face)
9858 (propertize (match-string-no-properties 6)
9859 'face 'markdown-reference-face)
9860 (propertize "]" 'face 'markdown-markup-face))
9861 (propertize (match-string-no-properties 6)
9862 'face 'markdown-url-face)))))
9863 ;; Hidden language name for fenced code blocks
9864 ((and (markdown-code-block-at-point-p)
9865 (not (get-text-property (point) 'markdown-pre))
9866 markdown-hide-markup)
9867 (let ((lang (save-excursion (markdown-code-block-lang))))
9868 (unless lang (setq lang "[unspecified]"))
9869 (format "Hidden code block language: %s (%s to toggle markup)"
9870 (propertize lang 'face 'markdown-language-keyword-face)
9871 (markdown--substitute-command-keys
9872 "\\[markdown-toggle-markup-hiding]"))))))
9875 ;;; Mode Definition ==========================================================
9877 (defun markdown-show-version ()
9878 "Show the version number in the minibuffer."
9879 (interactive)
9880 (message "markdown-mode, version %s" markdown-mode-version))
9882 (defun markdown-mode-info ()
9883 "Open the `markdown-mode' homepage."
9884 (interactive)
9885 (browse-url "https://jblevins.org/projects/markdown-mode/"))
9887 ;;;###autoload
9888 (define-derived-mode markdown-mode text-mode "Markdown"
9889 "Major mode for editing Markdown files."
9890 ;; Natural Markdown tab width
9891 (setq tab-width 4)
9892 ;; Comments
9893 (setq-local comment-start "<!-- ")
9894 (setq-local comment-end " -->")
9895 (setq-local comment-start-skip "<!--[ \t]*")
9896 (setq-local comment-column 0)
9897 (setq-local comment-auto-fill-only-comments nil)
9898 (setq-local comment-use-syntax t)
9899 ;; Syntax
9900 (add-hook 'syntax-propertize-extend-region-functions
9901 #'markdown-syntax-propertize-extend-region)
9902 (add-hook 'jit-lock-after-change-extend-region-functions
9903 #'markdown-font-lock-extend-region-function t t)
9904 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
9905 ;; Font lock.
9906 (setq-local font-lock-defaults nil)
9907 (setq-local font-lock-multiline t)
9908 (setq-local font-lock-extra-managed-props
9909 (append font-lock-extra-managed-props
9910 '(composition display invisible)))
9911 (if markdown-hide-markup
9912 (add-to-invisibility-spec 'markdown-markup)
9913 (remove-from-invisibility-spec 'markdown-markup))
9914 (setq font-lock-defaults
9915 '(markdown-mode-font-lock-keywords-basic
9916 nil nil nil nil
9917 (font-lock-syntactic-face-function . markdown-syntactic-face)))
9918 ;; Wiki links
9919 (markdown-setup-wiki-link-hooks)
9920 ;; Math mode
9921 (when markdown-enable-math (markdown-toggle-math t))
9922 ;; Add a buffer-local hook to reload after file-local variables are read
9923 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
9924 ;; For imenu support
9925 (setq imenu-create-index-function
9926 (if markdown-nested-imenu-heading-index
9927 #'markdown-imenu-create-nested-index
9928 #'markdown-imenu-create-flat-index))
9929 ;; For menu support in XEmacs
9930 (easy-menu-add markdown-mode-menu markdown-mode-map)
9931 ;; Defun movement
9932 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
9933 (setq-local end-of-defun-function #'markdown-end-of-defun)
9934 ;; Paragraph filling
9935 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
9936 (setq-local paragraph-start
9937 ;; Should match start of lines that start or separate paragraphs
9938 (mapconcat #'identity
9940 "\f" ; starts with a literal line-feed
9941 "[ \t\f]*$" ; space-only line
9942 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9943 "[ \t]*[*+-][ \t]+" ; unordered list item
9944 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
9945 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
9946 "[ \t]*:[ \t]+" ; definition
9947 "^|" ; table or Pandoc line block
9949 "\\|"))
9950 (setq-local paragraph-separate
9951 ;; Should match lines that separate paragraphs without being
9952 ;; part of any paragraph:
9953 (mapconcat #'identity
9954 '("[ \t\f]*$" ; space-only line
9955 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
9956 ;; The following is not ideal, but the Fill customization
9957 ;; options really only handle paragraph-starting prefixes,
9958 ;; not paragraph-ending suffixes:
9959 ".* $" ; line ending in two spaces
9960 "^#+"
9961 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
9962 "\\|"))
9963 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
9964 (setq-local adaptive-fill-regexp "\\s-*")
9965 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
9966 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
9967 ;; Outline mode
9968 (setq-local outline-regexp markdown-regex-header)
9969 (setq-local outline-level #'markdown-outline-level)
9970 ;; Cause use of ellipses for invisible text.
9971 (add-to-invisibility-spec '(outline . t))
9972 ;; ElDoc support
9973 (if (eval-when-compile (fboundp 'add-function))
9974 (add-function :before-until (local 'eldoc-documentation-function)
9975 #'markdown-eldoc-function)
9976 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
9977 ;; Inhibiting line-breaking:
9978 ;; Separating out each condition into a separate function so that users can
9979 ;; override if desired (with remove-hook)
9980 (add-hook 'fill-nobreak-predicate
9981 #'markdown-line-is-reference-definition-p nil t)
9982 (add-hook 'fill-nobreak-predicate
9983 #'markdown-pipe-at-bol-p nil t)
9985 ;; Indentation
9986 (setq-local indent-line-function markdown-indent-function)
9988 ;; Flyspell
9989 (setq-local flyspell-generic-check-word-predicate
9990 #'markdown-flyspell-check-word-p)
9992 ;; Electric quoting
9993 (add-hook 'electric-quote-inhibit-functions
9994 #'markdown--inhibit-electric-quote nil :local)
9996 ;; Backwards compatibility with markdown-css-path
9997 (when (boundp 'markdown-css-path)
9998 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
9999 (add-to-list 'markdown-css-paths markdown-css-path))
10001 ;; Prepare hooks for XEmacs compatibility
10002 (when (featurep 'xemacs)
10003 (make-local-hook 'after-change-functions)
10004 (make-local-hook 'font-lock-extend-region-functions)
10005 (make-local-hook 'window-configuration-change-hook))
10007 ;; Make checkboxes buttons
10008 (when markdown-make-gfm-checkboxes-buttons
10009 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
10010 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
10011 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
10013 ;; edit-indirect
10014 (add-hook 'edit-indirect-after-commit-functions
10015 #'markdown--edit-indirect-after-commit-function
10016 nil 'local)
10018 ;; Marginalized headings
10019 (when markdown-marginalize-headers
10020 (add-hook 'window-configuration-change-hook
10021 #'markdown-marginalize-update-current nil t))
10023 ;; add live preview export hook
10024 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
10025 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
10027 ;;;###autoload
10028 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
10029 ;;;###autoload
10030 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
10033 ;;; GitHub Flavored Markdown Mode ============================================
10035 (defvar gfm-mode-hook nil
10036 "Hook run when entering GFM mode.")
10038 (defvar gfm-font-lock-keywords
10039 ;; Basic Markdown features (excluding possibly overridden ones)
10040 markdown-mode-font-lock-keywords-basic
10041 "Default highlighting expressions for GitHub Flavored Markdown mode.")
10043 ;;;###autoload
10044 (define-derived-mode gfm-mode markdown-mode "GFM"
10045 "Major mode for editing GitHub Flavored Markdown files."
10046 (setq markdown-link-space-sub-char "-")
10047 (setq markdown-wiki-link-search-subdirectories t)
10048 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
10049 ;; do the initial link fontification
10050 (markdown-gfm-parse-buffer-for-languages))
10053 ;;; Live Preview Mode ============================================
10054 (define-minor-mode markdown-live-preview-mode
10055 "Toggle native previewing on save for a specific markdown file."
10056 :lighter " MD-Preview"
10057 (if markdown-live-preview-mode
10058 (if (markdown-live-preview-get-filename)
10059 (markdown-display-buffer-other-window (markdown-live-preview-export))
10060 (markdown-live-preview-mode -1)
10061 (user-error "Buffer %s does not visit a file" (current-buffer)))
10062 (markdown-live-preview-remove)))
10065 (provide 'markdown-mode)
10067 ;; Local Variables:
10068 ;; indent-tabs-mode: nil
10069 ;; coding: utf-8
10070 ;; End:
10071 ;;; markdown-mode.el ends here