More efficient propertization of YAML metadata
[markdown-mode.git] / markdown-mode.el
blob31bfc324be2376e2233d8736c725463a1444639a
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. Large
253 ;; images may be scaled down to fit in the buffer using
254 ;; `markdown-max-image-size', a cons cell of the form
255 ;; `(max-width . max-height)`. Resizing requires Emacs to be
256 ;; built with ImageMagick support.
258 ;; * Text Styles: `C-c C-s`
260 ;; `C-c C-s i` inserts markup to make a region or word italic. If
261 ;; there is an active region, make the region italic. If the point
262 ;; is at a non-italic word, make the word italic. If the point is
263 ;; at an italic word or phrase, remove the italic markup.
264 ;; Otherwise, simply insert italic delimiters and place the point
265 ;; in between them. Similarly, use `C-c C-s b` for bold, `C-c C-s c`
266 ;; for inline code, and `C-c C-s k` for inserting `<kbd>` tags.
268 ;; `C-c C-s q` inserts a blockquote using the active region, if
269 ;; any, or starts a new blockquote. `C-c C-s Q` is a variation
270 ;; which always operates on the region, regardless of whether it
271 ;; is active or not (i.e., when `transient-mark-mode` is off but
272 ;; the mark is set). The appropriate amount of indentation, if
273 ;; any, is calculated automatically given the surrounding context,
274 ;; but may be adjusted later using the region indentation
275 ;; commands.
277 ;; `C-c C-s p` behaves similarly for inserting preformatted code
278 ;; blocks (with `C-c C-s P` being the region-only counterpart)
279 ;; and `C-c C-s C` inserts a GFM style backquote fenced code block.
281 ;; * Headings: `C-c C-s`
283 ;; To insert or replace headings, there are two options. You can
284 ;; insert a specific level heading directly or you can have
285 ;; `markdown-mode' determine the level for you based on the previous
286 ;; heading. As with the other markup commands, the heading
287 ;; insertion commands use the text in the active region, if any,
288 ;; as the heading text. Otherwise, if the current line is not
289 ;; blank, they use the text on the current line. Finally, the
290 ;; setext commands will prompt for heading text if there is no
291 ;; active region and the current line is blank.
293 ;; `C-c C-s h` inserts a heading with automatically chosen type and
294 ;; level (both determined by the previous heading). `C-c C-s H`
295 ;; behaves similarly, but uses setext (underlined) headings when
296 ;; possible, still calculating the level automatically.
297 ;; In cases where the automatically-determined level is not what
298 ;; you intended, the level can be quickly promoted or demoted
299 ;; (as described below). Alternatively, a `C-u` prefix can be
300 ;; given to insert a heading _promoted_ (lower number) by one
301 ;; level or a `C-u C-u` prefix can be given to insert a heading
302 ;; demoted (higher number) by one level.
304 ;; To insert a heading of a specific level and type, use `C-c C-s 1`
305 ;; through `C-c C-s 6` for atx (hash mark) headings and `C-c C-s !` or
306 ;; `C-c C-s @` for setext headings of level one or two, respectively.
307 ;; Note that `!` is `S-1` and `@` is `S-2`.
309 ;; If the point is at a heading, these commands will replace the
310 ;; existing markup in order to update the level and/or type of the
311 ;; heading. To remove the markup of the heading at the point,
312 ;; press `C-c C-k` to kill the heading and press `C-y` to yank the
313 ;; heading text back into the buffer.
315 ;; * Horizontal Rules: `C-c C-s -`
317 ;; `C-c C-s -` inserts a horizontal rule. By default, insert the
318 ;; first string in the list `markdown-hr-strings' (the most
319 ;; prominent rule). With a `C-u` prefix, insert the last string.
320 ;; With a numeric prefix `N`, insert the string in position `N`
321 ;; (counting from 1).
323 ;; * Footnotes: `C-c C-s f`
325 ;; `C-c C-s f` inserts a footnote marker at the point, inserts a
326 ;; footnote definition below, and positions the point for
327 ;; inserting the footnote text. Note that footnotes are an
328 ;; extension to Markdown and are not supported by all processors.
330 ;; * Wiki Links: `C-c C-s w`
332 ;; `C-c C-s w` inserts a wiki link of the form `[[WikiLink]]`. If
333 ;; there is an active region, use the region as the link text. If the
334 ;; point is at a word, use the word as the link text. If there is
335 ;; no active region and the point is not at word, simply insert
336 ;; link markup. Note that wiki links are an extension to Markdown
337 ;; and are not supported by all processors.
339 ;; * Markdown and Maintenance Commands: `C-c C-c`
341 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
342 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
343 ;; runs Markdown on the current buffer and previews, stores the
344 ;; output in a temporary file, and displays the file in a browser.
345 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
346 ;; and save the result in the file `basename.html`, where
347 ;; `basename` is the name of the Markdown file with the extension
348 ;; removed. *Export and View:* press `C-c C-c v` to export the
349 ;; file and view it in a browser. *Open:* `C-c C-c o` will open
350 ;; the Markdown source file directly using `markdown-open-command'.
351 ;; *Live Export*: Press `C-c C-c l` to turn on
352 ;; `markdown-live-preview-mode' to view the exported output
353 ;; side-by-side with the source Markdown. **For all export commands,
354 ;; the output file will be overwritten without notice.**
355 ;; `markdown-live-preview-window-function' can be customized to open
356 ;; in a browser other than `eww'. If you want to force the
357 ;; preview window to appear at the bottom or right, you can
358 ;; customize `markdown-split-window-direction'.
360 ;; To summarize:
362 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
363 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
364 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
365 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
366 ;; - `C-c C-c w`: `markdown-command' > kill ring.
367 ;; - `C-c C-c o`: `markdown-open-command'.
368 ;; - `C-c C-c l`: `markdown-live-preview-mode' > `*eww*` buffer.
370 ;; `C-c C-c c` will check for undefined references. If there are
371 ;; any, a small buffer will open with a list of undefined
372 ;; references and the line numbers on which they appear. In Emacs
373 ;; 22 and greater, selecting a reference from this list and
374 ;; pressing `RET` will insert an empty reference definition at the
375 ;; end of the buffer. Similarly, selecting the line number will
376 ;; jump to the corresponding line.
378 ;; `C-c C-c n` renumbers any ordered lists in the buffer that are
379 ;; out of sequence.
381 ;; `C-c C-c ]` completes all headings and normalizes all horizontal
382 ;; rules in the buffer.
384 ;; * Following Links: `C-c C-o`
386 ;; Press `C-c C-o` when the point is on an inline or reference
387 ;; link to open the URL in a browser. When the point is at a
388 ;; wiki link, open it in another buffer (in the current window,
389 ;; or in the other window with the `C-u` prefix). Use `M-p` and
390 ;; `M-n` to quickly jump to the previous or next link of any type.
392 ;; * Doing Things: `C-c C-d`
394 ;; Use `C-c C-d` to do something sensible with the object at the point:
396 ;; - Jumps between reference links and reference definitions.
397 ;; If more than one link uses the same reference label, a
398 ;; window will be shown containing clickable buttons for
399 ;; jumping to each link. Pressing `TAB` or `S-TAB` cycles
400 ;; between buttons in this window.
401 ;; - Jumps between footnote markers and footnote text.
402 ;; - Toggles the completion status of GFM task list items
403 ;; (checkboxes).
404 ;; - Re-aligns table columns.
406 ;; * Promotion and Demotion: `C-c C--` and `C-c C-=`
408 ;; Headings, horizontal rules, and list items can be promoted and
409 ;; demoted, as well as bold and italic text. For headings,
410 ;; "promotion" means *decreasing* the level (i.e., moving from
411 ;; `<h2>` to `<h1>`) while "demotion" means *increasing* the
412 ;; level. For horizontal rules, promotion and demotion means
413 ;; moving backward or forward through the list of rule strings in
414 ;; `markdown-hr-strings'. For bold and italic text, promotion and
415 ;; demotion means changing the markup from underscores to asterisks.
416 ;; Press `C-c C--` or `C-c LEFT` to promote the element at the point
417 ;; if possible.
419 ;; To remember these commands, note that `-` is for decreasing the
420 ;; level (promoting), and `=` (on the same key as `+`) is for
421 ;; increasing the level (demoting). Similarly, the left and right
422 ;; arrow keys indicate the direction that the atx heading markup
423 ;; is moving in when promoting or demoting.
425 ;; * Completion: `C-c C-]`
427 ;; Complete markup is in normalized form, which means, for
428 ;; example, that the underline portion of a setext header is the
429 ;; same length as the heading text, or that the number of leading
430 ;; and trailing hash marks of an atx header are equal and that
431 ;; there is no extra whitespace in the header text. `C-c C-]`
432 ;; completes the markup at the point, if it is determined to be
433 ;; incomplete.
435 ;; * Editing Lists: `M-RET`, `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
437 ;; New list items can be inserted with `M-RET` or `C-c C-j`. This
438 ;; command determines the appropriate marker (one of the possible
439 ;; unordered list markers or the next number in sequence for an
440 ;; ordered list) and indentation level by examining nearby list
441 ;; items. If there is no list before or after the point, start a
442 ;; new list. As with heading insertion, you may prefix this
443 ;; command by `C-u` to decrease the indentation by one level.
444 ;; Prefix this command by `C-u C-u` to increase the indentation by
445 ;; one level.
447 ;; Existing list items (and their nested sub-items) can be moved
448 ;; up or down with `C-c UP` or `C-c DOWN` and indented or
449 ;; outdented with `C-c RIGHT` or `C-c LEFT`.
451 ;; * Editing Subtrees: `C-c UP`, `C-c DOWN`, `C-c LEFT`, and `C-c RIGHT`
453 ;; Entire subtrees of ATX headings can be promoted and demoted
454 ;; with `C-c LEFT` and `C-c RIGHT`, which are the same keybindings
455 ;; used for promotion and demotion of list items. If the point is in
456 ;; a list item, the operate on the list item. Otherwise, they operate
457 ;; on the current heading subtree. Similarly, subtrees can be
458 ;; moved up and down with `C-c UP` and `C-c DOWN`.
460 ;; These commands currently do not work properly if there are
461 ;; Setext headings in the affected region.
463 ;; Please note the following "boundary" behavior for promotion and
464 ;; demotion. Any level-six headings will not be demoted further
465 ;; (i.e., they remain at level six, since Markdown and HTML define
466 ;; only six levels) and any level-one headings will promoted away
467 ;; entirely (i.e., heading markup will be removed, since a
468 ;; level-zero heading is not defined).
470 ;; * Shifting the Region: `C-c <` and `C-c >`
472 ;; Text in the region can be indented or outdented as a group using
473 ;; `C-c >` to indent to the next indentation point (calculated in
474 ;; the current context), and `C-c <` to outdent to the previous
475 ;; indentation point. These keybindings are the same as those for
476 ;; similar commands in `python-mode'.
478 ;; * Killing Elements: `C-c C-k`
480 ;; Press `C-c C-k` to kill the thing at point and add important
481 ;; text, without markup, to the kill ring. Possible things to
482 ;; kill include (roughly in order of precedece): inline code,
483 ;; headings, horizonal rules, links (add link text to kill ring),
484 ;; images (add alt text to kill ring), angle URIs, email
485 ;; addresses, bold, italics, reference definitions (add URI to
486 ;; kill ring), footnote markers and text (kill both marker and
487 ;; text, add text to kill ring), and list items.
489 ;; * Outline Navigation: `C-c C-n`, `C-c C-p`, `C-c C-f`, `C-c C-b`, and `C-c C-u`
491 ;; These keys are used for hierarchical navigation in lists and
492 ;; headings. When the point is in a list, they move between list
493 ;; items. Otherwise, they move between headings. Use `C-c C-n` and
494 ;; `C-c C-p` to move between the next and previous visible
495 ;; headings or list items of any level. Similarly, `C-c C-f` and
496 ;; `C-c C-b` move to the next and previous visible headings or
497 ;; list items at the same level as the one at the point. Finally,
498 ;; `C-c C-u` will move up to the parent heading or list item.
500 ;; * Movement by Markdown paragraph: `M-{`, `M-}`, and `M-h`
502 ;; Paragraphs in `markdown-mode' are regular paragraphs,
503 ;; paragraphs inside blockquotes, individual list items, headings,
504 ;; etc. These keys are usually bound to `forward-paragraph' and
505 ;; `backward-paragraph', but the built-in Emacs functions are
506 ;; based on simple regular expressions that fail in Markdown
507 ;; files. Instead, they are bound to `markdown-forward-paragraph'
508 ;; and `markdown-backward-paragraph'. To mark a paragraph,
509 ;; you can use `M-h` (`markdown-mark-paragraph').
511 ;; * Movement by Markdown block: `C-M-{`, `C-M-}`, and `C-c M-h`
513 ;; Markdown blocks are regular paragraphs in many cases, but
514 ;; contain many paragraphs in other cases: blocks are considered
515 ;; to be entire lists, entire code blocks, and entire blockquotes.
516 ;; To move backward one block use `C-M-{`
517 ;; (`markdown-beginning-block`) and to move forward use `C-M-}`
518 ;; (`markdown-end-of-block`). To mark a block, use `C-c M-h`
519 ;; (`markdown-mark-block`).
521 ;; * Movement by Defuns: `C-M-a`, `C-M-e`, and `C-M-h`
523 ;; The usual Emacs commands can be used to move by defuns
524 ;; (top-level major definitions). In markdown-mode, a defun is a
525 ;; section. As usual, `C-M-a` will move the point to the
526 ;; beginning of the current or preceding defun, `C-M-e` will move
527 ;; to the end of the current or following defun, and `C-M-h` will
528 ;; put the region around the entire defun.
530 ;; * Table Editing:
532 ;; Markdown Mode includes support for editing tables, which
533 ;; have the following basic format:
535 ;; | Right | Left | Center | Default |
536 ;; |------:|:-----|:------:|---------|
537 ;; | 12 | 12 | 12 | 12 |
538 ;; | 123 | 123 | 123 | 123 |
539 ;; | 1 | 1 | 1 | 1 |
541 ;; The first line contains column headers. The second line
542 ;; contains a separator line between the headers and the content.
543 ;; Each following line is a row in the table. Columns are always
544 ;; separated by the pipe character. The colons indicate column
545 ;; alignment.
547 ;; A table is re-aligned automatically each time you press `TAB`
548 ;; or `RET` inside the table. `TAB` also moves to the next
549 ;; field (`RET` to the next row) and creates new table rows at
550 ;; the end of the table or before horizontal separator lines. The
551 ;; indentation of the table is set by the first line. Column
552 ;; centering inside Emacs is not supported.
554 ;; Beginning pipe characters are required for proper detection of
555 ;; table borders inside Emacs. Any line starting with `|-` or `|:`
556 ;; is considered as a horizontal separator line and will be
557 ;; expanded on the next re-align to span the whole table width. No
558 ;; padding is allowed between the beginning pipe character and
559 ;; header separator symbol. So, to create the above table, you
560 ;; would only type
562 ;; |Right|Left|Center|Default|
563 ;; |-
565 ;; and then press `TAB` to align the table and start filling in
566 ;; cells.
568 ;; Then you can jump with `TAB` from one cell to the next or with
569 ;; `S-TAB` to the previous one. `RET` will jump to the to the
570 ;; next cell in the same column, and create a new row if there is
571 ;; no such cell or if the next row is beyond a separator line.
573 ;; You can also convert selected region to a table. Basic editing
574 ;; capabilities include inserting, deleting, and moving of columns
575 ;; and rows, and table re-alignment, sorting, transposition:
577 ;; - `C-c UP` or `C-c DOWN` - Move the current row up or down.
578 ;; - `C-c LEFT` or `C-c RIGHT` - Move the current column left or right.
579 ;; - `C-c S-UP` - Kill the current row.
580 ;; - `C-c S-DOWN` - Insert a row above the current row. With a
581 ;; prefix argument, row line is created below the current one.
582 ;; - `C-c S-LEFT` - Kill the current column.
583 ;; - `C-c S-RIGHT` - Insert a new column to the left of the current one.
584 ;; - `C-c C-d` - Re-align the current table (`markdown-do`).
585 ;; - `C-c C-c ^` - Sort the rows of a table by a specified column.
586 ;; This command prompts you for the column number and a sort
587 ;; method (alphabetical or numerical, optionally in reverse).
588 ;; - `C-c C-c |` - Convert the region to a table. This function
589 ;; attempts to recognize comma, tab, and space separated data
590 ;; and then splits the data into cells accordingly.
591 ;; - `C-c C-c t` - Transpose table at point.
593 ;; The table editing functions try to handle markup hiding
594 ;; correctly when calculating column widths, however, columns
595 ;; containing hidden markup may not always be aligned properly.
597 ;; * Miscellaneous Commands:
599 ;; When the [`edit-indirect'][ei] package is installed, `C-c '`
600 ;; (`markdown-edit-code-block`) can be used to edit a code block
601 ;; in an indirect buffer in the native major mode. Press `C-c C-c`
602 ;; to commit changes and return or `C-c C-k` to cancel. You can
603 ;; also give a prefix argument to the insertion command, as in
604 ;; `C-u C-c C-s C`, to edit the code block in an indirect buffer
605 ;; upon insertion.
607 ;; As noted, many of the commands above behave differently depending
608 ;; on whether Transient Mark mode is enabled or not. When it makes
609 ;; sense, if Transient Mark mode is on and the region is active, the
610 ;; command applies to the text in the region (e.g., `C-c C-s b` makes the
611 ;; region bold). For users who prefer to work outside of Transient
612 ;; Mark mode, since Emacs 22 it can be enabled temporarily by pressing
613 ;; `C-SPC C-SPC`. When this is not the case, many commands then
614 ;; proceed to look work with the word or line at the point.
616 ;; When applicable, commands that specifically act on the region even
617 ;; outside of Transient Mark mode have the same keybinding as their
618 ;; standard counterpart, but the letter is uppercase. For example,
619 ;; `markdown-insert-blockquote' is bound to `C-c C-s q` and only acts on
620 ;; the region in Transient Mark mode while `markdown-blockquote-region'
621 ;; is bound to `C-c C-s Q` and always applies to the region (when nonempty).
623 ;; Note that these region-specific functions are useful in many
624 ;; cases where it may not be obvious. For example, yanking text from
625 ;; the kill ring sets the mark at the beginning of the yanked text
626 ;; and moves the point to the end. Therefore, the (inactive) region
627 ;; contains the yanked text. So, `C-y` followed by `C-c C-s Q` will
628 ;; yank text and turn it into a blockquote.
630 ;; markdown-mode attempts to be flexible in how it handles
631 ;; indentation. When you press `TAB` repeatedly, the point will cycle
632 ;; through several possible indentation levels corresponding to things
633 ;; you might have in mind when you press `RET` at the end of a line or
634 ;; `TAB`. For example, you may want to start a new list item,
635 ;; continue a list item with hanging indentation, indent for a nested
636 ;; pre block, and so on. Outdenting is handled similarly when backspace
637 ;; is pressed at the beginning of the non-whitespace portion of a line.
639 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
640 ;; visibility cycling for atx- or hash-style headings. There are two
641 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
642 ;; the table of contents view (headings only), outline view (top-level
643 ;; headings only), and the full document view. Pressing `TAB` while the
644 ;; point is at a heading will cycle through levels of visibility for the
645 ;; subtree: completely folded, visible children, and fully visible.
646 ;; Note that mixing hash and underline style headings will give undesired
647 ;; results.
649 ;;; Customization:
651 ;; Although no configuration is *necessary* there are a few things
652 ;; that can be customized. The `M-x customize-mode` command
653 ;; provides an interface to all of the possible customizations:
655 ;; * `markdown-command' - the command used to run Markdown (default:
656 ;; `markdown`). This variable may be customized to pass
657 ;; command-line options to your Markdown processor of choice. It can
658 ;; also be a function; in this case `markdown' will call it with three
659 ;; arguments: the beginning and end of the region to process, and
660 ;; a buffer to write the output to.
662 ;; * `markdown-command-needs-filename' - set to `t' if
663 ;; `markdown-command' does not accept standard input (default:
664 ;; `nil'). When `nil', `markdown-mode' will pass the Markdown
665 ;; content to `markdown-command' using standard input (`stdin`).
666 ;; When set to `t', `markdown-mode' will pass the name of the file
667 ;; as the final command-line argument to `markdown-command'. Note
668 ;; that in the latter case, you will only be able to run
669 ;; `markdown-command' from buffers which are visiting a file. If
670 ;; `markdown-command' is a function, `markdown-command-needs-filename'
671 ;; is ignored.
673 ;; * `markdown-open-command' - the command used for calling a standalone
674 ;; Markdown previewer which is capable of opening Markdown source files
675 ;; directly (default: `nil'). This command will be called
676 ;; with a single argument, the filename of the current buffer.
677 ;; A representative program is the Mac app [Marked 2][], a
678 ;; live-updating Markdown previewer which can be [called from a
679 ;; simple shell script](https://jblevins.org/log/marked-2-command).
680 ;; This variable can also be a function; in this case `markdown-open'
681 ;; will call it without arguments to preview the current buffer.
683 ;; * `markdown-hr-strings' - list of strings to use when inserting
684 ;; horizontal rules. Different strings will not be distinguished
685 ;; when converted to HTML--they will all be converted to
686 ;; `<hr/>`--but they may add visual distinction and style to plain
687 ;; text documents. To maintain some notion of promotion and
688 ;; demotion, keep these sorted from largest to smallest.
690 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
691 ;; underscores when inserting bold text instead of two asterisks
692 ;; (default: `nil').
694 ;; * `markdown-italic-underscore' - set to a non-nil value to use
695 ;; underscores when inserting italic text instead of asterisks
696 ;; (default: `nil').
698 ;; * `markdown-asymmetric-header' - set to a non-nil value to use
699 ;; asymmetric header styling, placing header characters only on
700 ;; the left of headers (default: `nil').
702 ;; * `markdown-header-scaling' - set to a non-nil value to use
703 ;; a variable-pitch font for headings where the size corresponds
704 ;; to the level of the heading (default: `nil').
706 ;; * `markdown-header-scaling-values' - list of scaling values,
707 ;; relative to baseline, for headers of levels one through six,
708 ;; used when `markdown-header-scaling' is non-nil
709 ;; (default: `(2.0 1.7 1.4 1.1 1.0 1.0)`).
711 ;; * `markdown-marginalize-headers' - put opening atx header markup
712 ;; in the left margin when non-nil (default: `nil').
714 ;; * `markdown-marginalize-headers-margin-width' - width of margin
715 ;; used for marginalized headers (default: 6).
717 ;; * `markdown-list-indent-width' - depth of indentation for lists
718 ;; when inserting, promoting, and demoting list items (default: 4).
720 ;; * `markdown-indent-function' - the function to use for automatic
721 ;; indentation (default: `markdown-indent-line').
723 ;; * `markdown-indent-on-enter' - Set to a non-nil value to
724 ;; automatically indent new lines when `RET` is pressed.
725 ;; Set to `indent-and-new-item' to additionally continue lists
726 ;; when `RET` is pressed (default: `t').
728 ;; * `markdown-enable-wiki-links' - syntax highlighting for wiki
729 ;; links (default: `nil'). Set this to a non-nil value to turn on
730 ;; wiki link support by default. Wiki link support can be toggled
731 ;; later using the function `markdown-toggle-wiki-links'."
733 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
734 ;; treat aliased wiki links like `[[link text|PageName]]`
735 ;; (default: `t'). When set to nil, they will be treated as
736 ;; `[[PageName|link text]]'.
738 ;; * `markdown-uri-types' - a list of protocol schemes (e.g., "http")
739 ;; for URIs that `markdown-mode' should highlight.
741 ;; * `markdown-enable-math' - font lock for inline and display LaTeX
742 ;; math expressions (default: `nil'). Set this to `t' to turn on
743 ;; math support by default. Math support can be toggled
744 ;; interactively later using `C-c C-x C-e`
745 ;; (`markdown-toggle-math').
747 ;; * `markdown-enable-html' - font lock for HTML tags and attributes
748 ;; (default: `t').
750 ;; * `markdown-css-paths' - CSS files to link to in XHTML output
751 ;; (default: `nil`).
753 ;; * `markdown-content-type' - when set to a nonempty string, an
754 ;; `http-equiv` attribute will be included in the XHTML `<head>`
755 ;; block (default: `""`). If needed, the suggested values are
756 ;; `application/xhtml+xml` or `text/html`. See also:
757 ;; `markdown-coding-system'.
759 ;; * `markdown-coding-system' - used for specifying the character
760 ;; set identifier in the `http-equiv` attribute when included
761 ;; (default: `nil'). See `markdown-content-type', which must
762 ;; be set before this variable has any effect. When set to `nil',
763 ;; `buffer-file-coding-system' will be used to automatically
764 ;; determine the coding system string (falling back to
765 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
766 ;; and `iso-latin-1'.
768 ;; * `markdown-xhtml-header-content' - additional content to include
769 ;; in the XHTML `<head>` block (default: `""`).
771 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
772 ;; `markdown-mode' uses to determine whether the output of
773 ;; `markdown-command' is a standalone XHTML document or an XHTML
774 ;; fragment (default: `"^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"`). If
775 ;; this regular expression not matched in the first five lines of
776 ;; output, `markdown-mode' assumes the output is a fragment and
777 ;; adds a header and footer.
779 ;; * `markdown-link-space-sub-char' - a character to replace spaces
780 ;; when mapping wiki links to filenames (default: `"_"`).
781 ;; For example, use an underscore for compatibility with the
782 ;; Python Markdown WikiLinks extension. In `gfm-mode', this is
783 ;; set to `"-"` to conform with GitHub wiki links.
785 ;; * `markdown-reference-location' - where to insert reference
786 ;; definitions (default: `header`). The possible locations are
787 ;; the end of the document (`end`), after the current block
788 ;; (`immediately`), the end of the current subtree (`subtree'),
789 ;; or before the next header (`header`).
791 ;; * `markdown-footnote-location' - where to insert footnote text
792 ;; (default: `end`). The set of location options is the same as
793 ;; for `markdown-reference-location'.
795 ;; * `markdown-nested-imenu-heading-index' - Use nested imenu
796 ;; heading instead of a flat index (default: `t'). A nested
797 ;; index may provide more natural browsing from the menu, but a
798 ;; flat list may allow for faster keyboard navigation via tab
799 ;; completion.
801 ;; * `comment-auto-fill-only-comments' - variable is made
802 ;; buffer-local and set to `nil' by default. In programming
803 ;; language modes, when this variable is non-nil, only comments
804 ;; will be filled by auto-fill-mode. However, comments in
805 ;; Markdown documents are rare and the most users probably intend
806 ;; for the actual content of the document to be filled. Making
807 ;; this variable buffer-local allows `markdown-mode' to override
808 ;; the default behavior induced when the global variable is non-nil.
810 ;; * `markdown-gfm-additional-languages', - additional languages to
811 ;; make available, aside from those predefined in
812 ;; `markdown-gfm-recognized-languages', when inserting GFM code
813 ;; blocks (default: `nil`). Language strings must have be trimmed
814 ;; of whitespace and not contain any curly braces. They may be of
815 ;; arbitrary capitalization, though.
817 ;; * `markdown-gfm-use-electric-backquote' - use
818 ;; `markdown-electric-backquote' for interactive insertion of GFM
819 ;; code blocks when backquote is pressed three times (default: `t`).
821 ;; * `markdown-make-gfm-checkboxes-buttons' - Whether GitHub
822 ;; Flavored Markdown style task lists (checkboxes) should be
823 ;; turned into buttons that can be toggled with mouse-1 or RET. If
824 ;; non-nil (default), then buttons are enabled. This works in
825 ;; `markdown-mode' as well as `gfm-mode'.
827 ;; * `markdown-hide-urls' - Determines whether URL and reference
828 ;; labels are hidden for inline and reference links (default: `nil').
829 ;; When non-nil, inline links will appear in the buffer as
830 ;; `[link](∞)` instead of
831 ;; `[link](http://perhaps.a/very/long/url/)`. To change the
832 ;; placeholder (composition) character used, set the variable
833 ;; `markdown-url-compose-char'. URL hiding can be toggled
834 ;; interactively using `C-c C-x C-l` (`markdown-toggle-url-hiding')
835 ;; or from the Markdown | Links & Images menu.
837 ;; * `markdown-hide-markup' - Determines whether all possible markup
838 ;; is hidden or otherwise beautified (default: `nil'). The actual
839 ;; buffer text remains unchanged, but the display will be altered.
840 ;; Brackets and URLs for links will be hidden, asterisks and
841 ;; underscores for italic and bold text will be hidden, text
842 ;; bullets for unordered lists will be replaced by Unicode
843 ;; bullets, and so on. Since this includes URLs and reference
844 ;; labels, when non-nil this setting supersedes `markdown-hide-urls'.
845 ;; Markup hiding can be toggled using `C-c C-x C-m`
846 ;; (`markdown-toggle-markup-hiding') or from the Markdown | Show &
847 ;; Hide menu.
849 ;; Unicode bullets are used to replace ASCII list item markers.
850 ;; The list of characters used, in order of list level, can be
851 ;; specified by setting the variable `markdown-list-item-bullets'.
852 ;; The placeholder characters used to replace other markup can
853 ;; be changed by customizing the corresponding variables:
854 ;; `markdown-blockquote-display-char',
855 ;; `markdown-hr-display-char', and
856 ;; `markdown-definition-display-char'.
858 ;; * `markdown-fontify-code-blocks-natively' - Whether to fontify
859 ;; code in code blocks using the native major mode. This only
860 ;; works for fenced code blocks where the language is specified
861 ;; where we can automatically determine the appropriate mode to
862 ;; use. The language to mode mapping may be customized by setting
863 ;; the variable `markdown-code-lang-modes'. This can be toggled
864 ;; interactively by pressing `C-c C-x C-f`
865 ;; (`markdown-toggle-fontify-code-blocks-natively').
867 ;; * `markdown-gfm-uppercase-checkbox' - When non-nil, complete GFM
868 ;; task list items with `[X]` instead of `[x]` (default: `nil').
869 ;; This is useful for compatibility with `org-mode', which doesn't
870 ;; recognize the lowercase variant.
872 ;; * `markdown-translate-filename-function' - A function to be used to
873 ;; translate filenames in links.
875 ;; Additionally, the faces used for syntax highlighting can be modified to
876 ;; your liking by issuing `M-x customize-group RET markdown-faces`
877 ;; or by using the "Markdown Faces" link at the bottom of the mode
878 ;; customization screen.
880 ;; [Marked 2]: https://itunes.apple.com/us/app/marked-2/id890031187?mt=12&uo=4&at=11l5Vs&ct=mm
882 ;;; Extensions:
884 ;; Besides supporting the basic Markdown syntax, Markdown Mode also
885 ;; includes syntax highlighting for `[[Wiki Links]]`. This can be
886 ;; enabled by setting `markdown-enable-wiki-links' to a non-nil value.
887 ;; Wiki links may be followed by pressing `C-c C-o` when the point
888 ;; is at a wiki link. Use `M-p` and `M-n` to quickly jump to the
889 ;; previous and next links (including links of other types).
890 ;; Aliased or piped wiki links of the form `[[link text|PageName]]`
891 ;; are also supported. Since some wikis reverse these components, set
892 ;; `markdown-wiki-link-alias-first' to nil to treat them as
893 ;; `[[PageName|link text]]`. If `markdown-wiki-link-fontify-missing'
894 ;; is also non-nil, Markdown Mode will highlight wiki links with
895 ;; missing target file in a different color. By default, Markdown
896 ;; Mode only searches for target files in the current directory.
897 ;; Search in subdirectories can be enabled by setting
898 ;; `markdown-wiki-link-search-subdirectories' to a non-nil value.
899 ;; Sequential parent directory search (as in [Ikiwiki][]) can be
900 ;; enabled by setting `markdown-wiki-link-search-parent-directories'
901 ;; to a non-nil value.
903 ;; [Ikiwiki]: https://ikiwiki.info
905 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
906 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
907 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
908 ;; You can do this either by using `M-x customize-group markdown`
909 ;; or by placing the following in your `.emacs` file:
911 ;; ``` Lisp
912 ;; (setq markdown-command "markdown | smartypants")
913 ;; ```
915 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
917 ;; Syntax highlighting for mathematical expressions written
918 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
919 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
920 ;; either via customize or by placing `(setq markdown-enable-math t)`
921 ;; in `.emacs`, and then restarting Emacs or calling
922 ;; `markdown-reload-extensions'.
924 ;;; GitHub Flavored Markdown (GFM):
926 ;; A [GitHub Flavored Markdown][GFM] mode, `gfm-mode', is also
927 ;; available. The GitHub implementation differs slightly from
928 ;; standard Markdown in that it supports things like different
929 ;; behavior for underscores inside of words, automatic linking of
930 ;; URLs, strikethrough text, and fenced code blocks with an optional
931 ;; language keyword.
933 ;; The GFM-specific features above apply to `README.md` files, wiki
934 ;; pages, and other Markdown-formatted files in repositories on
935 ;; GitHub. GitHub also enables [additional features][GFM comments] for
936 ;; writing on the site (for issues, pull requests, messages, etc.)
937 ;; that are further extensions of GFM. These features include task
938 ;; lists (checkboxes), newlines corresponding to hard line breaks,
939 ;; auto-linked references to issues and commits, wiki links, and so
940 ;; on. To make matters more confusing, although task lists are not
941 ;; part of [GFM proper][GFM], [since 2014][] they are rendered (in a
942 ;; read-only fashion) in all Markdown documents in repositories on the
943 ;; site. These additional extensions are supported to varying degrees
944 ;; by `markdown-mode' and `gfm-mode' as described below.
946 ;; * **URL autolinking:** Both `markdown-mode' and `gfm-mode' support
947 ;; highlighting of URLs without angle brackets.
949 ;; * **Multiple underscores in words:** You must enable `gfm-mode' to
950 ;; toggle support for underscores inside of words. In this mode
951 ;; variable names such as `a_test_variable` will not trigger
952 ;; emphasis (italics).
954 ;; * **Fenced code blocks:** Code blocks quoted with backquotes, with
955 ;; optional programming language keywords, are highlighted in
956 ;; both `markdown-mode' and `gfm-mode'. They can be inserted with
957 ;; `C-c C-s C`. If there is an active region, the text in the
958 ;; region will be placed inside the code block. You will be
959 ;; prompted for the name of the language, but may press enter to
960 ;; continue without naming a language.
962 ;; * **Strikethrough:** Strikethrough text is supported in both
963 ;; `markdown-mode' and `gfm-mode'. It can be inserted (and toggled)
964 ;; using `C-c C-s s`.
966 ;; * **Task lists:** GFM task lists will be rendered as checkboxes
967 ;; (Emacs buttons) in both `markdown-mode' and `gfm-mode' when
968 ;; `markdown-make-gfm-checkboxes-buttons' is set to a non-nil value
969 ;; (and it is set to t by default). These checkboxes can be
970 ;; toggled by clicking `mouse-1`, pressing `RET` over the button,
971 ;; or by pressing `C-c C-d` (`markdown-do`) with the point anywhere
972 ;; in the task list item. A normal list item can be turned to a
973 ;; check list item by the same command, or more specifically
974 ;; `C-c C-s [` (`markdown-insert-gfm-checkbox`).
976 ;; * **Wiki links:** Generic wiki links are supported in
977 ;; `markdown-mode', but in `gfm-mode' specifically they will be
978 ;; treated as they are on GitHub: spaces will be replaced by hyphens
979 ;; in filenames and the first letter of the filename will be
980 ;; capitalized. For example, `[[wiki link]]' will map to a file
981 ;; named `Wiki-link` with the same extension as the current file.
982 ;; If a file with this name does not exist in the current directory,
983 ;; the first match in a subdirectory, if any, will be used instead.
985 ;; * **Newlines:** Neither `markdown-mode' nor `gfm-mode' do anything
986 ;; specifically with respect to newline behavior. If you use
987 ;; `gfm-mode' mostly to write text for comments or issues on the
988 ;; GitHub site--where newlines are significant and correspond to
989 ;; hard line breaks--then you may want to enable `visual-line-mode'
990 ;; for line wrapping in buffers. You can do this with a
991 ;; `gfm-mode-hook' as follows:
993 ;; ``` Lisp
994 ;; ;; Use visual-line-mode in gfm-mode
995 ;; (defun my-gfm-mode-hook ()
996 ;; (visual-line-mode 1))
997 ;; (add-hook 'gfm-mode-hook 'my-gfm-mode-hook)
998 ;; ```
1000 ;; * **Preview:** GFM-specific preview can be powered by setting
1001 ;; `markdown-command' to use [Docter][]. This may also be
1002 ;; configured to work with [Marked 2][] for `markdown-open-command'.
1004 ;; [GFM]: http://github.github.com/github-flavored-markdown/
1005 ;; [GFM comments]: https://help.github.com/articles/writing-on-github/
1006 ;; [since 2014]: https://github.com/blog/1825-task-lists-in-all-markdown-documents
1007 ;; [Docter]: https://github.com/alampros/Docter
1009 ;;; Acknowledgments:
1011 ;; markdown-mode has benefited greatly from the efforts of the many
1012 ;; volunteers who have sent patches, test cases, bug reports,
1013 ;; suggestions, helped with packaging, etc. Thank you for your
1014 ;; contributions! See the [contributors graph][contrib] for details.
1016 ;; [contrib]: https://github.com/jrblevin/markdown-mode/graphs/contributors
1018 ;;; Bugs:
1020 ;; markdown-mode is developed and tested primarily for compatibility
1021 ;; with GNU Emacs 24.3 and later. If you find any bugs in
1022 ;; markdown-mode, please construct a test case or a patch and open a
1023 ;; ticket on the [GitHub issue tracker][issues]. See the
1024 ;; contributing guidelines in `CONTRIBUTING.md` for details on
1025 ;; creating pull requests.
1027 ;; [issues]: https://github.com/jrblevin/markdown-mode/issues
1029 ;;; History:
1031 ;; markdown-mode was written and is maintained by Jason Blevins. The
1032 ;; first version was released on May 24, 2007.
1034 ;; * 2007-05-24: [Version 1.1][]
1035 ;; * 2007-05-25: [Version 1.2][]
1036 ;; * 2007-06-05: [Version 1.3][]
1037 ;; * 2007-06-29: [Version 1.4][]
1038 ;; * 2007-10-11: [Version 1.5][]
1039 ;; * 2008-06-04: [Version 1.6][]
1040 ;; * 2009-10-01: [Version 1.7][]
1041 ;; * 2011-08-12: [Version 1.8][]
1042 ;; * 2011-08-15: [Version 1.8.1][]
1043 ;; * 2013-01-25: [Version 1.9][]
1044 ;; * 2013-03-24: [Version 2.0][]
1045 ;; * 2016-01-09: [Version 2.1][]
1046 ;; * 2017-05-26: [Version 2.2][]
1047 ;; * 2017-08-31: [Version 2.3][]
1049 ;; [Version 1.1]: https://jblevins.org/projects/markdown-mode/rev-1-1
1050 ;; [Version 1.2]: https://jblevins.org/projects/markdown-mode/rev-1-2
1051 ;; [Version 1.3]: https://jblevins.org/projects/markdown-mode/rev-1-3
1052 ;; [Version 1.4]: https://jblevins.org/projects/markdown-mode/rev-1-4
1053 ;; [Version 1.5]: https://jblevins.org/projects/markdown-mode/rev-1-5
1054 ;; [Version 1.6]: https://jblevins.org/projects/markdown-mode/rev-1-6
1055 ;; [Version 1.7]: https://jblevins.org/projects/markdown-mode/rev-1-7
1056 ;; [Version 1.8]: https://jblevins.org/projects/markdown-mode/rev-1-8
1057 ;; [Version 1.8.1]: https://jblevins.org/projects/markdown-mode/rev-1-8-1
1058 ;; [Version 1.9]: https://jblevins.org/projects/markdown-mode/rev-1-9
1059 ;; [Version 2.0]: https://jblevins.org/projects/markdown-mode/rev-2-0
1060 ;; [Version 2.1]: https://jblevins.org/projects/markdown-mode/rev-2-1
1061 ;; [Version 2.2]: https://jblevins.org/projects/markdown-mode/rev-2-2
1062 ;; [Version 2.3]: https://jblevins.org/projects/markdown-mode/rev-2-3
1065 ;;; Code:
1067 (require 'easymenu)
1068 (require 'outline)
1069 (require 'thingatpt)
1070 (require 'cl-lib)
1071 (require 'url-parse)
1072 (require 'button)
1073 (require 'color)
1074 (require 'rx)
1076 (defvar jit-lock-start)
1077 (defvar jit-lock-end)
1078 (defvar flyspell-generic-check-word-predicate)
1080 (declare-function eww-open-file "eww")
1081 (declare-function url-path-and-query "url-parse")
1084 ;;; Constants =================================================================
1086 (defconst markdown-mode-version "2.4-dev"
1087 "Markdown mode version number.")
1089 (defconst markdown-output-buffer-name "*markdown-output*"
1090 "Name of temporary buffer for markdown command output.")
1092 (defconst markdown-sub-superscript-display
1093 '(((raise -0.3) (height 0.7)) ; subscript
1094 ((raise 0.3) (height 0.7))) ; superscript
1095 "Parameters for sub- and superscript formatting.")
1098 ;;; Global Variables ==========================================================
1100 (defvar markdown-reference-label-history nil
1101 "History of used reference labels.")
1103 (defvar markdown-live-preview-mode nil
1104 "Sentinel variable for command `markdown-live-preview-mode'.")
1106 (defvar markdown-gfm-language-history nil
1107 "History list of languages used in the current buffer in GFM code blocks.")
1110 ;;; Customizable Variables ====================================================
1112 (defvar markdown-mode-hook nil
1113 "Hook run when entering Markdown mode.")
1115 (defvar markdown-before-export-hook nil
1116 "Hook run before running Markdown to export XHTML output.
1117 The hook may modify the buffer, which will be restored to it's
1118 original state after exporting is complete.")
1120 (defvar markdown-after-export-hook nil
1121 "Hook run after XHTML output has been saved.
1122 Any changes to the output buffer made by this hook will be saved.")
1124 (defgroup markdown nil
1125 "Major mode for editing text files in Markdown format."
1126 :prefix "markdown-"
1127 :group 'wp
1128 :link '(url-link "https://jblevins.org/projects/markdown-mode/"))
1130 (defcustom markdown-command "markdown"
1131 "Command to run markdown."
1132 :group 'markdown
1133 :type '(choice (string :tag "Shell command") function))
1135 (defcustom markdown-command-needs-filename nil
1136 "Set to non-nil if `markdown-command' does not accept input from stdin.
1137 Instead, it will be passed a filename as the final command line
1138 option. As a result, you will only be able to run Markdown from
1139 buffers which are visiting a file."
1140 :group 'markdown
1141 :type 'boolean)
1143 (defcustom markdown-open-command nil
1144 "Command used for opening Markdown files directly.
1145 For example, a standalone Markdown previewer. This command will
1146 be called with a single argument: the filename of the current
1147 buffer. It can also be a function, which will be called without
1148 arguments."
1149 :group 'markdown
1150 :type '(choice file function (const :tag "None" nil)))
1152 (defcustom markdown-hr-strings
1153 '("-------------------------------------------------------------------------------"
1154 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
1155 "---------------------------------------"
1156 "* * * * * * * * * * * * * * * * * * * *"
1157 "---------"
1158 "* * * * *")
1159 "Strings to use when inserting horizontal rules.
1160 The first string in the list will be the default when inserting a
1161 horizontal rule. Strings should be listed in decreasing order of
1162 prominence (as in headings from level one to six) for use with
1163 promotion and demotion functions."
1164 :group 'markdown
1165 :type '(repeat string))
1167 (defcustom markdown-bold-underscore nil
1168 "Use two underscores when inserting bold text instead of two asterisks."
1169 :group 'markdown
1170 :type 'boolean)
1172 (defcustom markdown-italic-underscore nil
1173 "Use underscores when inserting italic text instead of asterisks."
1174 :group 'markdown
1175 :type 'boolean)
1177 (defcustom markdown-marginalize-headers nil
1178 "When non-nil, put opening atx header markup in a left margin.
1180 This setting goes well with `markdown-asymmetric-header'. But
1181 sadly it conflicts with `linum-mode' since they both use the
1182 same margin."
1183 :group 'markdown
1184 :type 'boolean
1185 :safe 'booleanp
1186 :package-version '(markdown-mode . "2.4"))
1188 (defcustom markdown-marginalize-headers-margin-width 6
1189 "Character width of margin used for marginalized headers.
1190 The default value is based on there being six heading levels
1191 defined by Markdown and HTML. Increasing this produces extra
1192 whitespace on the left. Decreasing it may be preferred when
1193 fewer than six nested heading levels are used."
1194 :group 'markdown
1195 :type 'natnump
1196 :safe 'natnump
1197 :package-version '(markdown-mode . "2.4"))
1199 (defcustom markdown-asymmetric-header nil
1200 "Determines if atx header style will be asymmetric.
1201 Set to a non-nil value to use asymmetric header styling, placing
1202 header markup only at the beginning of the line. By default,
1203 balanced markup will be inserted at the beginning and end of the
1204 line around the header title."
1205 :group 'markdown
1206 :type 'boolean)
1208 (defcustom markdown-indent-function 'markdown-indent-line
1209 "Function to use to indent."
1210 :group 'markdown
1211 :type 'function)
1213 (defcustom markdown-indent-on-enter t
1214 "Determines indentation behavior when pressing \\[newline].
1215 Possible settings are nil, t, and 'indent-and-new-item.
1217 When non-nil, pressing \\[newline] will call `newline-and-indent'
1218 to indent the following line according to the context using
1219 `markdown-indent-function'. In this case, note that
1220 \\[electric-newline-and-maybe-indent] can still be used to insert
1221 a newline without indentation.
1223 When set to 'indent-and-new-item and the point is in a list item
1224 when \\[newline] is pressed, the list will be continued on the next
1225 line, where a new item will be inserted.
1227 When set to nil, simply call `newline' as usual. In this case,
1228 you can still indent lines using \\[markdown-cycle] and continue
1229 lists with \\[markdown-insert-list-item].
1231 Note that this assumes the variable `electric-indent-mode' is
1232 non-nil (enabled). When it is *disabled*, the behavior of
1233 \\[newline] and `\\[electric-newline-and-maybe-indent]' are
1234 reversed."
1235 :group 'markdown
1236 :type '(choice (const :tag "Don't automatically indent" nil)
1237 (const :tag "Automatically indent" t)
1238 (const :tag "Automatically indent and insert new list items" indent-and-new-item)))
1240 (defcustom markdown-enable-wiki-links nil
1241 "Syntax highlighting for wiki links.
1242 Set this to a non-nil value to turn on wiki link support by default.
1243 Support can be toggled later using the `markdown-toggle-wiki-links'
1244 function or \\[markdown-toggle-wiki-links]."
1245 :group 'markdown
1246 :type 'boolean
1247 :safe 'booleanp
1248 :package-version '(markdown-mode . "2.2"))
1250 (defcustom markdown-wiki-link-alias-first t
1251 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
1252 Otherwise, they will be treated as [[PageName|alias text]]."
1253 :group 'markdown
1254 :type 'boolean
1255 :safe 'booleanp)
1257 (defcustom markdown-wiki-link-search-subdirectories nil
1258 "When non-nil, search for wiki link targets in subdirectories.
1259 This is the default search behavior for GitHub and is
1260 automatically set to t in `gfm-mode'."
1261 :group 'markdown
1262 :type 'boolean
1263 :safe 'booleanp
1264 :package-version '(markdown-mode . "2.2"))
1266 (defcustom markdown-wiki-link-search-parent-directories nil
1267 "When non-nil, search for wiki link targets in parent directories.
1268 This is the default search behavior of Ikiwiki."
1269 :group 'markdown
1270 :type 'boolean
1271 :safe 'booleanp
1272 :package-version '(markdown-mode . "2.2"))
1274 (defcustom markdown-wiki-link-fontify-missing nil
1275 "When non-nil, change wiki link face according to existence of target files.
1276 This is expensive because it requires checking for the file each time the buffer
1277 changes or the user switches windows. It is disabled by default because it may
1278 cause lag when typing on slower machines."
1279 :group 'markdown
1280 :type 'boolean
1281 :safe 'booleanp
1282 :package-version '(markdown-mode . "2.2"))
1284 (defcustom markdown-uri-types
1285 '("acap" "cid" "data" "dav" "fax" "file" "ftp"
1286 "gopher" "http" "https" "imap" "ldap" "mailto"
1287 "mid" "message" "modem" "news" "nfs" "nntp"
1288 "pop" "prospero" "rtsp" "service" "sip" "tel"
1289 "telnet" "tip" "urn" "vemmi" "wais")
1290 "Link types for syntax highlighting of URIs."
1291 :group 'markdown
1292 :type '(repeat (string :tag "URI scheme")))
1294 (defcustom markdown-url-compose-char
1295 '(?∞ ?… ?⋯ ?# ?★ ?⚓)
1296 "Placeholder character for hidden URLs.
1297 This may be a single character or a list of characters. In case
1298 of a list, the first one that satisfies `char-displayable-p' will
1299 be used."
1300 :type '(choice
1301 (character :tag "Single URL replacement character")
1302 (repeat :tag "List of possible URL replacement characters"
1303 character))
1304 :package-version '(markdown-mode . "2.3"))
1306 (defcustom markdown-blockquote-display-char
1307 '("▌" "┃" ">")
1308 "String to display when hiding blockquote markup.
1309 This may be a single string or a list of string. In case of a
1310 list, the first one that satisfies `char-displayable-p' will be
1311 used."
1312 :type 'string
1313 :type '(choice
1314 (string :tag "Single blockquote display string")
1315 (repeat :tag "List of possible blockquote display strings" string))
1316 :package-version '(markdown-mode . "2.3"))
1318 (defcustom markdown-hr-display-char
1319 '(?─ ?━ ?-)
1320 "Character for hiding horizontal rule markup.
1321 This may be a single character or a list of characters. In case
1322 of a list, the first one that satisfies `char-displayable-p' will
1323 be used."
1324 :group 'markdown
1325 :type '(choice
1326 (character :tag "Single HR display character")
1327 (repeat :tag "List of possible HR display characters" character))
1328 :package-version '(markdown-mode . "2.3"))
1330 (defcustom markdown-definition-display-char
1331 '(?⁘ ?⁙ ?≡ ?⌑ ?◊ ?:)
1332 "Character for replacing definition list markup.
1333 This may be a single character or a list of characters. In case
1334 of a list, the first one that satisfies `char-displayable-p' will
1335 be used."
1336 :type '(choice
1337 (character :tag "Single definition list character")
1338 (repeat :tag "List of possible definition list characters" character))
1339 :package-version '(markdown-mode . "2.3"))
1341 (defcustom markdown-enable-math nil
1342 "Syntax highlighting for inline LaTeX and itex expressions.
1343 Set this to a non-nil value to turn on math support by default.
1344 Math support can be enabled, disabled, or toggled later using
1345 `markdown-toggle-math' or \\[markdown-toggle-math]."
1346 :group 'markdown
1347 :type 'boolean
1348 :safe 'booleanp)
1349 (make-variable-buffer-local 'markdown-enable-math)
1351 (defcustom markdown-enable-html t
1352 "Enable font-lock support for HTML tags and attributes."
1353 :group 'markdown
1354 :type 'boolean
1355 :safe 'booleanp
1356 :package-version '(markdown-mode . "2.4"))
1358 (defcustom markdown-css-paths nil
1359 "URL of CSS file to link to in the output XHTML."
1360 :group 'markdown
1361 :type '(repeat (string :tag "CSS File Path")))
1363 (defcustom markdown-content-type ""
1364 "Content type string for the http-equiv header in XHTML output.
1365 When set to a non-empty string, insert the http-equiv attribute.
1366 Otherwise, this attribute is omitted."
1367 :group 'markdown
1368 :type 'string)
1370 (defcustom markdown-coding-system nil
1371 "Character set string for the http-equiv header in XHTML output.
1372 Defaults to `buffer-file-coding-system' (and falling back to
1373 `iso-8859-1' when not available). Common settings are `utf-8'
1374 and `iso-latin-1'. Use `list-coding-systems' for more choices."
1375 :group 'markdown
1376 :type 'coding-system)
1378 (defcustom markdown-export-kill-buffer t
1379 "Kill output buffer after HTML export.
1380 When non-nil, kill the HTML output buffer after
1381 exporting with `markdown-export'."
1382 :group 'markdown
1383 :type 'boolean
1384 :safe 'booleanp
1385 :package-version '(markdown-mode . "2.4"))
1387 (defcustom markdown-xhtml-header-content ""
1388 "Additional content to include in the XHTML <head> block."
1389 :group 'markdown
1390 :type 'string)
1392 (defcustom markdown-xhtml-standalone-regexp
1393 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
1394 "Regexp indicating whether `markdown-command' output is standalone XHTML."
1395 :group 'markdown
1396 :type 'regexp)
1398 (defcustom markdown-link-space-sub-char "_"
1399 "Character to use instead of spaces when mapping wiki links to filenames."
1400 :group 'markdown
1401 :type 'string)
1403 (defcustom markdown-reference-location 'header
1404 "Position where new reference definitions are inserted in the document."
1405 :group 'markdown
1406 :type '(choice (const :tag "At the end of the document" end)
1407 (const :tag "Immediately after the current block" immediately)
1408 (const :tag "At the end of the subtree" subtree)
1409 (const :tag "Before next header" header)))
1411 (defcustom markdown-footnote-location 'end
1412 "Position where new footnotes are inserted in the document."
1413 :group 'markdown
1414 :type '(choice (const :tag "At the end of the document" end)
1415 (const :tag "Immediately after the current block" immediately)
1416 (const :tag "At the end of the subtree" subtree)
1417 (const :tag "Before next header" header)))
1419 (defcustom markdown-footnote-display '((raise 0.2) (height 0.8))
1420 "Display specification for footnote markers and inline footnotes.
1421 By default, footnote text is reduced in size and raised. Set to
1422 nil to disable this."
1423 :group 'markdown
1424 :type '(choice (sexp :tag "Display specification")
1425 (const :tag "Don't set display property" nil))
1426 :package-version '(markdown-mode . "2.4"))
1428 (defcustom markdown-sub-superscript-display
1429 '(((raise -0.3) (height 0.7)) . ((raise 0.3) (height 0.7)))
1430 "Display specification for subscript and superscripts.
1431 The car is used for subscript, the cdr is used for superscripts."
1432 :group 'markdown
1433 :type '(cons (choice (sexp :tag "Subscript form")
1434 (const :tag "No lowering" nil))
1435 (choice (sexp :tag "Superscript form")
1436 (const :tag "No raising" nil)))
1437 :package-version '(markdown-mode . "2.4"))
1439 (defcustom markdown-unordered-list-item-prefix " * "
1440 "String inserted before unordered list items."
1441 :group 'markdown
1442 :type 'string)
1444 (defcustom markdown-nested-imenu-heading-index t
1445 "Use nested or flat imenu heading index.
1446 A nested index may provide more natural browsing from the menu,
1447 but a flat list may allow for faster keyboard navigation via tab
1448 completion."
1449 :group 'markdown
1450 :type 'boolean
1451 :safe 'booleanp
1452 :package-version '(markdown-mode . "2.2"))
1454 (defcustom markdown-make-gfm-checkboxes-buttons t
1455 "When non-nil, make GFM checkboxes into buttons."
1456 :group 'markdown
1457 :type 'boolean)
1459 (defcustom markdown-use-pandoc-style-yaml-metadata nil
1460 "When non-nil, allow YAML metadata anywhere in the document."
1461 :group 'markdown
1462 :type 'boolean)
1464 (defcustom markdown-split-window-direction 'any
1465 "Preference for splitting windows for static and live preview.
1466 The default value is 'any, which instructs Emacs to use
1467 `split-window-sensibly' to automatically choose how to split
1468 windows based on the values of `split-width-threshold' and
1469 `split-height-threshold' and the available windows. To force
1470 vertically split (left and right) windows, set this to 'vertical
1471 or 'right. To force horizontally split (top and bottom) windows,
1472 set this to 'horizontal or 'below."
1473 :group 'markdown
1474 :type '(choice (const :tag "Automatic" any)
1475 (const :tag "Right (vertical)" right)
1476 (const :tag "Below (horizontal)" below))
1477 :package-version '(markdown-mode . "2.2"))
1479 (defcustom markdown-live-preview-window-function
1480 'markdown-live-preview-window-eww
1481 "Function to display preview of Markdown output within Emacs.
1482 Function must update the buffer containing the preview and return
1483 the buffer."
1484 :group 'markdown
1485 :type 'function)
1487 (defcustom markdown-live-preview-delete-export 'delete-on-destroy
1488 "Delete exported HTML file when using `markdown-live-preview-export'.
1489 If set to 'delete-on-export, delete on every export. When set to
1490 'delete-on-destroy delete when quitting from command
1491 `markdown-live-preview-mode'. Never delete if set to nil."
1492 :group 'markdown
1493 :type '(choice
1494 (const :tag "Delete on every export" delete-on-export)
1495 (const :tag "Delete when quitting live preview" delete-on-destroy)
1496 (const :tag "Never delete" nil)))
1498 (defcustom markdown-list-indent-width 4
1499 "Depth of indentation for markdown lists.
1500 Used in `markdown-demote-list-item' and
1501 `markdown-promote-list-item'."
1502 :group 'markdown
1503 :type 'integer)
1505 (defcustom markdown-enable-prefix-prompts t
1506 "Display prompts for certain prefix commands.
1507 Set to nil to disable these prompts."
1508 :group 'markdown
1509 :type 'boolean
1510 :safe 'booleanp
1511 :package-version '(markdown-mode . "2.3"))
1513 (defcustom markdown-gfm-additional-languages nil
1514 "Extra languages made available when inserting GFM code blocks.
1515 Language strings must have be trimmed of whitespace and not
1516 contain any curly braces. They may be of arbitrary
1517 capitalization, though."
1518 :group 'markdown
1519 :type '(repeat (string :validate markdown-validate-language-string)))
1521 (defcustom markdown-gfm-use-electric-backquote t
1522 "Use `markdown-electric-backquote' when backquote is hit three times."
1523 :group 'markdown
1524 :type 'boolean)
1526 (defcustom markdown-gfm-downcase-languages t
1527 "If non-nil, downcase suggested languages.
1528 This applies to insertions done with
1529 `markdown-electric-backquote'."
1530 :group 'markdown
1531 :type 'boolean)
1533 (defcustom markdown-edit-code-block-default-mode 'normal-mode
1534 "Default mode to use for editing code blocks.
1535 This mode is used when automatic detection fails, such as for GFM
1536 code blocks with no language specified."
1537 :group 'markdown
1538 :type 'symbol
1539 :package-version '(markdown-mode . "2.4"))
1541 (defcustom markdown-gfm-uppercase-checkbox nil
1542 "If non-nil, use [X] for completed checkboxes, [x] otherwise."
1543 :group 'markdown
1544 :type 'boolean
1545 :safe 'booleanp)
1547 (defcustom markdown-hide-urls nil
1548 "Hide URLs of inline links and reference tags of reference links.
1549 Such URLs will be replaced by a single customizable
1550 character, defined by `markdown-url-compose-char', but are still part
1551 of the buffer. Links can be edited interactively with
1552 \\[markdown-insert-link] or, for example, by deleting the final
1553 parenthesis to remove the invisibility property. You can also
1554 hover your mouse pointer over the link text to see the URL.
1555 Set this to a non-nil value to turn this feature on by default.
1556 You can interactively set the value of this variable by calling
1557 `markdown-toggle-url-hiding', pressing \\[markdown-toggle-url-hiding],
1558 or from the menu Markdown > Links & Images menu."
1559 :group 'markdown
1560 :type 'boolean
1561 :safe 'booleanp
1562 :package-version '(markdown-mode . "2.3"))
1563 (make-variable-buffer-local 'markdown-hide-urls)
1565 (defcustom markdown-translate-filename-function #'identity
1566 "Function to use to translate filenames when following links.
1567 \\<markdown-mode-map>\\[markdown-follow-thing-at-point] and \\[markdown-follow-link-at-point]
1568 call this function with the filename as only argument whenever
1569 they encounter a filename (instead of a URL) to be visited and
1570 use its return value instead of the filename in the link. For
1571 example, if absolute filenames are actually relative to a server
1572 root directory, you can set
1573 `markdown-translate-filename-function' to a function that
1574 prepends the root directory to the given filename."
1575 :group 'markdown
1576 :type 'function
1577 :risky t
1578 :package-version '(markdown-mode . "2.4"))
1580 (defcustom markdown-max-image-size nil
1581 "Maximum width and height for displayed inline images.
1582 This variable may be nil or a cons cell (MAX-WIDTH . MAX-HEIGHT).
1583 When nil, use the actual size. Otherwise, use ImageMagick to
1584 resize larger images to be of the given maximum dimensions. This
1585 requires Emacs to be built with ImageMagick support."
1586 :group 'markdown
1587 :package-version '(markdown-mode . "2.4")
1588 :type '(choice
1589 (const :tag "Use actual image width" nil)
1590 (cons (choice (sexp :tag "Maximum width in pixels")
1591 (const :tag "No maximum width" nil))
1592 (choice (sexp :tag "Maximum height in pixels")
1593 (const :tag "No maximum height" nil)))))
1596 ;;; Regular Expressions =======================================================
1598 (defconst markdown-regex-comment-start
1599 "<!--"
1600 "Regular expression matches HTML comment opening.")
1602 (defconst markdown-regex-comment-end
1603 "--[ \t]*>"
1604 "Regular expression matches HTML comment closing.")
1606 (defconst markdown-regex-link-inline
1607 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)\\((\\)\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?\\()\\)"
1608 "Regular expression for a [text](file) or an image link ![text](file).
1609 Group 1 matches the leading exclamation point (optional).
1610 Group 2 matches the opening square bracket.
1611 Group 3 matches the text inside the square brackets.
1612 Group 4 matches the closing square bracket.
1613 Group 5 matches the opening parenthesis.
1614 Group 6 matches the URL.
1615 Group 7 matches the title (optional).
1616 Group 8 matches the closing parenthesis.")
1618 (defconst markdown-regex-link-reference
1619 "\\(!\\)?\\(\\[\\)\\([^]^][^]]*\\|\\)\\(\\]\\)[ ]?\\(\\[\\)\\([^]]*?\\)\\(\\]\\)"
1620 "Regular expression for a reference link [text][id].
1621 Group 1 matches the leading exclamation point (optional).
1622 Group 2 matches the opening square bracket for the link text.
1623 Group 3 matches the text inside the square brackets.
1624 Group 4 matches the closing square bracket for the link text.
1625 Group 5 matches the opening square bracket for the reference label.
1626 Group 6 matches the reference label.
1627 Group 7 matches the closing square bracket for the reference label.")
1629 (defconst markdown-regex-reference-definition
1630 "^ \\{0,3\\}\\(\\[\\)\\([^]\n]+?\\)\\(\\]\\)\\(:\\)\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1631 "Regular expression for a reference definition.
1632 Group 1 matches the opening square bracket.
1633 Group 2 matches the reference label.
1634 Group 3 matches the closing square bracket.
1635 Group 4 matches the colon.
1636 Group 5 matches the URL.
1637 Group 6 matches the title attribute (optional).")
1639 (defconst markdown-regex-footnote
1640 "\\(\\[\\^\\)\\(.+?\\)\\(\\]\\)"
1641 "Regular expression for a footnote marker [^fn].
1642 Group 1 matches the opening square bracket and carat.
1643 Group 2 matches only the label, without the surrounding markup.
1644 Group 3 matches the closing square bracket.")
1646 (defconst markdown-regex-header
1647 "^\\(?:\\([^\r\n\t -].*\\)\n\\(?:\\(=+\\)\\|\\(-+\\)\\)\\|\\(#+[ \t]+\\)\\(.*?\\)\\([ \t]*#*\\)\\)$"
1648 "Regexp identifying Markdown headings.
1649 Group 1 matches the text of a setext heading.
1650 Group 2 matches the underline of a level-1 setext heading.
1651 Group 3 matches the underline of a level-2 setext heading.
1652 Group 4 matches the opening hash marks of an atx heading and whitespace.
1653 Group 5 matches the text, without surrounding whitespace, of an atx heading.
1654 Group 6 matches the closing whitespace and hash marks of an atx heading.")
1656 (defconst markdown-regex-header-setext
1657 "^\\([^\r\n\t -].*\\)\n\\(=+\\|-+\\)$"
1658 "Regular expression for generic setext-style (underline) headers.")
1660 (defconst markdown-regex-header-atx
1661 "^\\(#+\\)[ \t]+\\(.*?\\)[ \t]*\\(#*\\)$"
1662 "Regular expression for generic atx-style (hash mark) headers.")
1664 (defconst markdown-regex-hr
1665 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1666 "Regular expression for matching Markdown horizontal rules.")
1668 (defconst markdown-regex-code
1669 "\\(?:\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(?:.\\|\n[^\n]\\)*?[^`]\\)\\(\\2\\)\\)\\(?:[^`]\\|\\'\\)"
1670 "Regular expression for matching inline code fragments.
1672 Group 1 matches the entire code fragment including the backquotes.
1673 Group 2 matches the opening backquotes.
1674 Group 3 matches the code fragment itself, without backquotes.
1675 Group 4 matches the closing backquotes.
1677 The leading, unnumbered group ensures that the leading backquote
1678 character is not escaped.
1679 The last group, also unnumbered, requires that the character
1680 following the code fragment is not a backquote.
1681 Note that \\(?:.\\|\n[^\n]\\) matches any character, including newlines,
1682 but not two newlines in a row.")
1684 (defconst markdown-regex-kbd
1685 "\\(<kbd>\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(</kbd>\\)"
1686 "Regular expression for matching <kbd> tags.
1687 Groups 1 and 3 match the opening and closing tags.
1688 Group 2 matches the key sequence.")
1690 (defconst markdown-regex-gfm-code-block-open
1691 "^[[:blank:]]*\\(```\\)\\([[:blank:]]*{?[[:blank:]]*\\)\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$"
1692 "Regular expression matching opening of GFM code blocks.
1693 Group 1 matches the opening three backquotes and any following whitespace.
1694 Group 2 matches the opening brace (optional) and surrounding whitespace.
1695 Group 3 matches the language identifier (optional).
1696 Group 4 matches the info string (optional).
1697 Group 5 matches the closing brace (optional), whitespace, and newline.
1698 Groups need to agree with `markdown-regex-tilde-fence-begin'.")
1700 (defconst markdown-regex-gfm-code-block-close
1701 "^[[:blank:]]*\\(```\\)\\(\\s *?\\)$"
1702 "Regular expression matching closing of GFM code blocks.
1703 Group 1 matches the closing three backquotes.
1704 Group 2 matches any whitespace and the final newline.")
1706 (defconst markdown-regex-pre
1707 "^\\( \\|\t\\).*$"
1708 "Regular expression for matching preformatted text sections.")
1710 (defconst markdown-regex-list
1711 "^\\([ \t]*\\)\\([0-9#]+\\.\\|[\\*\\+:-]\\)\\([ \t]+\\)"
1712 "Regular expression for matching list items.")
1714 (defconst markdown-regex-bold
1715 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1716 "Regular expression for matching bold text.
1717 Group 1 matches the character before the opening asterisk or
1718 underscore, if any, ensuring that it is not a backslash escape.
1719 Group 2 matches the entire expression, including delimiters.
1720 Groups 3 and 5 matches the opening and closing delimiters.
1721 Group 4 matches the text inside the delimiters.")
1723 (defconst markdown-regex-italic
1724 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1725 "Regular expression for matching italic text.
1726 The leading unnumbered matches the character before the opening
1727 asterisk or underscore, if any, ensuring that it is not a
1728 backslash escape.
1729 Group 1 matches the entire expression, including delimiters.
1730 Groups 2 and 4 matches the opening and closing delimiters.
1731 Group 3 matches the text inside the delimiters.")
1733 (defconst markdown-regex-strike-through
1734 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1735 "Regular expression for matching strike-through text.
1736 Group 1 matches the character before the opening tilde, if any,
1737 ensuring that it is not a backslash escape.
1738 Group 2 matches the entire expression, including delimiters.
1739 Groups 3 and 5 matches the opening and closing delimiters.
1740 Group 4 matches the text inside the delimiters.")
1742 (defconst markdown-regex-gfm-italic
1743 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1744 "Regular expression for matching italic text in GitHub Flavored Markdown.
1745 Underscores in words are not treated as special.
1746 Group 1 matches the entire expression, including delimiters.
1747 Groups 2 and 4 matches the opening and closing delimiters.
1748 Group 3 matches the text inside the delimiters.")
1750 (defconst markdown-regex-blockquote
1751 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1752 "Regular expression for matching blockquote lines.
1753 Also accounts for a potential capital letter preceding the angle
1754 bracket, for use with Leanpub blocks (asides, warnings, info
1755 blocks, etc.).
1756 Group 1 matches the leading angle bracket.
1757 Group 2 matches the separating whitespace.
1758 Group 3 matches the text.")
1760 (defconst markdown-regex-line-break
1761 "[^ \n\t][ \t]*\\( \\)$"
1762 "Regular expression for matching line breaks.")
1764 (defconst markdown-regex-wiki-link
1765 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1766 "Regular expression for matching wiki links.
1767 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1768 wiki links of the form [[PageName|link text]].
1769 The meanings of the first and second components depend
1770 on the value of `markdown-wiki-link-alias-first'.
1772 Group 1 matches the entire link.
1773 Group 2 matches the opening square brackets.
1774 Group 3 matches the first component of the wiki link.
1775 Group 4 matches the pipe separator, when present.
1776 Group 5 matches the second component of the wiki link, when present.
1777 Group 6 matches the closing square brackets.")
1779 (defconst markdown-regex-uri
1780 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1781 "Regular expression for matching inline URIs.")
1783 (defconst markdown-regex-angle-uri
1784 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1785 "Regular expression for matching inline URIs in angle brackets.")
1787 (defconst markdown-regex-email
1788 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1789 "Regular expression for matching inline email addresses.")
1791 (defsubst markdown-make-regex-link-generic ()
1792 "Make regular expression for matching any recognized link."
1793 (concat "\\(?:" markdown-regex-link-inline
1794 (when markdown-enable-wiki-links
1795 (concat "\\|" markdown-regex-wiki-link))
1796 "\\|" markdown-regex-link-reference
1797 "\\|" markdown-regex-angle-uri "\\)"))
1799 (defconst markdown-regex-gfm-checkbox
1800 " \\(\\[[ xX]\\]\\) "
1801 "Regular expression for matching GFM checkboxes.
1802 Group 1 matches the text to become a button.")
1804 (defconst markdown-regex-block-separator
1805 "\n[\n\t\f ]*\n"
1806 "Regular expression for matching block boundaries.")
1808 (defconst markdown-regex-block-separator-noindent
1809 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1810 "Regexp for block separators before lines with no indentation.")
1812 (defconst markdown-regex-math-inline-single
1813 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1814 "Regular expression for itex $..$ math mode expressions.
1815 Groups 1 and 3 match the opening and closing dollar signs.
1816 Group 2 matches the mathematical expression contained within.")
1818 (defconst markdown-regex-math-inline-double
1819 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1820 "Regular expression for itex $$..$$ math mode expressions.
1821 Groups 1 and 3 match opening and closing dollar signs.
1822 Group 2 matches the mathematical expression contained within.")
1824 (defconst markdown-regex-math-display
1825 (rx line-start (* blank)
1826 (group (group (repeat 1 2 "\\")) "[")
1827 (group (*? anything))
1828 (group (backref 2) "]")
1829 line-end)
1830 "Regular expression for \[..\] or \\[..\\] display math.
1831 Groups 1 and 4 match the opening and closing markup.
1832 Group 3 matches the mathematical expression contained within.
1833 Group 2 matches the opening slashes, and is used internally to
1834 match the closing slashes.")
1836 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1837 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1838 END-OF-LINE is the regexp construct to indicate end of line; $ if
1839 missing."
1840 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1841 (or end-of-line "$")))
1843 (defconst markdown-regex-tilde-fence-begin
1844 (markdown-make-tilde-fence-regex
1845 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1846 "Regular expression for matching tilde-fenced code blocks.
1847 Group 1 matches the opening tildes.
1848 Group 2 matches (optional) opening brace and surrounding whitespace.
1849 Group 3 matches the language identifier (optional).
1850 Group 4 matches the info string (optional).
1851 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1852 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1854 (defconst markdown-regex-declarative-metadata
1855 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1856 "Regular expression for matching declarative metadata statements.
1857 This matches MultiMarkdown metadata as well as YAML and TOML
1858 assignments such as the following:
1860 variable: value
1864 variable = value")
1866 (defconst markdown-regex-pandoc-metadata
1867 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1868 "Regular expression for matching Pandoc metadata.")
1870 (defconst markdown-regex-yaml-metadata-border
1871 "\\(-\\{3\\}\\)$"
1872 "Regular expression for matching YAML metadata.")
1874 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1875 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1876 "Regular expression for matching YAML metadata end borders.")
1878 (defsubst markdown-get-yaml-metadata-start-border ()
1879 "Return YAML metadata start border depending upon whether Pandoc is used."
1880 (concat
1881 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1882 markdown-regex-yaml-metadata-border))
1884 (defsubst markdown-get-yaml-metadata-end-border (_)
1885 "Return YAML metadata end border depending upon whether Pandoc is used."
1886 (if markdown-use-pandoc-style-yaml-metadata
1887 markdown-regex-yaml-pandoc-metadata-end-border
1888 markdown-regex-yaml-metadata-border))
1890 (defconst markdown-regex-inline-attributes
1891 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1892 "Regular expression for matching inline identifiers or attribute lists.
1893 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1895 (defconst markdown-regex-leanpub-sections
1896 (concat
1897 "^\\({\\)\\("
1898 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1899 "\\)\\(}\\)[ \t]*\n")
1900 "Regular expression for Leanpub section markers and related syntax.")
1902 (defconst markdown-regex-sub-superscript
1903 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1904 "The regular expression matching a sub- or superscript.
1905 The leading un-numbered group matches the character before the
1906 opening tilde or carat, if any, ensuring that it is not a
1907 backslash escape, carat, or tilde.
1908 Group 1 matches the entire expression, including markup.
1909 Group 2 matches the opening markup--a tilde or carat.
1910 Group 3 matches the text inside the delimiters.
1911 Group 4 matches the closing markup--a tilde or carat.")
1913 (defconst markdown-regex-include
1914 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1915 "Regular expression matching common forms of include syntax.
1916 Marked 2, Leanpub, and other processors support some of these forms:
1918 <<[sections/section1.md]
1919 <<(folder/filename)
1920 <<[Code title](folder/filename)
1921 <<{folder/raw_file.html}
1923 Group 1 matches the opening two angle brackets.
1924 Groups 2-4 match the opening square bracket, the text inside,
1925 and the closing square bracket, respectively.
1926 Groups 5-7 match the opening parenthesis, the text inside, and
1927 the closing parenthesis.
1928 Groups 8-10 match the opening brace, the text inside, and the brace.")
1930 (defconst markdown-regex-pandoc-inline-footnote
1931 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1932 "Regular expression for Pandoc inline footnote^[footnote text].
1933 Group 1 matches the opening caret.
1934 Group 2 matches the opening square bracket.
1935 Group 3 matches the footnote text, without the surrounding markup.
1936 Group 4 matches the closing square bracket.")
1938 (defconst markdown-regex-html-attr
1939 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1940 "Regular expression for matching HTML attributes and values.
1941 Group 1 matches the attribute name.
1942 Group 2 matches the following whitespace, equals sign, and value, if any.
1943 Group 3 matches the equals sign, if any.
1944 Group 4 matches single-, double-, or un-quoted attribute values.")
1946 (defconst markdown-regex-html-tag
1947 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1948 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1949 "Regular expression for matching HTML tags.
1950 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1951 Group 2 matches the tag name.
1952 Group 3 matches all attributes and whitespace following the tag name.")
1954 (defconst markdown-regex-html-entity
1955 "\\(&#?[[:alnum:]]+;\\)"
1956 "Regular expression for matching HTML entities.")
1959 ;;; Syntax ====================================================================
1961 (defsubst markdown-in-comment-p (&optional pos)
1962 "Return non-nil if POS is in a comment.
1963 If POS is not given, use point instead."
1964 (nth 4 (syntax-ppss pos)))
1966 (defun markdown-syntax-propertize-extend-region (start end)
1967 "Extend START to END region to include an entire block of text.
1968 This helps improve syntax analysis for block constructs.
1969 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1970 Function is called repeatedly until it returns nil. For details, see
1971 `syntax-propertize-extend-region-functions'."
1972 (save-match-data
1973 (save-excursion
1974 (let* ((new-start (progn (goto-char start)
1975 (skip-chars-forward "\n")
1976 (if (re-search-backward "\n\n" nil t)
1977 (min start (match-end 0))
1978 (point-min))))
1979 (new-end (progn (goto-char end)
1980 (skip-chars-backward "\n")
1981 (if (re-search-forward "\n\n" nil t)
1982 (max end (match-beginning 0))
1983 (point-max))))
1984 (code-match (markdown-code-block-at-pos new-start))
1985 (new-start (or (and code-match (cl-first code-match)) new-start))
1986 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1987 (new-end (or (and code-match (cl-second code-match)) new-end)))
1988 (unless (and (eq new-start start) (eq new-end end))
1989 (cons new-start (min new-end (point-max))))))))
1991 (defun markdown-font-lock-extend-region-function (start end _)
1992 "Used in `jit-lock-after-change-extend-region-functions'.
1993 Delegates to `markdown-syntax-propertize-extend-region'. START
1994 and END are the previous region to refontify."
1995 (let ((res (markdown-syntax-propertize-extend-region start end)))
1996 (when res
1997 ;; syntax-propertize-function is not called when character at
1998 ;; (point-max) is deleted, but font-lock-extend-region-functions
1999 ;; are called. Force a syntax property update in that case.
2000 (when (= end (point-max))
2001 ;; This function is called in a buffer modification hook.
2002 ;; `markdown-syntax-propertize' doesn't save the match data,
2003 ;; so we have to do it here.
2004 (save-match-data
2005 (markdown-syntax-propertize (car res) (cdr res))))
2006 (setq jit-lock-start (car res)
2007 jit-lock-end (cdr res)))))
2009 (defun markdown-syntax-propertize-pre-blocks (start end)
2010 "Match preformatted text blocks from START to END."
2011 (save-excursion
2012 (goto-char start)
2013 (let ((levels (markdown-calculate-list-levels))
2014 indent pre-regexp close-regexp open close)
2015 (while (and (< (point) end) (not close))
2016 ;; Search for a region with sufficient indentation
2017 (if (null levels)
2018 (setq indent 1)
2019 (setq indent (1+ (length levels))))
2020 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
2021 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
2023 (cond
2024 ;; If not at the beginning of a line, move forward
2025 ((not (bolp)) (forward-line))
2026 ;; Move past blank lines
2027 ((markdown-cur-line-blank) (forward-line))
2028 ;; At headers and horizontal rules, reset levels
2029 ((markdown-new-baseline) (forward-line) (setq levels nil))
2030 ;; If the current line has sufficient indentation, mark out pre block
2031 ;; The opening should be preceded by a blank line.
2032 ((and (looking-at pre-regexp)
2033 (markdown-prev-line-blank-p))
2034 (setq open (match-beginning 0))
2035 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank))
2036 (not (eobp)))
2037 (forward-line))
2038 (skip-syntax-backward "-")
2039 (setq close (point)))
2040 ;; If current line has a list marker, update levels, move to end of block
2041 ((looking-at markdown-regex-list)
2042 (setq levels (markdown-update-list-levels
2043 (match-string 2) (current-indentation) levels))
2044 (markdown-end-of-text-block))
2045 ;; If this is the end of the indentation level, adjust levels accordingly.
2046 ;; Only match end of indentation level if levels is not the empty list.
2047 ((and (car levels) (looking-at-p close-regexp))
2048 (setq levels (markdown-update-list-levels
2049 nil (current-indentation) levels))
2050 (markdown-end-of-text-block))
2051 (t (markdown-end-of-text-block))))
2053 (when (and open close)
2054 ;; Set text property data
2055 (put-text-property open close 'markdown-pre (list open close))
2056 ;; Recursively search again
2057 (markdown-syntax-propertize-pre-blocks (point) end)))))
2059 (defconst markdown-fenced-block-pairs
2060 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
2061 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
2062 markdown-fenced-code)
2063 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
2064 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2065 markdown-yaml-metadata-section)
2066 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2067 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2068 markdown-gfm-code))
2069 "Mapping of regular expressions to \"fenced-block\" constructs.
2070 These constructs are distinguished by having a distinctive start
2071 and end pattern, both of which take up an entire line of text,
2072 but no special pattern to identify text within the fenced
2073 blocks (unlike blockquotes and indented-code sections).
2075 Each element within this list takes the form:
2077 ((START-REGEX-OR-FUN START-PROPERTY)
2078 (END-REGEX-OR-FUN END-PROPERTY)
2079 MIDDLE-PROPERTY)
2081 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2082 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2083 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2084 which is the length of the first group of the START-REGEX-OR-FUN match, which
2085 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2086 evaluate these into \"real\" regexps.
2088 The *-PROPERTY elements are the text properties applied to each part of the
2089 block construct when it is matched using
2090 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2091 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2092 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2093 `match-data' when the regexp was matched to the text. In the case of
2094 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2095 begin and end set to the edges of the \"middle\" text. This makes fontification
2096 easier.")
2098 (defun markdown-text-property-at-point (prop)
2099 (get-text-property (point) prop))
2101 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2102 (cond ((functionp object)
2103 (if arg (funcall object arg) (funcall object)))
2104 ((stringp object) object)
2105 (t (error "Object cannot be turned into regex"))))
2107 (defsubst markdown-get-start-fence-regexp ()
2108 "Return regexp to find all \"start\" sections of fenced block constructs.
2109 Which construct is actually contained in the match must be found separately."
2110 (mapconcat
2111 #'identity
2112 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2113 markdown-fenced-block-pairs)
2114 "\\|"))
2116 (defun markdown-get-fenced-block-begin-properties ()
2117 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2119 (defun markdown-get-fenced-block-end-properties ()
2120 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2122 (defun markdown-get-fenced-block-middle-properties ()
2123 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2125 (defun markdown-find-previous-prop (prop &optional lim)
2126 "Find previous place where property PROP is non-nil, up to LIM.
2127 Return a cons of (pos . property). pos is point if point contains
2128 non-nil PROP."
2129 (let ((res
2130 (if (get-text-property (point) prop) (point)
2131 (previous-single-property-change
2132 (point) prop nil (or lim (point-min))))))
2133 (when (and (not (get-text-property res prop))
2134 (> res (point-min))
2135 (get-text-property (1- res) prop))
2136 (cl-decf res))
2137 (when (and res (get-text-property res prop)) (cons res prop))))
2139 (defun markdown-find-next-prop (prop &optional lim)
2140 "Find next place where property PROP is non-nil, up to LIM.
2141 Return a cons of (POS . PROPERTY) where POS is point if point
2142 contains non-nil PROP."
2143 (let ((res
2144 (if (get-text-property (point) prop) (point)
2145 (next-single-property-change
2146 (point) prop nil (or lim (point-max))))))
2147 (when (and res (get-text-property res prop)) (cons res prop))))
2149 (defun markdown-min-of-seq (map-fn seq)
2150 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2151 (cl-loop for el in seq
2152 with min = 1.0e+INF ; infinity
2153 with min-el = nil
2154 do (let ((res (funcall map-fn el)))
2155 (when (< res min)
2156 (setq min res)
2157 (setq min-el el)))
2158 finally return min-el))
2160 (defun markdown-max-of-seq (map-fn seq)
2161 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2162 (cl-loop for el in seq
2163 with max = -1.0e+INF ; negative infinity
2164 with max-el = nil
2165 do (let ((res (funcall map-fn el)))
2166 (when (and res (> res max))
2167 (setq max res)
2168 (setq max-el el)))
2169 finally return max-el))
2171 (defun markdown-find-previous-block ()
2172 "Find previous block.
2173 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2174 unable to propertize the entire block, but was able to propertize the beginning
2175 of the block. If so, return a cons of (pos . property) where the beginning of
2176 the block was propertized."
2177 (let ((start-pt (point))
2178 (closest-open
2179 (markdown-max-of-seq
2180 #'car
2181 (cl-remove-if
2182 #'null
2183 (cl-mapcar
2184 #'markdown-find-previous-prop
2185 (markdown-get-fenced-block-begin-properties))))))
2186 (when closest-open
2187 (let* ((length-of-open-match
2188 (let ((match-d
2189 (get-text-property (car closest-open) (cdr closest-open))))
2190 (- (cl-fourth match-d) (cl-third match-d))))
2191 (end-regexp
2192 (markdown-maybe-funcall-regexp
2193 (cl-caadr
2194 (cl-find-if
2195 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2196 markdown-fenced-block-pairs))
2197 length-of-open-match))
2198 (end-prop-loc
2199 (save-excursion
2200 (save-match-data
2201 (goto-char (car closest-open))
2202 (and (re-search-forward end-regexp start-pt t)
2203 (match-beginning 0))))))
2204 (and (not end-prop-loc) closest-open)))))
2206 (defun markdown-get-fenced-block-from-start (prop)
2207 "Return limits of an enclosing fenced block from its start, using PROP.
2208 Return value is a list usable as `match-data'."
2209 (catch 'no-rest-of-block
2210 (let* ((correct-entry
2211 (cl-find-if
2212 (lambda (entry) (eq (cl-cadar entry) prop))
2213 markdown-fenced-block-pairs))
2214 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2215 (middle-prop (cl-third correct-entry))
2216 (end-prop (cl-cadadr correct-entry))
2217 (end-of-end
2218 (save-excursion
2219 (goto-char (match-end 0)) ; end of begin
2220 (unless (eobp) (forward-char))
2221 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2222 (if (not mid-prop-v) ; no middle
2223 (progn
2224 ;; try to find end by advancing one
2225 (let ((end-prop-v
2226 (markdown-text-property-at-point end-prop)))
2227 (if end-prop-v (cl-second end-prop-v)
2228 (throw 'no-rest-of-block nil))))
2229 (set-match-data mid-prop-v)
2230 (goto-char (match-end 0)) ; end of middle
2231 (beginning-of-line) ; into end
2232 (cl-second (markdown-text-property-at-point end-prop)))))))
2233 (list begin-of-begin end-of-end))))
2235 (defun markdown-get-fenced-block-from-middle (prop)
2236 "Return limits of an enclosing fenced block from its middle, using PROP.
2237 Return value is a list usable as `match-data'."
2238 (let* ((correct-entry
2239 (cl-find-if
2240 (lambda (entry) (eq (cl-third entry) prop))
2241 markdown-fenced-block-pairs))
2242 (begin-prop (cl-cadar correct-entry))
2243 (begin-of-begin
2244 (save-excursion
2245 (goto-char (match-beginning 0))
2246 (unless (bobp) (forward-line -1))
2247 (beginning-of-line)
2248 (cl-first (markdown-text-property-at-point begin-prop))))
2249 (end-prop (cl-cadadr correct-entry))
2250 (end-of-end
2251 (save-excursion
2252 (goto-char (match-end 0))
2253 (beginning-of-line)
2254 (cl-second (markdown-text-property-at-point end-prop)))))
2255 (list begin-of-begin end-of-end)))
2257 (defun markdown-get-fenced-block-from-end (prop)
2258 "Return limits of an enclosing fenced block from its end, using PROP.
2259 Return value is a list usable as `match-data'."
2260 (let* ((correct-entry
2261 (cl-find-if
2262 (lambda (entry) (eq (cl-cadadr entry) prop))
2263 markdown-fenced-block-pairs))
2264 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2265 (middle-prop (cl-third correct-entry))
2266 (begin-prop (cl-cadar correct-entry))
2267 (begin-of-begin
2268 (save-excursion
2269 (goto-char (match-beginning 0)) ; beginning of end
2270 (unless (bobp) (backward-char)) ; into middle
2271 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2272 (if (not mid-prop-v)
2273 (progn
2274 (beginning-of-line)
2275 (cl-first (markdown-text-property-at-point begin-prop)))
2276 (set-match-data mid-prop-v)
2277 (goto-char (match-beginning 0)) ; beginning of middle
2278 (unless (bobp) (forward-line -1)) ; into beginning
2279 (beginning-of-line)
2280 (cl-first (markdown-text-property-at-point begin-prop)))))))
2281 (list begin-of-begin end-of-end)))
2283 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2284 "Get \"fake\" match data for block enclosing POS.
2285 Returns fake match data which encloses the start, middle, and end
2286 of the block construct enclosing POS, if it exists. Used in
2287 `markdown-code-block-at-pos'."
2288 (save-excursion
2289 (when pos (goto-char pos))
2290 (beginning-of-line)
2291 (car
2292 (cl-remove-if
2293 #'null
2294 (cl-mapcar
2295 (lambda (fun-and-prop)
2296 (cl-destructuring-bind (fun prop) fun-and-prop
2297 (when prop
2298 (save-match-data
2299 (set-match-data (markdown-text-property-at-point prop))
2300 (funcall fun prop)))))
2301 `((markdown-get-fenced-block-from-start
2302 ,(cl-find-if
2303 #'markdown-text-property-at-point
2304 (markdown-get-fenced-block-begin-properties)))
2305 (markdown-get-fenced-block-from-middle
2306 ,(cl-find-if
2307 #'markdown-text-property-at-point
2308 (markdown-get-fenced-block-middle-properties)))
2309 (markdown-get-fenced-block-from-end
2310 ,(cl-find-if
2311 #'markdown-text-property-at-point
2312 (markdown-get-fenced-block-end-properties)))))))))
2314 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2315 "Get match for REG up to END, if exists, and propertize appropriately.
2316 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2317 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2318 (when (re-search-forward reg end t)
2319 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2320 (close-end (match-end 0)) ; End of closing line.
2321 (close-data (match-data t))) ; Match data for closing line.
2322 ;; Propertize middle section of fenced block.
2323 (put-text-property middle-begin close-begin
2324 (cl-third fence-spec)
2325 (list middle-begin close-begin))
2326 ;; If the block is a YAML block, propertize the declarations inside
2327 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
2328 ;; Propertize closing line of fenced block.
2329 (put-text-property close-begin close-end
2330 (cl-cadadr fence-spec) close-data))))
2332 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2333 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2334 If unable to propertize an entire block (if the start of a block is within START
2335 and END, but the end of the block is not), propertize the start section of a
2336 block, then in a subsequent call propertize both middle and end by finding the
2337 start which was previously propertized."
2338 (let ((start-reg (markdown-get-start-fence-regexp)))
2339 (save-excursion
2340 (goto-char start)
2341 ;; start from previous unclosed block, if exists
2342 (let ((prev-begin-block (markdown-find-previous-block)))
2343 (when prev-begin-block
2344 (let* ((correct-entry
2345 (cl-find-if (lambda (entry)
2346 (eq (cdr prev-begin-block) (cl-cadar entry)))
2347 markdown-fenced-block-pairs))
2348 (enclosed-text-start (1+ (car prev-begin-block)))
2349 (start-length
2350 (save-excursion
2351 (goto-char (car prev-begin-block))
2352 (string-match
2353 (markdown-maybe-funcall-regexp
2354 (caar correct-entry))
2355 (buffer-substring
2356 (point-at-bol) (point-at-eol)))
2357 (- (match-end 1) (match-beginning 1))))
2358 (end-reg (markdown-maybe-funcall-regexp
2359 (cl-caadr correct-entry) start-length)))
2360 (markdown-propertize-end-match
2361 end-reg end correct-entry enclosed-text-start))))
2362 ;; find all new blocks within region
2363 (while (re-search-forward start-reg end t)
2364 ;; we assume the opening constructs take up (only) an entire line,
2365 ;; so we re-check the current line
2366 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2367 ;; find entry in `markdown-fenced-block-pairs' corresponding
2368 ;; to regex which was matched
2369 (correct-entry
2370 (cl-find-if
2371 (lambda (fenced-pair)
2372 (string-match-p
2373 (markdown-maybe-funcall-regexp (caar fenced-pair))
2374 cur-line))
2375 markdown-fenced-block-pairs))
2376 (enclosed-text-start
2377 (save-excursion (1+ (point-at-eol))))
2378 (end-reg
2379 (markdown-maybe-funcall-regexp
2380 (cl-caadr correct-entry)
2381 (if (and (match-beginning 1) (match-end 1))
2382 (- (match-end 1) (match-beginning 1))
2383 0))))
2384 ;; get correct match data
2385 (save-excursion
2386 (beginning-of-line)
2387 (re-search-forward
2388 (markdown-maybe-funcall-regexp (caar correct-entry))
2389 (point-at-eol)))
2390 ;; mark starting, even if ending is outside of region
2391 (put-text-property (match-beginning 0) (match-end 0)
2392 (cl-cadar correct-entry) (match-data t))
2393 (markdown-propertize-end-match
2394 end-reg end correct-entry enclosed-text-start))))))
2396 (defun markdown-syntax-propertize-blockquotes (start end)
2397 "Match blockquotes from START to END."
2398 (save-excursion
2399 (goto-char start)
2400 (while (and (re-search-forward markdown-regex-blockquote end t)
2401 (not (markdown-code-block-at-pos (match-beginning 0))))
2402 (put-text-property (match-beginning 0) (match-end 0)
2403 'markdown-blockquote
2404 (match-data t)))))
2406 (defun markdown-syntax-propertize-hrs (start end)
2407 "Match horizontal rules from START to END."
2408 (save-excursion
2409 (goto-char start)
2410 (while (re-search-forward markdown-regex-hr end t)
2411 (unless (or (markdown-on-heading-p)
2412 (markdown-code-block-at-point-p))
2413 (put-text-property (match-beginning 0) (match-end 0)
2414 'markdown-hr
2415 (match-data t))))))
2417 (defun markdown-syntax-propertize-yaml-metadata (start end)
2418 "Propertize elements inside YAML metadata blocks from START to END.
2419 Assumes region from START and END is already known to be the interior
2420 region of a YAML metadata block as propertized by
2421 `markdown-syntax-propertize-fenced-block-constructs'."
2422 (save-excursion
2423 (goto-char start)
2424 (cl-loop
2425 while (re-search-forward markdown-regex-declarative-metadata end t)
2426 do (progn
2427 (put-text-property (match-beginning 1) (match-end 1)
2428 'markdown-metadata-key (match-data t))
2429 (put-text-property (match-beginning 2) (match-end 2)
2430 'markdown-metadata-markup (match-data t))
2431 (put-text-property (match-beginning 3) (match-end 3)
2432 'markdown-metadata-value (match-data t))))))
2434 (defun markdown-syntax-propertize-headings (start end)
2435 "Match headings of type SYMBOL with REGEX from START to END."
2436 (goto-char start)
2437 (while (re-search-forward markdown-regex-header end t)
2438 (unless (markdown-code-block-at-pos (match-beginning 0))
2439 (put-text-property
2440 (match-beginning 0) (match-end 0) 'markdown-heading
2441 (match-data t))
2442 (put-text-property
2443 (match-beginning 0) (match-end 0)
2444 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2445 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2446 (t (let ((atx-level (length (markdown-trim-whitespace
2447 (match-string-no-properties 4)))))
2448 (intern (format "markdown-heading-%d-atx" atx-level)))))
2449 (match-data t)))))
2451 (defun markdown-syntax-propertize-comments (start end)
2452 "Match HTML comments from the START to END."
2453 (let* ((in-comment (markdown-in-comment-p)))
2454 (goto-char start)
2455 (cond
2456 ;; Comment start
2457 ((and (not in-comment)
2458 (re-search-forward markdown-regex-comment-start end t)
2459 (not (markdown-inline-code-at-point-p))
2460 (not (markdown-code-block-at-point-p)))
2461 (let ((open-beg (match-beginning 0)))
2462 (put-text-property open-beg (1+ open-beg)
2463 'syntax-table (string-to-syntax "<"))
2464 (markdown-syntax-propertize-comments
2465 (min (1+ (match-end 0)) end (point-max)) end)))
2466 ;; Comment end
2467 ((and in-comment
2468 (re-search-forward markdown-regex-comment-end end t))
2469 (put-text-property (1- (match-end 0)) (match-end 0)
2470 'syntax-table (string-to-syntax ">"))
2471 (markdown-syntax-propertize-comments
2472 (min (1+ (match-end 0)) end (point-max)) end))
2473 ;; Nothing found
2474 (t nil))))
2476 (defvar markdown--syntax-properties
2477 (list 'markdown-tilde-fence-begin nil
2478 'markdown-tilde-fence-end nil
2479 'markdown-fenced-code nil
2480 'markdown-yaml-metadata-begin nil
2481 'markdown-yaml-metadata-end nil
2482 'markdown-yaml-metadata-section nil
2483 'markdown-gfm-block-begin nil
2484 'markdown-gfm-block-end nil
2485 'markdown-gfm-code nil
2486 'markdown-pre nil
2487 'markdown-blockquote nil
2488 'markdown-hr nil
2489 'markdown-heading nil
2490 'markdown-heading-1-setext nil
2491 'markdown-heading-2-setext nil
2492 'markdown-heading-1-atx nil
2493 'markdown-heading-2-atx nil
2494 'markdown-heading-3-atx nil
2495 'markdown-heading-4-atx nil
2496 'markdown-heading-5-atx nil
2497 'markdown-heading-6-atx nil
2498 'markdown-metadata-key nil
2499 'markdown-metadata-value nil
2500 'markdown-metadata-markup nil)
2501 "Property list of all Markdown syntactic properties.")
2503 (defun markdown-syntax-propertize (start end)
2504 "Function used as `syntax-propertize-function'.
2505 START and END delimit region to propertize."
2506 (with-silent-modifications
2507 (save-excursion
2508 (remove-text-properties start end markdown--syntax-properties)
2509 (markdown-syntax-propertize-fenced-block-constructs start end)
2510 (markdown-syntax-propertize-pre-blocks start end)
2511 (markdown-syntax-propertize-blockquotes start end)
2512 (markdown-syntax-propertize-headings start end)
2513 (markdown-syntax-propertize-hrs start end)
2514 (markdown-syntax-propertize-comments start end))))
2517 ;;; Markup Hiding
2519 (defconst markdown-markup-properties
2520 '(face markdown-markup-face invisible markdown-markup)
2521 "List of properties and values to apply to markup.")
2523 (defconst markdown-language-keyword-properties
2524 '(face markdown-language-keyword-face invisible markdown-markup)
2525 "List of properties and values to apply to code block language names.")
2527 (defconst markdown-language-info-properties
2528 '(face markdown-language-info-face invisible markdown-markup)
2529 "List of properties and values to apply to code block language info strings.")
2531 (defconst markdown-include-title-properties
2532 '(face markdown-link-title-face invisible markdown-markup)
2533 "List of properties and values to apply to included code titles.")
2535 (defcustom markdown-hide-markup nil
2536 "Determines whether markup in the buffer will be hidden.
2537 When set to nil, all markup is displayed in the buffer as it
2538 appears in the file. An exception is when `markdown-hide-urls'
2539 is non-nil.
2540 Set this to a non-nil value to turn this feature on by default.
2541 You can interactively toggle the value of this variable with
2542 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2543 or from the Markdown > Show & Hide menu.
2545 Markup hiding works by adding text properties to positions in the
2546 buffer---either the `invisible' property or the `display' property
2547 in cases where alternative glyphs are used (e.g., list bullets).
2548 This does not, however, affect printing or other output.
2549 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2550 not honor these text properties. For printing, it would be better
2551 to first convert to HTML or PDF (e.g,. using Pandoc)."
2552 :group 'markdown
2553 :type 'boolean
2554 :safe 'booleanp
2555 :package-version '(markdown-mode . "2.3"))
2556 (make-variable-buffer-local 'markdown-hide-markup)
2558 (defun markdown-toggle-markup-hiding (&optional arg)
2559 "Toggle the display or hiding of markup.
2560 With a prefix argument ARG, enable markup hiding if ARG is positive,
2561 and disable it otherwise.
2562 See `markdown-hide-markup' for additional details."
2563 (interactive (list (or current-prefix-arg 'toggle)))
2564 (setq markdown-hide-markup
2565 (if (eq arg 'toggle)
2566 (not markdown-hide-markup)
2567 (> (prefix-numeric-value arg) 0)))
2568 (if markdown-hide-markup
2569 (progn (add-to-invisibility-spec 'markdown-markup)
2570 (message "markdown-mode markup hiding enabled"))
2571 (progn (remove-from-invisibility-spec 'markdown-markup)
2572 (message "markdown-mode markup hiding disabled")))
2573 (markdown-reload-extensions))
2576 ;;; Font Lock =================================================================
2578 (require 'font-lock)
2580 (defvar markdown-italic-face 'markdown-italic-face
2581 "Face name to use for italic text.")
2583 (defvar markdown-bold-face 'markdown-bold-face
2584 "Face name to use for bold text.")
2586 (defvar markdown-strike-through-face 'markdown-strike-through-face
2587 "Face name to use for strike-through text.")
2589 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2590 "Face name to use as a base for header delimiters.")
2592 (defvar markdown-header-rule-face 'markdown-header-rule-face
2593 "Face name to use as a base for header rules.")
2595 (defvar markdown-header-face 'markdown-header-face
2596 "Face name to use as a base for headers.")
2598 (defvar markdown-header-face-1 'markdown-header-face-1
2599 "Face name to use for level-1 headers.")
2601 (defvar markdown-header-face-2 'markdown-header-face-2
2602 "Face name to use for level-2 headers.")
2604 (defvar markdown-header-face-3 'markdown-header-face-3
2605 "Face name to use for level-3 headers.")
2607 (defvar markdown-header-face-4 'markdown-header-face-4
2608 "Face name to use for level-4 headers.")
2610 (defvar markdown-header-face-5 'markdown-header-face-5
2611 "Face name to use for level-5 headers.")
2613 (defvar markdown-header-face-6 'markdown-header-face-6
2614 "Face name to use for level-6 headers.")
2616 (defvar markdown-inline-code-face 'markdown-inline-code-face
2617 "Face name to use for inline code.")
2619 (defvar markdown-list-face 'markdown-list-face
2620 "Face name to use for list markers.")
2622 (defvar markdown-blockquote-face 'markdown-blockquote-face
2623 "Face name to use for blockquote.")
2625 (defvar markdown-pre-face 'markdown-pre-face
2626 "Face name to use for preformatted text.")
2628 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2629 "Face name to use for programming language identifiers.")
2631 (defvar markdown-language-info-face 'markdown-language-info-face
2632 "Face name to use for programming info strings.")
2634 (defvar markdown-link-face 'markdown-link-face
2635 "Face name to use for links.")
2637 (defvar markdown-missing-link-face 'markdown-missing-link-face
2638 "Face name to use for links where the linked file does not exist.")
2640 (defvar markdown-reference-face 'markdown-reference-face
2641 "Face name to use for reference.")
2643 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2644 "Face name to use for footnote markers.")
2646 (defvar markdown-url-face 'markdown-url-face
2647 "Face name to use for URLs.")
2649 (defvar markdown-link-title-face 'markdown-link-title-face
2650 "Face name to use for reference link titles.")
2652 (defvar markdown-line-break-face 'markdown-line-break-face
2653 "Face name to use for hard line breaks.")
2655 (defvar markdown-comment-face 'markdown-comment-face
2656 "Face name to use for HTML comments.")
2658 (defvar markdown-math-face 'markdown-math-face
2659 "Face name to use for LaTeX expressions.")
2661 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2662 "Face name to use for metadata keys.")
2664 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2665 "Face name to use for metadata values.")
2667 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2668 "Face name to use for GFM checkboxes.")
2670 (defvar markdown-highlight-face 'markdown-highlight-face
2671 "Face name to use for mouse highlighting.")
2673 (defvar markdown-markup-face 'markdown-markup-face
2674 "Face name to use for markup elements.")
2676 (defgroup markdown-faces nil
2677 "Faces used in Markdown Mode"
2678 :group 'markdown
2679 :group 'faces)
2681 (defface markdown-italic-face
2682 '((t (:inherit italic)))
2683 "Face for italic text."
2684 :group 'markdown-faces)
2686 (defface markdown-bold-face
2687 '((t (:inherit bold)))
2688 "Face for bold text."
2689 :group 'markdown-faces)
2691 (defface markdown-strike-through-face
2692 '((t (:strike-through t)))
2693 "Face for strike-through text."
2694 :group 'markdown-faces)
2696 (defface markdown-markup-face
2697 '((t (:inherit shadow :slant normal :weight normal)))
2698 "Face for markup elements."
2699 :group 'markdown-faces)
2701 (defface markdown-header-rule-face
2702 '((t (:inherit markdown-markup-face)))
2703 "Base face for headers rules."
2704 :group 'markdown-faces)
2706 (defface markdown-header-delimiter-face
2707 '((t (:inherit markdown-markup-face)))
2708 "Base face for headers hash delimiter."
2709 :group 'markdown-faces)
2711 (defface markdown-list-face
2712 '((t (:inherit markdown-markup-face)))
2713 "Face for list item markers."
2714 :group 'markdown-faces)
2716 (defface markdown-blockquote-face
2717 '((t (:inherit font-lock-doc-face)))
2718 "Face for blockquote sections."
2719 :group 'markdown-faces)
2721 (defface markdown-code-face
2722 '((t (:inherit fixed-pitch)))
2723 "Face for inline code, pre blocks, and fenced code blocks.
2724 This may be used, for example, to add a contrasting background to
2725 inline code fragments and code blocks."
2726 :group 'markdown-faces)
2728 (defface markdown-inline-code-face
2729 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2730 "Face for inline code."
2731 :group 'markdown-faces)
2733 (defface markdown-pre-face
2734 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2735 "Face for preformatted text."
2736 :group 'markdown-faces)
2738 (defface markdown-table-face
2739 '((t (:inherit (markdown-code-face))))
2740 "Face for tables."
2741 :group 'markdown-faces)
2743 (defface markdown-language-keyword-face
2744 '((t (:inherit font-lock-type-face)))
2745 "Face for programming language identifiers."
2746 :group 'markdown-faces)
2748 (defface markdown-language-info-face
2749 '((t (:inherit font-lock-string-face)))
2750 "Face for programming language info strings."
2751 :group 'markdown-faces)
2753 (defface markdown-link-face
2754 '((t (:inherit link)))
2755 "Face for links."
2756 :group 'markdown-faces)
2758 (defface markdown-missing-link-face
2759 '((t (:inherit font-lock-warning-face)))
2760 "Face for missing links."
2761 :group 'markdown-faces)
2763 (defface markdown-reference-face
2764 '((t (:inherit markdown-markup-face)))
2765 "Face for link references."
2766 :group 'markdown-faces)
2768 (define-obsolete-face-alias 'markdown-footnote-face
2769 'markdown-footnote-marker-face "v2.3")
2771 (defface markdown-footnote-marker-face
2772 '((t (:inherit markdown-markup-face)))
2773 "Face for footnote markers."
2774 :group 'markdown-faces)
2776 (defface markdown-footnote-text-face
2777 '((t (:inherit font-lock-comment-face)))
2778 "Face for footnote text."
2779 :group 'markdown-faces)
2781 (defface markdown-url-face
2782 '((t (:inherit font-lock-string-face)))
2783 "Face for URLs that are part of markup.
2784 For example, this applies to URLs in inline links:
2785 [link text](http://example.com/)."
2786 :group 'markdown-faces)
2788 (defface markdown-plain-url-face
2789 '((t (:inherit markdown-link-face)))
2790 "Face for URLs that are also links.
2791 For example, this applies to plain angle bracket URLs:
2792 <http://example.com/>."
2793 :group 'markdown-faces)
2795 (defface markdown-link-title-face
2796 '((t (:inherit font-lock-comment-face)))
2797 "Face for reference link titles."
2798 :group 'markdown-faces)
2800 (defface markdown-line-break-face
2801 '((t (:inherit font-lock-constant-face :underline t)))
2802 "Face for hard line breaks."
2803 :group 'markdown-faces)
2805 (defface markdown-comment-face
2806 '((t (:inherit font-lock-comment-face)))
2807 "Face for HTML comments."
2808 :group 'markdown-faces)
2810 (defface markdown-math-face
2811 '((t (:inherit font-lock-string-face)))
2812 "Face for LaTeX expressions."
2813 :group 'markdown-faces)
2815 (defface markdown-metadata-key-face
2816 '((t (:inherit font-lock-variable-name-face)))
2817 "Face for metadata keys."
2818 :group 'markdown-faces)
2820 (defface markdown-metadata-value-face
2821 '((t (:inherit font-lock-string-face)))
2822 "Face for metadata values."
2823 :group 'markdown-faces)
2825 (defface markdown-gfm-checkbox-face
2826 '((t (:inherit font-lock-builtin-face)))
2827 "Face for GFM checkboxes."
2828 :group 'markdown-faces)
2830 (defface markdown-highlight-face
2831 '((t (:inherit highlight)))
2832 "Face for mouse highlighting."
2833 :group 'markdown-faces)
2835 (defface markdown-hr-face
2836 '((t (:inherit markdown-markup-face)))
2837 "Face for horizontal rules."
2838 :group 'markdown-faces)
2840 (defface markdown-html-tag-name-face
2841 '((t (:inherit font-lock-type-face)))
2842 "Face for HTML tag names."
2843 :group 'markdown-faces)
2845 (defface markdown-html-tag-delimiter-face
2846 '((t (:inherit markdown-markup-face)))
2847 "Face for HTML tag delimiters."
2848 :group 'markdown-faces)
2850 (defface markdown-html-attr-name-face
2851 '((t (:inherit font-lock-variable-name-face)))
2852 "Face for HTML attribute names."
2853 :group 'markdown-faces)
2855 (defface markdown-html-attr-value-face
2856 '((t (:inherit font-lock-string-face)))
2857 "Face for HTML attribute values."
2858 :group 'markdown-faces)
2860 (defface markdown-html-entity-face
2861 '((t (:inherit font-lock-variable-name-face)))
2862 "Face for HTML entities."
2863 :group 'markdown-faces)
2865 (defcustom markdown-header-scaling nil
2866 "Whether to use variable-height faces for headers.
2867 When non-nil, `markdown-header-face' will inherit from
2868 `variable-pitch' and the scaling values in
2869 `markdown-header-scaling-values' will be applied to
2870 headers of levels one through six respectively."
2871 :type 'boolean
2872 :initialize 'custom-initialize-default
2873 :set (lambda (symbol value)
2874 (set-default symbol value)
2875 (markdown-update-header-faces value))
2876 :group 'markdown-faces
2877 :package-version '(markdown-mode . "2.2"))
2879 (defcustom markdown-header-scaling-values
2880 '(2.0 1.7 1.4 1.1 1.0 1.0)
2881 "List of scaling values for headers of level one through six.
2882 Used when `markdown-header-scaling' is non-nil."
2883 :type 'list
2884 :initialize 'custom-initialize-default
2885 :set (lambda (symbol value)
2886 (set-default symbol value)
2887 (markdown-update-header-faces markdown-header-scaling value))
2888 :group 'markdown-faces)
2890 (defun markdown-make-header-faces ()
2891 "Build the faces used for Markdown headers."
2892 (let ((inherit-faces '(font-lock-function-name-face)))
2893 (when markdown-header-scaling
2894 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2895 (defface markdown-header-face
2896 `((t (:inherit ,inherit-faces :weight bold)))
2897 "Base face for headers."
2898 :group 'markdown-faces))
2899 (dotimes (num 6)
2900 (let* ((num1 (1+ num))
2901 (face-name (intern (format "markdown-header-face-%s" num1)))
2902 (scale (if markdown-header-scaling
2903 (float (nth num markdown-header-scaling-values))
2904 1.0)))
2905 (eval
2906 `(defface ,face-name
2907 '((t (:inherit markdown-header-face :height ,scale)))
2908 (format "Face for level %s headers.
2909 You probably don't want to customize this face directly. Instead
2910 you can customize the base face `markdown-header-face' or the
2911 variable-height variable `markdown-header-scaling'." ,num1)
2912 :group 'markdown-faces)))))
2914 (markdown-make-header-faces)
2916 (defun markdown-update-header-faces (&optional scaling scaling-values)
2917 "Update header faces, depending on if header SCALING is desired.
2918 If so, use given list of SCALING-VALUES relative to the baseline
2919 size of `markdown-header-face'."
2920 (dotimes (num 6)
2921 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2922 (scale (cond ((not scaling) 1.0)
2923 (scaling-values (float (nth num scaling-values)))
2924 (t (float (nth num markdown-header-scaling-values))))))
2925 (unless (get face-name 'saved-face) ; Don't update customized faces
2926 (set-face-attribute face-name nil :height scale)))))
2928 (defun markdown-syntactic-face (state)
2929 "Return font-lock face for characters with given STATE.
2930 See `font-lock-syntactic-face-function' for details."
2931 (let ((in-comment (nth 4 state)))
2932 (cond
2933 (in-comment 'markdown-comment-face)
2934 (t nil))))
2936 (defcustom markdown-list-item-bullets
2937 '("●" "◎" "○" "◆" "◇" "►" "•")
2938 "List of bullets to use for unordered lists.
2939 It can contain any number of symbols, which will be repeated.
2940 Depending on your font, some reasonable choices are:
2941 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2942 :group 'markdown
2943 :type '(repeat (string :tag "Bullet character"))
2944 :package-version '(markdown-mode . "2.3"))
2946 (defun markdown--footnote-marker-properties ()
2947 "Return a font-lock facespec expression for footnote marker text."
2948 `(face markdown-footnote-marker-face
2949 ,@(when markdown-hide-markup
2950 `(display ,markdown-footnote-display))))
2952 (defun markdown--pandoc-inline-footnote-properties ()
2953 "Return a font-lock facespec expression for Pandoc inline footnote text."
2954 `(face markdown-footnote-text-face
2955 ,@(when markdown-hide-markup
2956 `(display ,markdown-footnote-display))))
2958 (defvar markdown-mode-font-lock-keywords-basic
2959 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2960 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2961 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2962 (2 markdown-markup-face)
2963 (3 markdown-metadata-value-face)))
2964 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2965 (2 markdown-markup-properties nil t)
2966 (3 markdown-language-keyword-properties nil t)
2967 (4 markdown-language-info-properties nil t)
2968 (5 markdown-markup-properties nil t)))
2969 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2970 (markdown-fontify-gfm-code-blocks)
2971 (markdown-fontify-tables)
2972 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2973 (2 markdown-markup-properties nil t)
2974 (3 markdown-language-keyword-properties nil t)
2975 (4 markdown-language-info-properties nil t)
2976 (5 markdown-markup-properties nil t)))
2977 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2978 (markdown-fontify-fenced-code-blocks)
2979 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2980 (markdown-fontify-headings)
2981 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2982 (2 markdown-markup-face)
2983 (3 markdown-metadata-value-face)))
2984 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2985 (2 markdown-markup-face)
2986 (3 markdown-metadata-value-face)))
2987 (markdown-fontify-hrs)
2988 (markdown-match-code . ((1 markdown-markup-properties prepend)
2989 (2 markdown-inline-code-face prepend)
2990 (3 markdown-markup-properties prepend)))
2991 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2992 (2 markdown-inline-code-face)
2993 (3 markdown-markup-properties)))
2994 (markdown-fontify-angle-uris)
2995 (,markdown-regex-email . 'markdown-plain-url-face)
2996 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
2997 (2 'markdown-html-tag-name-face t)
2998 (3 'markdown-html-tag-delimiter-face t)
2999 ;; Anchored matcher for HTML tag attributes
3000 (,markdown-regex-html-attr
3001 ;; Before searching, move past tag
3002 ;; name; set limit at tag close.
3003 (progn
3004 (goto-char (match-end 2)) (match-end 3))
3006 . ((1 'markdown-html-attr-name-face)
3007 (3 'markdown-html-tag-delimiter-face nil t)
3008 (4 'markdown-html-attr-value-face nil t)))))
3009 (,markdown-regex-html-entity . 'markdown-html-entity-face)
3010 (markdown-fontify-list-items)
3011 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
3012 (2 (markdown--footnote-marker-properties)) ; label
3013 (3 markdown-markup-properties))) ; ]
3014 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
3015 (2 markdown-markup-properties) ; [
3016 (3 (markdown--pandoc-inline-footnote-properties)) ; text
3017 (4 markdown-markup-properties))) ; ]
3018 (markdown-match-includes . ((1 markdown-markup-properties)
3019 (2 markdown-markup-properties nil t)
3020 (3 markdown-include-title-properties nil t)
3021 (4 markdown-markup-properties nil t)
3022 (5 markdown-markup-properties)
3023 (6 'markdown-url-face)
3024 (7 markdown-markup-properties)))
3025 (markdown-fontify-inline-links)
3026 (markdown-fontify-reference-links)
3027 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
3028 (2 markdown-reference-face) ; label
3029 (3 markdown-markup-face) ; ]
3030 (4 markdown-markup-face) ; :
3031 (5 markdown-url-face) ; url
3032 (6 markdown-link-title-face))) ; "title" (optional)
3033 (markdown-fontify-plain-uris)
3034 ;; Math mode $..$
3035 (markdown-match-math-single . ((1 markdown-markup-face prepend)
3036 (2 markdown-math-face append)
3037 (3 markdown-markup-face prepend)))
3038 ;; Math mode $$..$$
3039 (markdown-match-math-double . ((1 markdown-markup-face prepend)
3040 (2 markdown-math-face append)
3041 (3 markdown-markup-face prepend)))
3042 ;; Math mode \[..\] and \\[..\\]
3043 (markdown-match-math-display . ((1 markdown-markup-face prepend)
3044 (3 markdown-math-face append)
3045 (4 markdown-markup-face prepend)))
3046 (markdown-match-bold . ((1 markdown-markup-properties prepend)
3047 (2 markdown-bold-face append)
3048 (3 markdown-markup-properties prepend)))
3049 (markdown-match-italic . ((1 markdown-markup-properties prepend)
3050 (2 markdown-italic-face append)
3051 (3 markdown-markup-properties prepend)))
3052 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
3053 (4 markdown-strike-through-face)
3054 (5 markdown-markup-properties)))
3055 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
3056 (markdown-fontify-sub-superscripts)
3057 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
3058 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
3059 (markdown-fontify-blockquotes)
3060 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
3061 "Syntax highlighting for Markdown files.")
3063 ;; Footnotes
3064 (defvar markdown-footnote-counter 0
3065 "Counter for footnote numbers.")
3066 (make-variable-buffer-local 'markdown-footnote-counter)
3068 (defconst markdown-footnote-chars
3069 "[[:alnum:]-]"
3070 "Regular expression matching any character that is allowed in a footnote identifier.")
3072 (defconst markdown-regex-footnote-definition
3073 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
3074 "Regular expression matching a footnote definition, capturing the label.")
3077 ;;; Compatibility =============================================================
3079 (defun markdown-replace-regexp-in-string (regexp rep string)
3080 "Replace ocurrences of REGEXP with REP in STRING.
3081 This is a compatibility wrapper to provide `replace-regexp-in-string'
3082 in XEmacs 21."
3083 (if (featurep 'xemacs)
3084 (replace-in-string string regexp rep)
3085 (replace-regexp-in-string regexp rep string)))
3087 ;; `markdown-use-region-p' is a compatibility function which checks
3088 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
3089 (eval-and-compile
3090 (cond
3091 ;; Emacs 24 and newer
3092 ((fboundp 'use-region-p)
3093 (defalias 'markdown-use-region-p 'use-region-p))
3094 ;; XEmacs
3095 ((fboundp 'region-active-p)
3096 (defalias 'markdown-use-region-p 'region-active-p))))
3098 ;; Use new names for outline-mode functions in Emacs 25 and later.
3099 (eval-and-compile
3100 (defalias 'markdown-hide-sublevels
3101 (if (fboundp 'outline-hide-sublevels)
3102 'outline-hide-sublevels
3103 'hide-sublevels))
3104 (defalias 'markdown-show-all
3105 (if (fboundp 'outline-show-all)
3106 'outline-show-all
3107 'show-all))
3108 (defalias 'markdown-hide-body
3109 (if (fboundp 'outline-hide-body)
3110 'outline-hide-body
3111 'hide-body))
3112 (defalias 'markdown-show-children
3113 (if (fboundp 'outline-show-children)
3114 'outline-show-children
3115 'show-children))
3116 (defalias 'markdown-show-subtree
3117 (if (fboundp 'outline-show-subtree)
3118 'outline-show-subtree
3119 'show-subtree))
3120 (defalias 'markdown-hide-subtree
3121 (if (fboundp 'outline-hide-subtree)
3122 'outline-hide-subtree
3123 'hide-subtree)))
3125 ;; Provide directory-name-p to Emacs 24
3126 (defsubst markdown-directory-name-p (name)
3127 "Return non-nil if NAME ends with a directory separator character.
3128 Taken from `directory-name-p' from Emacs 25 and provided here for
3129 backwards compatibility."
3130 (let ((len (length name))
3131 (lastc ?.))
3132 (if (> len 0)
3133 (setq lastc (aref name (1- len))))
3134 (or (= lastc ?/)
3135 (and (memq system-type '(windows-nt ms-dos))
3136 (= lastc ?\\)))))
3138 ;; Provide a function to find files recursively in Emacs 24.
3139 (defalias 'markdown-directory-files-recursively
3140 (if (fboundp 'directory-files-recursively)
3141 'directory-files-recursively
3142 (lambda (dir regexp)
3143 "Return list of all files under DIR that have file names matching REGEXP.
3144 This function works recursively. Files are returned in \"depth first\"
3145 order, and files from each directory are sorted in alphabetical order.
3146 Each file name appears in the returned list in its absolute form.
3147 Based on `directory-files-recursively' from Emacs 25 and provided
3148 here for backwards compatibility."
3149 (let ((result nil)
3150 (files nil)
3151 ;; When DIR is "/", remote file names like "/method:" could
3152 ;; also be offered. We shall suppress them.
3153 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3154 (dolist (file (sort (file-name-all-completions "" dir)
3155 'string<))
3156 (unless (member file '("./" "../"))
3157 (if (markdown-directory-name-p file)
3158 (let* ((leaf (substring file 0 (1- (length file))))
3159 (full-file (expand-file-name leaf dir)))
3160 (setq result
3161 (nconc result (markdown-directory-files-recursively
3162 full-file regexp))))
3163 (when (string-match-p regexp file)
3164 (push (expand-file-name file dir) files)))))
3165 (nconc result (nreverse files))))))
3167 (defun markdown-flyspell-check-word-p ()
3168 "Return t if `flyspell' should check word just before point.
3169 Used for `flyspell-generic-check-word-predicate'."
3170 (save-excursion
3171 (goto-char (1- (point)))
3172 (not (or (markdown-code-block-at-point-p)
3173 (markdown-inline-code-at-point-p)
3174 (markdown-in-comment-p)
3175 (let ((faces (get-text-property (point) 'face)))
3176 (if (listp faces)
3177 (or (memq 'markdown-reference-face faces)
3178 (memq 'markdown-markup-face faces)
3179 (memq 'markdown-plain-url-face faces)
3180 (memq 'markdown-inline-code-face faces)
3181 (memq 'markdown-url-face faces))
3182 (memq faces '(markdown-reference-face
3183 markdown-markup-face
3184 markdown-plain-url-face
3185 markdown-inline-code-face
3186 markdown-url-face))))))))
3188 (defun markdown-font-lock-ensure ()
3189 "Provide `font-lock-ensure' in Emacs 24."
3190 (if (fboundp 'font-lock-ensure)
3191 (font-lock-ensure)
3192 (with-no-warnings
3193 ;; Suppress warning about non-interactive use of
3194 ;; `font-lock-fontify-buffer' in Emacs 25.
3195 (font-lock-fontify-buffer))))
3198 ;;; Markdown Parsing Functions ================================================
3200 (defun markdown-cur-line-blank (&optional predicate)
3201 "Return t if the current line is blank and nil otherwise.
3202 When PREDICATE is non-nil, don't modify the match data."
3203 (save-excursion
3204 (beginning-of-line)
3205 (let ((regexp "^\\s *$"))
3206 (if predicate
3207 (looking-at-p regexp)
3208 (looking-at regexp)))))
3210 (defun markdown-cur-line-blank-p ()
3211 "Same as `markdown-cur-line-blank', but does not change the match data."
3212 (markdown-cur-line-blank t))
3214 (defun markdown-prev-line-blank (&optional predicate)
3215 "Return t if the previous line is blank and nil otherwise.
3216 If we are at the first line, then consider the previous line to be blank.
3217 When PREDICATE is non-nil, don't modify the match data."
3218 (or (= (line-beginning-position) (point-min))
3219 (save-excursion
3220 (forward-line -1)
3221 (markdown-cur-line-blank predicate))))
3223 (defun markdown-prev-line-blank-p ()
3224 "Same as `markdown-prev-line-blank', but does not change the match data."
3225 (markdown-prev-line-blank t))
3227 (defun markdown-next-line-blank (&optional predicate)
3228 "Return t if the next line is blank and nil otherwise.
3229 If we are at the last line, then consider the next line to be blank.
3230 When PREDICATE is non-nil, don't modify the match data."
3231 (or (= (line-end-position) (point-max))
3232 (save-excursion
3233 (forward-line 1)
3234 (markdown-cur-line-blank predicate))))
3236 (defun markdown-next-line-blank-p ()
3237 "Same as `markdown-next-line-blank', but does not change the match data."
3238 (markdown-next-line-blank t))
3240 (defun markdown-prev-line-indent ()
3241 "Return the number of leading whitespace characters in the previous line.
3242 Return 0 if the current line is the first line in the buffer."
3243 (save-excursion
3244 (if (= (line-beginning-position) (point-min))
3246 (forward-line -1)
3247 (current-indentation))))
3249 (defun markdown-next-line-indent ()
3250 "Return the number of leading whitespace characters in the next line.
3251 Return 0 if line is the last line in the buffer."
3252 (save-excursion
3253 (if (= (line-end-position) (point-max))
3255 (forward-line 1)
3256 (current-indentation))))
3258 (defun markdown-cur-non-list-indent ()
3259 "Return beginning position of list item text (not including the list marker).
3260 Return nil if the current line is not the beginning of a list item."
3261 (save-match-data
3262 (save-excursion
3263 (beginning-of-line)
3264 (when (re-search-forward markdown-regex-list (line-end-position) t)
3265 (current-column)))))
3267 (defun markdown-prev-non-list-indent ()
3268 "Return position of the first non-list-marker on the previous line."
3269 (save-excursion
3270 (forward-line -1)
3271 (markdown-cur-non-list-indent)))
3273 (defun markdown-new-baseline ()
3274 "Determine if the current line begins a new baseline level."
3275 (save-excursion
3276 (beginning-of-line)
3277 (or (looking-at markdown-regex-header)
3278 (looking-at markdown-regex-hr)
3279 (and (null (markdown-cur-non-list-indent))
3280 (= (current-indentation) 0)
3281 (markdown-prev-line-blank)))))
3283 (defun markdown-search-backward-baseline ()
3284 "Search backward baseline point with no indentation and not a list item."
3285 (end-of-line)
3286 (let (stop)
3287 (while (not (or stop (bobp)))
3288 (re-search-backward markdown-regex-block-separator-noindent nil t)
3289 (when (match-end 2)
3290 (goto-char (match-end 2))
3291 (cond
3292 ((markdown-new-baseline)
3293 (setq stop t))
3294 ((looking-at-p markdown-regex-list)
3295 (setq stop nil))
3296 (t (setq stop t)))))))
3298 (defun markdown-update-list-levels (marker indent levels)
3299 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3300 Here, MARKER is a string representing the type of list, INDENT is an integer
3301 giving the indentation, in spaces, of the current block, and LEVELS is a
3302 list of the indentation levels of parent list items. When LEVELS is nil,
3303 it means we are at baseline (not inside of a nested list)."
3304 (cond
3305 ;; New list item at baseline.
3306 ((and marker (null levels))
3307 (setq levels (list indent)))
3308 ;; List item with greater indentation (four or more spaces).
3309 ;; Increase list level.
3310 ((and marker (>= indent (+ (car levels) 4)))
3311 (setq levels (cons indent levels)))
3312 ;; List item with greater or equal indentation (less than four spaces).
3313 ;; Do not increase list level.
3314 ((and marker (>= indent (car levels)))
3315 levels)
3316 ;; Lesser indentation level.
3317 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3318 ;; indentation could move back more than one list level). Note
3319 ;; that this block need not be the beginning of list item.
3320 ((< indent (car levels))
3321 (while (and (> (length levels) 1)
3322 (< indent (+ (cadr levels) 4)))
3323 (setq levels (cdr levels)))
3324 levels)
3325 ;; Otherwise, do nothing.
3326 (t levels)))
3328 (defun markdown-calculate-list-levels ()
3329 "Calculate list levels at point.
3330 Return a list of the form (n1 n2 n3 ...) where n1 is the
3331 indentation of the deepest nested list item in the branch of
3332 the list at the point, n2 is the indentation of the parent
3333 list item, and so on. The depth of the list item is therefore
3334 the length of the returned list. If the point is not at or
3335 immediately after a list item, return nil."
3336 (save-excursion
3337 (let ((first (point)) levels indent pre-regexp)
3338 ;; Find a baseline point with zero list indentation
3339 (markdown-search-backward-baseline)
3340 ;; Search for all list items between baseline and LOC
3341 (while (and (< (point) first)
3342 (re-search-forward markdown-regex-list first t))
3343 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3344 (beginning-of-line)
3345 (cond
3346 ;; Make sure this is not a header or hr
3347 ((markdown-new-baseline) (setq levels nil))
3348 ;; Make sure this is not a line from a pre block
3349 ((looking-at-p pre-regexp))
3350 ;; If not, then update levels
3352 (setq indent (current-indentation))
3353 (setq levels (markdown-update-list-levels (match-string 2)
3354 indent levels))))
3355 (end-of-line))
3356 levels)))
3358 (defun markdown-prev-list-item (level)
3359 "Search backward from point for a list item with indentation LEVEL.
3360 Set point to the beginning of the item, and return point, or nil
3361 upon failure."
3362 (let (bounds indent prev)
3363 (setq prev (point))
3364 (forward-line -1)
3365 (setq indent (current-indentation))
3366 (while
3367 (cond
3368 ;; List item
3369 ((and (looking-at-p markdown-regex-list)
3370 (setq bounds (markdown-cur-list-item-bounds)))
3371 (cond
3372 ;; Stop and return point at item of equal indentation
3373 ((= (nth 3 bounds) level)
3374 (setq prev (point))
3375 nil)
3376 ;; Stop and return nil at item with lesser indentation
3377 ((< (nth 3 bounds) level)
3378 (setq prev nil)
3379 nil)
3380 ;; Stop at beginning of buffer
3381 ((bobp) (setq prev nil))
3382 ;; Continue at item with greater indentation
3383 ((> (nth 3 bounds) level) t)))
3384 ;; Stop at beginning of buffer
3385 ((bobp) (setq prev nil))
3386 ;; Continue if current line is blank
3387 ((markdown-cur-line-blank-p) t)
3388 ;; Continue while indentation is the same or greater
3389 ((>= indent level) t)
3390 ;; Stop if current indentation is less than list item
3391 ;; and the next is blank
3392 ((and (< indent level)
3393 (markdown-next-line-blank-p))
3394 (setq prev nil))
3395 ;; Stop at a header
3396 ((looking-at-p markdown-regex-header) (setq prev nil))
3397 ;; Stop at a horizontal rule
3398 ((looking-at-p markdown-regex-hr) (setq prev nil))
3399 ;; Otherwise, continue.
3400 (t t))
3401 (forward-line -1)
3402 (setq indent (current-indentation)))
3403 prev))
3405 (defun markdown-next-list-item (level)
3406 "Search forward from point for the next list item with indentation LEVEL.
3407 Set point to the beginning of the item, and return point, or nil
3408 upon failure."
3409 (let (bounds indent next)
3410 (setq next (point))
3411 (if (looking-at markdown-regex-header-setext)
3412 (goto-char (match-end 0)))
3413 (forward-line)
3414 (setq indent (current-indentation))
3415 (while
3416 (cond
3417 ;; Stop at end of the buffer.
3418 ((eobp) nil)
3419 ;; Continue if the current line is blank
3420 ((markdown-cur-line-blank-p) t)
3421 ;; List item
3422 ((and (looking-at-p markdown-regex-list)
3423 (setq bounds (markdown-cur-list-item-bounds)))
3424 (cond
3425 ;; Continue at item with greater indentation
3426 ((> (nth 3 bounds) level) t)
3427 ;; Stop and return point at item of equal indentation
3428 ((= (nth 3 bounds) level)
3429 (setq next (point))
3430 nil)
3431 ;; Stop and return nil at item with lesser indentation
3432 ((< (nth 3 bounds) level)
3433 (setq next nil)
3434 nil)))
3435 ;; Continue while indentation is the same or greater
3436 ((>= indent level) t)
3437 ;; Stop if current indentation is less than list item
3438 ;; and the previous line was blank.
3439 ((and (< indent level)
3440 (markdown-prev-line-blank-p))
3441 (setq next nil))
3442 ;; Stop at a header
3443 ((looking-at-p markdown-regex-header) (setq next nil))
3444 ;; Stop at a horizontal rule
3445 ((looking-at-p markdown-regex-hr) (setq next nil))
3446 ;; Otherwise, continue.
3447 (t t))
3448 (forward-line)
3449 (setq indent (current-indentation)))
3450 next))
3452 (defun markdown-cur-list-item-end (level)
3453 "Move to the end of the current list item with nonlist indentation LEVEL.
3454 If the point is not in a list item, do nothing."
3455 (let (indent)
3456 (forward-line)
3457 (setq indent (current-indentation))
3458 (while
3459 (cond
3460 ;; Stop at end of the buffer.
3461 ((eobp) nil)
3462 ;; Continue if the current line is blank
3463 ((markdown-cur-line-blank-p) t)
3464 ;; Continue while indentation is the same or greater
3465 ((>= indent level) t)
3466 ;; Stop if current indentation is less than list item
3467 ;; and the previous line was blank.
3468 ((and (< indent level)
3469 (markdown-prev-line-blank-p))
3470 nil)
3471 ;; Stop at a new list item of the same or lesser indentation
3472 ((looking-at-p markdown-regex-list) nil)
3473 ;; Stop at a header
3474 ((looking-at-p markdown-regex-header) nil)
3475 ;; Stop at a horizontal rule
3476 ((looking-at-p markdown-regex-hr) nil)
3477 ;; Otherwise, continue.
3478 (t t))
3479 (forward-line)
3480 (setq indent (current-indentation)))
3481 ;; Don't skip over whitespace for empty list items (marker and
3482 ;; whitespace only), just move to end of whitespace.
3483 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3484 (goto-char (match-end 3))
3485 (skip-syntax-backward "-"))))
3487 (defun markdown-cur-list-item-bounds ()
3488 "Return bounds and indentation of the current list item.
3489 Return a list of the following form:
3491 (begin end indent nonlist-indent marker checkbox)
3493 The named components are:
3495 - begin: Position of beginning of list item, including leading indentation.
3496 - end: Position of the end of the list item, including list item text.
3497 - indent: Number of characters of indentation before list marker (an integer).
3498 - nonlist-indent: Number characters of indentation, list
3499 marker, and whitespace following list marker (an integer).
3500 - marker: String containing the list marker and following whitespace
3501 (e.g., \"- \" or \"* \").
3502 - checkbox: String containing the GFM checkbox portion, if any,
3503 including any trailing whitespace before the text
3504 begins (e.g., \"[x] \").
3506 As an example, for the following unordered list item
3508 - item
3510 the returned list would be
3512 (1 14 3 5 \"- \" nil)
3514 If the point is not inside a list item, return nil.
3515 Leave match data intact for `markdown-regex-list'."
3516 (save-excursion
3517 (let ((cur (point)))
3518 (end-of-line)
3519 (when (re-search-backward markdown-regex-list nil t)
3520 (let* ((begin (match-beginning 0))
3521 (indent (length (match-string-no-properties 1)))
3522 (nonlist-indent (length (match-string 0)))
3523 (marker (concat (match-string-no-properties 2)
3524 (match-string-no-properties 3)))
3525 (checkbox (progn (goto-char (match-end 0))
3526 (when (looking-at "\\[[xX ]\\]\\s-*")
3527 (match-string-no-properties 0))))
3528 (end (save-match-data
3529 (markdown-cur-list-item-end nonlist-indent)
3530 (point))))
3531 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3532 (list begin end indent nonlist-indent marker checkbox)))))))
3534 (defun markdown-list-item-at-point-p ()
3535 "Return t if there is a list item at the point and nil otherwise."
3536 (save-match-data (markdown-cur-list-item-bounds)))
3538 (defun markdown-prev-list-item-bounds ()
3539 "Return bounds of previous item in the same list of any level.
3540 The return value has the same form as that of
3541 `markdown-cur-list-item-bounds'."
3542 (save-excursion
3543 (let ((cur-bounds (markdown-cur-list-item-bounds))
3544 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3545 stop)
3546 (when cur-bounds
3547 (goto-char (nth 0 cur-bounds))
3548 (while (and (not stop) (not (bobp))
3549 (re-search-backward markdown-regex-list
3550 beginning-of-list t))
3551 (unless (or (looking-at markdown-regex-hr)
3552 (markdown-code-block-at-point-p))
3553 (setq stop (point))))
3554 (markdown-cur-list-item-bounds)))))
3556 (defun markdown-next-list-item-bounds ()
3557 "Return bounds of next item in the same list of any level.
3558 The return value has the same form as that of
3559 `markdown-cur-list-item-bounds'."
3560 (save-excursion
3561 (let ((cur-bounds (markdown-cur-list-item-bounds))
3562 (end-of-list (save-excursion (markdown-end-of-list)))
3563 stop)
3564 (when cur-bounds
3565 (goto-char (nth 0 cur-bounds))
3566 (end-of-line)
3567 (while (and (not stop) (not (eobp))
3568 (re-search-forward markdown-regex-list
3569 end-of-list t))
3570 (unless (or (looking-at markdown-regex-hr)
3571 (markdown-code-block-at-point-p))
3572 (setq stop (point))))
3573 (when stop
3574 (markdown-cur-list-item-bounds))))))
3576 (defun markdown-beginning-of-list ()
3577 "Move point to beginning of list at point, if any."
3578 (interactive)
3579 (let ((orig-point (point))
3580 (list-begin (save-excursion
3581 (markdown-search-backward-baseline)
3582 ;; Stop at next list item, regardless of the indentation.
3583 (markdown-next-list-item (point-max))
3584 (when (looking-at markdown-regex-list)
3585 (point)))))
3586 (when (and list-begin (<= list-begin orig-point))
3587 (goto-char list-begin))))
3589 (defun markdown-end-of-list ()
3590 "Move point to end of list at point, if any."
3591 (interactive)
3592 (let ((start (point))
3593 (end (save-excursion
3594 (when (markdown-beginning-of-list)
3595 ;; Items can't have nonlist-indent <= 1, so this
3596 ;; moves past all list items.
3597 (markdown-next-list-item 1)
3598 (skip-syntax-backward "-")
3599 (unless (eobp) (forward-char 1))
3600 (point)))))
3601 (when (and end (>= end start))
3602 (goto-char end))))
3604 (defun markdown-up-list ()
3605 "Move point to beginning of parent list item."
3606 (interactive)
3607 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3608 (when cur-bounds
3609 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3610 (let ((up-bounds (markdown-cur-list-item-bounds)))
3611 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3612 (point))))))
3614 (defun markdown-bounds-of-thing-at-point (thing)
3615 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3616 Does not include trailing newlines when THING is 'line. Handles the
3617 end of buffer case by setting both endpoints equal to the value of
3618 `point-max', since an empty region will trigger empty markup insertion.
3619 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3620 (let* ((bounds (bounds-of-thing-at-point thing))
3621 (a (car bounds))
3622 (b (cdr bounds)))
3623 (when bounds
3624 (when (eq thing 'line)
3625 (cond ((and (eobp) (markdown-cur-line-blank-p))
3626 (setq a b))
3627 ((char-equal (char-before b) ?\^J)
3628 (setq b (1- b)))))
3629 (cons a b))))
3631 (defun markdown-reference-definition (reference)
3632 "Find out whether Markdown REFERENCE is defined.
3633 REFERENCE should not include the square brackets.
3634 When REFERENCE is defined, return a list of the form (text start end)
3635 containing the definition text itself followed by the start and end
3636 locations of the text. Otherwise, return nil.
3637 Leave match data for `markdown-regex-reference-definition'
3638 intact additional processing."
3639 (let ((reference (downcase reference)))
3640 (save-excursion
3641 (goto-char (point-min))
3642 (catch 'found
3643 (while (re-search-forward markdown-regex-reference-definition nil t)
3644 (when (string= reference (downcase (match-string-no-properties 2)))
3645 (throw 'found
3646 (list (match-string-no-properties 5)
3647 (match-beginning 5) (match-end 5)))))))))
3649 (defun markdown-get-defined-references ()
3650 "Return a list of all defined reference labels (not including square brackets)."
3651 (save-excursion
3652 (goto-char (point-min))
3653 (let (refs)
3654 (while (re-search-forward markdown-regex-reference-definition nil t)
3655 (let ((target (match-string-no-properties 2)))
3656 (cl-pushnew target refs :test #'equal)))
3657 (reverse refs))))
3659 (defun markdown-get-used-uris ()
3660 "Return a list of all used URIs in the buffer."
3661 (save-excursion
3662 (goto-char (point-min))
3663 (let (uris)
3664 (while (re-search-forward
3665 (concat "\\(?:" markdown-regex-link-inline
3666 "\\|" markdown-regex-angle-uri
3667 "\\|" markdown-regex-uri
3668 "\\|" markdown-regex-email
3669 "\\)")
3670 nil t)
3671 (unless (or (markdown-inline-code-at-point-p)
3672 (markdown-code-block-at-point-p))
3673 (cl-pushnew (or (match-string-no-properties 6)
3674 (match-string-no-properties 10)
3675 (match-string-no-properties 12)
3676 (match-string-no-properties 13))
3677 uris :test #'equal)))
3678 (reverse uris))))
3680 (defun markdown-inline-code-at-pos (pos)
3681 "Return non-nil if there is an inline code fragment at POS.
3682 Return nil otherwise. Set match data according to
3683 `markdown-match-code' upon success.
3684 This function searches the block for a code fragment that
3685 contains the point using `markdown-match-code'. We do this
3686 because `thing-at-point-looking-at' does not work reliably with
3687 `markdown-regex-code'.
3689 The match data is set as follows:
3690 Group 1 matches the opening backquotes.
3691 Group 2 matches the code fragment itself, without backquotes.
3692 Group 3 matches the closing backquotes."
3693 (save-excursion
3694 (goto-char pos)
3695 (let ((old-point (point))
3696 (end-of-block (progn (markdown-end-of-text-block) (point)))
3697 found)
3698 (markdown-beginning-of-text-block)
3699 (while (and (markdown-match-code end-of-block)
3700 (setq found t)
3701 (< (match-end 0) old-point)))
3702 (and found ; matched something
3703 (<= (match-beginning 0) old-point) ; match contains old-point
3704 (>= (match-end 0) old-point)))))
3706 (defun markdown-inline-code-at-pos-p (pos)
3707 "Return non-nil if there is an inline code fragment at POS.
3708 Like `markdown-inline-code-at-pos`, but preserves match data."
3709 (save-match-data (markdown-inline-code-at-pos pos)))
3711 (defun markdown-inline-code-at-point ()
3712 "Return non-nil if the point is at an inline code fragment.
3713 See `markdown-inline-code-at-pos' for details."
3714 (markdown-inline-code-at-pos (point)))
3716 (defun markdown-inline-code-at-point-p ()
3717 "Return non-nil if there is inline code at the point.
3718 This is a predicate function counterpart to
3719 `markdown-inline-code-at-point' which does not modify the match
3720 data. See `markdown-code-block-at-point-p' for code blocks."
3721 (save-match-data (markdown-inline-code-at-pos (point))))
3723 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3725 (defun markdown-code-block-at-pos (pos)
3726 "Return match data list if there is a code block at POS.
3727 Uses text properties at the beginning of the line position.
3728 This includes pre blocks, tilde-fenced code blocks, and GFM
3729 quoted code blocks. Return nil otherwise."
3730 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3731 (or (get-text-property pos 'markdown-pre)
3732 (markdown-get-enclosing-fenced-block-construct pos)
3733 ;; polymode removes text properties set by markdown-mode, so
3734 ;; check if `poly-markdown-mode' is active and whether the
3735 ;; `chunkmode' property is non-nil at POS.
3736 (and (bound-and-true-p poly-markdown-mode)
3737 (get-text-property pos 'chunkmode))))
3739 ;; Function was renamed to emphasize that it does not modify match-data.
3740 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3742 (defun markdown-code-block-at-point-p ()
3743 "Return non-nil if there is a code block at the point.
3744 This includes pre blocks, tilde-fenced code blocks, and GFM
3745 quoted code blocks. This function does not modify the match
3746 data. See `markdown-inline-code-at-point-p' for inline code."
3747 (save-match-data (markdown-code-block-at-pos (point))))
3749 (defun markdown-heading-at-point ()
3750 "Return non-nil if there is a heading at the point.
3751 Set match data for `markdown-regex-header'."
3752 (let ((match-data (get-text-property (point) 'markdown-heading)))
3753 (when match-data
3754 (set-match-data match-data)
3755 t)))
3757 (defun markdown-pipe-at-bol-p ()
3758 "Return non-nil if the line begins with a pipe symbol.
3759 This may be useful for tables and Pandoc's line_blocks extension."
3760 (char-equal (char-after (point-at-bol)) ?|))
3763 ;;; Markdown Font Lock Matching Functions =====================================
3765 (defun markdown-range-property-any (begin end prop prop-values)
3766 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3767 Also returns t if PROP is a list containing one of the PROP-VALUES.
3768 Return nil otherwise."
3769 (let (props)
3770 (catch 'found
3771 (dolist (loc (number-sequence begin end))
3772 (when (setq props (get-text-property loc prop))
3773 (cond ((listp props)
3774 ;; props is a list, check for membership
3775 (dolist (val prop-values)
3776 (when (memq val props) (throw 'found loc))))
3778 ;; props is a scalar, check for equality
3779 (dolist (val prop-values)
3780 (when (eq val props) (throw 'found loc))))))))))
3782 (defun markdown-range-properties-exist (begin end props)
3783 (cl-loop
3784 for loc in (number-sequence begin end)
3785 with result = nil
3786 while (not
3787 (setq result
3788 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3789 finally return result))
3791 (defun markdown-match-inline-generic (regex last &optional faceless)
3792 "Match inline REGEX from the point to LAST.
3793 When FACELESS is non-nil, do not return matches where faces have been applied."
3794 (when (re-search-forward regex last t)
3795 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3796 (face (and faceless (text-property-not-all
3797 (match-beginning 0) (match-end 0) 'face nil))))
3798 (cond
3799 ;; In code block: move past it and recursively search again
3800 (bounds
3801 (when (< (goto-char (cl-second bounds)) last)
3802 (markdown-match-inline-generic regex last faceless)))
3803 ;; When faces are found in the match range, skip over the match and
3804 ;; recursively search again.
3805 (face
3806 (when (< (goto-char (match-end 0)) last)
3807 (markdown-match-inline-generic regex last faceless)))
3808 ;; Keep match data and return t when in bounds.
3810 (<= (match-end 0) last))))))
3812 (defun markdown-match-code (last)
3813 "Match inline code fragments from point to LAST."
3814 (unless (bobp)
3815 (backward-char 1))
3816 (when (markdown-match-inline-generic markdown-regex-code last)
3817 (let ((begin (match-beginning 1))
3818 (end (match-end 1))
3819 (open-begin (match-beginning 2))
3820 (open-end (match-end 2))
3821 (code-begin (match-beginning 3))
3822 (code-end (match-end 3))
3823 (close-begin (match-beginning 4))
3824 (close-end (match-end 4)))
3825 (if (or (markdown-in-comment-p begin)
3826 (markdown-in-comment-p end)
3827 (markdown-code-block-at-pos begin))
3828 (progn (goto-char (min (1+ begin) last))
3829 (when (< (point) last)
3830 (markdown-match-code last)))
3831 (set-match-data (list begin end
3832 open-begin open-end
3833 code-begin code-end
3834 close-begin close-end))
3835 t))))
3837 (defun markdown-match-bold (last)
3838 "Match inline bold from the point to LAST."
3839 (when (markdown-match-inline-generic markdown-regex-bold last)
3840 (let ((begin (match-beginning 2))
3841 (end (match-end 2)))
3842 (if (or (markdown-inline-code-at-pos-p begin)
3843 (markdown-inline-code-at-pos-p end)
3844 (markdown-in-comment-p)
3845 (markdown-range-property-any
3846 begin begin 'face '(markdown-url-face
3847 markdown-plain-url-face))
3848 (markdown-range-property-any
3849 begin end 'face '(markdown-math-face)))
3850 (progn (goto-char (min (1+ begin) last))
3851 (when (< (point) last)
3852 (markdown-match-italic last)))
3853 (set-match-data (list (match-beginning 2) (match-end 2)
3854 (match-beginning 3) (match-end 3)
3855 (match-beginning 4) (match-end 4)
3856 (match-beginning 5) (match-end 5)))
3857 t))))
3859 (defun markdown-match-italic (last)
3860 "Match inline italics from the point to LAST."
3861 (let ((regex (if (eq major-mode 'gfm-mode)
3862 markdown-regex-gfm-italic markdown-regex-italic)))
3863 (when (markdown-match-inline-generic regex last)
3864 (let ((begin (match-beginning 1))
3865 (end (match-end 1)))
3866 (if (or (markdown-inline-code-at-pos-p begin)
3867 (markdown-inline-code-at-pos-p end)
3868 (markdown-in-comment-p)
3869 (markdown-range-property-any
3870 begin begin 'face '(markdown-url-face
3871 markdown-plain-url-face))
3872 (markdown-range-property-any
3873 begin end 'face '(markdown-bold-face
3874 markdown-list-face
3875 markdown-math-face)))
3876 (progn (goto-char (min (1+ begin) last))
3877 (when (< (point) last)
3878 (markdown-match-italic last)))
3879 (set-match-data (list (match-beginning 1) (match-end 1)
3880 (match-beginning 2) (match-end 2)
3881 (match-beginning 3) (match-end 3)
3882 (match-beginning 4) (match-end 4)))
3883 t)))))
3885 (defun markdown-match-math-generic (regex last)
3886 "Match REGEX from point to LAST.
3887 REGEX is either `markdown-regex-math-inline-single' for matching
3888 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3889 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3890 (let ((begin (match-beginning 1)) (end (match-end 1)))
3891 (prog1
3892 (if (or (markdown-range-property-any
3893 begin end 'face (list markdown-inline-code-face
3894 markdown-bold-face))
3895 (markdown-range-properties-exist
3896 begin end
3897 (markdown-get-fenced-block-middle-properties)))
3898 (markdown-match-math-generic regex last)
3900 (goto-char (1+ (match-end 0)))))))
3902 (defun markdown-match-list-items (last)
3903 "Match list items from point to LAST."
3904 (when (markdown-match-inline-generic markdown-regex-list last)
3905 (let ((begin (match-beginning 2))
3906 (end (match-end 2)))
3907 (if (or (markdown-range-property-any
3908 begin end 'face (list markdown-inline-code-face
3909 markdown-bold-face
3910 markdown-math-face))
3911 (markdown-range-properties-exist begin end '(markdown-hr))
3912 (markdown-in-comment-p))
3913 (progn (goto-char (min (1+ (match-end 0)) last))
3914 (markdown-match-list-items last))
3915 (set-match-data (list (match-beginning 0) (match-end 0)
3916 (match-beginning 1) (match-end 1)
3917 (match-beginning 2) (match-end 2)))
3918 (goto-char (1+ (match-end 0)))))))
3920 (defun markdown-match-math-single (last)
3921 "Match single quoted $..$ math from point to LAST."
3922 (markdown-match-math-generic markdown-regex-math-inline-single last))
3924 (defun markdown-match-math-double (last)
3925 "Match double quoted $$..$$ math from point to LAST."
3926 (markdown-match-math-generic markdown-regex-math-inline-double last))
3928 (defun markdown-match-math-display (last)
3929 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3930 (markdown-match-math-generic markdown-regex-math-display last))
3932 (defun markdown-match-propertized-text (property last)
3933 "Match text with PROPERTY from point to LAST.
3934 Restore match data previously stored in PROPERTY."
3935 (let ((saved (get-text-property (point) property))
3936 pos)
3937 (unless saved
3938 (setq pos (next-single-char-property-change (point) property nil last))
3939 (setq saved (get-text-property pos property)))
3940 (when saved
3941 (set-match-data saved)
3942 ;; Step at least one character beyond point. Otherwise
3943 ;; `font-lock-fontify-keywords-region' infloops.
3944 (goto-char (min (1+ (max (match-end 0) (point)))
3945 (point-max)))
3946 saved)))
3948 (defun markdown-match-pre-blocks (last)
3949 "Match preformatted blocks from point to LAST.
3950 Use data stored in 'markdown-pre text property during syntax
3951 analysis."
3952 (markdown-match-propertized-text 'markdown-pre last))
3954 (defun markdown-match-gfm-code-blocks (last)
3955 "Match GFM quoted code blocks from point to LAST.
3956 Use data stored in 'markdown-gfm-code text property during syntax
3957 analysis."
3958 (markdown-match-propertized-text 'markdown-gfm-code last))
3960 (defun markdown-match-gfm-open-code-blocks (last)
3961 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3963 (defun markdown-match-gfm-close-code-blocks (last)
3964 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3966 (defun markdown-match-fenced-code-blocks (last)
3967 "Match fenced code blocks from the point to LAST."
3968 (markdown-match-propertized-text 'markdown-fenced-code last))
3970 (defun markdown-match-fenced-start-code-block (last)
3971 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3973 (defun markdown-match-fenced-end-code-block (last)
3974 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3976 (defun markdown-match-blockquotes (last)
3977 "Match blockquotes from point to LAST.
3978 Use data stored in 'markdown-blockquote text property during syntax
3979 analysis."
3980 (markdown-match-propertized-text 'markdown-blockquote last))
3982 (defun markdown-match-hr (last)
3983 "Match horizontal rules comments from the point to LAST."
3984 (markdown-match-propertized-text 'markdown-hr last))
3986 (defun markdown-match-comments (last)
3987 "Match HTML comments from the point to LAST."
3988 (when (and (skip-syntax-forward "^<" last))
3989 (let ((beg (point)))
3990 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3991 (forward-char)
3992 (set-match-data (list beg (point)))
3993 t))))
3995 (defun markdown-match-generic-links (last ref)
3996 "Match inline links from point to LAST.
3997 When REF is non-nil, match reference links instead of standard
3998 links with URLs."
3999 ;; Search for the next potential link (not in a code block).
4000 (while (and (progn
4001 ;; Clear match data to test for a match after functions returns.
4002 (set-match-data nil)
4003 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
4004 ;; Keep searching if this is in a code block, inline
4005 ;; code, or a comment, or if it is include syntax.
4006 (or (markdown-code-block-at-point-p)
4007 (markdown-inline-code-at-pos-p (match-beginning 0))
4008 (markdown-inline-code-at-pos-p (match-end 0))
4009 (markdown-in-comment-p)
4010 (and (char-equal (char-after (point-at-bol)) ?<)
4011 (char-equal (char-after (1+ (point-at-bol))) ?<)))
4012 (< (point) last)))
4013 ;; Match opening exclamation point (optional) and left bracket.
4014 (when (match-beginning 2)
4015 (let* ((bang (match-beginning 1))
4016 (first-begin (match-beginning 2))
4017 ;; Find end of block to prevent matching across blocks.
4018 (end-of-block (save-excursion
4019 (progn
4020 (goto-char (match-beginning 2))
4021 (markdown-end-of-text-block)
4022 (point))))
4023 ;; Move over balanced expressions to closing right bracket.
4024 ;; Catch unbalanced expression errors and return nil.
4025 (first-end (condition-case nil
4026 (and (goto-char first-begin)
4027 (scan-sexps (point) 1))
4028 (error nil)))
4029 ;; Continue with point at CONT-POINT upon failure.
4030 (cont-point (min (1+ first-begin) last))
4031 second-begin second-end url-begin url-end
4032 title-begin title-end)
4033 ;; When bracket found, in range, and followed by a left paren/bracket...
4034 (when (and first-end (< first-end end-of-block) (goto-char first-end)
4035 (char-equal (char-after (point)) (if ref ?\[ ?\()))
4036 ;; Scan across balanced expressions for closing parenthesis/bracket.
4037 (setq second-begin (point)
4038 second-end (condition-case nil
4039 (scan-sexps (point) 1)
4040 (error nil)))
4041 ;; Check that closing parenthesis/bracket is in range.
4042 (if (and second-end (<= second-end end-of-block) (<= second-end last))
4043 (progn
4044 ;; Search for (optional) title inside closing parenthesis
4045 (when (and (not ref) (search-forward "\"" second-end t))
4046 (setq title-begin (1- (point))
4047 title-end (and (goto-char second-end)
4048 (search-backward "\"" (1+ title-begin) t))
4049 title-end (and title-end (1+ title-end))))
4050 ;; Store URL/reference range
4051 (setq url-begin (1+ second-begin)
4052 url-end (1- (or title-begin second-end)))
4053 ;; Set match data, move point beyond link, and return
4054 (set-match-data
4055 (list (or bang first-begin) second-end ; 0 - all
4056 bang (and bang (1+ bang)) ; 1 - bang
4057 first-begin (1+ first-begin) ; 2 - markup
4058 (1+ first-begin) (1- first-end) ; 3 - link text
4059 (1- first-end) first-end ; 4 - markup
4060 second-begin (1+ second-begin) ; 5 - markup
4061 url-begin url-end ; 6 - url/reference
4062 title-begin title-end ; 7 - title
4063 (1- second-end) second-end)) ; 8 - markup
4064 ;; Nullify cont-point and leave point at end and
4065 (setq cont-point nil)
4066 (goto-char second-end))
4067 ;; If no closing parenthesis in range, update continuation point
4068 (setq cont-point (min end-of-block second-begin))))
4069 (cond
4070 ;; On failure, continue searching at cont-point
4071 ((and cont-point (< cont-point last))
4072 (goto-char cont-point)
4073 (markdown-match-generic-links last ref))
4074 ;; No more text, return nil
4075 ((and cont-point (= cont-point last))
4076 nil)
4077 ;; Return t if a match occurred
4078 (t t)))))
4080 (defun markdown-match-inline-links (last)
4081 "Match standard inline links from point to LAST."
4082 (markdown-match-generic-links last nil))
4084 (defun markdown-match-reference-links (last)
4085 "Match inline reference links from point to LAST."
4086 (markdown-match-generic-links last t))
4088 (defun markdown-match-angle-uris (last)
4089 "Match angle bracket URIs from point to LAST."
4090 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
4091 (goto-char (1+ (match-end 0)))))
4093 (defun markdown-match-plain-uris (last)
4094 "Match plain URIs from point to LAST."
4095 (when (markdown-match-inline-generic markdown-regex-uri last t)
4096 (goto-char (1+ (match-end 0)))))
4098 (defvar markdown-conditional-search-function #'re-search-forward
4099 "Conditional search function used in `markdown-search-until-condition'.
4100 Made into a variable to allow for dynamic let-binding.")
4102 (defun markdown-search-until-condition (condition &rest args)
4103 (let (ret)
4104 (while (and (not ret) (apply markdown-conditional-search-function args))
4105 (setq ret (funcall condition)))
4106 ret))
4108 (defun markdown-match-generic-metadata
4109 (regexp last &optional block-begin-re block-end-re)
4110 "Match metadata declarations specified by REGEXP from point to LAST.
4111 These declarations must appear inside a metadata block specified
4112 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
4113 expression denoting the beginning of a metadata block. If it is
4114 nil, we assume metadata can only appear at the beginning of the
4115 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
4116 the end of a metadata block. If it is nil, assume blocks end with
4117 a blank line or the end of the buffer. There may be at most one such
4118 block in a file. Subsequent blocks will be ignored."
4119 (let* ((first (point))
4120 (begin-re (or block-begin-re "\\`"))
4121 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
4123 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4124 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4125 ;; (block-begin (or prev-block-begin next-block-begin))
4127 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4128 (re-search-forward begin-re last t))
4129 (match-end 0)))
4131 (block-end (and block-begin (goto-char block-begin)
4132 (re-search-forward end-re nil t))))
4133 (cond
4134 ;; Don't match declarations if there is no metadata block or if
4135 ;; the point is beyond the block. Move point to point-max to
4136 ;; prevent additional searches and return return nil since nothing
4137 ;; was found.
4138 ((or (null block-begin) (and block-end (> first block-end)))
4139 (goto-char (point-max))
4140 nil)
4141 ;; No declarations to match if a block was found but not in
4142 ;; range. Move point to LAST, to resume there, and return nil.
4143 ((> block-begin last)
4144 (goto-char last)
4145 nil)
4146 ;; If a block was found that begins before LAST and ends after
4147 ;; point, search for declarations inside it.
4149 ;; If the starting is before the beginning of the block, start
4150 ;; there. Otherwise, move back to FIRST.
4151 (goto-char (if (< first block-begin) block-begin first))
4152 (if (re-search-forward regexp (min last block-end) t)
4153 ;; If a metadata declaration is found, set match-data and return t.
4154 (let ((key-beginning (match-beginning 1))
4155 (key-end (match-end 1))
4156 (markup-begin (match-beginning 2))
4157 (markup-end (match-end 2))
4158 (value-beginning (match-beginning 3)))
4159 (set-match-data (list key-beginning (point) ; complete metadata
4160 key-beginning key-end ; key
4161 markup-begin markup-end ; markup
4162 value-beginning (point))) ; value
4164 ;; Otherwise, move the point to last and return nil
4165 (goto-char last)
4166 nil)))))
4168 (defun markdown-match-declarative-metadata (last)
4169 "Match declarative metadata from the point to LAST."
4170 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4172 (defun markdown-match-pandoc-metadata (last)
4173 "Match Pandoc metadata from the point to LAST."
4174 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4176 (defun markdown-match-yaml-metadata-begin (last)
4177 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4179 (defun markdown-match-yaml-metadata-end (last)
4180 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4182 (defun markdown-match-yaml-metadata-key (last)
4183 (markdown-match-propertized-text 'markdown-metadata-key last))
4185 (defun markdown-match-wiki-link (last)
4186 "Match wiki links from point to LAST."
4187 (when (and markdown-enable-wiki-links
4188 (not markdown-wiki-link-fontify-missing)
4189 (markdown-match-inline-generic markdown-regex-wiki-link last))
4190 (let ((begin (match-beginning 1)) (end (match-end 1)))
4191 (if (or (markdown-in-comment-p begin)
4192 (markdown-in-comment-p end)
4193 (markdown-inline-code-at-pos-p begin)
4194 (markdown-inline-code-at-pos-p end)
4195 (markdown-code-block-at-pos begin))
4196 (progn (goto-char (min (1+ begin) last))
4197 (when (< (point) last)
4198 (markdown-match-wiki-link last)))
4199 (set-match-data (list begin end))
4200 t))))
4202 (defun markdown-match-inline-attributes (last)
4203 "Match inline attributes from point to LAST."
4204 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4205 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4206 (markdown-inline-code-at-pos-p (match-end 0))
4207 (markdown-in-comment-p))
4208 t)))
4210 (defun markdown-match-leanpub-sections (last)
4211 "Match Leanpub section markers from point to LAST."
4212 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4213 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4214 (markdown-inline-code-at-pos-p (match-end 0))
4215 (markdown-in-comment-p))
4216 t)))
4218 (defun markdown-match-includes (last)
4219 "Match include statements from point to LAST.
4220 Sets match data for the following seven groups:
4221 Group 1: opening two angle brackets
4222 Group 2: opening title delimiter (optional)
4223 Group 3: title text (optional)
4224 Group 4: closing title delimiter (optional)
4225 Group 5: opening filename delimiter
4226 Group 6: filename
4227 Group 7: closing filename delimiter"
4228 (when (markdown-match-inline-generic markdown-regex-include last)
4229 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4230 (markdown-in-comment-p (match-end 0))
4231 (markdown-code-block-at-pos (match-beginning 0))))))
4232 (cond
4233 ;; Parentheses and maybe square brackets, but no curly braces:
4234 ;; match optional title in square brackets and file in parentheses.
4235 ((and valid (match-beginning 5)
4236 (not (match-beginning 8)))
4237 (set-match-data (list (match-beginning 1) (match-end 7)
4238 (match-beginning 1) (match-end 1)
4239 (match-beginning 2) (match-end 2)
4240 (match-beginning 3) (match-end 3)
4241 (match-beginning 4) (match-end 4)
4242 (match-beginning 5) (match-end 5)
4243 (match-beginning 6) (match-end 6)
4244 (match-beginning 7) (match-end 7))))
4245 ;; Only square brackets present: match file in square brackets.
4246 ((and valid (match-beginning 2)
4247 (not (match-beginning 5))
4248 (not (match-beginning 7)))
4249 (set-match-data (list (match-beginning 1) (match-end 4)
4250 (match-beginning 1) (match-end 1)
4251 nil nil
4252 nil nil
4253 nil nil
4254 (match-beginning 2) (match-end 2)
4255 (match-beginning 3) (match-end 3)
4256 (match-beginning 4) (match-end 4))))
4257 ;; Only curly braces present: match file in curly braces.
4258 ((and valid (match-beginning 8)
4259 (not (match-beginning 2))
4260 (not (match-beginning 5)))
4261 (set-match-data (list (match-beginning 1) (match-end 10)
4262 (match-beginning 1) (match-end 1)
4263 nil nil
4264 nil nil
4265 nil nil
4266 (match-beginning 8) (match-end 8)
4267 (match-beginning 9) (match-end 9)
4268 (match-beginning 10) (match-end 10))))
4270 ;; Not a valid match, move to next line and search again.
4271 (forward-line)
4272 (when (< (point) last)
4273 (setq valid (markdown-match-includes last)))))
4274 valid)))
4276 (defun markdown-match-html-tag (last)
4277 "Match HTML tags from point to LAST."
4278 (when (and markdown-enable-html
4279 (markdown-match-inline-generic markdown-regex-html-tag last t))
4280 (set-match-data (list (match-beginning 0) (match-end 0)
4281 (match-beginning 1) (match-end 1)
4282 (match-beginning 2) (match-end 2)
4283 (match-beginning 9) (match-end 9)))
4287 ;;; Markdown Font Fontification Functions =====================================
4289 (defun markdown--first-displayable (seq)
4290 "Return the first displayable character or string in SEQ.
4291 SEQ may be an atom or a sequence."
4292 (let ((seq (if (listp seq) seq (list seq))))
4293 (cond ((stringp (car seq))
4294 (cl-find-if
4295 (lambda (str)
4296 (and (mapcar #'char-displayable-p (string-to-list str))))
4297 seq))
4298 ((characterp (car seq))
4299 (cl-find-if #'char-displayable-p seq)))))
4301 (defun markdown--marginalize-string (level)
4302 "Generate atx markup string of given LEVEL for left margin."
4303 (let ((margin-left-space-count
4304 (- markdown-marginalize-headers-margin-width level)))
4305 (concat (make-string margin-left-space-count ? )
4306 (make-string level ?#))))
4308 (defun markdown-marginalize-update-current ()
4309 "Update the window configuration to create a left margin."
4310 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4311 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4312 (let* ((header-delimiter-font-width
4313 (window-font-width nil 'markdown-header-delimiter-face))
4314 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4315 header-delimiter-font-width))
4316 (margin-char-width (/ margin-pixel-width (default-font-width))))
4317 (set-window-margins nil margin-char-width))
4318 ;; As a fallback, simply set margin based on character count.
4319 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4321 (defun markdown-fontify-headings (last)
4322 "Add text properties to headings from point to LAST."
4323 (when (markdown-match-propertized-text 'markdown-heading last)
4324 (let* ((level (markdown-outline-level))
4325 (heading-face
4326 (intern (format "markdown-header-face-%d" level)))
4327 (heading-props `(face ,heading-face))
4328 (left-markup-props
4329 `(face markdown-header-delimiter-face
4330 ,@(cond
4331 (markdown-hide-markup
4332 `(display ""))
4333 (markdown-marginalize-headers
4334 `(display ((margin left-margin)
4335 ,(markdown--marginalize-string level)))))))
4336 (right-markup-props
4337 `(face markdown-header-delimiter-face
4338 ,@(when markdown-hide-markup `(display ""))))
4339 (rule-props `(face markdown-header-rule-face
4340 ,@(when markdown-hide-markup `(display "")))))
4341 (if (match-end 1)
4342 ;; Setext heading
4343 (progn (add-text-properties
4344 (match-beginning 1) (match-end 1) heading-props)
4345 (if (= level 1)
4346 (add-text-properties
4347 (match-beginning 2) (match-end 2) rule-props)
4348 (add-text-properties
4349 (match-beginning 3) (match-end 3) rule-props)))
4350 ;; atx heading
4351 (add-text-properties
4352 (match-beginning 4) (match-end 4) left-markup-props)
4353 (add-text-properties
4354 (match-beginning 5) (match-end 5) heading-props)
4355 (when (match-end 6)
4356 (add-text-properties
4357 (match-beginning 6) (match-end 6) right-markup-props))))
4360 (defun markdown-fontify-tables (last)
4361 (when (and (re-search-forward "|" last t)
4362 (markdown-table-at-point-p))
4363 (font-lock-append-text-property
4364 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
4365 'face 'markdown-table-face)
4366 (forward-line 1)
4369 (defun markdown-fontify-blockquotes (last)
4370 "Apply font-lock properties to blockquotes from point to LAST."
4371 (when (markdown-match-blockquotes last)
4372 (let ((display-string
4373 (markdown--first-displayable markdown-blockquote-display-char)))
4374 (add-text-properties
4375 (match-beginning 1) (match-end 1)
4376 (if markdown-hide-markup
4377 `(face markdown-blockquote-face display ,display-string)
4378 `(face markdown-markup-face)))
4379 (font-lock-append-text-property
4380 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4381 t)))
4383 (defun markdown-fontify-list-items (last)
4384 "Apply font-lock properties to list markers from point to LAST."
4385 (when (markdown-match-list-items last)
4386 (let* ((indent (length (match-string-no-properties 1)))
4387 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4388 (bullet (nth (mod level (length markdown-list-item-bullets))
4389 markdown-list-item-bullets)))
4390 (add-text-properties
4391 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4392 (when markdown-hide-markup
4393 (cond
4394 ;; Unordered lists
4395 ((string-match-p "[\\*\\+-]" (match-string 2))
4396 (add-text-properties
4397 (match-beginning 2) (match-end 2) `(display ,bullet)))
4398 ;; Definition lists
4399 ((string-equal ":" (match-string 2))
4400 (let ((display-string
4401 (char-to-string (markdown--first-displayable
4402 markdown-definition-display-char))))
4403 (add-text-properties (match-beginning 2) (match-end 2)
4404 `(display ,display-string)))))))
4407 (defun markdown-fontify-hrs (last)
4408 "Add text properties to horizontal rules from point to LAST."
4409 (when (markdown-match-hr last)
4410 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4411 (add-text-properties
4412 (match-beginning 0) (match-end 0)
4413 `(face markdown-hr-face
4414 font-lock-multiline t
4415 ,@(when (and markdown-hide-markup hr-char)
4416 `(display ,(make-string
4417 (window-body-width) hr-char)))))
4418 t)))
4420 (defun markdown-fontify-sub-superscripts (last)
4421 "Apply text properties to sub- and superscripts from point to LAST."
4422 (when (markdown-search-until-condition
4423 (lambda () (and (not (markdown-code-block-at-point-p))
4424 (not (markdown-inline-code-at-point-p))
4425 (not (markdown-in-comment-p))))
4426 markdown-regex-sub-superscript last t)
4427 (let* ((subscript-p (string= (match-string 2) "~"))
4428 (props
4429 (if subscript-p
4430 (car markdown-sub-superscript-display)
4431 (cdr markdown-sub-superscript-display)))
4432 (mp (list 'face 'markdown-markup-face
4433 'invisible 'markdown-markup)))
4434 (when markdown-hide-markup
4435 (put-text-property (match-beginning 3) (match-end 3)
4436 'display props))
4437 (add-text-properties (match-beginning 2) (match-end 2) mp)
4438 (add-text-properties (match-beginning 4) (match-end 4) mp)
4439 t)))
4442 ;;; Syntax Table ==============================================================
4444 (defvar markdown-mode-syntax-table
4445 (let ((tab (make-syntax-table text-mode-syntax-table)))
4446 (modify-syntax-entry ?\" "." tab)
4447 tab)
4448 "Syntax table for `markdown-mode'.")
4451 ;;; Element Insertion =========================================================
4453 (defun markdown-ensure-blank-line-before ()
4454 "If previous line is not already blank, insert a blank line before point."
4455 (unless (bolp) (insert "\n"))
4456 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4458 (defun markdown-ensure-blank-line-after ()
4459 "If following line is not already blank, insert a blank line after point.
4460 Return the point where it was originally."
4461 (save-excursion
4462 (unless (eolp) (insert "\n"))
4463 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4465 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4466 "Insert the strings S1 and S2, wrapping around region or THING.
4467 If a region is specified by the optional BEG and END arguments,
4468 wrap the strings S1 and S2 around that region.
4469 If there is an active region, wrap the strings S1 and S2 around
4470 the region. If there is not an active region but the point is at
4471 THING, wrap that thing (which defaults to word). Otherwise, just
4472 insert S1 and S2 and place the point in between. Return the
4473 bounds of the entire wrapped string, or nil if nothing was wrapped
4474 and S1 and S2 were only inserted."
4475 (let (a b bounds new-point)
4476 (cond
4477 ;; Given region
4478 ((and beg end)
4479 (setq a beg
4480 b end
4481 new-point (+ (point) (length s1))))
4482 ;; Active region
4483 ((markdown-use-region-p)
4484 (setq a (region-beginning)
4485 b (region-end)
4486 new-point (+ (point) (length s1))))
4487 ;; Thing (word) at point
4488 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4489 (setq a (car bounds)
4490 b (cdr bounds)
4491 new-point (+ (point) (length s1))))
4492 ;; No active region and no word
4494 (setq a (point)
4495 b (point))))
4496 (goto-char b)
4497 (insert s2)
4498 (goto-char a)
4499 (insert s1)
4500 (when new-point (goto-char new-point))
4501 (if (= a b)
4503 (setq b (+ b (length s1) (length s2)))
4504 (cons a b))))
4506 (defun markdown-point-after-unwrap (cur prefix suffix)
4507 "Return desired position of point after an unwrapping operation.
4508 CUR gives the position of the point before the operation.
4509 Additionally, two cons cells must be provided. PREFIX gives the
4510 bounds of the prefix string and SUFFIX gives the bounds of the
4511 suffix string."
4512 (cond ((< cur (cdr prefix)) (car prefix))
4513 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4514 ((<= cur (cdr suffix))
4515 (- cur (+ (- (cdr prefix) (car prefix))
4516 (- cur (car suffix)))))
4517 (t cur)))
4519 (defun markdown-unwrap-thing-at-point (regexp all text)
4520 "Remove prefix and suffix of thing at point and reposition the point.
4521 When the thing at point matches REGEXP, replace the subexpression
4522 ALL with the string in subexpression TEXT. Reposition the point
4523 in an appropriate location accounting for the removal of prefix
4524 and suffix strings. Return new bounds of string from group TEXT.
4525 When REGEXP is nil, assumes match data is already set."
4526 (when (or (null regexp)
4527 (thing-at-point-looking-at regexp))
4528 (let ((cur (point))
4529 (prefix (cons (match-beginning all) (match-beginning text)))
4530 (suffix (cons (match-end text) (match-end all)))
4531 (bounds (cons (match-beginning text) (match-end text))))
4532 ;; Replace the thing at point
4533 (replace-match (match-string text) t t nil all)
4534 ;; Reposition the point
4535 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4536 ;; Adjust bounds
4537 (setq bounds (cons (car prefix)
4538 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4540 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4541 "Remove prefix and suffix of all things in region from BEG to END.
4542 When a thing in the region matches REGEXP, replace the
4543 subexpression ALL with the string in subexpression TEXT.
4544 Return a cons cell containing updated bounds for the region."
4545 (save-excursion
4546 (goto-char beg)
4547 (let ((removed 0) len-all len-text)
4548 (while (re-search-forward regexp (- end removed) t)
4549 (setq len-all (length (match-string-no-properties all)))
4550 (setq len-text (length (match-string-no-properties text)))
4551 (setq removed (+ removed (- len-all len-text)))
4552 (replace-match (match-string text) t t nil all))
4553 (cons beg (- end removed)))))
4555 (defun markdown-insert-hr (arg)
4556 "Insert or replace a horizonal rule.
4557 By default, use the first element of `markdown-hr-strings'. When
4558 ARG is non-nil, as when given a prefix, select a different
4559 element as follows. When prefixed with \\[universal-argument],
4560 use the last element of `markdown-hr-strings' instead. When
4561 prefixed with an integer from 1 to the length of
4562 `markdown-hr-strings', use the element in that position instead."
4563 (interactive "*P")
4564 (when (thing-at-point-looking-at markdown-regex-hr)
4565 (delete-region (match-beginning 0) (match-end 0)))
4566 (markdown-ensure-blank-line-before)
4567 (cond ((equal arg '(4))
4568 (insert (car (reverse markdown-hr-strings))))
4569 ((and (integerp arg) (> arg 0)
4570 (<= arg (length markdown-hr-strings)))
4571 (insert (nth (1- arg) markdown-hr-strings)))
4573 (insert (car markdown-hr-strings))))
4574 (markdown-ensure-blank-line-after))
4576 (defun markdown-insert-bold ()
4577 "Insert markup to make a region or word bold.
4578 If there is an active region, make the region bold. If the point
4579 is at a non-bold word, make the word bold. If the point is at a
4580 bold word or phrase, remove the bold markup. Otherwise, simply
4581 insert bold delimiters and place the point in between them."
4582 (interactive)
4583 (let ((delim (if markdown-bold-underscore "__" "**")))
4584 (if (markdown-use-region-p)
4585 ;; Active region
4586 (let ((bounds (markdown-unwrap-things-in-region
4587 (region-beginning) (region-end)
4588 markdown-regex-bold 2 4)))
4589 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4590 ;; Bold markup removal, bold word at point, or empty markup insertion
4591 (if (thing-at-point-looking-at markdown-regex-bold)
4592 (markdown-unwrap-thing-at-point nil 2 4)
4593 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4595 (defun markdown-insert-italic ()
4596 "Insert markup to make a region or word italic.
4597 If there is an active region, make the region italic. If the point
4598 is at a non-italic word, make the word italic. If the point is at an
4599 italic word or phrase, remove the italic markup. Otherwise, simply
4600 insert italic delimiters and place the point in between them."
4601 (interactive)
4602 (let ((delim (if markdown-italic-underscore "_" "*")))
4603 (if (markdown-use-region-p)
4604 ;; Active region
4605 (let ((bounds (markdown-unwrap-things-in-region
4606 (region-beginning) (region-end)
4607 markdown-regex-italic 1 3)))
4608 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4609 ;; Italic markup removal, italic word at point, or empty markup insertion
4610 (if (thing-at-point-looking-at markdown-regex-italic)
4611 (markdown-unwrap-thing-at-point nil 1 3)
4612 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4614 (defun markdown-insert-strike-through ()
4615 "Insert markup to make a region or word strikethrough.
4616 If there is an active region, make the region strikethrough. If the point
4617 is at a non-bold word, make the word strikethrough. If the point is at a
4618 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4619 simply insert bold delimiters and place the point in between them."
4620 (interactive)
4621 (let ((delim "~~"))
4622 (if (markdown-use-region-p)
4623 ;; Active region
4624 (let ((bounds (markdown-unwrap-things-in-region
4625 (region-beginning) (region-end)
4626 markdown-regex-strike-through 2 4)))
4627 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4628 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4629 (if (thing-at-point-looking-at markdown-regex-strike-through)
4630 (markdown-unwrap-thing-at-point nil 2 4)
4631 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4633 (defun markdown-insert-code ()
4634 "Insert markup to make a region or word an inline code fragment.
4635 If there is an active region, make the region an inline code
4636 fragment. If the point is at a word, make the word an inline
4637 code fragment. Otherwise, simply insert code delimiters and
4638 place the point in between them."
4639 (interactive)
4640 (if (markdown-use-region-p)
4641 ;; Active region
4642 (let ((bounds (markdown-unwrap-things-in-region
4643 (region-beginning) (region-end)
4644 markdown-regex-code 1 3)))
4645 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4646 ;; Code markup removal, code markup for word, or empty markup insertion
4647 (if (markdown-inline-code-at-point)
4648 (markdown-unwrap-thing-at-point nil 0 2)
4649 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4651 (defun markdown-insert-kbd ()
4652 "Insert markup to wrap region or word in <kbd> tags.
4653 If there is an active region, use the region. If the point is at
4654 a word, use the word. Otherwise, simply insert <kbd> tags and
4655 place the point in between them."
4656 (interactive)
4657 (if (markdown-use-region-p)
4658 ;; Active region
4659 (let ((bounds (markdown-unwrap-things-in-region
4660 (region-beginning) (region-end)
4661 markdown-regex-kbd 0 2)))
4662 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4663 ;; Markup removal, markup for word, or empty markup insertion
4664 (if (thing-at-point-looking-at markdown-regex-kbd)
4665 (markdown-unwrap-thing-at-point nil 0 2)
4666 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4668 (defun markdown-insert-inline-link (text url &optional title)
4669 "Insert an inline link with TEXT pointing to URL.
4670 Optionally, the user can provide a TITLE."
4671 (let ((cur (point)))
4672 (setq title (and title (concat " \"" title "\"")))
4673 (insert (concat "[" text "](" url title ")"))
4674 (cond ((not text) (goto-char (+ 1 cur)))
4675 ((not url) (goto-char (+ 3 (length text) cur))))))
4677 (defun markdown-insert-inline-image (text url &optional title)
4678 "Insert an inline link with alt TEXT pointing to URL.
4679 Optionally, also provide a TITLE."
4680 (let ((cur (point)))
4681 (setq title (and title (concat " \"" title "\"")))
4682 (insert (concat "![" text "](" url title ")"))
4683 (cond ((not text) (goto-char (+ 2 cur)))
4684 ((not url) (goto-char (+ 4 (length text) cur))))))
4686 (defun markdown-insert-reference-link (text label &optional url title)
4687 "Insert a reference link and, optionally, a reference definition.
4688 The link TEXT will be inserted followed by the optional LABEL.
4689 If a URL is given, also insert a definition for the reference
4690 LABEL according to `markdown-reference-location'. If a TITLE is
4691 given, it will be added to the end of the reference definition
4692 and will be used to populate the title attribute when converted
4693 to XHTML. If URL is nil, insert only the link portion (for
4694 example, when a reference label is already defined)."
4695 (insert (concat "[" text "][" label "]"))
4696 (when url
4697 (markdown-insert-reference-definition
4698 (if (string-equal label "") text label)
4699 url title)))
4701 (defun markdown-insert-reference-image (text label &optional url title)
4702 "Insert a reference image and, optionally, a reference definition.
4703 The alt TEXT will be inserted followed by the optional LABEL.
4704 If a URL is given, also insert a definition for the reference
4705 LABEL according to `markdown-reference-location'. If a TITLE is
4706 given, it will be added to the end of the reference definition
4707 and will be used to populate the title attribute when converted
4708 to XHTML. If URL is nil, insert only the link portion (for
4709 example, when a reference label is already defined)."
4710 (insert (concat "![" text "][" label "]"))
4711 (when url
4712 (markdown-insert-reference-definition
4713 (if (string-equal label "") text label)
4714 url title)))
4716 (defun markdown-insert-reference-definition (label &optional url title)
4717 "Add definition for reference LABEL with URL and TITLE.
4718 LABEL is a Markdown reference label without square brackets.
4719 URL and TITLE are optional. When given, the TITLE will
4720 be used to populate the title attribute when converted to XHTML."
4721 ;; END specifies where to leave the point upon return
4722 (let ((end (point)))
4723 (cl-case markdown-reference-location
4724 (end (goto-char (point-max)))
4725 (immediately (markdown-end-of-text-block))
4726 (subtree (markdown-end-of-subtree))
4727 (header (markdown-end-of-defun)))
4728 ;; Skip backwards over local variables. This logic is similar to the one
4729 ;; used in ‘hack-local-variables’.
4730 (when (and enable-local-variables (eobp))
4731 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4732 (when (let ((case-fold-search t))
4733 (search-forward "Local Variables:" nil :move))
4734 (beginning-of-line 0)
4735 (when (eq (char-before) ?\n) (backward-char))))
4736 (unless (or (markdown-cur-line-blank-p)
4737 (thing-at-point-looking-at markdown-regex-reference-definition))
4738 (insert "\n"))
4739 (insert "\n[" label "]: ")
4740 (if url
4741 (insert url)
4742 ;; When no URL is given, leave point at END following the colon
4743 (setq end (point)))
4744 (when (> (length title) 0)
4745 (insert " \"" title "\""))
4746 (unless (looking-at-p "\n")
4747 (insert "\n"))
4748 (goto-char end)
4749 (when url
4750 (message
4751 (markdown--substitute-command-keys
4752 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4753 label))))
4755 (define-obsolete-function-alias
4756 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4757 (define-obsolete-function-alias
4758 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4760 (defun markdown--insert-link-or-image (image)
4761 "Interactively insert new or update an existing link or image.
4762 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4763 This is an internal function called by
4764 `markdown-insert-link' and `markdown-insert-image'."
4765 (cl-multiple-value-bind (begin end text uri ref title)
4766 (if (markdown-use-region-p)
4767 ;; Use region as either link text or URL as appropriate.
4768 (let ((region (buffer-substring-no-properties
4769 (region-beginning) (region-end))))
4770 (if (string-match markdown-regex-uri region)
4771 ;; Region contains a URL; use it as such.
4772 (list (region-beginning) (region-end)
4773 nil (match-string 0 region) nil nil)
4774 ;; Region doesn't contain a URL, so use it as text.
4775 (list (region-beginning) (region-end)
4776 region nil nil nil)))
4777 ;; Extract and use properties of existing link, if any.
4778 (markdown-link-at-pos (point)))
4779 (let* ((ref (when ref (concat "[" ref "]")))
4780 (defined-refs (append
4781 (mapcar (lambda (ref) (concat "[" ref "]"))
4782 (markdown-get-defined-references))))
4783 (used-uris (markdown-get-used-uris))
4784 (uri-or-ref (completing-read
4785 "URL or [reference]: "
4786 (append defined-refs used-uris)
4787 nil nil (or uri ref)))
4788 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4789 (match-string 1 uri-or-ref))
4790 ((string-equal "" uri-or-ref)
4791 "")))
4792 (uri (unless ref uri-or-ref))
4793 (text-prompt (if image
4794 "Alt text: "
4795 (if ref
4796 "Link text: "
4797 "Link text (blank for plain URL): ")))
4798 (text (read-string text-prompt text))
4799 (text (if (= (length text) 0) nil text))
4800 (plainp (and uri (not text)))
4801 (implicitp (string-equal ref ""))
4802 (ref (if implicitp text ref))
4803 (definedp (and ref (markdown-reference-definition ref)))
4804 (ref-url (unless (or uri definedp)
4805 (completing-read "Reference URL: " used-uris)))
4806 (title (unless (or plainp definedp)
4807 (read-string "Title (tooltip text, optional): " title)))
4808 (title (if (= (length title) 0) nil title)))
4809 (when (and image implicitp)
4810 (user-error "Reference required: implicit image references are invalid"))
4811 (when (and begin end)
4812 (delete-region begin end))
4813 (cond
4814 ((and (not image) uri text)
4815 (markdown-insert-inline-link text uri title))
4816 ((and image uri text)
4817 (markdown-insert-inline-image text uri title))
4818 ((and ref text)
4819 (if image
4820 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4821 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4822 (unless definedp
4823 (markdown-insert-reference-definition ref ref-url title)))
4824 ((and (not image) uri)
4825 (markdown-insert-uri uri))))))
4827 (defun markdown-insert-link ()
4828 "Insert new or update an existing link, with interactive prompts.
4829 If the point is at an existing link or URL, update the link text,
4830 URL, reference label, and/or title. Otherwise, insert a new link.
4831 The type of link inserted (inline, reference, or plain URL)
4832 depends on which values are provided:
4834 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4835 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4836 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4837 * If only a URL is given, insert a plain link: <URL>.
4839 In other words, to create an implicit reference link, leave the
4840 URL prompt empty and to create a plain URL link, leave the link
4841 text empty.
4843 If there is an active region, use the text as the default URL, if
4844 it seems to be a URL, or link text value otherwise.
4846 If a given reference is not defined, this function will
4847 additionally prompt for the URL and optional title. In this case,
4848 the reference definition is placed at the location determined by
4849 `markdown-reference-location'.
4851 Through updating the link, this function can be used to convert a
4852 link of one type (inline, reference, or plain) to another type by
4853 selectively adding or removing information via the prompts."
4854 (interactive)
4855 (markdown--insert-link-or-image nil))
4857 (defun markdown-insert-image ()
4858 "Insert new or update an existing image, with interactive prompts.
4859 If the point is at an existing image, update the alt text, URL,
4860 reference label, and/or title. Otherwise, insert a new image.
4861 The type of image inserted (inline or reference) depends on which
4862 values are provided:
4864 * If a URL and ALT-TEXT are given, insert an inline image:
4865 ![ALT-TEXT](URL).
4866 * If [REF] and ALT-TEXT are given, insert a reference image:
4867 ![ALT-TEXT][REF].
4869 If there is an active region, use the text as the default URL, if
4870 it seems to be a URL, or alt text value otherwise.
4872 If a given reference is not defined, this function will
4873 additionally prompt for the URL and optional title. In this case,
4874 the reference definition is placed at the location determined by
4875 `markdown-reference-location'.
4877 Through updating the image, this function can be used to convert an
4878 image of one type (inline or reference) to another type by
4879 selectively adding or removing information via the prompts."
4880 (interactive)
4881 (markdown--insert-link-or-image t))
4883 (defun markdown-insert-uri (&optional uri)
4884 "Insert markup for an inline URI.
4885 If there is an active region, use it as the URI. If the point is
4886 at a URI, wrap it with angle brackets. If the point is at an
4887 inline URI, remove the angle brackets. Otherwise, simply insert
4888 angle brackets place the point between them."
4889 (interactive)
4890 (if (markdown-use-region-p)
4891 ;; Active region
4892 (let ((bounds (markdown-unwrap-things-in-region
4893 (region-beginning) (region-end)
4894 markdown-regex-angle-uri 0 2)))
4895 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4896 ;; Markup removal, URI at point, new URI, or empty markup insertion
4897 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4898 (markdown-unwrap-thing-at-point nil 0 2)
4899 (if uri
4900 (insert "<" uri ">")
4901 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4903 (defun markdown-insert-wiki-link ()
4904 "Insert a wiki link of the form [[WikiLink]].
4905 If there is an active region, use the region as the link text.
4906 If the point is at a word, use the word as the link text. If
4907 there is no active region and the point is not at word, simply
4908 insert link markup."
4909 (interactive)
4910 (if (markdown-use-region-p)
4911 ;; Active region
4912 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4913 ;; Markup removal, wiki link at at point, or empty markup insertion
4914 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4915 (if (or markdown-wiki-link-alias-first
4916 (null (match-string 5)))
4917 (markdown-unwrap-thing-at-point nil 1 3)
4918 (markdown-unwrap-thing-at-point nil 1 5))
4919 (markdown-wrap-or-insert "[[" "]]"))))
4921 (defun markdown-remove-header ()
4922 "Remove header markup if point is at a header.
4923 Return bounds of remaining header text if a header was removed
4924 and nil otherwise."
4925 (interactive "*")
4926 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4927 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4929 (defun markdown-insert-header (&optional level text setext)
4930 "Insert or replace header markup.
4931 The level of the header is specified by LEVEL and header text is
4932 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4933 default value is 1.
4934 When TEXT is nil, the header text is obtained as follows.
4935 If there is an active region, it is used as the header text.
4936 Otherwise, the current line will be used as the header text.
4937 If there is not an active region and the point is at a header,
4938 remove the header markup and replace with level N header.
4939 Otherwise, insert empty header markup and place the point in
4940 between.
4941 The style of the header will be atx (hash marks) unless
4942 SETEXT is non-nil, in which case a setext-style (underlined)
4943 header will be inserted."
4944 (interactive "p\nsHeader text: ")
4945 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4946 ;; Determine header text if not given
4947 (when (null text)
4948 (if (markdown-use-region-p)
4949 ;; Active region
4950 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4951 ;; No active region
4952 (markdown-remove-header)
4953 (setq text (delete-and-extract-region
4954 (line-beginning-position) (line-end-position)))
4955 (when (and setext (string-match-p "^[ \t]*$" text))
4956 (setq text (read-string "Header text: "))))
4957 (setq text (markdown-compress-whitespace-string text)))
4958 ;; Insertion with given text
4959 (markdown-ensure-blank-line-before)
4960 (let (hdr)
4961 (cond (setext
4962 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4963 (insert text "\n" hdr))
4965 (setq hdr (make-string level ?#))
4966 (insert hdr " " text)
4967 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4968 (markdown-ensure-blank-line-after)
4969 ;; Leave point at end of text
4970 (cond (setext
4971 (backward-char (1+ (string-width text))))
4972 ((null markdown-asymmetric-header)
4973 (backward-char (1+ level)))))
4975 (defun markdown-insert-header-dwim (&optional arg setext)
4976 "Insert or replace header markup.
4977 The level and type of the header are determined automatically by
4978 the type and level of the previous header, unless a prefix
4979 argument is given via ARG.
4980 With a numeric prefix valued 1 to 6, insert a header of the given
4981 level, with the type being determined automatically (note that
4982 only level 1 or 2 setext headers are possible).
4984 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4985 promote the heading by one level.
4986 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4987 demote the heading by one level.
4988 When SETEXT is non-nil, prefer setext-style headers when
4989 possible (levels one and two).
4991 When there is an active region, use it for the header text. When
4992 the point is at an existing header, change the type and level
4993 according to the rules above.
4994 Otherwise, if the line is not empty, create a header using the
4995 text on the current line as the header text.
4996 Finally, if the point is on a blank line, insert empty header
4997 markup (atx) or prompt for text (setext).
4998 See `markdown-insert-header' for more details about how the
4999 header text is determined."
5000 (interactive "*P")
5001 (let (level)
5002 (save-excursion
5003 (when (or (thing-at-point-looking-at markdown-regex-header)
5004 (re-search-backward markdown-regex-header nil t))
5005 ;; level of current or previous header
5006 (setq level (markdown-outline-level))
5007 ;; match group 1 indicates a setext header
5008 (setq setext (match-end 1))))
5009 ;; check prefix argument
5010 (cond
5011 ((and (equal arg '(4)) level (> level 1)) ;; C-u
5012 (cl-decf level))
5013 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
5014 (cl-incf level))
5015 (arg ;; numeric prefix
5016 (setq level (prefix-numeric-value arg))))
5017 ;; setext headers must be level one or two
5018 (and level (setq setext (and setext (<= level 2))))
5019 ;; insert the heading
5020 (markdown-insert-header level nil setext)))
5022 (defun markdown-insert-header-setext-dwim (&optional arg)
5023 "Insert or replace header markup, with preference for setext.
5024 See `markdown-insert-header-dwim' for details, including how ARG is handled."
5025 (interactive "*P")
5026 (markdown-insert-header-dwim arg t))
5028 (defun markdown-insert-header-atx-1 ()
5029 "Insert a first level atx-style (hash mark) header.
5030 See `markdown-insert-header'."
5031 (interactive "*")
5032 (markdown-insert-header 1 nil nil))
5034 (defun markdown-insert-header-atx-2 ()
5035 "Insert a level two atx-style (hash mark) header.
5036 See `markdown-insert-header'."
5037 (interactive "*")
5038 (markdown-insert-header 2 nil nil))
5040 (defun markdown-insert-header-atx-3 ()
5041 "Insert a level three atx-style (hash mark) header.
5042 See `markdown-insert-header'."
5043 (interactive "*")
5044 (markdown-insert-header 3 nil nil))
5046 (defun markdown-insert-header-atx-4 ()
5047 "Insert a level four atx-style (hash mark) header.
5048 See `markdown-insert-header'."
5049 (interactive "*")
5050 (markdown-insert-header 4 nil nil))
5052 (defun markdown-insert-header-atx-5 ()
5053 "Insert a level five atx-style (hash mark) header.
5054 See `markdown-insert-header'."
5055 (interactive "*")
5056 (markdown-insert-header 5 nil nil))
5058 (defun markdown-insert-header-atx-6 ()
5059 "Insert a sixth level atx-style (hash mark) header.
5060 See `markdown-insert-header'."
5061 (interactive "*")
5062 (markdown-insert-header 6 nil nil))
5064 (defun markdown-insert-header-setext-1 ()
5065 "Insert a setext-style (underlined) first-level header.
5066 See `markdown-insert-header'."
5067 (interactive "*")
5068 (markdown-insert-header 1 nil t))
5070 (defun markdown-insert-header-setext-2 ()
5071 "Insert a setext-style (underlined) second-level header.
5072 See `markdown-insert-header'."
5073 (interactive "*")
5074 (markdown-insert-header 2 nil t))
5076 (defun markdown-blockquote-indentation (loc)
5077 "Return string containing necessary indentation for a blockquote at LOC.
5078 Also see `markdown-pre-indentation'."
5079 (save-excursion
5080 (goto-char loc)
5081 (let* ((list-level (length (markdown-calculate-list-levels)))
5082 (indent ""))
5083 (dotimes (_ list-level indent)
5084 (setq indent (concat indent " "))))))
5086 (defun markdown-insert-blockquote ()
5087 "Start a blockquote section (or blockquote the region).
5088 If Transient Mark mode is on and a region is active, it is used as
5089 the blockquote text."
5090 (interactive)
5091 (if (markdown-use-region-p)
5092 (markdown-blockquote-region (region-beginning) (region-end))
5093 (markdown-ensure-blank-line-before)
5094 (insert (markdown-blockquote-indentation (point)) "> ")
5095 (markdown-ensure-blank-line-after)))
5097 (defun markdown-block-region (beg end prefix)
5098 "Format the region using a block prefix.
5099 Arguments BEG and END specify the beginning and end of the
5100 region. The characters PREFIX will appear at the beginning
5101 of each line."
5102 (save-excursion
5103 (let* ((end-marker (make-marker))
5104 (beg-marker (make-marker))
5105 (prefix-without-trailing-whitespace
5106 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
5107 ;; Ensure blank line after and remove extra whitespace
5108 (goto-char end)
5109 (skip-syntax-backward "-")
5110 (set-marker end-marker (point))
5111 (delete-horizontal-space)
5112 (markdown-ensure-blank-line-after)
5113 ;; Ensure blank line before and remove extra whitespace
5114 (goto-char beg)
5115 (skip-syntax-forward "-")
5116 (delete-horizontal-space)
5117 (markdown-ensure-blank-line-before)
5118 (set-marker beg-marker (point))
5119 ;; Insert PREFIX before each line
5120 (goto-char beg-marker)
5121 (while (and (< (line-beginning-position) end-marker)
5122 (not (eobp)))
5123 ;; Don’t insert trailing whitespace.
5124 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
5125 (forward-line)))))
5127 (defun markdown-blockquote-region (beg end)
5128 "Blockquote the region.
5129 Arguments BEG and END specify the beginning and end of the region."
5130 (interactive "*r")
5131 (markdown-block-region
5132 beg end (concat (markdown-blockquote-indentation
5133 (max (point-min) (1- beg))) "> ")))
5135 (defun markdown-pre-indentation (loc)
5136 "Return string containing necessary whitespace for a pre block at LOC.
5137 Also see `markdown-blockquote-indentation'."
5138 (save-excursion
5139 (goto-char loc)
5140 (let* ((list-level (length (markdown-calculate-list-levels)))
5141 indent)
5142 (dotimes (_ (1+ list-level) indent)
5143 (setq indent (concat indent " "))))))
5145 (defun markdown-insert-pre ()
5146 "Start a preformatted section (or apply to the region).
5147 If Transient Mark mode is on and a region is active, it is marked
5148 as preformatted text."
5149 (interactive)
5150 (if (markdown-use-region-p)
5151 (markdown-pre-region (region-beginning) (region-end))
5152 (markdown-ensure-blank-line-before)
5153 (insert (markdown-pre-indentation (point)))
5154 (markdown-ensure-blank-line-after)))
5156 (defun markdown-pre-region (beg end)
5157 "Format the region as preformatted text.
5158 Arguments BEG and END specify the beginning and end of the region."
5159 (interactive "*r")
5160 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5161 (markdown-block-region beg end indent)))
5163 (defun markdown-electric-backquote (arg)
5164 "Insert a backquote.
5165 The numeric prefix argument ARG says how many times to repeat the insertion.
5166 Call `markdown-insert-gfm-code-block' interactively
5167 if three backquotes inserted at the beginning of line."
5168 (interactive "*P")
5169 (self-insert-command (prefix-numeric-value arg))
5170 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5171 (replace-match "")
5172 (call-interactively #'markdown-insert-gfm-code-block)))
5174 (defconst markdown-gfm-recognized-languages
5175 ;; To reproduce/update, evaluate the let-form in
5176 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5177 ;; but with appropriate use of a keyboard macro, indenting and filling it
5178 ;; properly is pretty fast.
5179 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5180 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5181 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5182 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5183 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5184 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5185 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5186 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5187 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5188 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5189 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5190 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5191 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5192 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5193 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5194 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5195 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5196 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5197 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5198 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5199 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5200 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5201 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5202 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5203 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5204 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5205 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5206 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5207 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5208 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5209 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5210 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5211 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5212 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5213 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5214 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5215 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5216 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5217 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5218 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5219 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5220 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5221 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5222 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5223 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5224 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5225 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5226 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5227 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5228 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5229 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5230 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5231 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5232 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5233 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5234 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5235 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5236 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5237 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5238 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5239 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5240 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5241 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5242 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5243 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5244 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5245 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5246 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5247 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5248 "Language specifiers recognized by GitHub's syntax highlighting features.")
5250 (defvar markdown-gfm-used-languages nil
5251 "Language names used in GFM code blocks.")
5252 (make-variable-buffer-local 'markdown-gfm-used-languages)
5254 (defun markdown-trim-whitespace (str)
5255 (markdown-replace-regexp-in-string
5256 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5258 (defun markdown-clean-language-string (str)
5259 (markdown-replace-regexp-in-string
5260 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5262 (defun markdown-validate-language-string (widget)
5263 (let ((str (widget-value widget)))
5264 (unless (string= str (markdown-clean-language-string str))
5265 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5266 widget)))
5268 (defun markdown-gfm-get-corpus ()
5269 "Create corpus of recognized GFM code block languages for the given buffer."
5270 (let ((given-corpus (append markdown-gfm-additional-languages
5271 markdown-gfm-recognized-languages)))
5272 (append
5273 markdown-gfm-used-languages
5274 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5275 given-corpus))))
5277 (defun markdown-gfm-add-used-language (lang)
5278 "Clean LANG and add to list of used languages."
5279 (setq markdown-gfm-used-languages
5280 (cons lang (remove lang markdown-gfm-used-languages))))
5282 (defcustom markdown-spaces-after-code-fence 1
5283 "Number of space characters to insert after a code fence.
5284 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5285 opening code fence and an info string."
5286 :group 'markdown
5287 :type 'integer
5288 :safe #'natnump
5289 :package-version '(markdown-mode . "2.3"))
5291 (defun markdown-insert-gfm-code-block (&optional lang edit)
5292 "Insert GFM code block for language LANG.
5293 If LANG is nil, the language will be queried from user. If a
5294 region is active, wrap this region with the markup instead. If
5295 the region boundaries are not on empty lines, these are added
5296 automatically in order to have the correct markup. When EDIT is
5297 non-nil (e.g., when \\[universal-argument] is given), edit the
5298 code block in an indirect buffer after insertion."
5299 (interactive
5300 (list (let ((completion-ignore-case nil))
5301 (condition-case nil
5302 (markdown-clean-language-string
5303 (completing-read
5304 "Programming language: "
5305 (markdown-gfm-get-corpus)
5306 nil 'confirm (car markdown-gfm-used-languages)
5307 'markdown-gfm-language-history))
5308 (quit "")))
5309 current-prefix-arg))
5310 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5311 (when (> (length lang) 0)
5312 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5313 lang)))
5314 (if (markdown-use-region-p)
5315 (let* ((b (region-beginning)) (e (region-end)) end
5316 (indent (progn (goto-char b) (current-indentation))))
5317 (goto-char e)
5318 ;; if we're on a blank line, don't newline, otherwise the ```
5319 ;; should go on its own line
5320 (unless (looking-back "\n" nil)
5321 (newline))
5322 (indent-to indent)
5323 (insert "```")
5324 (markdown-ensure-blank-line-after)
5325 (setq end (point))
5326 (goto-char b)
5327 ;; if we're on a blank line, insert the quotes here, otherwise
5328 ;; add a new line first
5329 (unless (looking-at-p "\n")
5330 (newline)
5331 (forward-line -1))
5332 (markdown-ensure-blank-line-before)
5333 (indent-to indent)
5334 (insert "```" lang)
5335 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5336 (let ((indent (current-indentation)) start)
5337 (delete-horizontal-space :backward-only)
5338 (markdown-ensure-blank-line-before)
5339 (indent-to indent)
5340 (setq start (point))
5341 (insert "```" lang "\n")
5342 (indent-to indent)
5343 (unless edit (insert ?\n))
5344 (indent-to indent)
5345 (insert "```")
5346 (markdown-ensure-blank-line-after)
5347 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5348 (end-of-line 0)
5349 (when edit (markdown-edit-code-block))))
5351 (defun markdown-code-block-lang (&optional pos-prop)
5352 "Return the language name for a GFM or tilde fenced code block.
5353 The beginning of the block may be described by POS-PROP,
5354 a cons of (pos . prop) giving the position and property
5355 at the beginning of the block."
5356 (or pos-prop
5357 (setq pos-prop
5358 (markdown-max-of-seq
5359 #'car
5360 (cl-remove-if
5361 #'null
5362 (cl-mapcar
5363 #'markdown-find-previous-prop
5364 (markdown-get-fenced-block-begin-properties))))))
5365 (when pos-prop
5366 (goto-char (car pos-prop))
5367 (set-match-data (get-text-property (point) (cdr pos-prop)))
5368 ;; Note: Hard-coded group number assumes tilde
5369 ;; and GFM fenced code regexp groups agree.
5370 (let ((begin (match-beginning 3))
5371 (end (match-end 3)))
5372 (when (and begin end)
5373 ;; Fix language strings beginning with periods, like ".ruby".
5374 (when (eq (char-after begin) ?.)
5375 (setq begin (1+ begin)))
5376 (buffer-substring-no-properties begin end)))))
5378 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5379 (with-current-buffer (or buffer (current-buffer))
5380 (save-excursion
5381 (goto-char (point-min))
5382 (cl-loop
5383 with prop = 'markdown-gfm-block-begin
5384 for pos-prop = (markdown-find-next-prop prop)
5385 while pos-prop
5386 for lang = (markdown-code-block-lang pos-prop)
5387 do (progn (when lang (markdown-gfm-add-used-language lang))
5388 (goto-char (next-single-property-change (point) prop)))))))
5391 ;;; Footnotes ==================================================================
5393 (defun markdown-footnote-counter-inc ()
5394 "Increment `markdown-footnote-counter' and return the new value."
5395 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5396 (save-excursion
5397 (goto-char (point-min))
5398 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5399 (point-max) t)
5400 (let ((fn (string-to-number (match-string 1))))
5401 (when (> fn markdown-footnote-counter)
5402 (setq markdown-footnote-counter fn))))))
5403 (cl-incf markdown-footnote-counter))
5405 (defun markdown-insert-footnote ()
5406 "Insert footnote with a new number and move point to footnote definition."
5407 (interactive)
5408 (let ((fn (markdown-footnote-counter-inc)))
5409 (insert (format "[^%d]" fn))
5410 (markdown-footnote-text-find-new-location)
5411 (markdown-ensure-blank-line-before)
5412 (unless (markdown-cur-line-blank-p)
5413 (insert "\n"))
5414 (insert (format "[^%d]: " fn))
5415 (markdown-ensure-blank-line-after)))
5417 (defun markdown-footnote-text-find-new-location ()
5418 "Position the point at the proper location for a new footnote text."
5419 (cond
5420 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5421 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5422 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5423 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5425 (defun markdown-footnote-kill ()
5426 "Kill the footnote at point.
5427 The footnote text is killed (and added to the kill ring), the
5428 footnote marker is deleted. Point has to be either at the
5429 footnote marker or in the footnote text."
5430 (interactive)
5431 (let ((marker-pos nil)
5432 (skip-deleting-marker nil)
5433 (starting-footnote-text-positions
5434 (markdown-footnote-text-positions)))
5435 (when starting-footnote-text-positions
5436 ;; We're starting in footnote text, so mark our return position and jump
5437 ;; to the marker if possible.
5438 (let ((marker-pos (markdown-footnote-find-marker
5439 (cl-first starting-footnote-text-positions))))
5440 (if marker-pos
5441 (goto-char (1- marker-pos))
5442 ;; If there isn't a marker, we still want to kill the text.
5443 (setq skip-deleting-marker t))))
5444 ;; Either we didn't start in the text, or we started in the text and jumped
5445 ;; to the marker. We want to assume we're at the marker now and error if
5446 ;; we're not.
5447 (unless skip-deleting-marker
5448 (let ((marker (markdown-footnote-delete-marker)))
5449 (unless marker
5450 (error "Not at a footnote"))
5451 ;; Even if we knew the text position before, it changed when we deleted
5452 ;; the label.
5453 (setq marker-pos (cl-second marker))
5454 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5455 (unless new-text-pos
5456 (error "No text for footnote `%s'" (cl-first marker)))
5457 (goto-char new-text-pos))))
5458 (let ((pos (markdown-footnote-kill-text)))
5459 (goto-char (if starting-footnote-text-positions
5461 marker-pos)))))
5463 (defun markdown-footnote-delete-marker ()
5464 "Delete a footnote marker at point.
5465 Returns a list (ID START) containing the footnote ID and the
5466 start position of the marker before deletion. If no footnote
5467 marker was deleted, this function returns NIL."
5468 (let ((marker (markdown-footnote-marker-positions)))
5469 (when marker
5470 (delete-region (cl-second marker) (cl-third marker))
5471 (butlast marker))))
5473 (defun markdown-footnote-kill-text ()
5474 "Kill footnote text at point.
5475 Returns the start position of the footnote text before deletion,
5476 or NIL if point was not inside a footnote text.
5478 The killed text is placed in the kill ring (without the footnote
5479 number)."
5480 (let ((fn (markdown-footnote-text-positions)))
5481 (when fn
5482 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5483 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5484 (kill-new (match-string 1 text))
5485 (when (and (markdown-cur-line-blank-p)
5486 (markdown-prev-line-blank-p)
5487 (not (bobp)))
5488 (delete-region (1- (point)) (point)))
5489 (cl-second fn)))))
5491 (defun markdown-footnote-goto-text ()
5492 "Jump to the text of the footnote at point."
5493 (interactive)
5494 (let ((fn (car (markdown-footnote-marker-positions))))
5495 (unless fn
5496 (user-error "Not at a footnote marker"))
5497 (let ((new-pos (markdown-footnote-find-text fn)))
5498 (unless new-pos
5499 (error "No definition found for footnote `%s'" fn))
5500 (goto-char new-pos))))
5502 (defun markdown-footnote-return ()
5503 "Return from a footnote to its footnote number in the main text."
5504 (interactive)
5505 (let ((fn (save-excursion
5506 (car (markdown-footnote-text-positions)))))
5507 (unless fn
5508 (user-error "Not in a footnote"))
5509 (let ((new-pos (markdown-footnote-find-marker fn)))
5510 (unless new-pos
5511 (error "Footnote marker `%s' not found" fn))
5512 (goto-char new-pos))))
5514 (defun markdown-footnote-find-marker (id)
5515 "Find the location of the footnote marker with ID.
5516 The actual buffer position returned is the position directly
5517 following the marker's closing bracket. If no marker is found,
5518 NIL is returned."
5519 (save-excursion
5520 (goto-char (point-min))
5521 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5522 (skip-chars-backward "^]")
5523 (point))))
5525 (defun markdown-footnote-find-text (id)
5526 "Find the location of the text of footnote ID.
5527 The actual buffer position returned is the position of the first
5528 character of the text, after the footnote's identifier. If no
5529 footnote text is found, NIL is returned."
5530 (save-excursion
5531 (goto-char (point-min))
5532 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5533 (skip-chars-forward "[ \t]")
5534 (point))))
5536 (defun markdown-footnote-marker-positions ()
5537 "Return the position and ID of the footnote marker point is on.
5538 The return value is a list (ID START END). If point is not on a
5539 footnote, NIL is returned."
5540 ;; first make sure we're at a footnote marker
5541 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5542 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5543 (save-excursion
5544 ;; move point between [ and ^:
5545 (if (looking-at-p "\\[")
5546 (forward-char 1)
5547 (skip-chars-backward "^["))
5548 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5549 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5551 (defun markdown-footnote-text-positions ()
5552 "Return the start and end positions of the footnote text point is in.
5553 The exact return value is a list of three elements: (ID START END).
5554 The start position is the position of the opening bracket
5555 of the footnote id. The end position is directly after the
5556 newline that ends the footnote. If point is not in a footnote,
5557 NIL is returned instead."
5558 (save-excursion
5559 (let (result)
5560 (move-beginning-of-line 1)
5561 ;; Try to find the label. If we haven't found the label and we're at a blank
5562 ;; or indented line, back up if possible.
5563 (while (and
5564 (not (and (looking-at markdown-regex-footnote-definition)
5565 (setq result (list (match-string 1) (point)))))
5566 (and (not (bobp))
5567 (or (markdown-cur-line-blank-p)
5568 (>= (current-indentation) 4))))
5569 (forward-line -1))
5570 (when result
5571 ;; Advance if there is a next line that is either blank or indented.
5572 ;; (Need to check if we're on the last line, because
5573 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5574 (while (and (/= (line-end-position) (point-max))
5575 (or (markdown-next-line-blank-p)
5576 (>= (markdown-next-line-indent) 4)))
5577 (forward-line))
5578 ;; Move back while the current line is blank.
5579 (while (markdown-cur-line-blank-p)
5580 (forward-line -1))
5581 ;; Advance to capture this line and a single trailing newline (if there
5582 ;; is one).
5583 (forward-line)
5584 (append result (list (point)))))))
5587 ;;; Element Removal ===========================================================
5589 (defun markdown-kill-thing-at-point ()
5590 "Kill thing at point and add important text, without markup, to kill ring.
5591 Possible things to kill include (roughly in order of precedence):
5592 inline code, headers, horizonal rules, links (add link text to
5593 kill ring), images (add alt text to kill ring), angle uri, email
5594 addresses, bold, italics, reference definition (add URI to kill
5595 ring), footnote markers and text (kill both marker and text, add
5596 text to kill ring), and list items."
5597 (interactive "*")
5598 (let (val)
5599 (cond
5600 ;; Inline code
5601 ((markdown-inline-code-at-point)
5602 (kill-new (match-string 2))
5603 (delete-region (match-beginning 0) (match-end 0)))
5604 ;; ATX header
5605 ((thing-at-point-looking-at markdown-regex-header-atx)
5606 (kill-new (match-string 2))
5607 (delete-region (match-beginning 0) (match-end 0)))
5608 ;; Setext header
5609 ((thing-at-point-looking-at markdown-regex-header-setext)
5610 (kill-new (match-string 1))
5611 (delete-region (match-beginning 0) (match-end 0)))
5612 ;; Horizonal rule
5613 ((thing-at-point-looking-at markdown-regex-hr)
5614 (kill-new (match-string 0))
5615 (delete-region (match-beginning 0) (match-end 0)))
5616 ;; Inline link or image (add link or alt text to kill ring)
5617 ((thing-at-point-looking-at markdown-regex-link-inline)
5618 (kill-new (match-string 3))
5619 (delete-region (match-beginning 0) (match-end 0)))
5620 ;; Reference link or image (add link or alt text to kill ring)
5621 ((thing-at-point-looking-at markdown-regex-link-reference)
5622 (kill-new (match-string 3))
5623 (delete-region (match-beginning 0) (match-end 0)))
5624 ;; Angle URI (add URL to kill ring)
5625 ((thing-at-point-looking-at markdown-regex-angle-uri)
5626 (kill-new (match-string 2))
5627 (delete-region (match-beginning 0) (match-end 0)))
5628 ;; Email address in angle brackets (add email address to kill ring)
5629 ((thing-at-point-looking-at markdown-regex-email)
5630 (kill-new (match-string 1))
5631 (delete-region (match-beginning 0) (match-end 0)))
5632 ;; Wiki link (add alias text to kill ring)
5633 ((and markdown-enable-wiki-links
5634 (thing-at-point-looking-at markdown-regex-wiki-link))
5635 (kill-new (markdown-wiki-link-alias))
5636 (delete-region (match-beginning 1) (match-end 1)))
5637 ;; Bold
5638 ((thing-at-point-looking-at markdown-regex-bold)
5639 (kill-new (match-string 4))
5640 (delete-region (match-beginning 2) (match-end 2)))
5641 ;; Italics
5642 ((thing-at-point-looking-at markdown-regex-italic)
5643 (kill-new (match-string 3))
5644 (delete-region (match-beginning 1) (match-end 1)))
5645 ;; Strikethrough
5646 ((thing-at-point-looking-at markdown-regex-strike-through)
5647 (kill-new (match-string 4))
5648 (delete-region (match-beginning 2) (match-end 2)))
5649 ;; Footnote marker (add footnote text to kill ring)
5650 ((thing-at-point-looking-at markdown-regex-footnote)
5651 (markdown-footnote-kill))
5652 ;; Footnote text (add footnote text to kill ring)
5653 ((setq val (markdown-footnote-text-positions))
5654 (markdown-footnote-kill))
5655 ;; Reference definition (add URL to kill ring)
5656 ((thing-at-point-looking-at markdown-regex-reference-definition)
5657 (kill-new (match-string 5))
5658 (delete-region (match-beginning 0) (match-end 0)))
5659 ;; List item
5660 ((setq val (markdown-cur-list-item-bounds))
5661 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5663 (user-error "Nothing found at point to kill")))))
5666 ;;; Indentation ====================================================================
5668 (defun markdown-indent-find-next-position (cur-pos positions)
5669 "Return the position after the index of CUR-POS in POSITIONS.
5670 Positions are calculated by `markdown-calc-indents'."
5671 (while (and positions
5672 (not (equal cur-pos (car positions))))
5673 (setq positions (cdr positions)))
5674 (or (cadr positions) 0))
5676 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5677 'markdown-outdent-find-next-position "v2.3")
5679 (defun markdown-outdent-find-next-position (cur-pos positions)
5680 "Return the maximal element that precedes CUR-POS from POSITIONS.
5681 Positions are calculated by `markdown-calc-indents'."
5682 (let ((result 0))
5683 (dolist (i positions)
5684 (when (< i cur-pos)
5685 (setq result (max result i))))
5686 result))
5688 (defun markdown-indent-line ()
5689 "Indent the current line using some heuristics.
5690 If the _previous_ command was either `markdown-enter-key' or
5691 `markdown-cycle', then we should cycle to the next
5692 reasonable indentation position. Otherwise, we could have been
5693 called directly by `markdown-enter-key', by an initial call of
5694 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5695 these cases, indent to the default position.
5696 Positions are calculated by `markdown-calc-indents'."
5697 (interactive)
5698 (let ((positions (markdown-calc-indents))
5699 (point-pos (current-column))
5700 (_ (back-to-indentation))
5701 (cur-pos (current-column)))
5702 (if (not (equal this-command 'markdown-cycle))
5703 (indent-line-to (car positions))
5704 (setq positions (sort (delete-dups positions) '<))
5705 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5706 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5707 (indent-line-to next-pos)
5708 (move-to-column new-point-pos)))))
5710 (defun markdown-calc-indents ()
5711 "Return a list of indentation columns to cycle through.
5712 The first element in the returned list should be considered the
5713 default indentation level. This function does not worry about
5714 duplicate positions, which are handled up by calling functions."
5715 (let (pos prev-line-pos positions)
5717 ;; Indentation of previous line
5718 (setq prev-line-pos (markdown-prev-line-indent))
5719 (setq positions (cons prev-line-pos positions))
5721 ;; Indentation of previous non-list-marker text
5722 (when (setq pos (markdown-prev-non-list-indent))
5723 (setq positions (cons pos positions)))
5725 ;; Indentation required for a pre block in current context
5726 (setq pos (length (markdown-pre-indentation (point))))
5727 (setq positions (cons pos positions))
5729 ;; Indentation of the previous line + tab-width
5730 (if prev-line-pos
5731 (setq positions (cons (+ prev-line-pos tab-width) positions))
5732 (setq positions (cons tab-width positions)))
5734 ;; Indentation of the previous line - tab-width
5735 (if (and prev-line-pos (> prev-line-pos tab-width))
5736 (setq positions (cons (- prev-line-pos tab-width) positions)))
5738 ;; Indentation of all preceeding list markers (when in a list)
5739 (when (setq pos (markdown-calculate-list-levels))
5740 (setq positions (append pos positions)))
5742 ;; First column
5743 (setq positions (cons 0 positions))
5745 ;; Return reversed list
5746 (reverse positions)))
5748 (defun markdown-enter-key ()
5749 "Handle RET depending on the context.
5750 If the point is at a table, move to the next row. Otherwise,
5751 indent according to value of `markdown-indent-on-enter'.
5752 When it is nil, simply call `newline'. Otherwise, indent the next line
5753 following RET using `markdown-indent-line'. Furthermore, when it
5754 is set to 'indent-and-new-item and the point is in a list item,
5755 start a new item with the same indentation. If the point is in an
5756 empty list item, remove it (so that pressing RET twice when in a
5757 list simply adds a blank line)."
5758 (interactive)
5759 (cond
5760 ;; Table
5761 ((markdown-table-at-point-p)
5762 (call-interactively #'markdown-table-next-row))
5763 ;; Indent non-table text
5764 (markdown-indent-on-enter
5765 (let (bounds)
5766 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5767 (setq bounds (markdown-cur-list-item-bounds)))
5768 (let ((beg (cl-first bounds))
5769 (end (cl-second bounds))
5770 (length (cl-fourth bounds)))
5771 ;; Point is in a list item
5772 (if (= (- end beg) length)
5773 ;; Delete blank list
5774 (progn
5775 (delete-region beg end)
5776 (newline)
5777 (markdown-indent-line))
5778 (call-interactively #'markdown-insert-list-item)))
5779 ;; Point is not in a list
5780 (newline)
5781 (markdown-indent-line))))
5782 ;; Insert a raw newline
5783 (t (newline))))
5785 (define-obsolete-function-alias 'markdown-exdent-or-delete
5786 'markdown-outdent-or-delete "v2.3")
5788 (defun markdown-outdent-or-delete (arg)
5789 "Handle BACKSPACE by cycling through indentation points.
5790 When BACKSPACE is pressed, if there is only whitespace
5791 before the current point, then outdent the line one level.
5792 Otherwise, do normal delete by repeating
5793 `backward-delete-char-untabify' ARG times."
5794 (interactive "*p")
5795 (if (use-region-p)
5796 (backward-delete-char-untabify arg)
5797 (let ((cur-pos (current-column))
5798 (start-of-indention (save-excursion
5799 (back-to-indentation)
5800 (current-column)))
5801 (positions (markdown-calc-indents)))
5802 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5803 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5804 (backward-delete-char-untabify arg)))))
5806 (defun markdown-find-leftmost-column (beg end)
5807 "Find the leftmost column in the region from BEG to END."
5808 (let ((mincol 1000))
5809 (save-excursion
5810 (goto-char beg)
5811 (while (< (point) end)
5812 (back-to-indentation)
5813 (unless (looking-at-p "[ \t]*$")
5814 (setq mincol (min mincol (current-column))))
5815 (forward-line 1)
5817 mincol))
5819 (defun markdown-indent-region (beg end arg)
5820 "Indent the region from BEG to END using some heuristics.
5821 When ARG is non-nil, outdent the region instead.
5822 See `markdown-indent-line' and `markdown-indent-line'."
5823 (interactive "*r\nP")
5824 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5825 (leftmostcol (markdown-find-leftmost-column beg end))
5826 (next-pos (if arg
5827 (markdown-outdent-find-next-position leftmostcol positions)
5828 (markdown-indent-find-next-position leftmostcol positions))))
5829 (indent-rigidly beg end (- next-pos leftmostcol))
5830 (setq deactivate-mark nil)))
5832 (define-obsolete-function-alias 'markdown-exdent-region
5833 'markdown-outdent-region "v2.3")
5835 (defun markdown-outdent-region (beg end)
5836 "Call `markdown-indent-region' on region from BEG to END with prefix."
5837 (interactive "*r")
5838 (markdown-indent-region beg end t))
5841 ;;; Markup Completion =========================================================
5843 (defconst markdown-complete-alist
5844 '((markdown-regex-header-atx . markdown-complete-atx)
5845 (markdown-regex-header-setext . markdown-complete-setext)
5846 (markdown-regex-hr . markdown-complete-hr))
5847 "Association list of form (regexp . function) for markup completion.")
5849 (defun markdown-incomplete-atx-p ()
5850 "Return t if ATX header markup is incomplete and nil otherwise.
5851 Assumes match data is available for `markdown-regex-header-atx'.
5852 Checks that the number of trailing hash marks equals the number of leading
5853 hash marks, that there is only a single space before and after the text,
5854 and that there is no extraneous whitespace in the text."
5856 ;; Number of starting and ending hash marks differs
5857 (not (= (length (match-string 1)) (length (match-string 3))))
5858 ;; When the header text is not empty...
5859 (and (> (length (match-string 2)) 0)
5860 ;; ...if there are extra leading, trailing, or interior spaces
5861 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5862 (not (= (match-beginning 3) (1+ (match-end 2))))
5863 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5864 ;; When the header text is empty...
5865 (and (= (length (match-string 2)) 0)
5866 ;; ...if there are too many or too few spaces
5867 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5869 (defun markdown-complete-atx ()
5870 "Complete and normalize ATX headers.
5871 Add or remove hash marks to the end of the header to match the
5872 beginning. Ensure that there is only a single space between hash
5873 marks and header text. Removes extraneous whitespace from header text.
5874 Assumes match data is available for `markdown-regex-header-atx'.
5875 Return nil if markup was complete and non-nil if markup was completed."
5876 (when (markdown-incomplete-atx-p)
5877 (let* ((new-marker (make-marker))
5878 (new-marker (set-marker new-marker (match-end 2))))
5879 ;; Hash marks and spacing at end
5880 (goto-char (match-end 2))
5881 (delete-region (match-end 2) (match-end 3))
5882 (insert " " (match-string 1))
5883 ;; Remove extraneous whitespace from title
5884 (replace-match (markdown-compress-whitespace-string (match-string 2))
5885 t t nil 2)
5886 ;; Spacing at beginning
5887 (goto-char (match-end 1))
5888 (delete-region (match-end 1) (match-beginning 2))
5889 (insert " ")
5890 ;; Leave point at end of text
5891 (goto-char new-marker))))
5893 (defun markdown-incomplete-setext-p ()
5894 "Return t if setext header markup is incomplete and nil otherwise.
5895 Assumes match data is available for `markdown-regex-header-setext'.
5896 Checks that length of underline matches text and that there is no
5897 extraneous whitespace in the text."
5898 (or (not (= (length (match-string 1)) (length (match-string 2))))
5899 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5901 (defun markdown-complete-setext ()
5902 "Complete and normalize setext headers.
5903 Add or remove underline characters to match length of header
5904 text. Removes extraneous whitespace from header text. Assumes
5905 match data is available for `markdown-regex-header-setext'.
5906 Return nil if markup was complete and non-nil if markup was completed."
5907 (when (markdown-incomplete-setext-p)
5908 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5909 (char (char-after (match-beginning 2)))
5910 (level (if (char-equal char ?-) 2 1)))
5911 (goto-char (match-beginning 0))
5912 (delete-region (match-beginning 0) (match-end 0))
5913 (markdown-insert-header level text t)
5914 t)))
5916 (defun markdown-incomplete-hr-p ()
5917 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5918 Assumes match data is available for `markdown-regex-hr'."
5919 (not (member (match-string 0) markdown-hr-strings)))
5921 (defun markdown-complete-hr ()
5922 "Complete horizontal rules.
5923 If horizontal rule string is a member of `markdown-hr-strings',
5924 do nothing. Otherwise, replace with the car of
5925 `markdown-hr-strings'.
5926 Assumes match data is available for `markdown-regex-hr'.
5927 Return nil if markup was complete and non-nil if markup was completed."
5928 (when (markdown-incomplete-hr-p)
5929 (replace-match (car markdown-hr-strings))
5932 (defun markdown-complete ()
5933 "Complete markup of object near point or in region when active.
5934 Handle all objects in `markdown-complete-alist', in order.
5935 See `markdown-complete-at-point' and `markdown-complete-region'."
5936 (interactive "*")
5937 (if (markdown-use-region-p)
5938 (markdown-complete-region (region-beginning) (region-end))
5939 (markdown-complete-at-point)))
5941 (defun markdown-complete-at-point ()
5942 "Complete markup of object near point.
5943 Handle all elements of `markdown-complete-alist' in order."
5944 (interactive "*")
5945 (let ((list markdown-complete-alist) found changed)
5946 (while list
5947 (let ((regexp (eval (caar list)))
5948 (function (cdar list)))
5949 (setq list (cdr list))
5950 (when (thing-at-point-looking-at regexp)
5951 (setq found t)
5952 (setq changed (funcall function))
5953 (setq list nil))))
5954 (if found
5955 (or changed (user-error "Markup at point is complete"))
5956 (user-error "Nothing to complete at point"))))
5958 (defun markdown-complete-region (beg end)
5959 "Complete markup of objects in region from BEG to END.
5960 Handle all objects in `markdown-complete-alist', in order. Each
5961 match is checked to ensure that a previous regexp does not also
5962 match."
5963 (interactive "*r")
5964 (let ((end-marker (set-marker (make-marker) end))
5965 previous)
5966 (dolist (element markdown-complete-alist)
5967 (let ((regexp (eval (car element)))
5968 (function (cdr element)))
5969 (goto-char beg)
5970 (while (re-search-forward regexp end-marker 'limit)
5971 (when (match-string 0)
5972 ;; Make sure this is not a match for any of the preceding regexps.
5973 ;; This prevents mistaking an HR for a Setext subheading.
5974 (let (match)
5975 (save-match-data
5976 (dolist (prev-regexp previous)
5977 (or match (setq match (looking-back prev-regexp nil)))))
5978 (unless match
5979 (save-excursion (funcall function))))))
5980 (cl-pushnew regexp previous :test #'equal)))
5981 previous))
5983 (defun markdown-complete-buffer ()
5984 "Complete markup for all objects in the current buffer."
5985 (interactive "*")
5986 (markdown-complete-region (point-min) (point-max)))
5989 ;;; Markup Cycling ============================================================
5991 (defun markdown-cycle-atx (arg &optional remove)
5992 "Cycle ATX header markup.
5993 Promote header (decrease level) when ARG is 1 and demote
5994 header (increase level) if arg is -1. When REMOVE is non-nil,
5995 remove the header when the level reaches zero and stop cycling
5996 when it reaches six. Otherwise, perform a proper cycling through
5997 levels one through six. Assumes match data is available for
5998 `markdown-regex-header-atx'."
5999 (let* ((old-level (length (match-string 1)))
6000 (new-level (+ old-level arg))
6001 (text (match-string 2)))
6002 (when (not remove)
6003 (setq new-level (% new-level 6))
6004 (setq new-level (cond ((= new-level 0) 6)
6005 ((< new-level 0) (+ new-level 6))
6006 (t new-level))))
6007 (cond
6008 ((= new-level 0)
6009 (markdown-unwrap-thing-at-point nil 0 2))
6010 ((<= new-level 6)
6011 (goto-char (match-beginning 0))
6012 (delete-region (match-beginning 0) (match-end 0))
6013 (markdown-insert-header new-level text nil)))))
6015 (defun markdown-cycle-setext (arg &optional remove)
6016 "Cycle setext header markup.
6017 Promote header (increase level) when ARG is 1 and demote
6018 header (decrease level or remove) if arg is -1. When demoting a
6019 level-two setext header, replace with a level-three atx header.
6020 When REMOVE is non-nil, remove the header when the level reaches
6021 zero. Otherwise, cycle back to a level six atx header. Assumes
6022 match data is available for `markdown-regex-header-setext'."
6023 (let* ((char (char-after (match-beginning 2)))
6024 (old-level (if (char-equal char ?=) 1 2))
6025 (new-level (+ old-level arg)))
6026 (when (and (not remove) (= new-level 0))
6027 (setq new-level 6))
6028 (cond
6029 ((= new-level 0)
6030 (markdown-unwrap-thing-at-point nil 0 1))
6031 ((<= new-level 2)
6032 (markdown-insert-header new-level nil t))
6033 ((<= new-level 6)
6034 (markdown-insert-header new-level nil nil)))))
6036 (defun markdown-cycle-hr (arg &optional remove)
6037 "Cycle string used for horizontal rule from `markdown-hr-strings'.
6038 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
6039 backwards (promote). When REMOVE is non-nil, remove the hr instead
6040 of cycling when the end of the list is reached.
6041 Assumes match data is available for `markdown-regex-hr'."
6042 (let* ((strings (if (= arg -1)
6043 (reverse markdown-hr-strings)
6044 markdown-hr-strings))
6045 (tail (member (match-string 0) strings))
6046 (new (or (cadr tail)
6047 (if remove
6048 (if (= arg 1)
6050 (car tail))
6051 (car strings)))))
6052 (replace-match new)))
6054 (defun markdown-cycle-bold ()
6055 "Cycle bold markup between underscores and asterisks.
6056 Assumes match data is available for `markdown-regex-bold'."
6057 (save-excursion
6058 (let* ((old-delim (match-string 3))
6059 (new-delim (if (string-equal old-delim "**") "__" "**")))
6060 (replace-match new-delim t t nil 3)
6061 (replace-match new-delim t t nil 5))))
6063 (defun markdown-cycle-italic ()
6064 "Cycle italic markup between underscores and asterisks.
6065 Assumes match data is available for `markdown-regex-italic'."
6066 (save-excursion
6067 (let* ((old-delim (match-string 2))
6068 (new-delim (if (string-equal old-delim "*") "_" "*")))
6069 (replace-match new-delim t t nil 2)
6070 (replace-match new-delim t t nil 4))))
6073 ;;; Keymap ====================================================================
6075 (defun markdown--style-map-prompt ()
6076 "Return a formatted prompt for Markdown markup insertion."
6077 (when markdown-enable-prefix-prompts
6078 (concat
6079 "Markdown: "
6080 (propertize "bold" 'face 'markdown-bold-face) ", "
6081 (propertize "italic" 'face 'markdown-italic-face) ", "
6082 (propertize "code" 'face 'markdown-inline-code-face) ", "
6083 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
6084 (propertize "pre" 'face 'markdown-pre-face) ", "
6085 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
6086 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
6087 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
6088 (propertize "- = hr" 'face 'markdown-hr-face) ", "
6089 "C-h = more")))
6091 (defun markdown--command-map-prompt ()
6092 "Return prompt for Markdown buffer-wide commands."
6093 (when markdown-enable-prefix-prompts
6094 (concat
6095 "Command: "
6096 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
6097 (propertize "p" 'face 'markdown-bold-face) "review, "
6098 (propertize "o" 'face 'markdown-bold-face) "pen, "
6099 (propertize "e" 'face 'markdown-bold-face) "xport, "
6100 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
6101 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
6102 "C-h = more")))
6104 (defvar markdown-mode-style-map
6105 (let ((map (make-keymap (markdown--style-map-prompt))))
6106 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
6107 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
6108 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
6109 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
6110 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
6111 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
6112 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
6113 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
6114 (define-key map (kbd "b") 'markdown-insert-bold)
6115 (define-key map (kbd "c") 'markdown-insert-code)
6116 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
6117 (define-key map (kbd "f") 'markdown-insert-footnote)
6118 (define-key map (kbd "h") 'markdown-insert-header-dwim)
6119 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
6120 (define-key map (kbd "i") 'markdown-insert-italic)
6121 (define-key map (kbd "k") 'markdown-insert-kbd)
6122 (define-key map (kbd "l") 'markdown-insert-link)
6123 (define-key map (kbd "p") 'markdown-insert-pre)
6124 (define-key map (kbd "P") 'markdown-pre-region)
6125 (define-key map (kbd "q") 'markdown-insert-blockquote)
6126 (define-key map (kbd "s") 'markdown-insert-strike-through)
6127 (define-key map (kbd "Q") 'markdown-blockquote-region)
6128 (define-key map (kbd "w") 'markdown-insert-wiki-link)
6129 (define-key map (kbd "-") 'markdown-insert-hr)
6130 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
6131 ;; Deprecated keys that may be removed in a future version
6132 (define-key map (kbd "e") 'markdown-insert-italic)
6133 map)
6134 "Keymap for Markdown text styling commands.")
6136 (defvar markdown-mode-command-map
6137 (let ((map (make-keymap (markdown--command-map-prompt))))
6138 (define-key map (kbd "m") 'markdown-other-window)
6139 (define-key map (kbd "p") 'markdown-preview)
6140 (define-key map (kbd "e") 'markdown-export)
6141 (define-key map (kbd "v") 'markdown-export-and-preview)
6142 (define-key map (kbd "o") 'markdown-open)
6143 (define-key map (kbd "l") 'markdown-live-preview-mode)
6144 (define-key map (kbd "w") 'markdown-kill-ring-save)
6145 (define-key map (kbd "c") 'markdown-check-refs)
6146 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6147 (define-key map (kbd "]") 'markdown-complete-buffer)
6148 (define-key map (kbd "^") 'markdown-table-sort-lines)
6149 (define-key map (kbd "|") 'markdown-table-convert-region)
6150 (define-key map (kbd "t") 'markdown-table-transpose)
6151 map)
6152 "Keymap for Markdown buffer-wide commands.")
6154 (defvar markdown-mode-map
6155 (let ((map (make-keymap)))
6156 ;; Markup insertion & removal
6157 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6158 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6159 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6160 ;; Promotion, demotion, and cycling
6161 (define-key map (kbd "C-c C--") 'markdown-promote)
6162 (define-key map (kbd "C-c C-=") 'markdown-demote)
6163 (define-key map (kbd "C-c C-]") 'markdown-complete)
6164 ;; Following and doing things
6165 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6166 (define-key map (kbd "C-c C-d") 'markdown-do)
6167 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6168 ;; Indentation
6169 (define-key map (kbd "C-m") 'markdown-enter-key)
6170 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6171 (define-key map (kbd "C-c >") 'markdown-indent-region)
6172 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6173 ;; Visibility cycling
6174 (define-key map (kbd "TAB") 'markdown-cycle)
6175 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6176 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6177 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6178 ;; Heading and list navigation
6179 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6180 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6181 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6182 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6183 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6184 ;; Buffer-wide commands
6185 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6186 ;; Subtree, list, and table editing
6187 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6188 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6189 (define-key map (kbd "C-c <left>") 'markdown-promote)
6190 (define-key map (kbd "C-c <right>") 'markdown-demote)
6191 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6192 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6193 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6194 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6195 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6196 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6197 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6198 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6199 ;; Paragraphs (Markdown context aware)
6200 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6201 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6202 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6203 ;; Blocks (one or more paragraphs)
6204 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6205 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6206 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6207 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6208 ;; Pages (top-level sections)
6209 (define-key map [remap backward-page] 'markdown-backward-page)
6210 (define-key map [remap forward-page] 'markdown-forward-page)
6211 (define-key map [remap mark-page] 'markdown-mark-page)
6212 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6213 ;; Link Movement
6214 (define-key map (kbd "M-n") 'markdown-next-link)
6215 (define-key map (kbd "M-p") 'markdown-previous-link)
6216 ;; Toggling functionality
6217 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6218 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6219 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6220 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6221 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6222 ;; Alternative keys (in case of problems with the arrow keys)
6223 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6224 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6225 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6226 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6227 ;; Deprecated keys that may be removed in a future version
6228 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6229 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6230 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6231 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6232 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6233 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6234 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6235 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6236 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6237 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6238 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6239 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6240 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6241 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6242 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6243 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6244 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6245 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6246 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6247 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6248 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6249 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6250 map)
6251 "Keymap for Markdown major mode.")
6253 (defvar markdown-mode-mouse-map
6254 (let ((map (make-sparse-keymap)))
6255 (define-key map [follow-link] 'mouse-face)
6256 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6257 map)
6258 "Keymap for following links with mouse.")
6260 (defvar gfm-mode-map
6261 (let ((map (make-sparse-keymap)))
6262 (set-keymap-parent map markdown-mode-map)
6263 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6264 (define-key map "`" 'markdown-electric-backquote)
6265 map)
6266 "Keymap for `gfm-mode'.
6267 See also `markdown-mode-map'.")
6270 ;;; Menu ==================================================================
6272 (easy-menu-define markdown-mode-menu markdown-mode-map
6273 "Menu for Markdown mode"
6274 '("Markdown"
6275 "---"
6276 ("Movement"
6277 ["Jump" markdown-do]
6278 ["Follow Link" markdown-follow-thing-at-point]
6279 ["Next Link" markdown-next-link]
6280 ["Previous Link" markdown-previous-link]
6281 "---"
6282 ["Next Heading or List Item" markdown-outline-next]
6283 ["Previous Heading or List Item" markdown-outline-previous]
6284 ["Next at Same Level" markdown-outline-next-same-level]
6285 ["Previous at Same Level" markdown-outline-previous-same-level]
6286 ["Up to Parent" markdown-outline-up]
6287 "---"
6288 ["Forward Paragraph" markdown-forward-paragraph]
6289 ["Backward Paragraph" markdown-backward-paragraph]
6290 ["Forward Block" markdown-forward-block]
6291 ["Backward Block" markdown-backward-block])
6292 ("Show & Hide"
6293 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6294 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6295 "---"
6296 ["Narrow to Region" narrow-to-region]
6297 ["Narrow to Block" markdown-narrow-to-block]
6298 ["Narrow to Section" narrow-to-defun]
6299 ["Narrow to Subtree" markdown-narrow-to-subtree]
6300 ["Widen" widen (buffer-narrowed-p)]
6301 "---"
6302 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6303 :keys "C-c C-x C-m"
6304 :style radio
6305 :selected markdown-hide-markup])
6306 "---"
6307 ("Headings & Structure"
6308 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6309 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6310 ("Specific Heading (atx)"
6311 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6312 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6313 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6314 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6315 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6316 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6317 ("Specific Heading (Setext)"
6318 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6319 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6320 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6321 "---"
6322 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6323 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6324 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6325 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6326 ("Region & Mark"
6327 ["Indent Region" markdown-indent-region]
6328 ["Outdent Region" markdown-outdent-region]
6329 "--"
6330 ["Mark Paragraph" mark-paragraph]
6331 ["Mark Block" markdown-mark-block]
6332 ["Mark Section" mark-defun]
6333 ["Mark Subtree" markdown-mark-subtree])
6334 ("Lists"
6335 ["Insert List Item" markdown-insert-list-item]
6336 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6337 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6338 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6339 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6340 ["Renumber List" markdown-cleanup-list-numbers]
6341 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6342 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6343 ("Links & Images"
6344 ["Insert Link" markdown-insert-link]
6345 ["Insert Image" markdown-insert-image]
6346 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6347 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6348 "---"
6349 ["Check References" markdown-check-refs]
6350 ["Toggle URL Hiding" markdown-toggle-url-hiding
6351 :style radio
6352 :selected markdown-hide-urls]
6353 ["Toggle Inline Images" markdown-toggle-inline-images
6354 :keys "C-c C-x C-i"
6355 :style radio
6356 :selected markdown-inline-image-overlays]
6357 ["Toggle Wiki Links" markdown-toggle-wiki-links
6358 :style radio
6359 :selected markdown-enable-wiki-links])
6360 ("Styles"
6361 ["Bold" markdown-insert-bold]
6362 ["Italic" markdown-insert-italic]
6363 ["Code" markdown-insert-code]
6364 ["Strikethrough" markdown-insert-strike-through]
6365 ["Keyboard" markdown-insert-kbd]
6366 "---"
6367 ["Blockquote" markdown-insert-blockquote]
6368 ["Preformatted" markdown-insert-pre]
6369 ["GFM Code Block" markdown-insert-gfm-code-block]
6370 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6371 "---"
6372 ["Blockquote Region" markdown-blockquote-region]
6373 ["Preformatted Region" markdown-pre-region]
6374 "---"
6375 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6376 :style radio
6377 :selected markdown-fontify-code-blocks-natively]
6378 ["LaTeX Math Support" markdown-toggle-math
6379 :style radio
6380 :selected markdown-enable-math])
6381 "---"
6382 ("Preview & Export"
6383 ["Compile" markdown-other-window]
6384 ["Preview" markdown-preview]
6385 ["Export" markdown-export]
6386 ["Export & View" markdown-export-and-preview]
6387 ["Open" markdown-open]
6388 ["Live Export" markdown-live-preview-mode
6389 :style radio
6390 :selected markdown-live-preview-mode]
6391 ["Kill ring save" markdown-kill-ring-save])
6392 ("Markup Completion and Cycling"
6393 ["Complete Markup" markdown-complete]
6394 ["Promote Element" markdown-promote :keys "C-c C--"]
6395 ["Demote Element" markdown-demote :keys "C-c C-="])
6396 "---"
6397 ["Kill Element" markdown-kill-thing-at-point]
6398 "---"
6399 ("Documentation"
6400 ["Version" markdown-show-version]
6401 ["Homepage" markdown-mode-info]
6402 ["Describe Mode" (describe-function 'markdown-mode)]
6403 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6406 ;;; imenu =====================================================================
6408 (defun markdown-imenu-create-nested-index ()
6409 "Create and return a nested imenu index alist for the current buffer.
6410 See `imenu-create-index-function' and `imenu--index-alist' for details."
6411 (let* ((root '(nil . nil))
6412 cur-alist
6413 (cur-level 0)
6414 (empty-heading "-")
6415 (self-heading ".")
6416 hashes pos level heading)
6417 (save-excursion
6418 (goto-char (point-min))
6419 (while (re-search-forward markdown-regex-header (point-max) t)
6420 (unless (markdown-code-block-at-point-p)
6421 (cond
6422 ((match-string-no-properties 2) ;; level 1 setext
6423 (setq heading (match-string-no-properties 1))
6424 (setq pos (match-beginning 1)
6425 level 1))
6426 ((match-string-no-properties 3) ;; level 2 setext
6427 (setq heading (match-string-no-properties 1))
6428 (setq pos (match-beginning 1)
6429 level 2))
6430 ((setq hashes (markdown-trim-whitespace
6431 (match-string-no-properties 4)))
6432 (setq heading (match-string-no-properties 5)
6433 pos (match-beginning 4)
6434 level (length hashes))))
6435 (let ((alist (list (cons heading pos))))
6436 (cond
6437 ((= cur-level level) ; new sibling
6438 (setcdr cur-alist alist)
6439 (setq cur-alist alist))
6440 ((< cur-level level) ; first child
6441 (dotimes (_ (- level cur-level 1))
6442 (setq alist (list (cons empty-heading alist))))
6443 (if cur-alist
6444 (let* ((parent (car cur-alist))
6445 (self-pos (cdr parent)))
6446 (setcdr parent (cons (cons self-heading self-pos) alist)))
6447 (setcdr root alist)) ; primogenitor
6448 (setq cur-alist alist)
6449 (setq cur-level level))
6450 (t ; new sibling of an ancestor
6451 (let ((sibling-alist (last (cdr root))))
6452 (dotimes (_ (1- level))
6453 (setq sibling-alist (last (cdar sibling-alist))))
6454 (setcdr sibling-alist alist)
6455 (setq cur-alist alist))
6456 (setq cur-level level))))))
6457 (cdr root))))
6459 (defun markdown-imenu-create-flat-index ()
6460 "Create and return a flat imenu index alist for the current buffer.
6461 See `imenu-create-index-function' and `imenu--index-alist' for details."
6462 (let* ((empty-heading "-") index heading pos)
6463 (save-excursion
6464 (goto-char (point-min))
6465 (while (re-search-forward markdown-regex-header (point-max) t)
6466 (when (and (not (markdown-code-block-at-point-p))
6467 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6468 (cond
6469 ((setq heading (match-string-no-properties 1))
6470 (setq pos (match-beginning 1)))
6471 ((setq heading (match-string-no-properties 5))
6472 (setq pos (match-beginning 4))))
6473 (or (> (length heading) 0)
6474 (setq heading empty-heading))
6475 (setq index (append index (list (cons heading pos))))))
6476 index)))
6479 ;;; References ================================================================
6481 (defun markdown-reference-goto-definition ()
6482 "Jump to the definition of the reference at point or create it."
6483 (interactive)
6484 (when (thing-at-point-looking-at markdown-regex-link-reference)
6485 (let* ((text (match-string-no-properties 3))
6486 (reference (match-string-no-properties 6))
6487 (target (downcase (if (string= reference "") text reference)))
6488 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6489 (if loc
6490 (goto-char loc)
6491 (goto-char (match-beginning 0))
6492 (markdown-insert-reference-definition target)))))
6494 (defun markdown-reference-find-links (reference)
6495 "Return a list of all links for REFERENCE.
6496 REFERENCE should not include the surrounding square brackets.
6497 Elements of the list have the form (text start line), where
6498 text is the link text, start is the location at the beginning of
6499 the link, and line is the line number on which the link appears."
6500 (let* ((ref-quote (regexp-quote reference))
6501 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6502 ref-quote ref-quote))
6503 links)
6504 (save-excursion
6505 (goto-char (point-min))
6506 (while (re-search-forward regexp nil t)
6507 (let* ((text (or (match-string-no-properties 1)
6508 (match-string-no-properties 2)))
6509 (start (match-beginning 0))
6510 (line (markdown-line-number-at-pos)))
6511 (cl-pushnew (list text start line) links :test #'equal))))
6512 links))
6514 (defun markdown-get-undefined-refs ()
6515 "Return a list of undefined Markdown references.
6516 Result is an alist of pairs (reference . occurrences), where
6517 occurrences is itself another alist of pairs (label . line-number).
6518 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6519 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6520 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6521 (let ((missing))
6522 (save-excursion
6523 (goto-char (point-min))
6524 (while
6525 (re-search-forward markdown-regex-link-reference nil t)
6526 (let* ((text (match-string-no-properties 3))
6527 (reference (match-string-no-properties 6))
6528 (target (downcase (if (string= reference "") text reference))))
6529 (unless (markdown-reference-definition target)
6530 (let ((entry (assoc target missing)))
6531 (if (not entry)
6532 (cl-pushnew
6533 (cons target (list (cons text (markdown-line-number-at-pos))))
6534 missing :test #'equal)
6535 (setcdr entry
6536 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6537 (reverse missing))))
6539 (defconst markdown-reference-check-buffer
6540 "*Undefined references for %buffer%*"
6541 "Pattern for name of buffer for listing undefined references.
6542 The string %buffer% will be replaced by the corresponding
6543 `markdown-mode' buffer name.")
6545 (defun markdown-reference-check-buffer (&optional buffer-name)
6546 "Name and return buffer for reference checking.
6547 BUFFER-NAME is the name of the main buffer being visited."
6548 (or buffer-name (setq buffer-name (buffer-name)))
6549 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6550 "%buffer%" buffer-name
6551 markdown-reference-check-buffer))))
6552 (with-current-buffer refbuf
6553 (when view-mode
6554 (View-exit-and-edit))
6555 (use-local-map button-buffer-map)
6556 (erase-buffer))
6557 refbuf))
6559 (defconst markdown-reference-links-buffer
6560 "*Reference links for %buffer%*"
6561 "Pattern for name of buffer for listing references.
6562 The string %buffer% will be replaced by the corresponding buffer name.")
6564 (defun markdown-reference-links-buffer (&optional buffer-name)
6565 "Name, setup, and return a buffer for listing links.
6566 BUFFER-NAME is the name of the main buffer being visited."
6567 (or buffer-name (setq buffer-name (buffer-name)))
6568 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6569 "%buffer%" buffer-name
6570 markdown-reference-links-buffer))))
6571 (with-current-buffer linkbuf
6572 (when view-mode
6573 (View-exit-and-edit))
6574 (use-local-map button-buffer-map)
6575 (erase-buffer))
6576 linkbuf))
6578 ;; Add an empty Markdown reference definition to buffer
6579 ;; specified in the 'target-buffer property. The reference name is
6580 ;; the button's label.
6581 (define-button-type 'markdown-undefined-reference-button
6582 'help-echo "mouse-1, RET: create definition for undefined reference"
6583 'follow-link t
6584 'face 'bold
6585 'action (lambda (b)
6586 (let ((buffer (button-get b 'target-buffer))
6587 (line (button-get b 'target-line))
6588 (label (button-label b)))
6589 (switch-to-buffer-other-window buffer)
6590 (goto-char (point-min))
6591 (forward-line line)
6592 (markdown-insert-reference-definition label)
6593 (markdown-check-refs t))))
6595 ;; Jump to line in buffer specified by 'target-buffer property.
6596 ;; Line number is button's 'line property.
6597 (define-button-type 'markdown-goto-line-button
6598 'help-echo "mouse-1, RET: go to line"
6599 'follow-link t
6600 'face 'italic
6601 'action (lambda (b)
6602 (message (button-get b 'buffer))
6603 (switch-to-buffer-other-window (button-get b 'target-buffer))
6604 ;; use call-interactively to silence compiler
6605 (let ((current-prefix-arg (button-get b 'target-line)))
6606 (call-interactively 'goto-line))))
6608 ;; Jumps to a particular link at location given by 'target-char
6609 ;; property in buffer given by 'target-buffer property.
6610 (define-button-type 'markdown-location-button
6611 'help-echo "mouse-1, RET: jump to location of link"
6612 'follow-link t
6613 'face 'bold
6614 'action (lambda (b)
6615 (let ((target (button-get b 'target-buffer))
6616 (loc (button-get b 'target-char)))
6617 (kill-buffer-and-window)
6618 (switch-to-buffer target)
6619 (goto-char loc))))
6621 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6622 "Insert a button for creating REFERENCE in buffer OLDBUF.
6623 REFERENCE should be a list of the form (reference . occurrences),
6624 as by `markdown-get-undefined-refs'."
6625 (let ((label (car reference)))
6626 ;; Create a reference button
6627 (insert-button label
6628 :type 'markdown-undefined-reference-button
6629 'target-buffer oldbuf
6630 'target-line (cdr (car (cdr reference))))
6631 (insert " (")
6632 (dolist (occurrence (cdr reference))
6633 (let ((line (cdr occurrence)))
6634 ;; Create a line number button
6635 (insert-button (number-to-string line)
6636 :type 'markdown-goto-line-button
6637 'target-buffer oldbuf
6638 'target-line line)
6639 (insert " ")))
6640 (delete-char -1)
6641 (insert ")")
6642 (newline)))
6644 (defun markdown-insert-link-button (link oldbuf)
6645 "Insert a button for jumping to LINK in buffer OLDBUF.
6646 LINK should be a list of the form (text char line) containing
6647 the link text, location, and line number."
6648 (let ((label (cl-first link))
6649 (char (cl-second link))
6650 (line (cl-third link)))
6651 ;; Create a reference button
6652 (insert-button label
6653 :type 'markdown-location-button
6654 'target-buffer oldbuf
6655 'target-char char)
6656 (insert (format " (line %d)\n" line))))
6658 (defun markdown-reference-goto-link (&optional reference)
6659 "Jump to the location of the first use of REFERENCE."
6660 (interactive)
6661 (unless reference
6662 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6663 (setq reference (match-string-no-properties 2))
6664 (user-error "No reference definition at point")))
6665 (let ((links (markdown-reference-find-links reference)))
6666 (cond ((= (length links) 1)
6667 (goto-char (cadr (car links))))
6668 ((> (length links) 1)
6669 (let ((oldbuf (current-buffer))
6670 (linkbuf (markdown-reference-links-buffer)))
6671 (with-current-buffer linkbuf
6672 (insert "Links using reference " reference ":\n\n")
6673 (dolist (link (reverse links))
6674 (markdown-insert-link-button link oldbuf)))
6675 (view-buffer-other-window linkbuf)
6676 (goto-char (point-min))
6677 (forward-line 2)))
6679 (error "No links for reference %s" reference)))))
6681 (defun markdown-check-refs (&optional silent)
6682 "Show all undefined Markdown references in current `markdown-mode' buffer.
6683 If SILENT is non-nil, do not message anything when no undefined
6684 references found.
6685 Links which have empty reference definitions are considered to be
6686 defined."
6687 (interactive "P")
6688 (when (not (eq major-mode 'markdown-mode))
6689 (user-error "Not available in current mode"))
6690 (let ((oldbuf (current-buffer))
6691 (refs (markdown-get-undefined-refs))
6692 (refbuf (markdown-reference-check-buffer)))
6693 (if (null refs)
6694 (progn
6695 (when (not silent)
6696 (message "No undefined references found"))
6697 (kill-buffer refbuf))
6698 (with-current-buffer refbuf
6699 (insert "The following references are undefined:\n\n")
6700 (dolist (ref refs)
6701 (markdown-insert-undefined-reference-button ref oldbuf))
6702 (view-buffer-other-window refbuf)
6703 (goto-char (point-min))
6704 (forward-line 2)))))
6707 ;;; Lists =====================================================================
6709 (defun markdown-insert-list-item (&optional arg)
6710 "Insert a new list item.
6711 If the point is inside unordered list, insert a bullet mark. If
6712 the point is inside ordered list, insert the next number followed
6713 by a period. Use the previous list item to determine the amount
6714 of whitespace to place before and after list markers.
6716 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6717 decrease the indentation by one level.
6719 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6720 increase the indentation by one level."
6721 (interactive "p")
6722 (let (bounds cur-indent marker indent new-indent new-loc)
6723 (save-match-data
6724 ;; Look for a list item on current or previous non-blank line
6725 (save-excursion
6726 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6727 (not (bobp))
6728 (markdown-cur-line-blank-p))
6729 (forward-line -1)))
6730 (when bounds
6731 (cond ((save-excursion
6732 (skip-chars-backward " \t")
6733 (looking-at-p markdown-regex-list))
6734 (beginning-of-line)
6735 (insert "\n")
6736 (forward-line -1))
6737 ((not (markdown-cur-line-blank-p))
6738 (newline)))
6739 (setq new-loc (point)))
6740 ;; Look ahead for a list item on next non-blank line
6741 (unless bounds
6742 (save-excursion
6743 (while (and (null bounds)
6744 (not (eobp))
6745 (markdown-cur-line-blank-p))
6746 (forward-line)
6747 (setq bounds (markdown-cur-list-item-bounds))))
6748 (when bounds
6749 (setq new-loc (point))
6750 (unless (markdown-cur-line-blank-p)
6751 (newline))))
6752 (if (not bounds)
6753 ;; When not in a list, start a new unordered one
6754 (progn
6755 (unless (markdown-cur-line-blank-p)
6756 (insert "\n"))
6757 (insert markdown-unordered-list-item-prefix))
6758 ;; Compute indentation and marker for new list item
6759 (setq cur-indent (nth 2 bounds))
6760 (setq marker (nth 4 bounds))
6761 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6762 (when (nth 5 bounds)
6763 (setq marker
6764 (concat marker
6765 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6766 (cond
6767 ;; Dedent: decrement indentation, find previous marker.
6768 ((= arg 4)
6769 (setq indent (max (- cur-indent 4) 0))
6770 (let ((prev-bounds
6771 (save-excursion
6772 (goto-char (nth 0 bounds))
6773 (when (markdown-up-list)
6774 (markdown-cur-list-item-bounds)))))
6775 (when prev-bounds
6776 (setq marker (nth 4 prev-bounds)))))
6777 ;; Indent: increment indentation by 4, use same marker.
6778 ((= arg 16) (setq indent (+ cur-indent 4)))
6779 ;; Same level: keep current indentation and marker.
6780 (t (setq indent cur-indent)))
6781 (setq new-indent (make-string indent 32))
6782 (goto-char new-loc)
6783 (cond
6784 ;; Ordered list
6785 ((string-match-p "[0-9]" marker)
6786 (if (= arg 16) ;; starting a new column indented one more level
6787 (insert (concat new-indent "1. "))
6788 ;; Don't use previous match-data
6789 (set-match-data nil)
6790 ;; travel up to the last item and pick the correct number. If
6791 ;; the argument was nil, "new-indent = cur-indent" is the same,
6792 ;; so we don't need special treatment. Neat.
6793 (save-excursion
6794 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6795 (>= (forward-line -1) 0))))
6796 (let* ((old-prefix (match-string 1))
6797 (old-spacing (match-string 2))
6798 (new-prefix (if old-prefix
6799 (int-to-string (1+ (string-to-number old-prefix)))
6800 "1"))
6801 (space-adjust (- (length old-prefix) (length new-prefix)))
6802 (new-spacing (if (and (match-string 2)
6803 (not (string-match-p "\t" old-spacing))
6804 (< space-adjust 0)
6805 (> space-adjust (- 1 (length (match-string 2)))))
6806 (substring (match-string 2) 0 space-adjust)
6807 (or old-spacing ". "))))
6808 (insert (concat new-indent new-prefix new-spacing)))))
6809 ;; Unordered list, GFM task list, or ordered list with hash mark
6810 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6811 (insert new-indent marker)))))))
6813 (defun markdown-move-list-item-up ()
6814 "Move the current list item up in the list when possible.
6815 In nested lists, move child items with the parent item."
6816 (interactive)
6817 (let (cur prev old)
6818 (when (setq cur (markdown-cur-list-item-bounds))
6819 (setq old (point))
6820 (goto-char (nth 0 cur))
6821 (if (markdown-prev-list-item (nth 3 cur))
6822 (progn
6823 (setq prev (markdown-cur-list-item-bounds))
6824 (condition-case nil
6825 (progn
6826 (transpose-regions (nth 0 prev) (nth 1 prev)
6827 (nth 0 cur) (nth 1 cur) t)
6828 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6829 ;; Catch error in case regions overlap.
6830 (error (goto-char old))))
6831 (goto-char old)))))
6833 (defun markdown-move-list-item-down ()
6834 "Move the current list item down in the list when possible.
6835 In nested lists, move child items with the parent item."
6836 (interactive)
6837 (let (cur next old)
6838 (when (setq cur (markdown-cur-list-item-bounds))
6839 (setq old (point))
6840 (if (markdown-next-list-item (nth 3 cur))
6841 (progn
6842 (setq next (markdown-cur-list-item-bounds))
6843 (condition-case nil
6844 (progn
6845 (transpose-regions (nth 0 cur) (nth 1 cur)
6846 (nth 0 next) (nth 1 next) nil)
6847 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6848 ;; Catch error in case regions overlap.
6849 (error (goto-char old))))
6850 (goto-char old)))))
6852 (defun markdown-demote-list-item (&optional bounds)
6853 "Indent (or demote) the current list item.
6854 Optionally, BOUNDS of the current list item may be provided if available.
6855 In nested lists, demote child items as well."
6856 (interactive)
6857 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6858 (save-excursion
6859 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6860 (goto-char (nth 0 bounds))
6861 (while (< (point) end-marker)
6862 (unless (markdown-cur-line-blank-p)
6863 (insert (make-string markdown-list-indent-width ? )))
6864 (forward-line))))))
6866 (defun markdown-promote-list-item (&optional bounds)
6867 "Unindent (or promote) the current list item.
6868 Optionally, BOUNDS of the current list item may be provided if available.
6869 In nested lists, demote child items as well."
6870 (interactive)
6871 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6872 (save-excursion
6873 (save-match-data
6874 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6875 num regexp)
6876 (goto-char (nth 0 bounds))
6877 (when (looking-at (format "^[ ]\\{1,%d\\}"
6878 markdown-list-indent-width))
6879 (setq num (- (match-end 0) (match-beginning 0)))
6880 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6881 (while (and (< (point) end-marker)
6882 (re-search-forward regexp end-marker t))
6883 (replace-match "" nil nil)
6884 (forward-line))))))))
6886 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6887 "Update the numbering for level PFX (as a string of spaces).
6889 Assume that the previously found match was for a numbered item in
6890 a list."
6891 (let ((cpfx pfx)
6892 (idx 0)
6893 (continue t)
6894 (step t)
6895 (sep nil))
6896 (while (and continue (not (eobp)))
6897 (setq step t)
6898 (cond
6899 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6900 (setq cpfx (match-string-no-properties 1))
6901 (cond
6902 ((string= cpfx pfx)
6903 (save-excursion
6904 (replace-match
6905 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6906 (setq sep nil))
6907 ;; indented a level
6908 ((string< pfx cpfx)
6909 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6910 (setq step nil))
6911 ;; exit the loop
6913 (setq step nil)
6914 (setq continue nil))))
6916 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6917 (setq cpfx (match-string-no-properties 1))
6918 (cond
6919 ;; reset if separated before
6920 ((string= cpfx pfx) (when sep (setq idx 0)))
6921 ((string< cpfx pfx)
6922 (setq step nil)
6923 (setq continue nil))))
6924 (t (setq sep t)))
6926 (when step
6927 (beginning-of-line)
6928 (setq continue (= (forward-line) 0))))
6929 sep))
6931 (defun markdown-cleanup-list-numbers ()
6932 "Update the numbering of ordered lists."
6933 (interactive)
6934 (save-excursion
6935 (goto-char (point-min))
6936 (markdown-cleanup-list-numbers-level "")))
6939 ;;; Movement ==================================================================
6941 (defun markdown-beginning-of-defun (&optional arg)
6942 "`beginning-of-defun-function' for Markdown.
6943 This is used to find the beginning of the defun and should behave
6944 like ‘beginning-of-defun’, returning non-nil if it found the
6945 beginning of a defun. It moves the point backward, right before a
6946 heading which defines a defun. When ARG is non-nil, repeat that
6947 many times. When ARG is negative, move forward to the ARG-th
6948 following section."
6949 (or arg (setq arg 1))
6950 (when (< arg 0) (end-of-line))
6951 ;; Adjust position for setext headings.
6952 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6953 (not (= (point) (match-beginning 0)))
6954 (not (markdown-code-block-at-point-p)))
6955 (goto-char (match-end 0)))
6956 (let (found)
6957 ;; Move backward with positive argument.
6958 (while (and (not (bobp)) (> arg 0))
6959 (setq found nil)
6960 (while (and (not found)
6961 (not (bobp))
6962 (re-search-backward markdown-regex-header nil 'move))
6963 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6964 (setq found (match-beginning 0)))
6965 (setq arg (1- arg)))
6966 ;; Move forward with negative argument.
6967 (while (and (not (eobp)) (< arg 0))
6968 (setq found nil)
6969 (while (and (not found)
6970 (not (eobp))
6971 (re-search-forward markdown-regex-header nil 'move))
6972 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6973 (setq found (match-beginning 0)))
6974 (setq arg (1+ arg)))
6975 (when found
6976 (beginning-of-line)
6977 t)))
6979 (defun markdown-end-of-defun ()
6980 "`end-of-defun-function’ for Markdown.
6981 This is used to find the end of the defun at point.
6982 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6983 so it can assume that point is at the beginning of the defun body.
6984 It should move point to the first position after the defun."
6985 (or (eobp) (forward-char 1))
6986 (let (found)
6987 (while (and (not found)
6988 (not (eobp))
6989 (re-search-forward markdown-regex-header nil 'move))
6990 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6991 (setq found (match-beginning 0))))
6992 (when found
6993 (goto-char found)
6994 (skip-syntax-backward "-"))))
6996 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6998 (defun markdown-beginning-of-text-block ()
6999 "Move backward to previous beginning of a plain text block.
7000 This function simply looks for blank lines without considering
7001 the surrounding context in light of Markdown syntax. For that, see
7002 `markdown-backward-block'."
7003 (interactive)
7004 (let ((start (point)))
7005 (if (re-search-backward markdown-regex-block-separator nil t)
7006 (goto-char (match-end 0))
7007 (goto-char (point-min)))
7008 (when (and (= start (point)) (not (bobp)))
7009 (forward-line -1)
7010 (if (re-search-backward markdown-regex-block-separator nil t)
7011 (goto-char (match-end 0))
7012 (goto-char (point-min))))))
7014 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
7016 (defun markdown-end-of-text-block ()
7017 "Move forward to next beginning of a plain text block.
7018 This function simply looks for blank lines without considering
7019 the surrounding context in light of Markdown syntax. For that, see
7020 `markdown-forward-block'."
7021 (interactive)
7022 (beginning-of-line)
7023 (skip-syntax-forward "-")
7024 (when (= (point) (point-min))
7025 (forward-char))
7026 (if (re-search-forward markdown-regex-block-separator nil t)
7027 (goto-char (match-end 0))
7028 (goto-char (point-max)))
7029 (skip-syntax-backward "-")
7030 (forward-line))
7032 (defun markdown-backward-paragraph (&optional arg)
7033 "Move the point to the start of the current paragraph.
7034 With argument ARG, do it ARG times; a negative argument ARG = -N
7035 means move forward N blocks."
7036 (interactive "^p")
7037 (or arg (setq arg 1))
7038 (if (< arg 0)
7039 (markdown-forward-paragraph (- arg))
7040 (dotimes (_ arg)
7041 ;; Skip over whitespace in between paragraphs when moving backward.
7042 (skip-syntax-backward "-")
7043 (beginning-of-line)
7044 ;; Skip over code block endings.
7045 (when (markdown-range-properties-exist
7046 (point-at-bol) (point-at-eol)
7047 '(markdown-gfm-block-end
7048 markdown-tilde-fence-end))
7049 (forward-line -1))
7050 ;; Skip over blank lines inside blockquotes.
7051 (while (and (not (eobp))
7052 (looking-at markdown-regex-blockquote)
7053 (= (length (match-string 3)) 0))
7054 (forward-line -1))
7055 ;; Proceed forward based on the type of block of paragraph.
7056 (let (bounds skip)
7057 (cond
7058 ;; Blockquotes
7059 ((looking-at markdown-regex-blockquote)
7060 (while (and (not (bobp))
7061 (looking-at markdown-regex-blockquote)
7062 (> (length (match-string 3)) 0)) ;; not blank
7063 (forward-line -1))
7064 (forward-line))
7065 ;; List items
7066 ((setq bounds (markdown-cur-list-item-bounds))
7067 (goto-char (nth 0 bounds)))
7068 ;; Other
7070 (while (and (not (bobp))
7071 (not skip)
7072 (not (markdown-cur-line-blank-p))
7073 (not (looking-at markdown-regex-blockquote))
7074 (not (markdown-range-properties-exist
7075 (point-at-bol) (point-at-eol)
7076 '(markdown-gfm-block-end
7077 markdown-tilde-fence-end))))
7078 (setq skip (markdown-range-properties-exist
7079 (point-at-bol) (point-at-eol)
7080 '(markdown-gfm-block-begin
7081 markdown-tilde-fence-begin)))
7082 (forward-line -1))
7083 (unless (bobp)
7084 (forward-line 1))))))))
7086 (defun markdown-forward-paragraph (&optional arg)
7087 "Move forward to the next end of a paragraph.
7088 With argument ARG, do it ARG times; a negative argument ARG = -N
7089 means move backward N blocks."
7090 (interactive "^p")
7091 (or arg (setq arg 1))
7092 (if (< arg 0)
7093 (markdown-backward-paragraph (- arg))
7094 (dotimes (_ arg)
7095 ;; Skip whitespace in between paragraphs.
7096 (when (markdown-cur-line-blank-p)
7097 (skip-syntax-forward "-")
7098 (beginning-of-line))
7099 ;; Proceed forward based on the type of block.
7100 (let (bounds skip)
7101 (cond
7102 ;; Blockquotes
7103 ((looking-at markdown-regex-blockquote)
7104 ;; Skip over blank lines inside blockquotes.
7105 (while (and (not (eobp))
7106 (looking-at markdown-regex-blockquote)
7107 (= (length (match-string 3)) 0))
7108 (forward-line))
7109 ;; Move to end of quoted text block
7110 (while (and (not (eobp))
7111 (looking-at markdown-regex-blockquote)
7112 (> (length (match-string 3)) 0)) ;; not blank
7113 (forward-line)))
7114 ;; List items
7115 ((and (markdown-cur-list-item-bounds)
7116 (setq bounds (markdown-next-list-item-bounds)))
7117 (goto-char (nth 0 bounds)))
7118 ;; Other
7120 (forward-line)
7121 (while (and (not (eobp))
7122 (not skip)
7123 (not (markdown-cur-line-blank-p))
7124 (not (looking-at markdown-regex-blockquote))
7125 (not (markdown-range-properties-exist
7126 (point-at-bol) (point-at-eol)
7127 '(markdown-gfm-block-begin
7128 markdown-tilde-fence-begin))))
7129 (setq skip (markdown-range-properties-exist
7130 (point-at-bol) (point-at-eol)
7131 '(markdown-gfm-block-end
7132 markdown-tilde-fence-end)))
7133 (forward-line))))))))
7135 (defun markdown-backward-block (&optional arg)
7136 "Move the point to the start of the current Markdown block.
7137 Moves across complete code blocks, list items, and blockquotes,
7138 but otherwise stops at blank lines, headers, and horizontal
7139 rules. With argument ARG, do it ARG times; a negative argument
7140 ARG = -N means move forward N blocks."
7141 (interactive "^p")
7142 (or arg (setq arg 1))
7143 (if (< arg 0)
7144 (markdown-forward-block (- arg))
7145 (dotimes (_ arg)
7146 ;; Skip over whitespace in between blocks when moving backward,
7147 ;; unless at a block boundary with no whitespace.
7148 (skip-syntax-backward "-")
7149 (beginning-of-line)
7150 ;; Proceed forward based on the type of block.
7151 (cond
7152 ;; Code blocks
7153 ((and (markdown-code-block-at-pos (point)) ;; this line
7154 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7155 (forward-line -1)
7156 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7157 (forward-line -1))
7158 (forward-line))
7159 ;; Headings
7160 ((markdown-heading-at-point)
7161 (goto-char (match-beginning 0)))
7162 ;; Horizontal rules
7163 ((looking-at markdown-regex-hr))
7164 ;; Blockquotes
7165 ((looking-at markdown-regex-blockquote)
7166 (forward-line -1)
7167 (while (and (looking-at markdown-regex-blockquote)
7168 (not (bobp)))
7169 (forward-line -1))
7170 (forward-line))
7171 ;; List items
7172 ((markdown-cur-list-item-bounds)
7173 (markdown-beginning-of-list))
7174 ;; Other
7176 ;; Move forward in case it is a one line regular paragraph.
7177 (unless (markdown-next-line-blank-p)
7178 (forward-line))
7179 (unless (markdown-prev-line-blank-p)
7180 (markdown-backward-paragraph)))))))
7182 (defun markdown-forward-block (&optional arg)
7183 "Move forward to the next end of a Markdown block.
7184 Moves across complete code blocks, list items, and blockquotes,
7185 but otherwise stops at blank lines, headers, and horizontal
7186 rules. With argument ARG, do it ARG times; a negative argument
7187 ARG = -N means move backward N blocks."
7188 (interactive "^p")
7189 (or arg (setq arg 1))
7190 (if (< arg 0)
7191 (markdown-backward-block (- arg))
7192 (dotimes (_ arg)
7193 ;; Skip over whitespace in between blocks when moving forward.
7194 (if (markdown-cur-line-blank-p)
7195 (skip-syntax-forward "-")
7196 (beginning-of-line))
7197 ;; Proceed forward based on the type of block.
7198 (cond
7199 ;; Code blocks
7200 ((markdown-code-block-at-point-p)
7201 (forward-line)
7202 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7203 (forward-line)))
7204 ;; Headings
7205 ((looking-at markdown-regex-header)
7206 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7207 (forward-line))
7208 ;; Horizontal rules
7209 ((looking-at markdown-regex-hr)
7210 (forward-line))
7211 ;; Blockquotes
7212 ((looking-at markdown-regex-blockquote)
7213 (forward-line)
7214 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7215 (forward-line)))
7216 ;; List items
7217 ((markdown-cur-list-item-bounds)
7218 (markdown-end-of-list)
7219 (forward-line))
7220 ;; Other
7221 (t (markdown-forward-paragraph))))
7222 (skip-syntax-backward "-")
7223 (unless (eobp)
7224 (forward-char 1))))
7226 (defun markdown-backward-page (&optional count)
7227 "Move backward to boundary of the current toplevel section.
7228 With COUNT, repeat, or go forward if negative."
7229 (interactive "p")
7230 (or count (setq count 1))
7231 (if (< count 0)
7232 (markdown-forward-page (- count))
7233 (skip-syntax-backward "-")
7234 (or (markdown-back-to-heading-over-code-block t t)
7235 (goto-char (point-min)))
7236 (when (looking-at markdown-regex-header)
7237 (let ((level (markdown-outline-level)))
7238 (when (> level 1) (markdown-up-heading level))
7239 (when (> count 1)
7240 (condition-case nil
7241 (markdown-backward-same-level (1- count))
7242 (error (goto-char (point-min)))))))))
7244 (defun markdown-forward-page (&optional count)
7245 "Move forward to boundary of the current toplevel section.
7246 With COUNT, repeat, or go backward if negative."
7247 (interactive "p")
7248 (or count (setq count 1))
7249 (if (< count 0)
7250 (markdown-backward-page (- count))
7251 (if (markdown-back-to-heading-over-code-block t t)
7252 (let ((level (markdown-outline-level)))
7253 (when (> level 1) (markdown-up-heading level))
7254 (condition-case nil
7255 (markdown-forward-same-level count)
7256 (error (goto-char (point-max)))))
7257 (markdown-next-visible-heading 1))))
7259 (defun markdown-next-link ()
7260 "Jump to next inline, reference, or wiki link.
7261 If successful, return point. Otherwise, return nil.
7262 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7263 (interactive)
7264 (let ((opoint (point)))
7265 (when (or (markdown-link-p) (markdown-wiki-link-p))
7266 ;; At a link already, move past it.
7267 (goto-char (+ (match-end 0) 1)))
7268 ;; Search for the next wiki link and move to the beginning.
7269 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7270 (markdown-code-block-at-point-p)
7271 (< (point) (point-max))))
7272 (if (and (not (eq (point) opoint))
7273 (or (markdown-link-p) (markdown-wiki-link-p)))
7274 ;; Group 1 will move past non-escape character in wiki link regexp.
7275 ;; Go to beginning of group zero for all other link types.
7276 (goto-char (or (match-beginning 1) (match-beginning 0)))
7277 (goto-char opoint)
7278 nil)))
7280 (defun markdown-previous-link ()
7281 "Jump to previous wiki link.
7282 If successful, return point. Otherwise, return nil.
7283 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7284 (interactive)
7285 (let ((opoint (point)))
7286 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7287 (markdown-code-block-at-point-p)
7288 (> (point) (point-min))))
7289 (if (and (not (eq (point) opoint))
7290 (or (markdown-link-p) (markdown-wiki-link-p)))
7291 (goto-char (or (match-beginning 1) (match-beginning 0)))
7292 (goto-char opoint)
7293 nil)))
7296 ;;; Outline ===================================================================
7298 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7299 "Wrapper for `outline-mode' functions to skip false positives.
7300 MOVE-FN is a function and ARG is its argument. For example,
7301 headings inside preformatted code blocks may match
7302 `outline-regexp' but should not be considered as headings.
7303 When ADJUST is non-nil, adjust the point for interactive calls
7304 to avoid leaving the point at invisible markup. This adjustment
7305 generally should only be done for interactive calls, since other
7306 functions may expect the point to be at the beginning of the
7307 regular expression."
7308 (let ((prev -1) (start (point)))
7309 (if arg (funcall move-fn arg) (funcall move-fn))
7310 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7311 (setq prev (point))
7312 (if arg (funcall move-fn arg) (funcall move-fn)))
7313 ;; Adjust point for setext headings and invisible text.
7314 (save-match-data
7315 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7316 (if markdown-hide-markup
7317 ;; Move to beginning of heading text if markup is hidden.
7318 (goto-char (or (match-beginning 1) (match-beginning 5)))
7319 ;; Move to beginning of markup otherwise.
7320 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7321 (if (= (point) start) nil (point))))
7323 (defun markdown-next-visible-heading (arg)
7324 "Move to the next visible heading line of any level.
7325 With argument, repeats or can move backward if negative. ARG is
7326 passed to `outline-next-visible-heading'."
7327 (interactive "p")
7328 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7330 (defun markdown-previous-visible-heading (arg)
7331 "Move to the previous visible heading line of any level.
7332 With argument, repeats or can move backward if negative. ARG is
7333 passed to `outline-previous-visible-heading'."
7334 (interactive "p")
7335 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7337 (defun markdown-next-heading ()
7338 "Move to the next heading line of any level."
7339 (markdown-move-heading-common #'outline-next-heading))
7341 (defun markdown-previous-heading ()
7342 "Move to the previous heading line of any level."
7343 (markdown-move-heading-common #'outline-previous-heading))
7345 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7346 "Move back to the beginning of the previous heading.
7347 Returns t if the point is at a heading, the location if a heading
7348 was found, and nil otherwise.
7349 Only visible heading lines are considered, unless INVISIBLE-OK is
7350 non-nil. Throw an error if there is no previous heading unless
7351 NO-ERROR is non-nil.
7352 Leaves match data intact for `markdown-regex-header'."
7353 (beginning-of-line)
7354 (or (and (markdown-heading-at-point)
7355 (not (markdown-code-block-at-point-p)))
7356 (let (found)
7357 (save-excursion
7358 (while (and (not found)
7359 (re-search-backward markdown-regex-header nil t))
7360 (when (and (or invisible-ok (not (outline-invisible-p)))
7361 (not (markdown-code-block-at-point-p)))
7362 (setq found (point))))
7363 (if (not found)
7364 (unless no-error (user-error "Before first heading"))
7365 (setq found (point))))
7366 (when found (goto-char found)))))
7368 (defun markdown-forward-same-level (arg)
7369 "Move forward to the ARG'th heading at same level as this one.
7370 Stop at the first and last headings of a superior heading."
7371 (interactive "p")
7372 (markdown-back-to-heading-over-code-block)
7373 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7375 (defun markdown-backward-same-level (arg)
7376 "Move backward to the ARG'th heading at same level as this one.
7377 Stop at the first and last headings of a superior heading."
7378 (interactive "p")
7379 (markdown-back-to-heading-over-code-block)
7380 (while (> arg 0)
7381 (let ((point-to-move-to
7382 (save-excursion
7383 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7384 (if point-to-move-to
7385 (progn
7386 (goto-char point-to-move-to)
7387 (setq arg (1- arg)))
7388 (user-error "No previous same-level heading")))))
7390 (defun markdown-up-heading (arg)
7391 "Move to the visible heading line of which the present line is a subheading.
7392 With argument, move up ARG levels."
7393 (interactive "p")
7394 (and (called-interactively-p 'any)
7395 (not (eq last-command 'markdown-up-heading)) (push-mark))
7396 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7398 (defun markdown-back-to-heading (&optional invisible-ok)
7399 "Move to previous heading line, or beg of this line if it's a heading.
7400 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7401 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7403 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7405 (defun markdown-on-heading-p ()
7406 "Return non-nil if point is on a heading line."
7407 (get-text-property (point-at-bol) 'markdown-heading))
7409 (defun markdown-end-of-subtree (&optional invisible-OK)
7410 "Move to the end of the current subtree.
7411 Only visible heading lines are considered, unless INVISIBLE-OK is
7412 non-nil.
7413 Derived from `org-end-of-subtree'."
7414 (markdown-back-to-heading invisible-OK)
7415 (let ((first t)
7416 (level (markdown-outline-level)))
7417 (while (and (not (eobp))
7418 (or first (> (markdown-outline-level) level)))
7419 (setq first nil)
7420 (markdown-next-heading))
7421 (if (memq (preceding-char) '(?\n ?\^M))
7422 (progn
7423 ;; Go to end of line before heading
7424 (forward-char -1)
7425 (if (memq (preceding-char) '(?\n ?\^M))
7426 ;; leave blank line before heading
7427 (forward-char -1)))))
7428 (point))
7430 (defun markdown-outline-fix-visibility ()
7431 "Hide any false positive headings that should not be shown.
7432 For example, headings inside preformatted code blocks may match
7433 `outline-regexp' but should not be shown as headings when cycling.
7434 Also, the ending --- line in metadata blocks appears to be a
7435 setext header, but should not be folded."
7436 (save-excursion
7437 (goto-char (point-min))
7438 ;; Unhide any false positives in metadata blocks
7439 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7440 (let ((body (progn (forward-line)
7441 (markdown-text-property-at-point
7442 'markdown-yaml-metadata-section))))
7443 (when body
7444 (let ((end (progn (goto-char (cl-second body))
7445 (markdown-text-property-at-point
7446 'markdown-yaml-metadata-end))))
7447 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7448 ;; Hide any false positives in code blocks
7449 (unless (outline-on-heading-p)
7450 (outline-next-visible-heading 1))
7451 (while (< (point) (point-max))
7452 (when (markdown-code-block-at-point-p)
7453 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7454 (outline-next-visible-heading 1))))
7456 (defvar markdown-cycle-global-status 1)
7457 (defvar markdown-cycle-subtree-status nil)
7459 (defun markdown-next-preface ()
7460 (let (finish)
7461 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7462 nil 'move))
7463 (unless (markdown-code-block-at-point-p)
7464 (goto-char (match-beginning 0))
7465 (setq finish t))))
7466 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7467 (forward-char -1)))
7469 (defun markdown-show-entry ()
7470 (save-excursion
7471 (outline-back-to-heading t)
7472 (outline-flag-region (1- (point))
7473 (progn
7474 (markdown-next-preface)
7475 (if (= 1 (- (point-max) (point)))
7476 (point-max)
7477 (point)))
7478 nil)))
7480 ;; This function was originally derived from `org-cycle' from org.el.
7481 (defun markdown-cycle (&optional arg)
7482 "Visibility cycling for Markdown mode.
7483 If ARG is t, perform global visibility cycling. If the point is
7484 at an atx-style header, cycle visibility of the corresponding
7485 subtree. Otherwise, indent the current line or insert a tab,
7486 as appropriate, by calling `indent-for-tab-command'."
7487 (interactive "P")
7488 (cond
7490 ;; Global cycling
7491 ((eq arg t)
7492 (cond
7493 ;; Move from overview to contents
7494 ((and (eq last-command this-command)
7495 (eq markdown-cycle-global-status 2))
7496 (markdown-hide-sublevels 1)
7497 (message "CONTENTS")
7498 (setq markdown-cycle-global-status 3)
7499 (markdown-outline-fix-visibility))
7500 ;; Move from contents to all
7501 ((and (eq last-command this-command)
7502 (eq markdown-cycle-global-status 3))
7503 (markdown-show-all)
7504 (message "SHOW ALL")
7505 (setq markdown-cycle-global-status 1))
7506 ;; Defaults to overview
7508 (markdown-hide-body)
7509 (message "OVERVIEW")
7510 (setq markdown-cycle-global-status 2)
7511 (markdown-outline-fix-visibility))))
7513 ;; At a heading: rotate between three different views
7514 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7515 (markdown-back-to-heading)
7516 (let ((goal-column 0) eoh eol eos)
7517 ;; Determine boundaries
7518 (save-excursion
7519 (markdown-back-to-heading)
7520 (save-excursion
7521 (beginning-of-line 2)
7522 (while (and (not (eobp)) ;; this is like `next-line'
7523 (get-char-property (1- (point)) 'invisible))
7524 (beginning-of-line 2)) (setq eol (point)))
7525 (markdown-end-of-heading) (setq eoh (point))
7526 (markdown-end-of-subtree t)
7527 (skip-chars-forward " \t\n")
7528 (beginning-of-line 1) ; in case this is an item
7529 (setq eos (1- (point))))
7530 ;; Find out what to do next and set `this-command'
7531 (cond
7532 ;; Nothing is hidden behind this heading
7533 ((= eos eoh)
7534 (message "EMPTY ENTRY")
7535 (setq markdown-cycle-subtree-status nil))
7536 ;; Entire subtree is hidden in one line: open it
7537 ((>= eol eos)
7538 (markdown-show-entry)
7539 (markdown-show-children)
7540 (message "CHILDREN")
7541 (setq markdown-cycle-subtree-status 'children))
7542 ;; We just showed the children, now show everything.
7543 ((and (eq last-command this-command)
7544 (eq markdown-cycle-subtree-status 'children))
7545 (markdown-show-subtree)
7546 (message "SUBTREE")
7547 (setq markdown-cycle-subtree-status 'subtree))
7548 ;; Default action: hide the subtree.
7550 (markdown-hide-subtree)
7551 (message "FOLDED")
7552 (setq markdown-cycle-subtree-status 'folded)))))
7554 ;; In a table, move forward by one cell
7555 ((markdown-table-at-point-p)
7556 (call-interactively #'markdown-table-forward-cell))
7558 ;; Otherwise, indent as appropriate
7560 (indent-for-tab-command))))
7562 (defun markdown-shifttab ()
7563 "Handle S-TAB keybinding based on context.
7564 When in a table, move backward one cell.
7565 Otherwise, cycle global heading visibility by calling
7566 `markdown-cycle' with argument t."
7567 (interactive)
7568 (cond ((markdown-table-at-point-p)
7569 (call-interactively #'markdown-table-backward-cell))
7570 (t (markdown-cycle t))))
7572 (defun markdown-outline-level ()
7573 "Return the depth to which a statement is nested in the outline."
7574 (cond
7575 ((and (match-beginning 0)
7576 (markdown-code-block-at-pos (match-beginning 0)))
7577 7) ;; Only 6 header levels are defined.
7578 ((match-end 2) 1)
7579 ((match-end 3) 2)
7580 ((match-end 4)
7581 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7583 (defun markdown-promote-subtree (&optional arg)
7584 "Promote the current subtree of ATX headings.
7585 Note that Markdown does not support heading levels higher than
7586 six and therefore level-six headings will not be promoted
7587 further. If ARG is non-nil promote the heading, otherwise
7588 demote."
7589 (interactive "*P")
7590 (save-excursion
7591 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7592 (re-search-backward markdown-regex-header-atx nil t))
7593 (not (markdown-code-block-at-point-p)))
7594 (let ((level (length (match-string 1)))
7595 (promote-or-demote (if arg 1 -1))
7596 (remove 't))
7597 (markdown-cycle-atx promote-or-demote remove)
7598 (catch 'end-of-subtree
7599 (while (and (markdown-next-heading)
7600 (looking-at markdown-regex-header-atx))
7601 ;; Exit if this not a higher level heading; promote otherwise.
7602 (if (and (looking-at markdown-regex-header-atx)
7603 (<= (length (match-string-no-properties 1)) level))
7604 (throw 'end-of-subtree nil)
7605 (markdown-cycle-atx promote-or-demote remove))))))))
7607 (defun markdown-demote-subtree ()
7608 "Demote the current subtree of ATX headings."
7609 (interactive)
7610 (markdown-promote-subtree t))
7612 (defun markdown-move-subtree-up ()
7613 "Move the current subtree of ATX headings up."
7614 (interactive)
7615 (outline-move-subtree-up 1))
7617 (defun markdown-move-subtree-down ()
7618 "Move the current subtree of ATX headings down."
7619 (interactive)
7620 (outline-move-subtree-down 1))
7622 (defun markdown-outline-next ()
7623 "Move to next list item, when in a list, or next visible heading."
7624 (interactive)
7625 (let ((bounds (markdown-next-list-item-bounds)))
7626 (if bounds
7627 (goto-char (nth 0 bounds))
7628 (markdown-next-visible-heading 1))))
7630 (defun markdown-outline-previous ()
7631 "Move to previous list item, when in a list, or previous visible heading."
7632 (interactive)
7633 (let ((bounds (markdown-prev-list-item-bounds)))
7634 (if bounds
7635 (goto-char (nth 0 bounds))
7636 (markdown-previous-visible-heading 1))))
7638 (defun markdown-outline-next-same-level ()
7639 "Move to next list item or heading of same level."
7640 (interactive)
7641 (let ((bounds (markdown-cur-list-item-bounds)))
7642 (if bounds
7643 (markdown-next-list-item (nth 3 bounds))
7644 (markdown-forward-same-level 1))))
7646 (defun markdown-outline-previous-same-level ()
7647 "Move to previous list item or heading of same level."
7648 (interactive)
7649 (let ((bounds (markdown-cur-list-item-bounds)))
7650 (if bounds
7651 (markdown-prev-list-item (nth 3 bounds))
7652 (markdown-backward-same-level 1))))
7654 (defun markdown-outline-up ()
7655 "Move to previous list item, when in a list, or next heading."
7656 (interactive)
7657 (unless (markdown-up-list)
7658 (markdown-up-heading 1)))
7661 ;;; Marking and Narrowing =====================================================
7663 (defun markdown-mark-paragraph ()
7664 "Put mark at end of this block, point at beginning.
7665 The block marked is the one that contains point or follows point.
7667 Interactively, if this command is repeated or (in Transient Mark
7668 mode) if the mark is active, it marks the next block 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-paragraph)
7677 (point)))
7678 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7679 (end-of-defun-function 'markdown-forward-paragraph))
7680 (mark-defun))))
7682 (defun markdown-mark-block ()
7683 "Put mark at end of this block, point at beginning.
7684 The block marked is the one that contains point or follows point.
7686 Interactively, if this command is repeated or (in Transient Mark
7687 mode) if the mark is active, it marks the next block after the
7688 ones already marked."
7689 (interactive)
7690 (if (or (and (eq last-command this-command) (mark t))
7691 (and transient-mark-mode mark-active))
7692 (set-mark
7693 (save-excursion
7694 (goto-char (mark))
7695 (markdown-forward-block)
7696 (point)))
7697 (let ((beginning-of-defun-function 'markdown-backward-block)
7698 (end-of-defun-function 'markdown-forward-block))
7699 (mark-defun))))
7701 (defun markdown-narrow-to-block ()
7702 "Make text outside current block invisible.
7703 The current block is the one that contains point or follows point."
7704 (interactive)
7705 (let ((beginning-of-defun-function 'markdown-backward-block)
7706 (end-of-defun-function 'markdown-forward-block))
7707 (narrow-to-defun)))
7709 (defun markdown-mark-text-block ()
7710 "Put mark at end of this plain text block, point at beginning.
7711 The block marked is the one that contains point or follows point.
7713 Interactively, if this command is repeated or (in Transient Mark
7714 mode) if the mark is active, it marks the next block after the
7715 ones already marked."
7716 (interactive)
7717 (if (or (and (eq last-command this-command) (mark t))
7718 (and transient-mark-mode mark-active))
7719 (set-mark
7720 (save-excursion
7721 (goto-char (mark))
7722 (markdown-end-of-text-block)
7723 (point)))
7724 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7725 (end-of-defun-function 'markdown-end-of-text-block))
7726 (mark-defun))))
7728 (defun markdown-mark-page ()
7729 "Put mark at end of this top level section, point at beginning.
7730 The top level section marked is the one that contains point or
7731 follows point.
7733 Interactively, if this command is repeated or (in Transient Mark
7734 mode) if the mark is active, it marks the next page after the
7735 ones already marked."
7736 (interactive)
7737 (if (or (and (eq last-command this-command) (mark t))
7738 (and transient-mark-mode mark-active))
7739 (set-mark
7740 (save-excursion
7741 (goto-char (mark))
7742 (markdown-forward-page)
7743 (point)))
7744 (let ((beginning-of-defun-function 'markdown-backward-page)
7745 (end-of-defun-function 'markdown-forward-page))
7746 (mark-defun))))
7748 (defun markdown-narrow-to-page ()
7749 "Make text outside current top level section invisible.
7750 The current section is the one that contains point or follows point."
7751 (interactive)
7752 (let ((beginning-of-defun-function 'markdown-backward-page)
7753 (end-of-defun-function 'markdown-forward-page))
7754 (narrow-to-defun)))
7756 (defun markdown-mark-subtree ()
7757 "Mark the current subtree.
7758 This puts point at the start of the current subtree, and mark at the end."
7759 (interactive)
7760 (let ((beg))
7761 (if (markdown-heading-at-point)
7762 (beginning-of-line)
7763 (markdown-previous-visible-heading 1))
7764 (setq beg (point))
7765 (markdown-end-of-subtree)
7766 (push-mark (point) nil t)
7767 (goto-char beg)))
7769 (defun markdown-narrow-to-subtree ()
7770 "Narrow buffer to the current subtree."
7771 (interactive)
7772 (save-excursion
7773 (save-match-data
7774 (narrow-to-region
7775 (progn (markdown-back-to-heading-over-code-block t) (point))
7776 (progn (markdown-end-of-subtree)
7777 (if (and (markdown-heading-at-point) (not (eobp)))
7778 (backward-char 1))
7779 (point))))))
7782 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7784 (defun markdown-move-up ()
7785 "Move thing at point up.
7786 When in a list item, call `markdown-move-list-item-up'.
7787 When in a table, call `markdown-table-move-row-up'.
7788 Otherwise, move the current heading subtree up with
7789 `markdown-move-subtree-up'."
7790 (interactive)
7791 (cond
7792 ((markdown-list-item-at-point-p)
7793 (call-interactively #'markdown-move-list-item-up))
7794 ((markdown-table-at-point-p)
7795 (call-interactively #'markdown-table-move-row-up))
7797 (call-interactively #'markdown-move-subtree-up))))
7799 (defun markdown-move-down ()
7800 "Move thing at point down.
7801 When in a list item, call `markdown-move-list-item-down'.
7802 Otherwise, move the current heading subtree up with
7803 `markdown-move-subtree-down'."
7804 (interactive)
7805 (cond
7806 ((markdown-list-item-at-point-p)
7807 (call-interactively #'markdown-move-list-item-down))
7808 ((markdown-table-at-point-p)
7809 (call-interactively #'markdown-table-move-row-down))
7811 (call-interactively #'markdown-move-subtree-down))))
7813 (defun markdown-promote ()
7814 "Promote or move element at point to the left.
7815 Depending on the context, this function will promote a heading or
7816 list item at the point, move a table column to the left, or cycle
7817 markup."
7818 (interactive)
7819 (let (bounds)
7820 (cond
7821 ;; Promote atx heading subtree
7822 ((thing-at-point-looking-at markdown-regex-header-atx)
7823 (markdown-promote-subtree))
7824 ;; Promote setext heading
7825 ((thing-at-point-looking-at markdown-regex-header-setext)
7826 (markdown-cycle-setext -1))
7827 ;; Promote horizonal rule
7828 ((thing-at-point-looking-at markdown-regex-hr)
7829 (markdown-cycle-hr -1))
7830 ;; Promote list item
7831 ((setq bounds (markdown-cur-list-item-bounds))
7832 (markdown-promote-list-item bounds))
7833 ;; Move table column to the left
7834 ((markdown-table-at-point-p)
7835 (call-interactively #'markdown-table-move-column-left))
7836 ;; Promote bold
7837 ((thing-at-point-looking-at markdown-regex-bold)
7838 (markdown-cycle-bold))
7839 ;; Promote italic
7840 ((thing-at-point-looking-at markdown-regex-italic)
7841 (markdown-cycle-italic))
7843 (user-error "Nothing to promote at point")))))
7845 (defun markdown-demote ()
7846 "Demote or move element at point to the right.
7847 Depending on the context, this function will demote a heading or
7848 list item at the point, move a table column to the right, or cycle
7849 or remove markup."
7850 (interactive)
7851 (let (bounds)
7852 (cond
7853 ;; Demote atx heading subtree
7854 ((thing-at-point-looking-at markdown-regex-header-atx)
7855 (markdown-demote-subtree))
7856 ;; Demote setext heading
7857 ((thing-at-point-looking-at markdown-regex-header-setext)
7858 (markdown-cycle-setext 1))
7859 ;; Demote horizonal rule
7860 ((thing-at-point-looking-at markdown-regex-hr)
7861 (markdown-cycle-hr 1))
7862 ;; Demote list item
7863 ((setq bounds (markdown-cur-list-item-bounds))
7864 (markdown-demote-list-item bounds))
7865 ;; Move table column to the right
7866 ((markdown-table-at-point-p)
7867 (call-interactively #'markdown-table-move-column-right))
7868 ;; Demote bold
7869 ((thing-at-point-looking-at markdown-regex-bold)
7870 (markdown-cycle-bold))
7871 ;; Demote italic
7872 ((thing-at-point-looking-at markdown-regex-italic)
7873 (markdown-cycle-italic))
7875 (user-error "Nothing to demote at point")))))
7878 ;;; Commands ==================================================================
7880 (defun markdown (&optional output-buffer-name)
7881 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7882 The output buffer name defaults to `markdown-output-buffer-name'.
7883 Return the name of the output buffer used."
7884 (interactive)
7885 (save-window-excursion
7886 (let ((begin-region)
7887 (end-region))
7888 (if (markdown-use-region-p)
7889 (setq begin-region (region-beginning)
7890 end-region (region-end))
7891 (setq begin-region (point-min)
7892 end-region (point-max)))
7894 (unless output-buffer-name
7895 (setq output-buffer-name markdown-output-buffer-name))
7896 (cond
7897 ;; Handle case when `markdown-command' does not read from stdin
7898 ((and (stringp markdown-command) markdown-command-needs-filename)
7899 (if (not buffer-file-name)
7900 (user-error "Must be visiting a file")
7901 (shell-command (concat markdown-command " "
7902 (shell-quote-argument buffer-file-name))
7903 output-buffer-name)))
7904 ;; Pass region to `markdown-command' via stdin
7906 (let ((buf (get-buffer-create output-buffer-name)))
7907 (with-current-buffer buf
7908 (setq buffer-read-only nil)
7909 (erase-buffer))
7910 (if (stringp markdown-command)
7911 (call-process-region begin-region end-region
7912 shell-file-name nil buf nil
7913 shell-command-switch markdown-command)
7914 (funcall markdown-command begin-region end-region buf))))))
7915 output-buffer-name))
7917 (defun markdown-standalone (&optional output-buffer-name)
7918 "Special function to provide standalone HTML output.
7919 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7920 (interactive)
7921 (setq output-buffer-name (markdown output-buffer-name))
7922 (with-current-buffer output-buffer-name
7923 (set-buffer output-buffer-name)
7924 (unless (markdown-output-standalone-p)
7925 (markdown-add-xhtml-header-and-footer output-buffer-name))
7926 (goto-char (point-min))
7927 (html-mode))
7928 output-buffer-name)
7930 (defun markdown-other-window (&optional output-buffer-name)
7931 "Run `markdown-command' on current buffer and display in other window.
7932 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7933 that name."
7934 (interactive)
7935 (markdown-display-buffer-other-window
7936 (markdown-standalone output-buffer-name)))
7938 (defun markdown-output-standalone-p ()
7939 "Determine whether `markdown-command' output is standalone XHTML.
7940 Standalone XHTML output is identified by an occurrence of
7941 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7942 (save-excursion
7943 (goto-char (point-min))
7944 (save-match-data
7945 (re-search-forward
7946 markdown-xhtml-standalone-regexp
7947 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7948 t))))
7950 (defun markdown-stylesheet-link-string (stylesheet-path)
7951 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7952 stylesheet-path
7953 "\" />"))
7955 (defun markdown-add-xhtml-header-and-footer (title)
7956 "Wrap XHTML header and footer with given TITLE around current buffer."
7957 (goto-char (point-min))
7958 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7959 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7960 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7961 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7962 "<head>\n<title>")
7963 (insert title)
7964 (insert "</title>\n")
7965 (when (> (length markdown-content-type) 0)
7966 (insert
7967 (format
7968 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7969 markdown-content-type
7970 (or (and markdown-coding-system
7971 (fboundp 'coding-system-get)
7972 (coding-system-get markdown-coding-system
7973 'mime-charset))
7974 (and (fboundp 'coding-system-get)
7975 (coding-system-get buffer-file-coding-system
7976 'mime-charset))
7977 "iso-8859-1"))))
7978 (if (> (length markdown-css-paths) 0)
7979 (insert (mapconcat #'markdown-stylesheet-link-string
7980 markdown-css-paths "\n")))
7981 (when (> (length markdown-xhtml-header-content) 0)
7982 (insert markdown-xhtml-header-content))
7983 (insert "\n</head>\n\n"
7984 "<body>\n\n")
7985 (goto-char (point-max))
7986 (insert "\n"
7987 "</body>\n"
7988 "</html>\n"))
7990 (defun markdown-preview (&optional output-buffer-name)
7991 "Run `markdown-command' on the current buffer and view output in browser.
7992 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7993 that name."
7994 (interactive)
7995 (browse-url-of-buffer
7996 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7998 (defun markdown-export-file-name (&optional extension)
7999 "Attempt to generate a filename for Markdown output.
8000 The file extension will be EXTENSION if given, or .html by default.
8001 If the current buffer is visiting a file, we construct a new
8002 output filename based on that filename. Otherwise, return nil."
8003 (when (buffer-file-name)
8004 (unless extension
8005 (setq extension ".html"))
8006 (let ((candidate
8007 (concat
8008 (cond
8009 ((buffer-file-name)
8010 (file-name-sans-extension (buffer-file-name)))
8011 (t (buffer-name)))
8012 extension)))
8013 (cond
8014 ((equal candidate (buffer-file-name))
8015 (concat candidate extension))
8017 candidate)))))
8019 (defun markdown-export (&optional output-file)
8020 "Run Markdown on the current buffer, save to file, and return the filename.
8021 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
8022 generated by `markdown-export-file-name', which will be constructed using the
8023 current filename, but with the extension removed and replaced with .html."
8024 (interactive)
8025 (unless output-file
8026 (setq output-file (markdown-export-file-name ".html")))
8027 (when output-file
8028 (let* ((init-buf (current-buffer))
8029 (init-point (point))
8030 (init-buf-string (buffer-string))
8031 (output-buffer (find-file-noselect output-file))
8032 (output-buffer-name (buffer-name output-buffer)))
8033 (run-hooks 'markdown-before-export-hook)
8034 (markdown-standalone output-buffer-name)
8035 (with-current-buffer output-buffer
8036 (run-hooks 'markdown-after-export-hook)
8037 (save-buffer)
8038 (when markdown-export-kill-buffer (kill-buffer)))
8039 ;; if modified, restore initial buffer
8040 (when (buffer-modified-p init-buf)
8041 (erase-buffer)
8042 (insert init-buf-string)
8043 (save-buffer)
8044 (goto-char init-point))
8045 output-file)))
8047 (defun markdown-export-and-preview ()
8048 "Export to XHTML using `markdown-export' and browse the resulting file."
8049 (interactive)
8050 (browse-url-of-file (markdown-export)))
8052 (defvar markdown-live-preview-buffer nil
8053 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
8054 (make-variable-buffer-local 'markdown-live-preview-buffer)
8056 (defvar markdown-live-preview-source-buffer nil
8057 "Source buffer from which current buffer was generated.
8058 This is the inverse of `markdown-live-preview-buffer'.")
8059 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
8061 (defvar markdown-live-preview-currently-exporting nil)
8063 (defun markdown-live-preview-get-filename ()
8064 "Standardize the filename exported by `markdown-live-preview-export'."
8065 (markdown-export-file-name ".html"))
8067 (defun markdown-live-preview-window-eww (file)
8068 "Preview FILE with eww.
8069 To be used with `markdown-live-preview-window-function'."
8070 (if (require 'eww nil t)
8071 (progn
8072 (eww-open-file file)
8073 (get-buffer "*eww*"))
8074 (error "EWW is not present or not loaded on this version of Emacs")))
8076 (defun markdown-visual-lines-between-points (beg end)
8077 (save-excursion
8078 (goto-char beg)
8079 (cl-loop with count = 0
8080 while (progn (end-of-visual-line)
8081 (and (< (point) end) (line-move-visual 1 t)))
8082 do (cl-incf count)
8083 finally return count)))
8085 (defun markdown-live-preview-window-serialize (buf)
8086 "Get window point and scroll data for all windows displaying BUF."
8087 (when (buffer-live-p buf)
8088 (with-current-buffer buf
8089 (mapcar
8090 (lambda (win)
8091 (with-selected-window win
8092 (let* ((start (window-start))
8093 (pt (window-point))
8094 (pt-or-sym (cond ((= pt (point-min)) 'min)
8095 ((= pt (point-max)) 'max)
8096 (t pt)))
8097 (diff (markdown-visual-lines-between-points
8098 start pt)))
8099 (list win pt-or-sym diff))))
8100 (get-buffer-window-list buf)))))
8102 (defun markdown-get-point-back-lines (pt num-lines)
8103 (save-excursion
8104 (goto-char pt)
8105 (line-move-visual (- num-lines) t)
8106 ;; in testing, can occasionally overshoot the number of lines to traverse
8107 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
8108 (when (> actual-num-lines num-lines)
8109 (line-move-visual (- actual-num-lines num-lines) t)))
8110 (point)))
8112 (defun markdown-live-preview-window-deserialize (window-posns)
8113 "Apply window point and scroll data from WINDOW-POSNS.
8114 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
8115 (cl-destructuring-bind (win pt-or-sym diff) window-posns
8116 (when (window-live-p win)
8117 (with-current-buffer markdown-live-preview-buffer
8118 (set-window-buffer win (current-buffer))
8119 (cl-destructuring-bind (actual-pt actual-diff)
8120 (cl-case pt-or-sym
8121 (min (list (point-min) 0))
8122 (max (list (point-max) diff))
8123 (t (list pt-or-sym diff)))
8124 (set-window-start
8125 win (markdown-get-point-back-lines actual-pt actual-diff))
8126 (set-window-point win actual-pt))))))
8128 (defun markdown-live-preview-export ()
8129 "Export to XHTML using `markdown-export'.
8130 Browse the resulting file within Emacs using
8131 `markdown-live-preview-window-function' Return the buffer
8132 displaying the rendered output."
8133 (interactive)
8134 (let ((filename (markdown-live-preview-get-filename)))
8135 (when filename
8136 (let* ((markdown-live-preview-currently-exporting t)
8137 (cur-buf (current-buffer))
8138 (export-file (markdown-export filename))
8139 ;; get positions in all windows currently displaying output buffer
8140 (window-data
8141 (markdown-live-preview-window-serialize
8142 markdown-live-preview-buffer)))
8143 (save-window-excursion
8144 (let ((output-buffer
8145 (funcall markdown-live-preview-window-function export-file)))
8146 (with-current-buffer output-buffer
8147 (setq markdown-live-preview-source-buffer cur-buf)
8148 (add-hook 'kill-buffer-hook
8149 #'markdown-live-preview-remove-on-kill t t))
8150 (with-current-buffer cur-buf
8151 (setq markdown-live-preview-buffer output-buffer))))
8152 (with-current-buffer cur-buf
8153 ;; reset all windows displaying output buffer to where they were,
8154 ;; now with the new output
8155 (mapc #'markdown-live-preview-window-deserialize window-data)
8156 ;; delete html editing buffer
8157 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8158 (when (and export-file (file-exists-p export-file)
8159 (eq markdown-live-preview-delete-export
8160 'delete-on-export))
8161 (delete-file export-file))
8162 markdown-live-preview-buffer)))))
8164 (defun markdown-live-preview-remove ()
8165 (when (buffer-live-p markdown-live-preview-buffer)
8166 (kill-buffer markdown-live-preview-buffer))
8167 (setq markdown-live-preview-buffer nil)
8168 ;; if set to 'delete-on-export, the output has already been deleted
8169 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8170 (let ((outfile-name (markdown-live-preview-get-filename)))
8171 (when (and outfile-name (file-exists-p outfile-name))
8172 (delete-file outfile-name)))))
8174 (defun markdown-get-other-window ()
8175 "Find another window to display preview or output content."
8176 (cond
8177 ((memq markdown-split-window-direction '(vertical below))
8178 (or (window-in-direction 'below) (split-window-vertically)))
8179 ((memq markdown-split-window-direction '(horizontal right))
8180 (or (window-in-direction 'right) (split-window-horizontally)))
8181 (t (split-window-sensibly (get-buffer-window)))))
8183 (defun markdown-display-buffer-other-window (buf)
8184 "Display preview or output buffer BUF in another window."
8185 (let ((cur-buf (current-buffer))
8186 (window (markdown-get-other-window)))
8187 (set-window-buffer window buf)
8188 (set-buffer cur-buf)))
8190 (defun markdown-live-preview-if-markdown ()
8191 (when (and (derived-mode-p 'markdown-mode)
8192 markdown-live-preview-mode)
8193 (unless markdown-live-preview-currently-exporting
8194 (if (buffer-live-p markdown-live-preview-buffer)
8195 (markdown-live-preview-export)
8196 (markdown-display-buffer-other-window
8197 (markdown-live-preview-export))))))
8199 (defun markdown-live-preview-remove-on-kill ()
8200 (cond ((and (derived-mode-p 'markdown-mode)
8201 markdown-live-preview-mode)
8202 (markdown-live-preview-remove))
8203 (markdown-live-preview-source-buffer
8204 (with-current-buffer markdown-live-preview-source-buffer
8205 (setq markdown-live-preview-buffer nil))
8206 (setq markdown-live-preview-source-buffer nil))))
8208 (defun markdown-live-preview-switch-to-output ()
8209 "Switch to output buffer."
8210 (interactive)
8211 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8212 output buffer in another window."
8213 (if markdown-live-preview-mode
8214 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8215 (markdown-live-preview-mode))
8217 (defun markdown-live-preview-re-export ()
8218 "Re export source buffer."
8219 (interactive)
8220 "If the current buffer is a buffer displaying the exported version of a
8221 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8222 update this buffer's contents."
8223 (when markdown-live-preview-source-buffer
8224 (with-current-buffer markdown-live-preview-source-buffer
8225 (markdown-live-preview-export))))
8227 (defun markdown-open ()
8228 "Open file for the current buffer with `markdown-open-command'."
8229 (interactive)
8230 (unless markdown-open-command
8231 (user-error "Variable `markdown-open-command' must be set"))
8232 (if (stringp markdown-open-command)
8233 (if (not buffer-file-name)
8234 (user-error "Must be visiting a file")
8235 (save-buffer)
8236 (call-process markdown-open-command nil 0 nil buffer-file-name))
8237 (funcall markdown-open-command))
8238 nil)
8240 (defun markdown-kill-ring-save ()
8241 "Run Markdown on file and store output in the kill ring."
8242 (interactive)
8243 (save-window-excursion
8244 (markdown)
8245 (with-current-buffer markdown-output-buffer-name
8246 (kill-ring-save (point-min) (point-max)))))
8249 ;;; Links =====================================================================
8251 (defun markdown-link-p ()
8252 "Return non-nil when `point' is at a non-wiki link.
8253 See `markdown-wiki-link-p' for more information."
8254 (let ((case-fold-search nil))
8255 (and (not (markdown-wiki-link-p))
8256 (not (markdown-code-block-at-point-p))
8257 (or (thing-at-point-looking-at markdown-regex-link-inline)
8258 (thing-at-point-looking-at markdown-regex-link-reference)
8259 (thing-at-point-looking-at markdown-regex-uri)
8260 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8262 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8264 (defun markdown-link-at-pos (pos)
8265 "Return properties of link or image at position POS.
8266 Value is a list of elements describing the link:
8267 0. beginning position
8268 1. end position
8269 2. link text
8270 3. URL
8271 4. reference label
8272 5. title text
8273 6. bang (nil or \"!\")"
8274 (save-excursion
8275 (goto-char pos)
8276 (let (begin end text url reference title bang)
8277 (cond
8278 ;; Inline or reference image or link at point.
8279 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8280 (thing-at-point-looking-at markdown-regex-link-reference))
8281 (setq bang (match-string-no-properties 1)
8282 begin (match-beginning 0)
8283 end (match-end 0)
8284 text (match-string-no-properties 3))
8285 (if (char-equal (char-after (match-beginning 5)) ?\[)
8286 ;; Reference link
8287 (setq reference (match-string-no-properties 6))
8288 ;; Inline link
8289 (setq url (match-string-no-properties 6))
8290 (when (match-end 7)
8291 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8292 ;; Angle bracket URI at point.
8293 ((thing-at-point-looking-at markdown-regex-angle-uri)
8294 (setq begin (match-beginning 0)
8295 end (match-end 0)
8296 url (match-string-no-properties 2)))
8297 ;; Plain URI at point.
8298 ((thing-at-point-looking-at markdown-regex-uri)
8299 (setq begin (match-beginning 0)
8300 end (match-end 0)
8301 url (match-string-no-properties 1))))
8302 (list begin end text url reference title bang))))
8304 (defun markdown-link-url ()
8305 "Return the URL part of the regular (non-wiki) link at point.
8306 Works with both inline and reference style links, and with images.
8307 If point is not at a link or the link reference is not defined
8308 returns nil."
8309 (let* ((values (markdown-link-at-pos (point)))
8310 (text (nth 2 values))
8311 (url (nth 3 values))
8312 (ref (nth 4 values)))
8313 (or url (and ref (car (markdown-reference-definition
8314 (downcase (if (string= ref "") text ref))))))))
8316 (defun markdown-follow-link-at-point ()
8317 "Open the current non-wiki link.
8318 If the link is a complete URL, open in browser with `browse-url'.
8319 Otherwise, open with `find-file' after stripping anchor and/or query string.
8320 Translate filenames using `markdown-filename-translate-function'."
8321 (interactive)
8322 (if (markdown-link-p)
8323 (let* ((url (markdown-link-url))
8324 (struct (url-generic-parse-url url))
8325 (full (url-fullness struct))
8326 (file url))
8327 ;; Parse URL, determine fullness, strip query string
8328 (if (fboundp 'url-path-and-query)
8329 (setq file (car (url-path-and-query struct)))
8330 (when (and (setq file (url-filename struct))
8331 (string-match "\\?" file))
8332 (setq file (substring file 0 (match-beginning 0)))))
8333 ;; Open full URLs in browser, files in Emacs
8334 (if full
8335 (browse-url url)
8336 (when (and file (> (length file) 0))
8337 (find-file (funcall markdown-translate-filename-function file)))))
8338 (user-error "Point is not at a Markdown link or URL")))
8340 (defun markdown-fontify-inline-links (last)
8341 "Add text properties to next inline link from point to LAST."
8342 (when (markdown-match-generic-links last nil)
8343 (let* ((link-start (match-beginning 3))
8344 (link-end (match-end 3))
8345 (url-start (match-beginning 6))
8346 (url-end (match-end 6))
8347 (url (match-string-no-properties 6))
8348 (title-start (match-beginning 7))
8349 (title-end (match-end 7))
8350 (title (match-string-no-properties 7))
8351 ;; Markup part
8352 (mp (list 'face 'markdown-markup-face
8353 'invisible 'markdown-markup
8354 'rear-nonsticky t
8355 'font-lock-multiline t))
8356 ;; Link part
8357 (lp (list 'keymap markdown-mode-mouse-map
8358 'face markdown-link-face
8359 'mouse-face 'markdown-highlight-face
8360 'font-lock-multiline t
8361 'help-echo (if title (concat title "\n" url) url)))
8362 ;; URL part
8363 (up (list 'keymap markdown-mode-mouse-map
8364 'face 'markdown-url-face
8365 'invisible 'markdown-markup
8366 'mouse-face 'markdown-highlight-face
8367 'font-lock-multiline t))
8368 ;; URL composition character
8369 (url-char (markdown--first-displayable markdown-url-compose-char))
8370 ;; Title part
8371 (tp (list 'face 'markdown-link-title-face
8372 'invisible 'markdown-markup
8373 'font-lock-multiline t)))
8374 (dolist (g '(1 2 4 5 8))
8375 (when (match-end g)
8376 (add-text-properties (match-beginning g) (match-end g) mp)))
8377 (when link-start (add-text-properties link-start link-end lp))
8378 (when url-start (add-text-properties url-start url-end up))
8379 (when title-start (add-text-properties url-end title-end tp))
8380 (when (and markdown-hide-urls url-start)
8381 (compose-region url-start (or title-end url-end) url-char))
8382 t)))
8384 (defun markdown-fontify-reference-links (last)
8385 "Add text properties to next reference link from point to LAST."
8386 (when (markdown-match-generic-links last t)
8387 (let* ((link-start (match-beginning 3))
8388 (link-end (match-end 3))
8389 (ref-start (match-beginning 6))
8390 (ref-end (match-end 6))
8391 ;; Markup part
8392 (mp (list 'face 'markdown-markup-face
8393 'invisible 'markdown-markup
8394 'rear-nonsticky t
8395 'font-lock-multiline t))
8396 ;; Link part
8397 (lp (list 'keymap markdown-mode-mouse-map
8398 'face markdown-link-face
8399 'mouse-face 'markdown-highlight-face
8400 'font-lock-multiline t
8401 'help-echo (lambda (_ __ pos)
8402 (save-match-data
8403 (save-excursion
8404 (goto-char pos)
8405 (or (markdown-link-url)
8406 "Undefined reference"))))))
8407 ;; URL composition character
8408 (url-char (markdown--first-displayable markdown-url-compose-char))
8409 ;; Reference part
8410 (rp (list 'face 'markdown-reference-face
8411 'invisible 'markdown-markup
8412 'font-lock-multiline t)))
8413 (dolist (g '(1 2 4 5 8))
8414 (when (match-end g)
8415 (add-text-properties (match-beginning g) (match-end g) mp)))
8416 (when link-start (add-text-properties link-start link-end lp))
8417 (when ref-start (add-text-properties ref-start ref-end rp)
8418 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8419 (compose-region ref-start ref-end url-char)))
8420 t)))
8422 (defun markdown-fontify-angle-uris (last)
8423 "Add text properties to angle URIs from point to LAST."
8424 (when (markdown-match-angle-uris last)
8425 (let* ((url-start (match-beginning 2))
8426 (url-end (match-end 2))
8427 ;; Markup part
8428 (mp (list 'face 'markdown-markup-face
8429 'invisible 'markdown-markup
8430 'rear-nonsticky t
8431 'font-lock-multiline t))
8432 ;; URI part
8433 (up (list 'keymap markdown-mode-mouse-map
8434 'face 'markdown-plain-url-face
8435 'mouse-face 'markdown-highlight-face
8436 'font-lock-multiline t)))
8437 (dolist (g '(1 3))
8438 (add-text-properties (match-beginning g) (match-end g) mp))
8439 (add-text-properties url-start url-end up)
8440 t)))
8442 (defun markdown-fontify-plain-uris (last)
8443 "Add text properties to plain URLs from point to LAST."
8444 (when (markdown-match-plain-uris last)
8445 (let* ((start (match-beginning 0))
8446 (end (match-end 0))
8447 (props (list 'keymap markdown-mode-mouse-map
8448 'face 'markdown-plain-url-face
8449 'mouse-face 'markdown-highlight-face
8450 'rear-nonsticky t
8451 'font-lock-multiline t)))
8452 (add-text-properties start end props)
8453 t)))
8455 (defun markdown-toggle-url-hiding (&optional arg)
8456 "Toggle the display or hiding of URLs.
8457 With a prefix argument ARG, enable URL hiding if ARG is positive,
8458 and disable it otherwise."
8459 (interactive (list (or current-prefix-arg 'toggle)))
8460 (setq markdown-hide-urls
8461 (if (eq arg 'toggle)
8462 (not markdown-hide-urls)
8463 (> (prefix-numeric-value arg) 0)))
8464 (if markdown-hide-urls
8465 (message "markdown-mode URL hiding enabled")
8466 (message "markdown-mode URL hiding disabled"))
8467 (markdown-reload-extensions))
8470 ;;; WikiLink Following/Markup =================================================
8472 (defun markdown-wiki-link-p ()
8473 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8474 A true wiki link name matches `markdown-regex-wiki-link' but does
8475 not match the current file name after conversion. This modifies
8476 the data returned by `match-data'. Note that the potential wiki
8477 link name must be available via `match-string'."
8478 (when markdown-enable-wiki-links
8479 (let ((case-fold-search nil))
8480 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8481 (not (markdown-code-block-at-point-p))
8482 (or (not buffer-file-name)
8483 (not (string-equal (buffer-file-name)
8484 (markdown-convert-wiki-link-to-filename
8485 (markdown-wiki-link-link)))))))))
8487 (defun markdown-wiki-link-link ()
8488 "Return the link part of the wiki link using current match data.
8489 The location of the link component depends on the value of
8490 `markdown-wiki-link-alias-first'."
8491 (if markdown-wiki-link-alias-first
8492 (or (match-string-no-properties 5) (match-string-no-properties 3))
8493 (match-string-no-properties 3)))
8495 (defun markdown-wiki-link-alias ()
8496 "Return the alias or text part of the wiki link using current match data.
8497 The location of the alias component depends on the value of
8498 `markdown-wiki-link-alias-first'."
8499 (if markdown-wiki-link-alias-first
8500 (match-string-no-properties 3)
8501 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8503 (defun markdown-convert-wiki-link-to-filename (name)
8504 "Generate a filename from the wiki link NAME.
8505 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8506 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8507 and [[test test]] both map to Test-test.ext. Look in the current
8508 directory first, then in subdirectories if
8509 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8510 in parent directories if
8511 `markdown-wiki-link-search-parent-directories' is non-nil."
8512 (let* ((basename (markdown-replace-regexp-in-string
8513 "[[:space:]\n]" markdown-link-space-sub-char name))
8514 (basename (if (eq major-mode 'gfm-mode)
8515 (concat (upcase (substring basename 0 1))
8516 (downcase (substring basename 1 nil)))
8517 basename))
8518 directory extension default candidates dir)
8519 (when buffer-file-name
8520 (setq directory (file-name-directory buffer-file-name)
8521 extension (file-name-extension buffer-file-name)))
8522 (setq default (concat basename
8523 (when extension (concat "." extension))))
8524 (cond
8525 ;; Look in current directory first.
8526 ((or (null buffer-file-name)
8527 (file-exists-p default))
8528 default)
8529 ;; Possibly search in subdirectories, next.
8530 ((and markdown-wiki-link-search-subdirectories
8531 (setq candidates
8532 (markdown-directory-files-recursively
8533 directory (concat "^" default "$"))))
8534 (car candidates))
8535 ;; Possibly search in parent directories as a last resort.
8536 ((and markdown-wiki-link-search-parent-directories
8537 (setq dir (locate-dominating-file directory default)))
8538 (concat dir default))
8539 ;; If nothing is found, return default in current directory.
8540 (t default))))
8542 (defun markdown-follow-wiki-link (name &optional other)
8543 "Follow the wiki link NAME.
8544 Convert the name to a file name and call `find-file'. Ensure that
8545 the new buffer remains in `markdown-mode'. Open the link in another
8546 window when OTHER is non-nil."
8547 (let ((filename (markdown-convert-wiki-link-to-filename name))
8548 (wp (when buffer-file-name
8549 (file-name-directory buffer-file-name))))
8550 (if (not wp)
8551 (user-error "Must be visiting a file")
8552 (when other (other-window 1))
8553 (let ((default-directory wp))
8554 (find-file filename)))
8555 (when (not (eq major-mode 'markdown-mode))
8556 (markdown-mode))))
8558 (defun markdown-follow-wiki-link-at-point (&optional arg)
8559 "Find Wiki Link at point.
8560 With prefix argument ARG, open the file in other window.
8561 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8562 (interactive "P")
8563 (if (markdown-wiki-link-p)
8564 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8565 (user-error "Point is not at a Wiki Link")))
8567 (defun markdown-highlight-wiki-link (from to face)
8568 "Highlight the wiki link in the region between FROM and TO using FACE."
8569 (put-text-property from to 'font-lock-face face))
8571 (defun markdown-unfontify-region-wiki-links (from to)
8572 "Remove wiki link faces from the region specified by FROM and TO."
8573 (interactive "*r")
8574 (let ((modified (buffer-modified-p)))
8575 (remove-text-properties from to '(font-lock-face markdown-link-face))
8576 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8577 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8578 ;; undo that if it wasn't originally marked modified
8579 (set-buffer-modified-p modified)))
8581 (defun markdown-fontify-region-wiki-links (from to)
8582 "Search region given by FROM and TO for wiki links and fontify them.
8583 If a wiki link is found check to see if the backing file exists
8584 and highlight accordingly."
8585 (goto-char from)
8586 (save-match-data
8587 (while (re-search-forward markdown-regex-wiki-link to t)
8588 (when (not (markdown-code-block-at-point-p))
8589 (let ((highlight-beginning (match-beginning 1))
8590 (highlight-end (match-end 1))
8591 (file-name
8592 (markdown-convert-wiki-link-to-filename
8593 (markdown-wiki-link-link))))
8594 (if (condition-case nil (file-exists-p file-name) (error nil))
8595 (markdown-highlight-wiki-link
8596 highlight-beginning highlight-end markdown-link-face)
8597 (markdown-highlight-wiki-link
8598 highlight-beginning highlight-end markdown-missing-link-face)))))))
8600 (defun markdown-extend-changed-region (from to)
8601 "Extend region given by FROM and TO so that we can fontify all links.
8602 The region is extended to the first newline before and the first
8603 newline after."
8604 ;; start looking for the first new line before 'from
8605 (goto-char from)
8606 (re-search-backward "\n" nil t)
8607 (let ((new-from (point-min))
8608 (new-to (point-max)))
8609 (if (not (= (point) from))
8610 (setq new-from (point)))
8611 ;; do the same thing for the first new line after 'to
8612 (goto-char to)
8613 (re-search-forward "\n" nil t)
8614 (if (not (= (point) to))
8615 (setq new-to (point)))
8616 (cl-values new-from new-to)))
8618 (defun markdown-check-change-for-wiki-link (from to)
8619 "Check region between FROM and TO for wiki links and re-fontify as needed."
8620 (interactive "*r")
8621 (let* ((modified (buffer-modified-p))
8622 (buffer-undo-list t)
8623 (inhibit-read-only t)
8624 (inhibit-point-motion-hooks t)
8625 deactivate-mark
8626 buffer-file-truename)
8627 (unwind-protect
8628 (save-excursion
8629 (save-match-data
8630 (save-restriction
8631 ;; Extend the region to fontify so that it starts
8632 ;; and ends at safe places.
8633 (cl-multiple-value-bind (new-from new-to)
8634 (markdown-extend-changed-region from to)
8635 (goto-char new-from)
8636 ;; Only refontify when the range contains text with a
8637 ;; wiki link face or if the wiki link regexp matches.
8638 (when (or (markdown-range-property-any
8639 new-from new-to 'font-lock-face
8640 (list markdown-link-face
8641 markdown-missing-link-face))
8642 (re-search-forward
8643 markdown-regex-wiki-link new-to t))
8644 ;; Unfontify existing fontification (start from scratch)
8645 (markdown-unfontify-region-wiki-links new-from new-to)
8646 ;; Now do the fontification.
8647 (markdown-fontify-region-wiki-links new-from new-to))))))
8648 (and (not modified)
8649 (buffer-modified-p)
8650 (set-buffer-modified-p nil)))))
8652 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8653 "Check region between FROM and TO for wiki links and re-fontify as needed.
8654 Designed to be used with the `after-change-functions' hook."
8655 (markdown-check-change-for-wiki-link from to))
8657 (defun markdown-fontify-buffer-wiki-links ()
8658 "Refontify all wiki links in the buffer."
8659 (interactive)
8660 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8663 ;;; Following & Doing =========================================================
8665 (defun markdown-follow-thing-at-point (arg)
8666 "Follow thing at point if possible, such as a reference link or wiki link.
8667 Opens inline and reference links in a browser. Opens wiki links
8668 to other files in the current window, or the another window if
8669 ARG is non-nil.
8670 See `markdown-follow-link-at-point' and
8671 `markdown-follow-wiki-link-at-point'."
8672 (interactive "P")
8673 (cond ((markdown-link-p)
8674 (markdown-follow-link-at-point))
8675 ((markdown-wiki-link-p)
8676 (markdown-follow-wiki-link-at-point arg))
8678 (user-error "Nothing to follow at point"))))
8680 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8682 (defun markdown-do ()
8683 "Do something sensible based on context at point.
8684 Jumps between reference links and definitions; between footnote
8685 markers and footnote text."
8686 (interactive)
8687 (cond
8688 ;; Footnote definition
8689 ((markdown-footnote-text-positions)
8690 (markdown-footnote-return))
8691 ;; Footnote marker
8692 ((markdown-footnote-marker-positions)
8693 (markdown-footnote-goto-text))
8694 ;; Reference link
8695 ((thing-at-point-looking-at markdown-regex-link-reference)
8696 (markdown-reference-goto-definition))
8697 ;; Reference definition
8698 ((thing-at-point-looking-at markdown-regex-reference-definition)
8699 (markdown-reference-goto-link (match-string-no-properties 2)))
8700 ;; GFM task list item
8701 ((markdown-gfm-task-list-item-at-point)
8702 (markdown-toggle-gfm-checkbox))
8703 ;; Align table
8704 ((markdown-table-at-point-p)
8705 (call-interactively #'markdown-table-align))
8706 ;; Otherwise
8708 (markdown-insert-gfm-checkbox))))
8711 ;;; Miscellaneous =============================================================
8713 (defun markdown-compress-whitespace-string (str)
8714 "Compress whitespace in STR and return result.
8715 Leading and trailing whitespace is removed. Sequences of multiple
8716 spaces, tabs, and newlines are replaced with single spaces."
8717 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8718 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8720 (defun markdown--substitute-command-keys (string)
8721 "Like `substitute-command-keys' but, but prefers control characters.
8722 First pass STRING to `substitute-command-keys' and then
8723 substitute `C-i` for `TAB` and `C-m` for `RET`."
8724 (replace-regexp-in-string
8725 "\\<TAB\\>" "C-i"
8726 (replace-regexp-in-string
8727 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8729 (defun markdown-line-number-at-pos (&optional pos)
8730 "Return (narrowed) buffer line number at position POS.
8731 If POS is nil, use current buffer location.
8732 This is an exact copy of `line-number-at-pos' for use in emacs21."
8733 (let ((opoint (or pos (point))) start)
8734 (save-excursion
8735 (goto-char (point-min))
8736 (setq start (point))
8737 (goto-char opoint)
8738 (forward-line 0)
8739 (1+ (count-lines start (point))))))
8741 (defun markdown-inside-link-p ()
8742 "Return t if point is within a link."
8743 (save-match-data
8744 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8746 (defun markdown-line-is-reference-definition-p ()
8747 "Return whether the current line is a (non-footnote) reference defition."
8748 (save-excursion
8749 (move-beginning-of-line 1)
8750 (and (looking-at-p markdown-regex-reference-definition)
8751 (not (looking-at-p "[ \t]*\\[^")))))
8753 (defun markdown-adaptive-fill-function ()
8754 "Return prefix for filling paragraph or nil if not determined."
8755 (cond
8756 ;; List item inside blockquote
8757 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8758 (markdown-replace-regexp-in-string
8759 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8760 ;; Blockquote
8761 ((looking-at markdown-regex-blockquote)
8762 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8763 ;; List items
8764 ((looking-at markdown-regex-list)
8765 (match-string-no-properties 0))
8766 ;; Footnote definition
8767 ((looking-at-p markdown-regex-footnote-definition)
8768 " ") ; four spaces
8769 ;; No match
8770 (t nil)))
8772 (defun markdown-fill-paragraph (&optional justify)
8773 "Fill paragraph at or after point.
8774 This function is like \\[fill-paragraph], but it skips Markdown
8775 code blocks. If the point is in a code block, or just before one,
8776 do not fill. Otherwise, call `fill-paragraph' as usual. If
8777 JUSTIFY is non-nil, justify text as well. Since this function
8778 handles filling itself, it always returns t so that
8779 `fill-paragraph' doesn't run."
8780 (interactive "P")
8781 (unless (or (markdown-code-block-at-point-p)
8782 (save-excursion
8783 (back-to-indentation)
8784 (skip-syntax-forward "-")
8785 (markdown-code-block-at-point-p)))
8786 (fill-paragraph justify))
8789 (make-obsolete 'markdown-fill-forward-paragraph-function
8790 'markdown-fill-forward-paragraph "v2.3")
8792 (defun markdown-fill-forward-paragraph (&optional arg)
8793 "Function used by `fill-paragraph' to move over ARG paragraphs.
8794 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8795 It is called with a single argument specifying the number of
8796 paragraphs to move. Just like `forward-paragraph', it should
8797 return the number of paragraphs left to move."
8798 (or arg (setq arg 1))
8799 (if (> arg 0)
8800 ;; With positive ARG, move across ARG non-code-block paragraphs,
8801 ;; one at a time. When passing a code block, don't decrement ARG.
8802 (while (and (not (eobp))
8803 (> arg 0)
8804 (= (forward-paragraph 1) 0)
8805 (or (markdown-code-block-at-pos (point-at-bol 0))
8806 (setq arg (1- arg)))))
8807 ;; Move backward by one paragraph with negative ARG (always -1).
8808 (let ((start (point)))
8809 (setq arg (forward-paragraph arg))
8810 (while (and (not (eobp))
8811 (progn (move-to-left-margin) (not (eobp)))
8812 (looking-at-p paragraph-separate))
8813 (forward-line 1))
8814 (cond
8815 ;; Move point past whitespace following list marker.
8816 ((looking-at markdown-regex-list)
8817 (goto-char (match-end 0)))
8818 ;; Move point past whitespace following pipe at beginning of line
8819 ;; to handle Pandoc line blocks.
8820 ((looking-at "^|\\s-*")
8821 (goto-char (match-end 0)))
8822 ;; Return point if the paragraph passed was a code block.
8823 ((markdown-code-block-at-pos (point-at-bol 2))
8824 (goto-char start)))))
8825 arg)
8827 (defun markdown--inhibit-electric-quote ()
8828 "Function added to `electric-quote-inhibit-functions'.
8829 Return non-nil if the quote has been inserted inside a code block
8830 or span."
8831 (let ((pos (1- (point))))
8832 (or (markdown-inline-code-at-pos pos)
8833 (markdown-code-block-at-pos pos))))
8836 ;;; Extension Framework =======================================================
8838 (defun markdown-reload-extensions ()
8839 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8840 (interactive)
8841 (when (member major-mode '(markdown-mode gfm-mode))
8842 ;; Refontify buffer
8843 (if (eval-when-compile (fboundp 'font-lock-flush))
8844 ;; Use font-lock-flush in Emacs >= 25.1
8845 (font-lock-flush)
8846 ;; Backwards compatibility for Emacs 24.3-24.5
8847 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8848 (font-lock-refresh-defaults)))
8849 ;; Add or remove hooks related to extensions
8850 (markdown-setup-wiki-link-hooks)))
8852 (defun markdown-handle-local-variables ()
8853 "Run in `hack-local-variables-hook' to update font lock rules.
8854 Checks to see if there is actually a ‘markdown-mode’ file local variable
8855 before regenerating font-lock rules for extensions."
8856 (when (and (boundp 'file-local-variables-alist)
8857 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8858 (assoc 'markdown-enable-math file-local-variables-alist)))
8859 (when (assoc 'markdown-enable-math file-local-variables-alist)
8860 (markdown-toggle-math markdown-enable-math))
8861 (markdown-reload-extensions)))
8864 ;;; Wiki Links ================================================================
8866 (defun markdown-toggle-wiki-links (&optional arg)
8867 "Toggle support for wiki links.
8868 With a prefix argument ARG, enable wiki link support if ARG is positive,
8869 and disable it otherwise."
8870 (interactive (list (or current-prefix-arg 'toggle)))
8871 (setq markdown-enable-wiki-links
8872 (if (eq arg 'toggle)
8873 (not markdown-enable-wiki-links)
8874 (> (prefix-numeric-value arg) 0)))
8875 (if markdown-enable-wiki-links
8876 (message "markdown-mode wiki link support enabled")
8877 (message "markdown-mode wiki link support disabled"))
8878 (markdown-reload-extensions))
8880 (defun markdown-setup-wiki-link-hooks ()
8881 "Add or remove hooks for fontifying wiki links.
8882 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8883 ;; Anytime text changes make sure it gets fontified correctly
8884 (if (and markdown-enable-wiki-links
8885 markdown-wiki-link-fontify-missing)
8886 (add-hook 'after-change-functions
8887 'markdown-check-change-for-wiki-link-after-change t t)
8888 (remove-hook 'after-change-functions
8889 'markdown-check-change-for-wiki-link-after-change t))
8890 ;; If we left the buffer there is a really good chance we were
8891 ;; creating one of the wiki link documents. Make sure we get
8892 ;; refontified when we come back.
8893 (if (and markdown-enable-wiki-links
8894 markdown-wiki-link-fontify-missing)
8895 (progn
8896 (add-hook 'window-configuration-change-hook
8897 'markdown-fontify-buffer-wiki-links t t)
8898 (markdown-fontify-buffer-wiki-links))
8899 (remove-hook 'window-configuration-change-hook
8900 'markdown-fontify-buffer-wiki-links t)
8901 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8904 ;;; Math Support ==============================================================
8906 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8908 (defconst markdown-mode-font-lock-keywords-math
8909 (list
8910 ;; Equation reference (eq:foo)
8911 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8912 (2 markdown-reference-face)
8913 (3 markdown-markup-face)))
8914 ;; Equation reference \eqref{foo}
8915 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8916 (2 markdown-reference-face)
8917 (3 markdown-markup-face))))
8918 "Font lock keywords to add and remove when toggling math support.")
8920 (defun markdown-toggle-math (&optional arg)
8921 "Toggle support for inline and display LaTeX math expressions.
8922 With a prefix argument ARG, enable math mode if ARG is positive,
8923 and disable it otherwise. If called from Lisp, enable the mode
8924 if ARG is omitted or nil."
8925 (interactive (list (or current-prefix-arg 'toggle)))
8926 (setq markdown-enable-math
8927 (if (eq arg 'toggle)
8928 (not markdown-enable-math)
8929 (> (prefix-numeric-value arg) 0)))
8930 (if markdown-enable-math
8931 (progn
8932 (font-lock-add-keywords
8933 'markdown-mode markdown-mode-font-lock-keywords-math)
8934 (message "markdown-mode math support enabled"))
8935 (font-lock-remove-keywords
8936 'markdown-mode markdown-mode-font-lock-keywords-math)
8937 (message "markdown-mode math support disabled"))
8938 (markdown-reload-extensions))
8941 ;;; GFM Checkboxes ============================================================
8943 (define-button-type 'markdown-gfm-checkbox-button
8944 'follow-link t
8945 'face 'markdown-gfm-checkbox-face
8946 'mouse-face 'markdown-highlight-face
8947 'action #'markdown-toggle-gfm-checkbox-button)
8949 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8950 "Return non-nil if there is a GFM task list item at the point.
8951 Optionally, the list item BOUNDS may be given if available, as
8952 returned by `markdown-cur-list-item-bounds'. When a task list item
8953 is found, the return value is the same value returned by
8954 `markdown-cur-list-item-bounds'."
8955 (unless bounds
8956 (setq bounds (markdown-cur-list-item-bounds)))
8957 (> (length (nth 5 bounds)) 0))
8959 (defun markdown-insert-gfm-checkbox ()
8960 "Add GFM checkbox at point.
8961 Returns t if added.
8962 Returns nil if non-applicable."
8963 (interactive)
8964 (let ((bounds (markdown-cur-list-item-bounds)))
8965 (if bounds
8966 (unless (cl-sixth bounds)
8967 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8968 (markup "[ ] "))
8969 (if (< pos (point))
8970 (save-excursion
8971 (goto-char pos)
8972 (insert markup))
8973 (goto-char pos)
8974 (insert markup))
8976 (unless (save-excursion
8977 (back-to-indentation)
8978 (or (markdown-list-item-at-point-p)
8979 (markdown-heading-at-point)
8980 (markdown-in-comment-p)
8981 (markdown-code-block-at-point-p)))
8982 (let ((pos (save-excursion
8983 (back-to-indentation)
8984 (point)))
8985 (markup (concat (or (save-excursion
8986 (beginning-of-line 0)
8987 (cl-fifth (markdown-cur-list-item-bounds)))
8988 markdown-unordered-list-item-prefix)
8989 "[ ] ")))
8990 (if (< pos (point))
8991 (save-excursion
8992 (goto-char pos)
8993 (insert markup))
8994 (goto-char pos)
8995 (insert markup))
8996 t)))))
8998 (defun markdown-toggle-gfm-checkbox ()
8999 "Toggle GFM checkbox at point.
9000 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
9001 Returns nil if there is no task list item at the point."
9002 (interactive)
9003 (save-match-data
9004 (save-excursion
9005 (let ((bounds (markdown-cur-list-item-bounds)))
9006 (when bounds
9007 ;; Move to beginning of task list item
9008 (goto-char (cl-first bounds))
9009 ;; Advance to column of first non-whitespace after marker
9010 (forward-char (cl-fourth bounds))
9011 (cond ((looking-at "\\[ \\]")
9012 (replace-match
9013 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
9014 nil t)
9015 (match-string-no-properties 0))
9016 ((looking-at "\\[[xX]\\]")
9017 (replace-match "[ ]" nil t)
9018 (match-string-no-properties 0))))))))
9020 (defun markdown-toggle-gfm-checkbox-button (button)
9021 "Toggle GFM checkbox BUTTON on click."
9022 (save-match-data
9023 (save-excursion
9024 (goto-char (button-start button))
9025 (markdown-toggle-gfm-checkbox))))
9027 (defun markdown-make-gfm-checkboxes-buttons (start end)
9028 "Make GFM checkboxes buttons in region between START and END."
9029 (save-excursion
9030 (goto-char start)
9031 (let ((case-fold-search t))
9032 (save-excursion
9033 (while (re-search-forward markdown-regex-gfm-checkbox end t)
9034 (make-button (match-beginning 1) (match-end 1)
9035 :type 'markdown-gfm-checkbox-button))))))
9037 ;; Called when any modification is made to buffer text.
9038 (defun markdown-gfm-checkbox-after-change-function (beg end _)
9039 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
9040 BEG and END are the limits of scanned region."
9041 (save-excursion
9042 (save-match-data
9043 ;; Rescan between start of line from `beg' and start of line after `end'.
9044 (markdown-make-gfm-checkboxes-buttons
9045 (progn (goto-char beg) (beginning-of-line) (point))
9046 (progn (goto-char end) (forward-line 1) (point))))))
9048 (defun markdown-remove-gfm-checkbox-overlays ()
9049 "Remove all GFM checkbox overlays in buffer."
9050 (save-excursion
9051 (save-restriction
9052 (widen)
9053 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
9056 ;;; Display inline image =================================================
9058 (defvar markdown-inline-image-overlays nil)
9059 (make-variable-buffer-local 'markdown-inline-image-overlays)
9061 (defun markdown-remove-inline-images ()
9062 "Remove inline image overlays from image links in the buffer.
9063 This can be toggled with `markdown-toggle-inline-images'
9064 or \\[markdown-toggle-inline-images]."
9065 (interactive)
9066 (mapc #'delete-overlay markdown-inline-image-overlays)
9067 (setq markdown-inline-image-overlays nil))
9069 (defun markdown-display-inline-images ()
9070 "Add inline image overlays to image links in the buffer.
9071 This can be toggled with `markdown-toggle-inline-images'
9072 or \\[markdown-toggle-inline-images]."
9073 (interactive)
9074 (unless (display-images-p)
9075 (error "Cannot show images"))
9076 (save-excursion
9077 (save-restriction
9078 (widen)
9079 (goto-char (point-min))
9080 (while (re-search-forward markdown-regex-link-inline nil t)
9081 (let ((start (match-beginning 0))
9082 (end (match-end 0))
9083 (file (match-string-no-properties 6)))
9084 (when (file-exists-p file)
9085 (let* ((abspath (if (file-name-absolute-p file)
9086 file
9087 (concat default-directory file)))
9088 (image
9089 (if (and markdown-max-image-size
9090 (image-type-available-p 'imagemagick))
9091 (create-image
9092 abspath 'imagemagick nil
9093 :max-width (car markdown-max-image-size)
9094 :max-height (cdr markdown-max-image-size))
9095 (create-image abspath))))
9096 (when image
9097 (let ((ov (make-overlay start end)))
9098 (overlay-put ov 'display image)
9099 (overlay-put ov 'face 'default)
9100 (push ov markdown-inline-image-overlays))))))))))
9102 (defun markdown-toggle-inline-images ()
9103 "Toggle inline image overlays in the buffer."
9104 (interactive)
9105 (if markdown-inline-image-overlays
9106 (markdown-remove-inline-images)
9107 (markdown-display-inline-images)))
9110 ;;; GFM Code Block Fontification ==============================================
9112 (defcustom markdown-fontify-code-blocks-natively nil
9113 "When non-nil, fontify code in code blocks using the native major mode.
9114 This only works for fenced code blocks where the language is
9115 specified where we can automatically determine the appropriate
9116 mode to use. The language to mode mapping may be customized by
9117 setting the variable `markdown-code-lang-modes'."
9118 :group 'markdown
9119 :type 'boolean
9120 :safe 'booleanp
9121 :package-version '(markdown-mode . "2.3"))
9123 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
9124 "Toggle the native fontification of code blocks.
9125 With a prefix argument ARG, enable if ARG is positive,
9126 and disable otherwise."
9127 (interactive (list (or current-prefix-arg 'toggle)))
9128 (setq markdown-fontify-code-blocks-natively
9129 (if (eq arg 'toggle)
9130 (not markdown-fontify-code-blocks-natively)
9131 (> (prefix-numeric-value arg) 0)))
9132 (if markdown-fontify-code-blocks-natively
9133 (message "markdown-mode native code block fontification enabled")
9134 (message "markdown-mode native code block fontification disabled"))
9135 (markdown-reload-extensions))
9137 ;; This is based on `org-src-lang-modes' from org-src.el
9138 (defcustom markdown-code-lang-modes
9139 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
9140 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
9141 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
9142 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9143 ("bash" . sh-mode))
9144 "Alist mapping languages to their major mode.
9145 The key is the language name, the value is the major mode. For
9146 many languages this is simple, but for language where this is not
9147 the case, this variable provides a way to simplify things on the
9148 user side. For example, there is no ocaml-mode in Emacs, but the
9149 mode to use is `tuareg-mode'."
9150 :group 'markdown
9151 :type '(repeat
9152 (cons
9153 (string "Language name")
9154 (symbol "Major mode")))
9155 :package-version '(markdown-mode . "2.3"))
9157 (defun markdown-get-lang-mode (lang)
9158 "Return major mode that should be used for LANG.
9159 LANG is a string, and the returned major mode is a symbol."
9160 (cl-find-if
9161 'fboundp
9162 (list (cdr (assoc lang markdown-code-lang-modes))
9163 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9164 (intern (concat lang "-mode"))
9165 (intern (concat (downcase lang) "-mode")))))
9167 (defun markdown-fontify-code-blocks-generic (matcher last)
9168 "Add text properties to next code block from point to LAST.
9169 Use matching function MATCHER."
9170 (when (funcall matcher last)
9171 (save-excursion
9172 (save-match-data
9173 (let* ((start (match-beginning 0))
9174 (end (match-end 0))
9175 ;; Find positions outside opening and closing backquotes.
9176 (bol-prev (progn (goto-char start)
9177 (if (bolp) (point-at-bol 0) (point-at-bol))))
9178 (eol-next (progn (goto-char end)
9179 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9180 lang)
9181 (if (and markdown-fontify-code-blocks-natively
9182 (setq lang (markdown-code-block-lang)))
9183 (markdown-fontify-code-block-natively lang start end)
9184 (add-text-properties start end '(face markdown-pre-face)))
9185 ;; Set background for block as well as opening and closing lines.
9186 (font-lock-append-text-property
9187 bol-prev eol-next 'face 'markdown-code-face)
9188 ;; Set invisible property for lines before and after, including newline.
9189 (add-text-properties bol-prev start '(invisible markdown-markup))
9190 (add-text-properties end eol-next '(invisible markdown-markup)))))
9193 (defun markdown-fontify-gfm-code-blocks (last)
9194 "Add text properties to next GFM code block from point to LAST."
9195 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9197 (defun markdown-fontify-fenced-code-blocks (last)
9198 "Add text properties to next tilde fenced code block from point to LAST."
9199 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9201 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9202 (defun markdown-fontify-code-block-natively (lang start end)
9203 "Fontify given GFM or fenced code block.
9204 This function is called by Emacs for automatic fontification when
9205 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9206 language used in the block. START and END specify the block
9207 position."
9208 (let ((lang-mode (markdown-get-lang-mode lang)))
9209 (when (fboundp lang-mode)
9210 (let ((string (buffer-substring-no-properties start end))
9211 (modified (buffer-modified-p))
9212 (markdown-buffer (current-buffer)) pos next)
9213 (remove-text-properties start end '(face nil))
9214 (with-current-buffer
9215 (get-buffer-create
9216 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9217 ;; Make sure that modification hooks are not inhibited in
9218 ;; the org-src-fontification buffer in case we're called
9219 ;; from `jit-lock-function' (Bug#25132).
9220 (let ((inhibit-modification-hooks nil))
9221 (delete-region (point-min) (point-max))
9222 (insert string " ")) ;; so there's a final property change
9223 (unless (eq major-mode lang-mode) (funcall lang-mode))
9224 (markdown-font-lock-ensure)
9225 (setq pos (point-min))
9226 (while (setq next (next-single-property-change pos 'face))
9227 (let ((val (get-text-property pos 'face)))
9228 (when val
9229 (put-text-property
9230 (+ start (1- pos)) (1- (+ start next)) 'face
9231 val markdown-buffer)))
9232 (setq pos next)))
9233 (add-text-properties
9234 start end
9235 '(font-lock-fontified t fontified t font-lock-multiline t))
9236 (set-buffer-modified-p modified)))))
9238 (require 'edit-indirect nil t)
9239 (defvar edit-indirect-guess-mode-function)
9240 (defvar edit-indirect-after-commit-functions)
9242 (defun markdown--edit-indirect-after-commit-function (_beg end)
9243 "Ensure trailing newlines at the END of code blocks."
9244 (goto-char end)
9245 (unless (eq (char-before) ?\n)
9246 (insert "\n")))
9248 (defun markdown-edit-code-block ()
9249 "Edit Markdown code block in an indirect buffer."
9250 (interactive)
9251 (save-excursion
9252 (if (fboundp 'edit-indirect-region)
9253 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9254 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9255 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9256 (if (and begin end)
9257 (let* ((lang (markdown-code-block-lang))
9258 (mode (or (and lang (markdown-get-lang-mode lang))
9259 markdown-edit-code-block-default-mode))
9260 (edit-indirect-guess-mode-function
9261 (lambda (_parent-buffer _beg _end)
9262 (funcall mode))))
9263 (edit-indirect-region begin end 'display-buffer))
9264 (user-error "Not inside a GFM or tilde fenced code block")))
9265 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9266 (progn (package-refresh-contents)
9267 (package-install 'edit-indirect)
9268 (markdown-edit-code-block))))))
9271 ;;; Table Editing
9273 ;; These functions were originally adapted from `org-table.el'.
9275 ;; General helper functions
9277 (defmacro markdown--with-gensyms (symbols &rest body)
9278 (declare (debug (sexp body)) (indent 1))
9279 `(let ,(mapcar (lambda (s)
9280 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9281 symbols)
9282 ,@body))
9284 (defun markdown--split-string (string &optional separators)
9285 "Splits STRING into substrings at SEPARATORS.
9286 SEPARATORS is a regular expression. If nil it defaults to
9287 `split-string-default-separators'. This version returns no empty
9288 strings if there are matches at the beginning and end of string."
9289 (let ((start 0) notfirst list)
9290 (while (and (string-match
9291 (or separators split-string-default-separators)
9292 string
9293 (if (and notfirst
9294 (= start (match-beginning 0))
9295 (< start (length string)))
9296 (1+ start) start))
9297 (< (match-beginning 0) (length string)))
9298 (setq notfirst t)
9299 (or (eq (match-beginning 0) 0)
9300 (and (eq (match-beginning 0) (match-end 0))
9301 (eq (match-beginning 0) start))
9302 (push (substring string start (match-beginning 0)) list))
9303 (setq start (match-end 0)))
9304 (or (eq start (length string))
9305 (push (substring string start) list))
9306 (nreverse list)))
9308 (defun markdown--string-width (s)
9309 "Return width of string S.
9310 This version ignores characters with invisibility property
9311 `markdown-markup'."
9312 (let (b)
9313 (when (or (eq t buffer-invisibility-spec)
9314 (member 'markdown-markup buffer-invisibility-spec))
9315 (while (setq b (text-property-any
9316 0 (length s)
9317 'invisible 'markdown-markup s))
9318 (setq s (concat
9319 (substring s 0 b)
9320 (substring s (or (next-single-property-change
9321 b 'invisible s)
9322 (length s))))))))
9323 (string-width s))
9325 (defun markdown--remove-invisible-markup (s)
9326 "Remove Markdown markup from string S.
9327 This version removes characters with invisibility property
9328 `markdown-markup'."
9329 (let (b)
9330 (while (setq b (text-property-any
9331 0 (length s)
9332 'invisible 'markdown-markup s))
9333 (setq s (concat
9334 (substring s 0 b)
9335 (substring s (or (next-single-property-change
9336 b 'invisible s)
9337 (length s)))))))
9340 ;; Functions for maintaining tables
9342 (defvar markdown-table-at-point-p-function nil
9343 "Function to decide if point is inside a table.
9345 The indirection serves to differentiate between standard markdown
9346 tables and gfm tables which are less strict about the markup.")
9348 (defconst markdown-table-line-regexp "^[ \t]*|"
9349 "Regexp matching any line inside a table.")
9351 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9352 "Regexp matching hline inside a table.")
9354 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9355 "Regexp matching dline inside a table.")
9357 (defun markdown-table-at-point-p ()
9358 "Return non-nil when point is inside a table."
9359 (if (functionp markdown-table-at-point-p-function)
9360 (funcall markdown-table-at-point-p-function)
9361 (markdown--table-at-point-p)))
9363 (defun markdown--table-at-point-p ()
9364 "Return non-nil when point is inside a table."
9365 (save-excursion
9366 (beginning-of-line)
9367 (and (looking-at-p markdown-table-line-regexp)
9368 (not (markdown-code-block-at-point-p)))))
9370 (defconst gfm-table-line-regexp "^.?*|"
9371 "Regexp matching any line inside a table.")
9373 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
9374 "Regexp matching hline inside a table.")
9376 ;; GFM simplified tables syntax is as follows:
9377 ;; - A header line for the column names, this is any text
9378 ;; separated by `|'.
9379 ;; - Followed by a string -|-|- ..., the number of dashes is optional
9380 ;; but must be higher than 1. The number of separators should match
9381 ;; the number of columns.
9382 ;; - Followed by the rows of data, which has the same format as the
9383 ;; header line.
9384 ;; Example:
9386 ;; foo | bar
9387 ;; ------|---------
9388 ;; bar | baz
9389 ;; bar | baz
9390 (defun gfm--table-at-point-p ()
9391 "Return non-nil when point is inside a gfm-compatible table."
9392 (or (markdown--table-at-point-p)
9393 (save-excursion
9394 (beginning-of-line)
9395 (when (looking-at-p gfm-table-line-regexp)
9396 ;; we might be at the first line of the table, check if the
9397 ;; line below is the hline
9398 (or (save-excursion
9399 (forward-line 1)
9400 (looking-at-p gfm-table-hline-regexp))
9401 ;; go up to find the header
9402 (catch 'done
9403 (while (looking-at-p gfm-table-line-regexp)
9404 (when (looking-at-p gfm-table-hline-regexp)
9405 (throw 'done t))
9406 (forward-line -1))
9407 nil))))))
9409 (defun markdown-table-hline-at-point-p ()
9410 "Return non-nil when point is on a hline in a table.
9411 This function assumes point is on a table."
9412 (save-excursion
9413 (beginning-of-line)
9414 (looking-at-p markdown-table-hline-regexp)))
9416 (defun markdown-table-begin ()
9417 "Find the beginning of the table and return its position.
9418 This function assumes point is on a table."
9419 (save-excursion
9420 (while (and (not (bobp))
9421 (markdown-table-at-point-p))
9422 (forward-line -1))
9423 (unless (eobp)
9424 (forward-line 1))
9425 (point)))
9427 (defun markdown-table-end ()
9428 "Find the end of the table and return its position.
9429 This function assumes point is on a table."
9430 (save-excursion
9431 (while (and (not (eobp))
9432 (markdown-table-at-point-p))
9433 (forward-line 1))
9434 (point)))
9436 (defun markdown-table-get-dline ()
9437 "Return index of the table data line at point.
9438 This function assumes point is on a table."
9439 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9440 (save-excursion
9441 (goto-char (markdown-table-begin))
9442 (while (and (re-search-forward
9443 markdown-table-dline-regexp end t)
9444 (setq cnt (1+ cnt))
9445 (< (point-at-eol) pos))))
9446 cnt))
9448 (defun markdown-table-get-column ()
9449 "Return table column at point.
9450 This function assumes point is on a table."
9451 (let ((pos (point)) (cnt 0))
9452 (save-excursion
9453 (beginning-of-line)
9454 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9455 cnt))
9457 (defun markdown-table-get-cell (&optional n)
9458 "Return the content of the cell in column N of current row.
9459 N defaults to column at point. This function assumes point is on
9460 a table."
9461 (and n (markdown-table-goto-column n))
9462 (skip-chars-backward "^|\n") (backward-char 1)
9463 (if (looking-at "|[^|\r\n]*")
9464 (let* ((pos (match-beginning 0))
9465 (val (buffer-substring (1+ pos) (match-end 0))))
9466 (goto-char (min (point-at-eol) (+ 2 pos)))
9467 ;; Trim whitespaces
9468 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9469 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9470 (forward-char 1) ""))
9472 (defun markdown-table-goto-dline (n)
9473 "Go to the Nth data line in the table at point.
9474 Return t when the line exists, nil otherwise. This function
9475 assumes point is on a table."
9476 (goto-char (markdown-table-begin))
9477 (let ((end (markdown-table-end)) (cnt 0))
9478 (while (and (re-search-forward
9479 markdown-table-dline-regexp end t)
9480 (< (setq cnt (1+ cnt)) n)))
9481 (= cnt n)))
9483 (defun markdown-table-goto-column (n &optional on-delim)
9484 "Go to the Nth column in the table line at point.
9485 With optional argument ON-DELIM, stop with point before the left
9486 delimiter of the cell. If there are less than N cells, just go
9487 beyond the last delimiter. This function assumes point is on a
9488 table."
9489 (beginning-of-line 1)
9490 (when (> n 0)
9491 (while (and (> (setq n (1- n)) -1)
9492 (search-forward "|" (point-at-eol) t)))
9493 (if on-delim
9494 (backward-char 1)
9495 (when (looking-at " ") (forward-char 1)))))
9497 (defmacro markdown-table-save-cell (&rest body)
9498 "Save cell at point, execute BODY and restore cell.
9499 This function assumes point is on a table."
9500 (declare (debug (body)))
9501 (markdown--with-gensyms (line column)
9502 `(let ((,line (copy-marker (line-beginning-position)))
9503 (,column (markdown-table-get-column)))
9504 (unwind-protect
9505 (progn ,@body)
9506 (goto-char ,line)
9507 (markdown-table-goto-column ,column)
9508 (set-marker ,line nil)))))
9510 (defun markdown-table-blank-line (s)
9511 "Convert a table line S into a line with blank cells."
9512 (if (string-match "^[ \t]*|-" s)
9513 (setq s (mapconcat
9514 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9515 s ""))
9516 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9517 (setq s (replace-match
9518 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9519 t t s)))
9522 (defun markdown-table-colfmt (fmtspec)
9523 "Process column alignment specifier FMTSPEC for tables."
9524 (when (stringp fmtspec)
9525 (mapcar (lambda (x)
9526 (cond ((string-match-p "^:.*:$" x) 'c)
9527 ((string-match-p "^:" x) 'l)
9528 ((string-match-p ":$" x) 'r)
9529 (t 'd)))
9530 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9532 (defun markdown-table-align ()
9533 "Align table at point.
9534 This function assumes point is on a table."
9535 (interactive)
9536 (let ((begin (markdown-table-begin))
9537 (end (copy-marker (markdown-table-end))))
9538 (markdown-table-save-cell
9539 (goto-char begin)
9540 (let* (fmtspec
9541 ;; Store table indent
9542 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9543 ;; Split table in lines and save column format specifier
9544 (lines (mapcar (lambda (l)
9545 (if (string-match-p "\\`[ \t]*|[-:]" l)
9546 (progn (setq fmtspec (or fmtspec l)) nil) l))
9547 (markdown--split-string (buffer-substring begin end) "\n")))
9548 ;; Split lines in cells
9549 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9550 (remq nil lines)))
9551 ;; Calculate maximum number of cells in a line
9552 (maxcells (if cells
9553 (apply #'max (mapcar #'length cells))
9554 (user-error "Empty table")))
9555 ;; Empty cells to fill short lines
9556 (emptycells (make-list maxcells "")) maxwidths)
9557 ;; Calculate maximum width for each column
9558 (dotimes (i maxcells)
9559 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9560 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9561 maxwidths)))
9562 (setq maxwidths (nreverse maxwidths))
9563 ;; Process column format specifier
9564 (setq fmtspec (markdown-table-colfmt fmtspec))
9565 ;; Compute formats needed for output of table lines
9566 (let ((hfmt (concat indent "|"))
9567 (rfmt (concat indent "|"))
9568 hfmt1 rfmt1 fmt)
9569 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9570 (setq fmt (pop fmtspec))
9571 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9572 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9573 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9574 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9575 (setq rfmt (concat rfmt (format rfmt1 width)))
9576 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9577 ;; Replace modified lines only
9578 (dolist (line lines)
9579 (let ((line (if line
9580 (apply #'format rfmt (append (pop cells) emptycells))
9581 hfmt))
9582 (previous (buffer-substring (point) (line-end-position))))
9583 (if (equal previous line)
9584 (forward-line)
9585 (insert line "\n")
9586 (delete-region (point) (line-beginning-position 2))))))
9587 (set-marker end nil)))))
9589 (defun markdown-table-insert-row (&optional arg)
9590 "Insert a new row above the row at point into the table.
9591 With optional argument ARG, insert below the current row."
9592 (interactive "P")
9593 (unless (markdown-table-at-point-p)
9594 (user-error "Not at a table"))
9595 (let* ((line (buffer-substring
9596 (line-beginning-position) (line-end-position)))
9597 (new (markdown-table-blank-line line)))
9598 (beginning-of-line (if arg 2 1))
9599 (unless (bolp) (insert "\n"))
9600 (insert-before-markers new "\n")
9601 (beginning-of-line 0)
9602 (re-search-forward "| ?" (line-end-position) t)))
9604 (defun markdown-table-delete-row ()
9605 "Delete row or horizontal line at point from the table."
9606 (interactive)
9607 (unless (markdown-table-at-point-p)
9608 (user-error "Not at a table"))
9609 (let ((col (current-column)))
9610 (kill-region (point-at-bol)
9611 (min (1+ (point-at-eol)) (point-max)))
9612 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9613 (move-to-column col)))
9615 (defun markdown-table-move-row (&optional up)
9616 "Move table line at point down.
9617 With optional argument UP, move it up."
9618 (interactive "P")
9619 (unless (markdown-table-at-point-p)
9620 (user-error "Not at a table"))
9621 (let* ((col (current-column)) (pos (point))
9622 (tonew (if up 0 2)) txt)
9623 (beginning-of-line tonew)
9624 (unless (markdown-table-at-point-p)
9625 (goto-char pos) (user-error "Cannot move row further"))
9626 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9627 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9628 (delete-region (point) (1+ (point-at-eol)))
9629 (beginning-of-line tonew)
9630 (insert txt) (beginning-of-line 0)
9631 (move-to-column col)))
9633 (defun markdown-table-move-row-up ()
9634 "Move table row at point up."
9635 (interactive)
9636 (markdown-table-move-row 'up))
9638 (defun markdown-table-move-row-down ()
9639 "Move table row at point down."
9640 (interactive)
9641 (markdown-table-move-row nil))
9643 (defun markdown-table-insert-column ()
9644 "Insert a new table column."
9645 (interactive)
9646 (unless (markdown-table-at-point-p)
9647 (user-error "Not at a table"))
9648 (let* ((col (max 1 (markdown-table-get-column)))
9649 (begin (markdown-table-begin))
9650 (end (copy-marker (markdown-table-end))))
9651 (markdown-table-save-cell
9652 (goto-char begin)
9653 (while (< (point) end)
9654 (markdown-table-goto-column col t)
9655 (if (markdown-table-hline-at-point-p)
9656 (insert "|---")
9657 (insert "| "))
9658 (forward-line)))
9659 (set-marker end nil)
9660 (markdown-table-align)))
9662 (defun markdown-table-delete-column ()
9663 "Delete column at point from table."
9664 (interactive)
9665 (unless (markdown-table-at-point-p)
9666 (user-error "Not at a table"))
9667 (let ((col (markdown-table-get-column))
9668 (begin (markdown-table-begin))
9669 (end (copy-marker (markdown-table-end))))
9670 (markdown-table-save-cell
9671 (goto-char begin)
9672 (while (< (point) end)
9673 (markdown-table-goto-column col t)
9674 (and (looking-at "|[^|\n]+|")
9675 (replace-match "|"))
9676 (forward-line)))
9677 (set-marker end nil)
9678 (markdown-table-goto-column (max 1 (1- col)))
9679 (markdown-table-align)))
9681 (defun markdown-table-move-column (&optional left)
9682 "Move table column at point to the right.
9683 With optional argument LEFT, move it to the left."
9684 (interactive "P")
9685 (unless (markdown-table-at-point-p)
9686 (user-error "Not at a table"))
9687 (let* ((col (markdown-table-get-column))
9688 (col1 (if left (1- col) col))
9689 (colpos (if left (1- col) (1+ col)))
9690 (begin (markdown-table-begin))
9691 (end (copy-marker (markdown-table-end))))
9692 (when (and left (= col 1))
9693 (user-error "Cannot move column further left"))
9694 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9695 (user-error "Cannot move column further right"))
9696 (markdown-table-save-cell
9697 (goto-char begin)
9698 (while (< (point) end)
9699 (markdown-table-goto-column col1 t)
9700 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9701 (replace-match "|\\2|\\1|"))
9702 (forward-line)))
9703 (set-marker end nil)
9704 (markdown-table-goto-column colpos)
9705 (markdown-table-align)))
9707 (defun markdown-table-move-column-left ()
9708 "Move table column at point to the left."
9709 (interactive)
9710 (markdown-table-move-column 'left))
9712 (defun markdown-table-move-column-right ()
9713 "Move table column at point to the right."
9714 (interactive)
9715 (markdown-table-move-column nil))
9717 (defun markdown-table-next-row ()
9718 "Go to the next row (same column) in the table.
9719 Create new table lines if required."
9720 (interactive)
9721 (unless (markdown-table-at-point-p)
9722 (user-error "Not at a table"))
9723 (if (or (looking-at "[ \t]*$")
9724 (save-excursion (skip-chars-backward " \t") (bolp)))
9725 (newline)
9726 (markdown-table-align)
9727 (let ((col (markdown-table-get-column)))
9728 (beginning-of-line 2)
9729 (if (or (not (markdown-table-at-point-p))
9730 (markdown-table-hline-at-point-p))
9731 (progn
9732 (beginning-of-line 0)
9733 (markdown-table-insert-row 'below)))
9734 (markdown-table-goto-column col)
9735 (skip-chars-backward "^|\n\r")
9736 (when (looking-at " ") (forward-char 1)))))
9738 (defun markdown-table-forward-cell ()
9739 "Go to the next cell in the table.
9740 Create new table lines if required."
9741 (interactive)
9742 (unless (markdown-table-at-point-p)
9743 (user-error "Not at a table"))
9744 (markdown-table-align)
9745 (let ((end (markdown-table-end)))
9746 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9747 (condition-case nil
9748 (progn
9749 (re-search-forward "|" end)
9750 (if (looking-at "[ \t]*$")
9751 (re-search-forward "|" end))
9752 (if (and (looking-at "[-:]")
9753 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9754 (goto-char (match-beginning 1)))
9755 (if (looking-at "[-:]")
9756 (progn
9757 (beginning-of-line 0)
9758 (markdown-table-insert-row 'below))
9759 (when (looking-at " ") (forward-char 1))))
9760 (error (markdown-table-insert-row 'below)))))
9762 (defun markdown-table-backward-cell ()
9763 "Go to the previous cell in the table."
9764 (interactive)
9765 (unless (markdown-table-at-point-p)
9766 (user-error "Not at a table"))
9767 (markdown-table-align)
9768 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9769 (condition-case nil
9770 (progn
9771 (re-search-backward "|" (markdown-table-begin))
9772 (re-search-backward "|" (markdown-table-begin)))
9773 (error (user-error "Cannot move to previous table cell")))
9774 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9775 (re-search-backward "|" (markdown-table-begin)))
9776 (when (looking-at "| ?") (goto-char (match-end 0))))
9778 (defun markdown-table-transpose ()
9779 "Transpose table at point.
9780 Horizontal separator lines will be eliminated."
9781 (interactive)
9782 (unless (markdown-table-at-point-p)
9783 (user-error "Not at a table"))
9784 (let* ((table (buffer-substring-no-properties
9785 (markdown-table-begin) (markdown-table-end)))
9786 ;; Convert table to a Lisp structure
9787 (table (delq nil
9788 (mapcar
9789 (lambda (x)
9790 (unless (string-match-p
9791 markdown-table-hline-regexp x)
9792 (markdown--split-string x "\\s-*|\\s-*")))
9793 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9794 (dline_old (markdown-table-get-dline))
9795 (col_old (markdown-table-get-column))
9796 (contents (mapcar (lambda (_)
9797 (let ((tp table))
9798 (mapcar
9799 (lambda (_)
9800 (prog1
9801 (pop (car tp))
9802 (setq tp (cdr tp))))
9803 table)))
9804 (car table))))
9805 (goto-char (markdown-table-begin))
9806 (re-search-forward "|") (backward-char)
9807 (delete-region (point) (markdown-table-end))
9808 (insert (mapconcat
9809 (lambda(x)
9810 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9811 contents ""))
9812 (markdown-table-goto-dline col_old)
9813 (markdown-table-goto-column dline_old))
9814 (markdown-table-align))
9816 (defun markdown-table-sort-lines (&optional sorting-type)
9817 "Sort table lines according to the column at point.
9819 The position of point indicates the column to be used for
9820 sorting, and the range of lines is the range between the nearest
9821 horizontal separator lines, or the entire table of no such lines
9822 exist. If point is before the first column, user will be prompted
9823 for the sorting column. If there is an active region, the mark
9824 specifies the first line and the sorting column, while point
9825 should be in the last line to be included into the sorting.
9827 The command then prompts for the sorting type which can be
9828 alphabetically or numerically. Sorting in reverse order is also
9829 possible.
9831 If SORTING-TYPE is specified when this function is called from a
9832 Lisp program, no prompting will take place. SORTING-TYPE must be
9833 a character, any of (?a ?A ?n ?N) where the capital letters
9834 indicate that sorting should be done in reverse order."
9835 (interactive)
9836 (unless (markdown-table-at-point-p)
9837 (user-error "Not at a table"))
9838 ;; Set sorting type and column used for sorting
9839 (let ((column (let ((c (markdown-table-get-column)))
9840 (cond ((> c 0) c)
9841 ((called-interactively-p 'any)
9842 (read-number "Use column N for sorting: "))
9843 (t 1))))
9844 (sorting-type
9845 (or sorting-type
9846 (read-char-exclusive
9847 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9848 (save-restriction
9849 ;; Narrow buffer to appropriate sorting area
9850 (if (region-active-p)
9851 (narrow-to-region
9852 (save-excursion
9853 (progn
9854 (goto-char (region-beginning)) (line-beginning-position)))
9855 (save-excursion
9856 (progn
9857 (goto-char (region-end)) (line-end-position))))
9858 (let ((start (markdown-table-begin))
9859 (end (markdown-table-end)))
9860 (narrow-to-region
9861 (save-excursion
9862 (if (re-search-backward
9863 markdown-table-hline-regexp start t)
9864 (line-beginning-position 2)
9865 start))
9866 (if (save-excursion (re-search-forward
9867 markdown-table-hline-regexp end t))
9868 (match-beginning 0)
9869 end))))
9870 ;; Determine arguments for `sort-subr'
9871 (let* ((extract-key-from-cell
9872 (cl-case sorting-type
9873 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9874 ((?n ?N) #'string-to-number)
9875 (t (user-error "Invalid sorting type: %c" sorting-type))))
9876 (predicate
9877 (cl-case sorting-type
9878 ((?n ?N) #'<)
9879 ((?a ?A) #'string<))))
9880 ;; Sort selected area
9881 (goto-char (point-min))
9882 (sort-subr (memq sorting-type '(?A ?N))
9883 (lambda ()
9884 (forward-line)
9885 (while (and (not (eobp))
9886 (not (looking-at
9887 markdown-table-dline-regexp)))
9888 (forward-line)))
9889 #'end-of-line
9890 (lambda ()
9891 (funcall extract-key-from-cell
9892 (markdown-table-get-cell column)))
9894 predicate)
9895 (goto-char (point-min))))))
9897 (defun markdown-table-convert-region (begin end &optional separator)
9898 "Convert region from BEGIN to END to table with SEPARATOR.
9900 If every line contains at least one TAB character, the function
9901 assumes that the material is tab separated (TSV). If every line
9902 contains a comma, comma-separated values (CSV) are assumed. If
9903 not, lines are split at whitespace into cells.
9905 You can use a prefix argument to force a specific separator:
9906 \\[universal-argument] once forces CSV, \\[universal-argument]
9907 twice forces TAB, and \\[universal-argument] three times will
9908 prompt for a regular expression to match the separator, and a
9909 numeric argument N indicates that at least N consecutive
9910 spaces, or alternatively a TAB should be used as the separator."
9912 (interactive "r\nP")
9913 (let* ((begin (min begin end)) (end (max begin end)) re)
9914 (goto-char begin) (beginning-of-line 1)
9915 (setq begin (point-marker))
9916 (goto-char end)
9917 (if (bolp) (backward-char 1) (end-of-line 1))
9918 (setq end (point-marker))
9919 (when (equal separator '(64))
9920 (setq separator (read-regexp "Regexp for cell separator: ")))
9921 (unless separator
9922 ;; Get the right cell separator
9923 (goto-char begin)
9924 (setq separator
9925 (cond
9926 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9927 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9928 (t 1))))
9929 (goto-char begin)
9930 (if (equal separator '(4))
9931 ;; Parse CSV
9932 (while (< (point) end)
9933 (cond
9934 ((looking-at "^") (insert "| "))
9935 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9936 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9937 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9938 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9939 ((looking-at "[ \t]*,") (replace-match " | "))
9940 (t (beginning-of-line 2))))
9941 (setq re
9942 (cond
9943 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9944 ((equal separator '(16)) "^\\|\t")
9945 ((integerp separator)
9946 (if (< separator 1)
9947 (user-error "Cell separator must contain one or more spaces")
9948 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9949 ((stringp separator) (format "^ *\\|%s" separator))
9950 (t (error "Invalid cell separator"))))
9951 (while (re-search-forward re end t) (replace-match "| " t t)))
9952 (goto-char begin)
9953 (markdown-table-align)))
9956 ;;; ElDoc Support
9958 (defun markdown-eldoc-function ()
9959 "Return a helpful string when appropriate based on context.
9960 * Report URL when point is at a hidden URL.
9961 * Report language name when point is a code block with hidden markup."
9962 (cond
9963 ;; Hidden URL or reference for inline link
9964 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9965 (thing-at-point-looking-at markdown-regex-link-reference))
9966 (or markdown-hide-urls markdown-hide-markup))
9967 (let* ((imagep (string-equal (match-string 1) "!"))
9968 (edit-keys (markdown--substitute-command-keys
9969 (if imagep
9970 "\\[markdown-insert-image]"
9971 "\\[markdown-insert-link]")))
9972 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9973 (referencep (string-equal (match-string 5) "["))
9974 (object (if referencep "reference" "URL")))
9975 (format "Hidden %s (%s to edit): %s" object edit-str
9976 (if referencep
9977 (concat
9978 (propertize "[" 'face 'markdown-markup-face)
9979 (propertize (match-string-no-properties 6)
9980 'face 'markdown-reference-face)
9981 (propertize "]" 'face 'markdown-markup-face))
9982 (propertize (match-string-no-properties 6)
9983 'face 'markdown-url-face)))))
9984 ;; Hidden language name for fenced code blocks
9985 ((and (markdown-code-block-at-point-p)
9986 (not (get-text-property (point) 'markdown-pre))
9987 markdown-hide-markup)
9988 (let ((lang (save-excursion (markdown-code-block-lang))))
9989 (unless lang (setq lang "[unspecified]"))
9990 (format "Hidden code block language: %s (%s to toggle markup)"
9991 (propertize lang 'face 'markdown-language-keyword-face)
9992 (markdown--substitute-command-keys
9993 "\\[markdown-toggle-markup-hiding]"))))))
9996 ;;; Mode Definition ==========================================================
9998 (defun markdown-show-version ()
9999 "Show the version number in the minibuffer."
10000 (interactive)
10001 (message "markdown-mode, version %s" markdown-mode-version))
10003 (defun markdown-mode-info ()
10004 "Open the `markdown-mode' homepage."
10005 (interactive)
10006 (browse-url "https://jblevins.org/projects/markdown-mode/"))
10008 ;;;###autoload
10009 (define-derived-mode markdown-mode text-mode "Markdown"
10010 "Major mode for editing Markdown files."
10011 ;; Natural Markdown tab width
10012 (setq tab-width 4)
10013 ;; Comments
10014 (setq-local comment-start "<!-- ")
10015 (setq-local comment-end " -->")
10016 (setq-local comment-start-skip "<!--[ \t]*")
10017 (setq-local comment-column 0)
10018 (setq-local comment-auto-fill-only-comments nil)
10019 (setq-local comment-use-syntax t)
10020 ;; Syntax
10021 (add-hook 'syntax-propertize-extend-region-functions
10022 #'markdown-syntax-propertize-extend-region)
10023 (add-hook 'jit-lock-after-change-extend-region-functions
10024 #'markdown-font-lock-extend-region-function t t)
10025 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
10026 ;; Font lock.
10027 (setq-local font-lock-defaults nil)
10028 (setq-local font-lock-multiline t)
10029 (setq-local font-lock-extra-managed-props
10030 (append font-lock-extra-managed-props
10031 '(composition display invisible)))
10032 (if markdown-hide-markup
10033 (add-to-invisibility-spec 'markdown-markup)
10034 (remove-from-invisibility-spec 'markdown-markup))
10035 (setq font-lock-defaults
10036 '(markdown-mode-font-lock-keywords-basic
10037 nil nil nil nil
10038 (font-lock-syntactic-face-function . markdown-syntactic-face)))
10039 ;; Wiki links
10040 (markdown-setup-wiki-link-hooks)
10041 ;; Math mode
10042 (when markdown-enable-math (markdown-toggle-math t))
10043 ;; Add a buffer-local hook to reload after file-local variables are read
10044 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
10045 ;; For imenu support
10046 (setq imenu-create-index-function
10047 (if markdown-nested-imenu-heading-index
10048 #'markdown-imenu-create-nested-index
10049 #'markdown-imenu-create-flat-index))
10050 ;; For menu support in XEmacs
10051 (easy-menu-add markdown-mode-menu markdown-mode-map)
10052 ;; Defun movement
10053 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
10054 (setq-local end-of-defun-function #'markdown-end-of-defun)
10055 ;; Paragraph filling
10056 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
10057 (setq-local paragraph-start
10058 ;; Should match start of lines that start or separate paragraphs
10059 (mapconcat #'identity
10061 "\f" ; starts with a literal line-feed
10062 "[ \t\f]*$" ; space-only line
10063 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10064 "[ \t]*[*+-][ \t]+" ; unordered list item
10065 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
10066 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
10067 "[ \t]*:[ \t]+" ; definition
10068 "^|" ; table or Pandoc line block
10070 "\\|"))
10071 (setq-local paragraph-separate
10072 ;; Should match lines that separate paragraphs without being
10073 ;; part of any paragraph:
10074 (mapconcat #'identity
10075 '("[ \t\f]*$" ; space-only line
10076 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10077 ;; The following is not ideal, but the Fill customization
10078 ;; options really only handle paragraph-starting prefixes,
10079 ;; not paragraph-ending suffixes:
10080 ".* $" ; line ending in two spaces
10081 "^#+"
10082 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
10083 "\\|"))
10084 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
10085 (setq-local adaptive-fill-regexp "\\s-*")
10086 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
10087 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
10088 ;; Outline mode
10089 (setq-local outline-regexp markdown-regex-header)
10090 (setq-local outline-level #'markdown-outline-level)
10091 ;; Cause use of ellipses for invisible text.
10092 (add-to-invisibility-spec '(outline . t))
10093 ;; ElDoc support
10094 (if (eval-when-compile (fboundp 'add-function))
10095 (add-function :before-until (local 'eldoc-documentation-function)
10096 #'markdown-eldoc-function)
10097 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
10098 ;; Inhibiting line-breaking:
10099 ;; Separating out each condition into a separate function so that users can
10100 ;; override if desired (with remove-hook)
10101 (add-hook 'fill-nobreak-predicate
10102 #'markdown-line-is-reference-definition-p nil t)
10103 (add-hook 'fill-nobreak-predicate
10104 #'markdown-pipe-at-bol-p nil t)
10106 ;; Indentation
10107 (setq-local indent-line-function markdown-indent-function)
10109 ;; Flyspell
10110 (setq-local flyspell-generic-check-word-predicate
10111 #'markdown-flyspell-check-word-p)
10113 ;; Electric quoting
10114 (add-hook 'electric-quote-inhibit-functions
10115 #'markdown--inhibit-electric-quote nil :local)
10117 ;; Backwards compatibility with markdown-css-path
10118 (when (boundp 'markdown-css-path)
10119 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
10120 (add-to-list 'markdown-css-paths markdown-css-path))
10122 ;; Prepare hooks for XEmacs compatibility
10123 (when (featurep 'xemacs)
10124 (make-local-hook 'after-change-functions)
10125 (make-local-hook 'font-lock-extend-region-functions)
10126 (make-local-hook 'window-configuration-change-hook))
10128 ;; Make checkboxes buttons
10129 (when markdown-make-gfm-checkboxes-buttons
10130 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
10131 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
10132 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
10134 ;; edit-indirect
10135 (add-hook 'edit-indirect-after-commit-functions
10136 #'markdown--edit-indirect-after-commit-function
10137 nil 'local)
10139 ;; Marginalized headings
10140 (when markdown-marginalize-headers
10141 (add-hook 'window-configuration-change-hook
10142 #'markdown-marginalize-update-current nil t))
10144 ;; add live preview export hook
10145 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
10146 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
10148 ;;;###autoload
10149 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
10150 ;;;###autoload
10151 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
10154 ;;; GitHub Flavored Markdown Mode ============================================
10156 (defvar gfm-mode-hook nil
10157 "Hook run when entering GFM mode.")
10159 (defvar gfm-font-lock-keywords
10160 ;; Basic Markdown features (excluding possibly overridden ones)
10161 markdown-mode-font-lock-keywords-basic
10162 "Default highlighting expressions for GitHub Flavored Markdown mode.")
10164 ;;;###autoload
10165 (define-derived-mode gfm-mode markdown-mode "GFM"
10166 "Major mode for editing GitHub Flavored Markdown files."
10167 (setq markdown-link-space-sub-char "-")
10168 (setq markdown-wiki-link-search-subdirectories t)
10169 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
10170 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
10171 ;; do the initial link fontification
10172 (markdown-gfm-parse-buffer-for-languages))
10175 ;;; Live Preview Mode ============================================
10176 (define-minor-mode markdown-live-preview-mode
10177 "Toggle native previewing on save for a specific markdown file."
10178 :lighter " MD-Preview"
10179 (if markdown-live-preview-mode
10180 (if (markdown-live-preview-get-filename)
10181 (markdown-display-buffer-other-window (markdown-live-preview-export))
10182 (markdown-live-preview-mode -1)
10183 (user-error "Buffer %s does not visit a file" (current-buffer)))
10184 (markdown-live-preview-remove)))
10187 (provide 'markdown-mode)
10189 ;; Local Variables:
10190 ;; indent-tabs-mode: nil
10191 ;; coding: utf-8
10192 ;; End:
10193 ;;; markdown-mode.el ends here