Optionally skip matching in markdown-cur-list-item-bounds
[markdown-mode.git] / markdown-mode.el
blob1a5733dd0a9126ea54d35409576e6945c5994955
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 (rx line-start
1712 ;; 1. Leading whitespace
1713 (group (* blank))
1714 ;; 2. List marker: a numeral, bullet, or colon
1715 (group (or (and (+ (any "0-9#")) ".")
1716 (any "*+:-")))
1717 ;; 3. Trailing whitespace
1718 (group (+ blank)))
1719 "Regular expression for matching list items.")
1721 (defconst markdown-regex-bold
1722 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1723 "Regular expression for matching bold text.
1724 Group 1 matches the character before the opening asterisk or
1725 underscore, if any, ensuring that it is not a backslash escape.
1726 Group 2 matches the entire expression, including delimiters.
1727 Groups 3 and 5 matches the opening and closing delimiters.
1728 Group 4 matches the text inside the delimiters.")
1730 (defconst markdown-regex-italic
1731 "\\(?:^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t*]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1732 "Regular expression for matching italic text.
1733 The leading unnumbered matches the character before the opening
1734 asterisk or underscore, if any, ensuring that it is not a
1735 backslash escape.
1736 Group 1 matches the entire expression, including delimiters.
1737 Groups 2 and 4 matches the opening and closing delimiters.
1738 Group 3 matches the text inside the delimiters.")
1740 (defconst markdown-regex-strike-through
1741 "\\(^\\|[^\\]\\)\\(\\(~~\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(~~\\)\\)"
1742 "Regular expression for matching strike-through text.
1743 Group 1 matches the character before the opening tilde, if any,
1744 ensuring that it is not a backslash escape.
1745 Group 2 matches the entire expression, including delimiters.
1746 Groups 3 and 5 matches the opening and closing delimiters.
1747 Group 4 matches the text inside the delimiters.")
1749 (defconst markdown-regex-gfm-italic
1750 "\\(?:^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\2\\|[^ ]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\2\\)\\)"
1751 "Regular expression for matching italic text in GitHub Flavored Markdown.
1752 Underscores in words are not treated as special.
1753 Group 1 matches the entire expression, including delimiters.
1754 Groups 2 and 4 matches the opening and closing delimiters.
1755 Group 3 matches the text inside the delimiters.")
1757 (defconst markdown-regex-blockquote
1758 "^[ \t]*\\([A-Z]?>\\)\\([ \t]*\\)\\(.*\\)$"
1759 "Regular expression for matching blockquote lines.
1760 Also accounts for a potential capital letter preceding the angle
1761 bracket, for use with Leanpub blocks (asides, warnings, info
1762 blocks, etc.).
1763 Group 1 matches the leading angle bracket.
1764 Group 2 matches the separating whitespace.
1765 Group 3 matches the text.")
1767 (defconst markdown-regex-line-break
1768 "[^ \n\t][ \t]*\\( \\)$"
1769 "Regular expression for matching line breaks.")
1771 (defconst markdown-regex-wiki-link
1772 "\\(?:^\\|[^\\]\\)\\(\\(\\[\\[\\)\\([^]|]+\\)\\(?:\\(|\\)\\([^]]+\\)\\)?\\(\\]\\]\\)\\)"
1773 "Regular expression for matching wiki links.
1774 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1775 wiki links of the form [[PageName|link text]].
1776 The meanings of the first and second components depend
1777 on the value of `markdown-wiki-link-alias-first'.
1779 Group 1 matches the entire link.
1780 Group 2 matches the opening square brackets.
1781 Group 3 matches the first component of the wiki link.
1782 Group 4 matches the pipe separator, when present.
1783 Group 5 matches the second component of the wiki link, when present.
1784 Group 6 matches the closing square brackets.")
1786 (defconst markdown-regex-uri
1787 (concat "\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+\\)")
1788 "Regular expression for matching inline URIs.")
1790 (defconst markdown-regex-angle-uri
1791 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1792 "Regular expression for matching inline URIs in angle brackets.")
1794 (defconst markdown-regex-email
1795 "<\\(\\(?:\\sw\\|\\s_\\|\\s.\\)+@\\(?:\\sw\\|\\s_\\|\\s.\\)+\\)>"
1796 "Regular expression for matching inline email addresses.")
1798 (defsubst markdown-make-regex-link-generic ()
1799 "Make regular expression for matching any recognized link."
1800 (concat "\\(?:" markdown-regex-link-inline
1801 (when markdown-enable-wiki-links
1802 (concat "\\|" markdown-regex-wiki-link))
1803 "\\|" markdown-regex-link-reference
1804 "\\|" markdown-regex-angle-uri "\\)"))
1806 (defconst markdown-regex-gfm-checkbox
1807 " \\(\\[[ xX]\\]\\) "
1808 "Regular expression for matching GFM checkboxes.
1809 Group 1 matches the text to become a button.")
1811 (defconst markdown-regex-block-separator
1812 "\n[\n\t\f ]*\n"
1813 "Regular expression for matching block boundaries.")
1815 (defconst markdown-regex-block-separator-noindent
1816 (concat "\\(\\`\\|\\(" markdown-regex-block-separator "\\)[^\n\t\f ]\\)")
1817 "Regexp for block separators before lines with no indentation.")
1819 (defconst markdown-regex-math-inline-single
1820 "\\(?:^\\|[^\\]\\)\\(\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\)"
1821 "Regular expression for itex $..$ math mode expressions.
1822 Groups 1 and 3 match the opening and closing dollar signs.
1823 Group 2 matches the mathematical expression contained within.")
1825 (defconst markdown-regex-math-inline-double
1826 "\\(?:^\\|[^\\]\\)\\(\\$\\$\\)\\(\\(?:[^\\$]\\|\\\\.\\)*\\)\\(\\$\\$\\)"
1827 "Regular expression for itex $$..$$ math mode expressions.
1828 Groups 1 and 3 match opening and closing dollar signs.
1829 Group 2 matches the mathematical expression contained within.")
1831 (defconst markdown-regex-math-display
1832 (rx line-start (* blank)
1833 (group (group (repeat 1 2 "\\")) "[")
1834 (group (*? anything))
1835 (group (backref 2) "]")
1836 line-end)
1837 "Regular expression for \[..\] or \\[..\\] display math.
1838 Groups 1 and 4 match the opening and closing markup.
1839 Group 3 matches the mathematical expression contained within.
1840 Group 2 matches the opening slashes, and is used internally to
1841 match the closing slashes.")
1843 (defsubst markdown-make-tilde-fence-regex (num-tildes &optional end-of-line)
1844 "Return regexp matching a tilde code fence at least NUM-TILDES long.
1845 END-OF-LINE is the regexp construct to indicate end of line; $ if
1846 missing."
1847 (format "%s%d%s%s" "^[[:blank:]]*\\([~]\\{" num-tildes ",\\}\\)"
1848 (or end-of-line "$")))
1850 (defconst markdown-regex-tilde-fence-begin
1851 (markdown-make-tilde-fence-regex
1852 3 "\\([[:blank:]]*{?\\)[[:blank:]]*\\([^[:space:]]+?\\)?\\(?:[[:blank:]]+\\(.+?\\)\\)?\\([[:blank:]]*}?[[:blank:]]*\\)$")
1853 "Regular expression for matching tilde-fenced code blocks.
1854 Group 1 matches the opening tildes.
1855 Group 2 matches (optional) opening brace and surrounding whitespace.
1856 Group 3 matches the language identifier (optional).
1857 Group 4 matches the info string (optional).
1858 Group 5 matches the closing brace (optional) and any surrounding whitespace.
1859 Groups need to agree with `markdown-regex-gfm-code-block-open'.")
1861 (defconst markdown-regex-declarative-metadata
1862 "^\\([[:alpha:]][[:alpha:] _-]*?\\)\\([:=][ \t]*\\)\\(.*\\)$"
1863 "Regular expression for matching declarative metadata statements.
1864 This matches MultiMarkdown metadata as well as YAML and TOML
1865 assignments such as the following:
1867 variable: value
1871 variable = value")
1873 (defconst markdown-regex-pandoc-metadata
1874 "^\\(%\\)\\([ \t]*\\)\\(.*\\(?:\n[ \t]+.*\\)*\\)"
1875 "Regular expression for matching Pandoc metadata.")
1877 (defconst markdown-regex-yaml-metadata-border
1878 "\\(-\\{3\\}\\)$"
1879 "Regular expression for matching YAML metadata.")
1881 (defconst markdown-regex-yaml-pandoc-metadata-end-border
1882 "^\\(\\.\\{3\\}\\|\\-\\{3\\}\\)$"
1883 "Regular expression for matching YAML metadata end borders.")
1885 (defsubst markdown-get-yaml-metadata-start-border ()
1886 "Return YAML metadata start border depending upon whether Pandoc is used."
1887 (concat
1888 (if markdown-use-pandoc-style-yaml-metadata "^" "\\`")
1889 markdown-regex-yaml-metadata-border))
1891 (defsubst markdown-get-yaml-metadata-end-border (_)
1892 "Return YAML metadata end border depending upon whether Pandoc is used."
1893 (if markdown-use-pandoc-style-yaml-metadata
1894 markdown-regex-yaml-pandoc-metadata-end-border
1895 markdown-regex-yaml-metadata-border))
1897 (defconst markdown-regex-inline-attributes
1898 "[ \t]*\\({:?\\)[ \t]*\\(\\(#[[:alpha:]_.:-]+\\|\\.[[:alpha:]_.:-]+\\|\\w+=['\"]?[^\n'\"]*['\"]?\\),?[ \t]*\\)+\\(}\\)[ \t]*$"
1899 "Regular expression for matching inline identifiers or attribute lists.
1900 Compatible with Pandoc, Python Markdown, PHP Markdown Extra, and Leanpub.")
1902 (defconst markdown-regex-leanpub-sections
1903 (concat
1904 "^\\({\\)\\("
1905 (regexp-opt '("frontmatter" "mainmatter" "backmatter" "appendix" "pagebreak"))
1906 "\\)\\(}\\)[ \t]*\n")
1907 "Regular expression for Leanpub section markers and related syntax.")
1909 (defconst markdown-regex-sub-superscript
1910 "\\(?:^\\|[^\\~^]\\)\\(\\([~^]\\)\\([[:alnum:]]+\\)\\(\\2\\)\\)"
1911 "The regular expression matching a sub- or superscript.
1912 The leading un-numbered group matches the character before the
1913 opening tilde or carat, if any, ensuring that it is not a
1914 backslash escape, carat, or tilde.
1915 Group 1 matches the entire expression, including markup.
1916 Group 2 matches the opening markup--a tilde or carat.
1917 Group 3 matches the text inside the delimiters.
1918 Group 4 matches the closing markup--a tilde or carat.")
1920 (defconst markdown-regex-include
1921 "^\\(<<\\)\\(?:\\(\\[\\)\\(.*\\)\\(\\]\\)\\)?\\(?:\\((\\)\\(.*\\)\\()\\)\\)?\\(?:\\({\\)\\(.*\\)\\(}\\)\\)?$"
1922 "Regular expression matching common forms of include syntax.
1923 Marked 2, Leanpub, and other processors support some of these forms:
1925 <<[sections/section1.md]
1926 <<(folder/filename)
1927 <<[Code title](folder/filename)
1928 <<{folder/raw_file.html}
1930 Group 1 matches the opening two angle brackets.
1931 Groups 2-4 match the opening square bracket, the text inside,
1932 and the closing square bracket, respectively.
1933 Groups 5-7 match the opening parenthesis, the text inside, and
1934 the closing parenthesis.
1935 Groups 8-10 match the opening brace, the text inside, and the brace.")
1937 (defconst markdown-regex-pandoc-inline-footnote
1938 "\\(\\^\\)\\(\\[\\)\\(\\(?:.\\|\n[^\n]\\)*?\\)\\(\\]\\)"
1939 "Regular expression for Pandoc inline footnote^[footnote text].
1940 Group 1 matches the opening caret.
1941 Group 2 matches the opening square bracket.
1942 Group 3 matches the footnote text, without the surrounding markup.
1943 Group 4 matches the closing square bracket.")
1945 (defconst markdown-regex-html-attr
1946 "\\(\\<[[:alpha:]:-]+\\>\\)\\(\\s-*\\(=\\)\\s-*\\(\".*?\"\\|'.*?'\\|[^'\">[:space:]]+\\)?\\)?"
1947 "Regular expression for matching HTML attributes and values.
1948 Group 1 matches the attribute name.
1949 Group 2 matches the following whitespace, equals sign, and value, if any.
1950 Group 3 matches the equals sign, if any.
1951 Group 4 matches single-, double-, or un-quoted attribute values.")
1953 (defconst markdown-regex-html-tag
1954 (concat "\\(</?\\)\\(\\w+\\)\\(\\(\\s-+" markdown-regex-html-attr
1955 "\\)+\\s-*\\|\\s-*\\)\\(/?>\\)")
1956 "Regular expression for matching HTML tags.
1957 Groups 1 and 9 match the beginning and ending angle brackets and slashes.
1958 Group 2 matches the tag name.
1959 Group 3 matches all attributes and whitespace following the tag name.")
1961 (defconst markdown-regex-html-entity
1962 "\\(&#?[[:alnum:]]+;\\)"
1963 "Regular expression for matching HTML entities.")
1966 ;;; Syntax ====================================================================
1968 (defsubst markdown-in-comment-p (&optional pos)
1969 "Return non-nil if POS is in a comment.
1970 If POS is not given, use point instead."
1971 (nth 4 (syntax-ppss pos)))
1973 (defun markdown-syntax-propertize-extend-region (start end)
1974 "Extend START to END region to include an entire block of text.
1975 This helps improve syntax analysis for block constructs.
1976 Returns a cons (NEW-START . NEW-END) or nil if no adjustment should be made.
1977 Function is called repeatedly until it returns nil. For details, see
1978 `syntax-propertize-extend-region-functions'."
1979 (save-match-data
1980 (save-excursion
1981 (let* ((new-start (progn (goto-char start)
1982 (skip-chars-forward "\n")
1983 (if (re-search-backward "\n\n" nil t)
1984 (min start (match-end 0))
1985 (point-min))))
1986 (new-end (progn (goto-char end)
1987 (skip-chars-backward "\n")
1988 (if (re-search-forward "\n\n" nil t)
1989 (max end (match-beginning 0))
1990 (point-max))))
1991 (code-match (markdown-code-block-at-pos new-start))
1992 (new-start (or (and code-match (cl-first code-match)) new-start))
1993 (code-match (and (< end (point-max)) (markdown-code-block-at-pos end)))
1994 (new-end (or (and code-match (cl-second code-match)) new-end)))
1995 (unless (and (eq new-start start) (eq new-end end))
1996 (cons new-start (min new-end (point-max))))))))
1998 (defun markdown-font-lock-extend-region-function (start end _)
1999 "Used in `jit-lock-after-change-extend-region-functions'.
2000 Delegates to `markdown-syntax-propertize-extend-region'. START
2001 and END are the previous region to refontify."
2002 (let ((res (markdown-syntax-propertize-extend-region start end)))
2003 (when res
2004 ;; syntax-propertize-function is not called when character at
2005 ;; (point-max) is deleted, but font-lock-extend-region-functions
2006 ;; are called. Force a syntax property update in that case.
2007 (when (= end (point-max))
2008 ;; This function is called in a buffer modification hook.
2009 ;; `markdown-syntax-propertize' doesn't save the match data,
2010 ;; so we have to do it here.
2011 (save-match-data
2012 (markdown-syntax-propertize (car res) (cdr res))))
2013 (setq jit-lock-start (car res)
2014 jit-lock-end (cdr res)))))
2016 (defun markdown-syntax-propertize-pre-blocks (start end)
2017 "Match preformatted text blocks from START to END."
2018 (save-excursion
2019 (goto-char start)
2020 (let ((levels (markdown-calculate-list-levels))
2021 indent pre-regexp close-regexp open close)
2022 (while (and (< (point) end) (not close))
2023 ;; Search for a region with sufficient indentation
2024 (if (null levels)
2025 (setq indent 1)
2026 (setq indent (1+ (length levels))))
2027 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
2028 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
2030 (cond
2031 ;; If not at the beginning of a line, move forward
2032 ((not (bolp)) (forward-line))
2033 ;; Move past blank lines
2034 ((markdown-cur-line-blank-p) (forward-line))
2035 ;; At headers and horizontal rules, reset levels
2036 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
2037 ;; If the current line has sufficient indentation, mark out pre block
2038 ;; The opening should be preceded by a blank line.
2039 ((and (looking-at pre-regexp)
2040 (markdown-prev-line-blank-p))
2041 (setq open (match-beginning 0))
2042 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
2043 (not (eobp)))
2044 (forward-line))
2045 (skip-syntax-backward "-")
2046 (setq close (point)))
2047 ;; If current line has a list marker, update levels, move to end of block
2048 ((looking-at markdown-regex-list)
2049 (setq levels (markdown-update-list-levels
2050 (match-string 2) (current-indentation) levels))
2051 (markdown-end-of-text-block))
2052 ;; If this is the end of the indentation level, adjust levels accordingly.
2053 ;; Only match end of indentation level if levels is not the empty list.
2054 ((and (car levels) (looking-at-p close-regexp))
2055 (setq levels (markdown-update-list-levels
2056 nil (current-indentation) levels))
2057 (markdown-end-of-text-block))
2058 (t (markdown-end-of-text-block))))
2060 (when (and open close)
2061 ;; Set text property data
2062 (put-text-property open close 'markdown-pre (list open close))
2063 ;; Recursively search again
2064 (markdown-syntax-propertize-pre-blocks (point) end)))))
2066 (defconst markdown-fenced-block-pairs
2067 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
2068 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
2069 markdown-fenced-code)
2070 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
2071 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2072 markdown-yaml-metadata-section)
2073 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2074 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2075 markdown-gfm-code))
2076 "Mapping of regular expressions to \"fenced-block\" constructs.
2077 These constructs are distinguished by having a distinctive start
2078 and end pattern, both of which take up an entire line of text,
2079 but no special pattern to identify text within the fenced
2080 blocks (unlike blockquotes and indented-code sections).
2082 Each element within this list takes the form:
2084 ((START-REGEX-OR-FUN START-PROPERTY)
2085 (END-REGEX-OR-FUN END-PROPERTY)
2086 MIDDLE-PROPERTY)
2088 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2089 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2090 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2091 which is the length of the first group of the START-REGEX-OR-FUN match, which
2092 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2093 evaluate these into \"real\" regexps.
2095 The *-PROPERTY elements are the text properties applied to each part of the
2096 block construct when it is matched using
2097 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2098 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2099 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2100 `match-data' when the regexp was matched to the text. In the case of
2101 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2102 begin and end set to the edges of the \"middle\" text. This makes fontification
2103 easier.")
2105 (defun markdown-text-property-at-point (prop)
2106 (get-text-property (point) prop))
2108 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2109 (cond ((functionp object)
2110 (if arg (funcall object arg) (funcall object)))
2111 ((stringp object) object)
2112 (t (error "Object cannot be turned into regex"))))
2114 (defsubst markdown-get-start-fence-regexp ()
2115 "Return regexp to find all \"start\" sections of fenced block constructs.
2116 Which construct is actually contained in the match must be found separately."
2117 (mapconcat
2118 #'identity
2119 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2120 markdown-fenced-block-pairs)
2121 "\\|"))
2123 (defun markdown-get-fenced-block-begin-properties ()
2124 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2126 (defun markdown-get-fenced-block-end-properties ()
2127 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2129 (defun markdown-get-fenced-block-middle-properties ()
2130 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2132 (defun markdown-find-previous-prop (prop &optional lim)
2133 "Find previous place where property PROP is non-nil, up to LIM.
2134 Return a cons of (pos . property). pos is point if point contains
2135 non-nil PROP."
2136 (let ((res
2137 (if (get-text-property (point) prop) (point)
2138 (previous-single-property-change
2139 (point) prop nil (or lim (point-min))))))
2140 (when (and (not (get-text-property res prop))
2141 (> res (point-min))
2142 (get-text-property (1- res) prop))
2143 (cl-decf res))
2144 (when (and res (get-text-property res prop)) (cons res prop))))
2146 (defun markdown-find-next-prop (prop &optional lim)
2147 "Find next place where property PROP is non-nil, up to LIM.
2148 Return a cons of (POS . PROPERTY) where POS is point if point
2149 contains non-nil PROP."
2150 (let ((res
2151 (if (get-text-property (point) prop) (point)
2152 (next-single-property-change
2153 (point) prop nil (or lim (point-max))))))
2154 (when (and res (get-text-property res prop)) (cons res prop))))
2156 (defun markdown-min-of-seq (map-fn seq)
2157 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2158 (cl-loop for el in seq
2159 with min = 1.0e+INF ; infinity
2160 with min-el = nil
2161 do (let ((res (funcall map-fn el)))
2162 (when (< res min)
2163 (setq min res)
2164 (setq min-el el)))
2165 finally return min-el))
2167 (defun markdown-max-of-seq (map-fn seq)
2168 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2169 (cl-loop for el in seq
2170 with max = -1.0e+INF ; negative infinity
2171 with max-el = nil
2172 do (let ((res (funcall map-fn el)))
2173 (when (and res (> res max))
2174 (setq max res)
2175 (setq max-el el)))
2176 finally return max-el))
2178 (defun markdown-find-previous-block ()
2179 "Find previous block.
2180 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2181 unable to propertize the entire block, but was able to propertize the beginning
2182 of the block. If so, return a cons of (pos . property) where the beginning of
2183 the block was propertized."
2184 (let ((start-pt (point))
2185 (closest-open
2186 (markdown-max-of-seq
2187 #'car
2188 (cl-remove-if
2189 #'null
2190 (cl-mapcar
2191 #'markdown-find-previous-prop
2192 (markdown-get-fenced-block-begin-properties))))))
2193 (when closest-open
2194 (let* ((length-of-open-match
2195 (let ((match-d
2196 (get-text-property (car closest-open) (cdr closest-open))))
2197 (- (cl-fourth match-d) (cl-third match-d))))
2198 (end-regexp
2199 (markdown-maybe-funcall-regexp
2200 (cl-caadr
2201 (cl-find-if
2202 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2203 markdown-fenced-block-pairs))
2204 length-of-open-match))
2205 (end-prop-loc
2206 (save-excursion
2207 (save-match-data
2208 (goto-char (car closest-open))
2209 (and (re-search-forward end-regexp start-pt t)
2210 (match-beginning 0))))))
2211 (and (not end-prop-loc) closest-open)))))
2213 (defun markdown-get-fenced-block-from-start (prop)
2214 "Return limits of an enclosing fenced block from its start, using PROP.
2215 Return value is a list usable as `match-data'."
2216 (catch 'no-rest-of-block
2217 (let* ((correct-entry
2218 (cl-find-if
2219 (lambda (entry) (eq (cl-cadar entry) prop))
2220 markdown-fenced-block-pairs))
2221 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2222 (middle-prop (cl-third correct-entry))
2223 (end-prop (cl-cadadr correct-entry))
2224 (end-of-end
2225 (save-excursion
2226 (goto-char (match-end 0)) ; end of begin
2227 (unless (eobp) (forward-char))
2228 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2229 (if (not mid-prop-v) ; no middle
2230 (progn
2231 ;; try to find end by advancing one
2232 (let ((end-prop-v
2233 (markdown-text-property-at-point end-prop)))
2234 (if end-prop-v (cl-second end-prop-v)
2235 (throw 'no-rest-of-block nil))))
2236 (set-match-data mid-prop-v)
2237 (goto-char (match-end 0)) ; end of middle
2238 (beginning-of-line) ; into end
2239 (cl-second (markdown-text-property-at-point end-prop)))))))
2240 (list begin-of-begin end-of-end))))
2242 (defun markdown-get-fenced-block-from-middle (prop)
2243 "Return limits of an enclosing fenced block from its middle, using PROP.
2244 Return value is a list usable as `match-data'."
2245 (let* ((correct-entry
2246 (cl-find-if
2247 (lambda (entry) (eq (cl-third entry) prop))
2248 markdown-fenced-block-pairs))
2249 (begin-prop (cl-cadar correct-entry))
2250 (begin-of-begin
2251 (save-excursion
2252 (goto-char (match-beginning 0))
2253 (unless (bobp) (forward-line -1))
2254 (beginning-of-line)
2255 (cl-first (markdown-text-property-at-point begin-prop))))
2256 (end-prop (cl-cadadr correct-entry))
2257 (end-of-end
2258 (save-excursion
2259 (goto-char (match-end 0))
2260 (beginning-of-line)
2261 (cl-second (markdown-text-property-at-point end-prop)))))
2262 (list begin-of-begin end-of-end)))
2264 (defun markdown-get-fenced-block-from-end (prop)
2265 "Return limits of an enclosing fenced block from its end, using PROP.
2266 Return value is a list usable as `match-data'."
2267 (let* ((correct-entry
2268 (cl-find-if
2269 (lambda (entry) (eq (cl-cadadr entry) prop))
2270 markdown-fenced-block-pairs))
2271 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2272 (middle-prop (cl-third correct-entry))
2273 (begin-prop (cl-cadar correct-entry))
2274 (begin-of-begin
2275 (save-excursion
2276 (goto-char (match-beginning 0)) ; beginning of end
2277 (unless (bobp) (backward-char)) ; into middle
2278 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2279 (if (not mid-prop-v)
2280 (progn
2281 (beginning-of-line)
2282 (cl-first (markdown-text-property-at-point begin-prop)))
2283 (set-match-data mid-prop-v)
2284 (goto-char (match-beginning 0)) ; beginning of middle
2285 (unless (bobp) (forward-line -1)) ; into beginning
2286 (beginning-of-line)
2287 (cl-first (markdown-text-property-at-point begin-prop)))))))
2288 (list begin-of-begin end-of-end)))
2290 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2291 "Get \"fake\" match data for block enclosing POS.
2292 Returns fake match data which encloses the start, middle, and end
2293 of the block construct enclosing POS, if it exists. Used in
2294 `markdown-code-block-at-pos'."
2295 (save-excursion
2296 (when pos (goto-char pos))
2297 (beginning-of-line)
2298 (car
2299 (cl-remove-if
2300 #'null
2301 (cl-mapcar
2302 (lambda (fun-and-prop)
2303 (cl-destructuring-bind (fun prop) fun-and-prop
2304 (when prop
2305 (save-match-data
2306 (set-match-data (markdown-text-property-at-point prop))
2307 (funcall fun prop)))))
2308 `((markdown-get-fenced-block-from-start
2309 ,(cl-find-if
2310 #'markdown-text-property-at-point
2311 (markdown-get-fenced-block-begin-properties)))
2312 (markdown-get-fenced-block-from-middle
2313 ,(cl-find-if
2314 #'markdown-text-property-at-point
2315 (markdown-get-fenced-block-middle-properties)))
2316 (markdown-get-fenced-block-from-end
2317 ,(cl-find-if
2318 #'markdown-text-property-at-point
2319 (markdown-get-fenced-block-end-properties)))))))))
2321 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2322 "Get match for REG up to END, if exists, and propertize appropriately.
2323 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2324 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2325 (when (re-search-forward reg end t)
2326 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2327 (close-end (match-end 0)) ; End of closing line.
2328 (close-data (match-data t))) ; Match data for closing line.
2329 ;; Propertize middle section of fenced block.
2330 (put-text-property middle-begin close-begin
2331 (cl-third fence-spec)
2332 (list middle-begin close-begin))
2333 ;; If the block is a YAML block, propertize the declarations inside
2334 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
2335 ;; Propertize closing line of fenced block.
2336 (put-text-property close-begin close-end
2337 (cl-cadadr fence-spec) close-data))))
2339 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2340 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2341 If unable to propertize an entire block (if the start of a block is within START
2342 and END, but the end of the block is not), propertize the start section of a
2343 block, then in a subsequent call propertize both middle and end by finding the
2344 start which was previously propertized."
2345 (let ((start-reg (markdown-get-start-fence-regexp)))
2346 (save-excursion
2347 (goto-char start)
2348 ;; start from previous unclosed block, if exists
2349 (let ((prev-begin-block (markdown-find-previous-block)))
2350 (when prev-begin-block
2351 (let* ((correct-entry
2352 (cl-find-if (lambda (entry)
2353 (eq (cdr prev-begin-block) (cl-cadar entry)))
2354 markdown-fenced-block-pairs))
2355 (enclosed-text-start (1+ (car prev-begin-block)))
2356 (start-length
2357 (save-excursion
2358 (goto-char (car prev-begin-block))
2359 (string-match
2360 (markdown-maybe-funcall-regexp
2361 (caar correct-entry))
2362 (buffer-substring
2363 (point-at-bol) (point-at-eol)))
2364 (- (match-end 1) (match-beginning 1))))
2365 (end-reg (markdown-maybe-funcall-regexp
2366 (cl-caadr correct-entry) start-length)))
2367 (markdown-propertize-end-match
2368 end-reg end correct-entry enclosed-text-start))))
2369 ;; find all new blocks within region
2370 (while (re-search-forward start-reg end t)
2371 ;; we assume the opening constructs take up (only) an entire line,
2372 ;; so we re-check the current line
2373 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2374 ;; find entry in `markdown-fenced-block-pairs' corresponding
2375 ;; to regex which was matched
2376 (correct-entry
2377 (cl-find-if
2378 (lambda (fenced-pair)
2379 (string-match-p
2380 (markdown-maybe-funcall-regexp (caar fenced-pair))
2381 cur-line))
2382 markdown-fenced-block-pairs))
2383 (enclosed-text-start
2384 (save-excursion (1+ (point-at-eol))))
2385 (end-reg
2386 (markdown-maybe-funcall-regexp
2387 (cl-caadr correct-entry)
2388 (if (and (match-beginning 1) (match-end 1))
2389 (- (match-end 1) (match-beginning 1))
2390 0))))
2391 ;; get correct match data
2392 (save-excursion
2393 (beginning-of-line)
2394 (re-search-forward
2395 (markdown-maybe-funcall-regexp (caar correct-entry))
2396 (point-at-eol)))
2397 ;; mark starting, even if ending is outside of region
2398 (put-text-property (match-beginning 0) (match-end 0)
2399 (cl-cadar correct-entry) (match-data t))
2400 (markdown-propertize-end-match
2401 end-reg end correct-entry enclosed-text-start))))))
2403 (defun markdown-syntax-propertize-blockquotes (start end)
2404 "Match blockquotes from START to END."
2405 (save-excursion
2406 (goto-char start)
2407 (while (and (re-search-forward markdown-regex-blockquote end t)
2408 (not (markdown-code-block-at-pos (match-beginning 0))))
2409 (put-text-property (match-beginning 0) (match-end 0)
2410 'markdown-blockquote
2411 (match-data t)))))
2413 (defun markdown-syntax-propertize-hrs (start end)
2414 "Match horizontal rules from START to END."
2415 (save-excursion
2416 (goto-char start)
2417 (while (re-search-forward markdown-regex-hr end t)
2418 (unless (or (markdown-on-heading-p)
2419 (markdown-code-block-at-point-p))
2420 (put-text-property (match-beginning 0) (match-end 0)
2421 'markdown-hr
2422 (match-data t))))))
2424 (defun markdown-syntax-propertize-yaml-metadata (start end)
2425 "Propertize elements inside YAML metadata blocks from START to END.
2426 Assumes region from START and END is already known to be the interior
2427 region of a YAML metadata block as propertized by
2428 `markdown-syntax-propertize-fenced-block-constructs'."
2429 (save-excursion
2430 (goto-char start)
2431 (cl-loop
2432 while (re-search-forward markdown-regex-declarative-metadata end t)
2433 do (progn
2434 (put-text-property (match-beginning 1) (match-end 1)
2435 'markdown-metadata-key (match-data t))
2436 (put-text-property (match-beginning 2) (match-end 2)
2437 'markdown-metadata-markup (match-data t))
2438 (put-text-property (match-beginning 3) (match-end 3)
2439 'markdown-metadata-value (match-data t))))))
2441 (defun markdown-syntax-propertize-headings (start end)
2442 "Match headings of type SYMBOL with REGEX from START to END."
2443 (goto-char start)
2444 (while (re-search-forward markdown-regex-header end t)
2445 (unless (markdown-code-block-at-pos (match-beginning 0))
2446 (put-text-property
2447 (match-beginning 0) (match-end 0) 'markdown-heading
2448 (match-data t))
2449 (put-text-property
2450 (match-beginning 0) (match-end 0)
2451 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2452 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2453 (t (let ((atx-level (length (markdown-trim-whitespace
2454 (match-string-no-properties 4)))))
2455 (intern (format "markdown-heading-%d-atx" atx-level)))))
2456 (match-data t)))))
2458 (defun markdown-syntax-propertize-comments (start end)
2459 "Match HTML comments from the START to END."
2460 (let* ((in-comment (markdown-in-comment-p)))
2461 (goto-char start)
2462 (cond
2463 ;; Comment start
2464 ((and (not in-comment)
2465 (re-search-forward markdown-regex-comment-start end t)
2466 (not (markdown-inline-code-at-point-p))
2467 (not (markdown-code-block-at-point-p)))
2468 (let ((open-beg (match-beginning 0)))
2469 (put-text-property open-beg (1+ open-beg)
2470 'syntax-table (string-to-syntax "<"))
2471 (markdown-syntax-propertize-comments
2472 (min (1+ (match-end 0)) end (point-max)) end)))
2473 ;; Comment end
2474 ((and in-comment
2475 (re-search-forward markdown-regex-comment-end end t))
2476 (put-text-property (1- (match-end 0)) (match-end 0)
2477 'syntax-table (string-to-syntax ">"))
2478 (markdown-syntax-propertize-comments
2479 (min (1+ (match-end 0)) end (point-max)) end))
2480 ;; Nothing found
2481 (t nil))))
2483 (defvar markdown--syntax-properties
2484 (list 'markdown-tilde-fence-begin nil
2485 'markdown-tilde-fence-end nil
2486 'markdown-fenced-code nil
2487 'markdown-yaml-metadata-begin nil
2488 'markdown-yaml-metadata-end nil
2489 'markdown-yaml-metadata-section nil
2490 'markdown-gfm-block-begin nil
2491 'markdown-gfm-block-end nil
2492 'markdown-gfm-code nil
2493 'markdown-pre nil
2494 'markdown-blockquote nil
2495 'markdown-hr nil
2496 'markdown-heading nil
2497 'markdown-heading-1-setext nil
2498 'markdown-heading-2-setext nil
2499 'markdown-heading-1-atx nil
2500 'markdown-heading-2-atx nil
2501 'markdown-heading-3-atx nil
2502 'markdown-heading-4-atx nil
2503 'markdown-heading-5-atx nil
2504 'markdown-heading-6-atx nil
2505 'markdown-metadata-key nil
2506 'markdown-metadata-value nil
2507 'markdown-metadata-markup nil)
2508 "Property list of all Markdown syntactic properties.")
2510 (defun markdown-syntax-propertize (start end)
2511 "Function used as `syntax-propertize-function'.
2512 START and END delimit region to propertize."
2513 (with-silent-modifications
2514 (save-excursion
2515 (remove-text-properties start end markdown--syntax-properties)
2516 (markdown-syntax-propertize-fenced-block-constructs start end)
2517 (markdown-syntax-propertize-pre-blocks start end)
2518 (markdown-syntax-propertize-blockquotes start end)
2519 (markdown-syntax-propertize-headings start end)
2520 (markdown-syntax-propertize-hrs start end)
2521 (markdown-syntax-propertize-comments start end))))
2524 ;;; Markup Hiding
2526 (defconst markdown-markup-properties
2527 '(face markdown-markup-face invisible markdown-markup)
2528 "List of properties and values to apply to markup.")
2530 (defconst markdown-language-keyword-properties
2531 '(face markdown-language-keyword-face invisible markdown-markup)
2532 "List of properties and values to apply to code block language names.")
2534 (defconst markdown-language-info-properties
2535 '(face markdown-language-info-face invisible markdown-markup)
2536 "List of properties and values to apply to code block language info strings.")
2538 (defconst markdown-include-title-properties
2539 '(face markdown-link-title-face invisible markdown-markup)
2540 "List of properties and values to apply to included code titles.")
2542 (defcustom markdown-hide-markup nil
2543 "Determines whether markup in the buffer will be hidden.
2544 When set to nil, all markup is displayed in the buffer as it
2545 appears in the file. An exception is when `markdown-hide-urls'
2546 is non-nil.
2547 Set this to a non-nil value to turn this feature on by default.
2548 You can interactively toggle the value of this variable with
2549 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2550 or from the Markdown > Show & Hide menu.
2552 Markup hiding works by adding text properties to positions in the
2553 buffer---either the `invisible' property or the `display' property
2554 in cases where alternative glyphs are used (e.g., list bullets).
2555 This does not, however, affect printing or other output.
2556 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2557 not honor these text properties. For printing, it would be better
2558 to first convert to HTML or PDF (e.g,. using Pandoc)."
2559 :group 'markdown
2560 :type 'boolean
2561 :safe 'booleanp
2562 :package-version '(markdown-mode . "2.3"))
2563 (make-variable-buffer-local 'markdown-hide-markup)
2565 (defun markdown-toggle-markup-hiding (&optional arg)
2566 "Toggle the display or hiding of markup.
2567 With a prefix argument ARG, enable markup hiding if ARG is positive,
2568 and disable it otherwise.
2569 See `markdown-hide-markup' for additional details."
2570 (interactive (list (or current-prefix-arg 'toggle)))
2571 (setq markdown-hide-markup
2572 (if (eq arg 'toggle)
2573 (not markdown-hide-markup)
2574 (> (prefix-numeric-value arg) 0)))
2575 (if markdown-hide-markup
2576 (progn (add-to-invisibility-spec 'markdown-markup)
2577 (message "markdown-mode markup hiding enabled"))
2578 (progn (remove-from-invisibility-spec 'markdown-markup)
2579 (message "markdown-mode markup hiding disabled")))
2580 (markdown-reload-extensions))
2583 ;;; Font Lock =================================================================
2585 (require 'font-lock)
2587 (defvar markdown-italic-face 'markdown-italic-face
2588 "Face name to use for italic text.")
2590 (defvar markdown-bold-face 'markdown-bold-face
2591 "Face name to use for bold text.")
2593 (defvar markdown-strike-through-face 'markdown-strike-through-face
2594 "Face name to use for strike-through text.")
2596 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2597 "Face name to use as a base for header delimiters.")
2599 (defvar markdown-header-rule-face 'markdown-header-rule-face
2600 "Face name to use as a base for header rules.")
2602 (defvar markdown-header-face 'markdown-header-face
2603 "Face name to use as a base for headers.")
2605 (defvar markdown-header-face-1 'markdown-header-face-1
2606 "Face name to use for level-1 headers.")
2608 (defvar markdown-header-face-2 'markdown-header-face-2
2609 "Face name to use for level-2 headers.")
2611 (defvar markdown-header-face-3 'markdown-header-face-3
2612 "Face name to use for level-3 headers.")
2614 (defvar markdown-header-face-4 'markdown-header-face-4
2615 "Face name to use for level-4 headers.")
2617 (defvar markdown-header-face-5 'markdown-header-face-5
2618 "Face name to use for level-5 headers.")
2620 (defvar markdown-header-face-6 'markdown-header-face-6
2621 "Face name to use for level-6 headers.")
2623 (defvar markdown-inline-code-face 'markdown-inline-code-face
2624 "Face name to use for inline code.")
2626 (defvar markdown-list-face 'markdown-list-face
2627 "Face name to use for list markers.")
2629 (defvar markdown-blockquote-face 'markdown-blockquote-face
2630 "Face name to use for blockquote.")
2632 (defvar markdown-pre-face 'markdown-pre-face
2633 "Face name to use for preformatted text.")
2635 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2636 "Face name to use for programming language identifiers.")
2638 (defvar markdown-language-info-face 'markdown-language-info-face
2639 "Face name to use for programming info strings.")
2641 (defvar markdown-link-face 'markdown-link-face
2642 "Face name to use for links.")
2644 (defvar markdown-missing-link-face 'markdown-missing-link-face
2645 "Face name to use for links where the linked file does not exist.")
2647 (defvar markdown-reference-face 'markdown-reference-face
2648 "Face name to use for reference.")
2650 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2651 "Face name to use for footnote markers.")
2653 (defvar markdown-url-face 'markdown-url-face
2654 "Face name to use for URLs.")
2656 (defvar markdown-link-title-face 'markdown-link-title-face
2657 "Face name to use for reference link titles.")
2659 (defvar markdown-line-break-face 'markdown-line-break-face
2660 "Face name to use for hard line breaks.")
2662 (defvar markdown-comment-face 'markdown-comment-face
2663 "Face name to use for HTML comments.")
2665 (defvar markdown-math-face 'markdown-math-face
2666 "Face name to use for LaTeX expressions.")
2668 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2669 "Face name to use for metadata keys.")
2671 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2672 "Face name to use for metadata values.")
2674 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2675 "Face name to use for GFM checkboxes.")
2677 (defvar markdown-highlight-face 'markdown-highlight-face
2678 "Face name to use for mouse highlighting.")
2680 (defvar markdown-markup-face 'markdown-markup-face
2681 "Face name to use for markup elements.")
2683 (defgroup markdown-faces nil
2684 "Faces used in Markdown Mode"
2685 :group 'markdown
2686 :group 'faces)
2688 (defface markdown-italic-face
2689 '((t (:inherit italic)))
2690 "Face for italic text."
2691 :group 'markdown-faces)
2693 (defface markdown-bold-face
2694 '((t (:inherit bold)))
2695 "Face for bold text."
2696 :group 'markdown-faces)
2698 (defface markdown-strike-through-face
2699 '((t (:strike-through t)))
2700 "Face for strike-through text."
2701 :group 'markdown-faces)
2703 (defface markdown-markup-face
2704 '((t (:inherit shadow :slant normal :weight normal)))
2705 "Face for markup elements."
2706 :group 'markdown-faces)
2708 (defface markdown-header-rule-face
2709 '((t (:inherit markdown-markup-face)))
2710 "Base face for headers rules."
2711 :group 'markdown-faces)
2713 (defface markdown-header-delimiter-face
2714 '((t (:inherit markdown-markup-face)))
2715 "Base face for headers hash delimiter."
2716 :group 'markdown-faces)
2718 (defface markdown-list-face
2719 '((t (:inherit markdown-markup-face)))
2720 "Face for list item markers."
2721 :group 'markdown-faces)
2723 (defface markdown-blockquote-face
2724 '((t (:inherit font-lock-doc-face)))
2725 "Face for blockquote sections."
2726 :group 'markdown-faces)
2728 (defface markdown-code-face
2729 '((t (:inherit fixed-pitch)))
2730 "Face for inline code, pre blocks, and fenced code blocks.
2731 This may be used, for example, to add a contrasting background to
2732 inline code fragments and code blocks."
2733 :group 'markdown-faces)
2735 (defface markdown-inline-code-face
2736 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2737 "Face for inline code."
2738 :group 'markdown-faces)
2740 (defface markdown-pre-face
2741 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2742 "Face for preformatted text."
2743 :group 'markdown-faces)
2745 (defface markdown-table-face
2746 '((t (:inherit (markdown-code-face))))
2747 "Face for tables."
2748 :group 'markdown-faces)
2750 (defface markdown-language-keyword-face
2751 '((t (:inherit font-lock-type-face)))
2752 "Face for programming language identifiers."
2753 :group 'markdown-faces)
2755 (defface markdown-language-info-face
2756 '((t (:inherit font-lock-string-face)))
2757 "Face for programming language info strings."
2758 :group 'markdown-faces)
2760 (defface markdown-link-face
2761 '((t (:inherit link)))
2762 "Face for links."
2763 :group 'markdown-faces)
2765 (defface markdown-missing-link-face
2766 '((t (:inherit font-lock-warning-face)))
2767 "Face for missing links."
2768 :group 'markdown-faces)
2770 (defface markdown-reference-face
2771 '((t (:inherit markdown-markup-face)))
2772 "Face for link references."
2773 :group 'markdown-faces)
2775 (define-obsolete-face-alias 'markdown-footnote-face
2776 'markdown-footnote-marker-face "v2.3")
2778 (defface markdown-footnote-marker-face
2779 '((t (:inherit markdown-markup-face)))
2780 "Face for footnote markers."
2781 :group 'markdown-faces)
2783 (defface markdown-footnote-text-face
2784 '((t (:inherit font-lock-comment-face)))
2785 "Face for footnote text."
2786 :group 'markdown-faces)
2788 (defface markdown-url-face
2789 '((t (:inherit font-lock-string-face)))
2790 "Face for URLs that are part of markup.
2791 For example, this applies to URLs in inline links:
2792 [link text](http://example.com/)."
2793 :group 'markdown-faces)
2795 (defface markdown-plain-url-face
2796 '((t (:inherit markdown-link-face)))
2797 "Face for URLs that are also links.
2798 For example, this applies to plain angle bracket URLs:
2799 <http://example.com/>."
2800 :group 'markdown-faces)
2802 (defface markdown-link-title-face
2803 '((t (:inherit font-lock-comment-face)))
2804 "Face for reference link titles."
2805 :group 'markdown-faces)
2807 (defface markdown-line-break-face
2808 '((t (:inherit font-lock-constant-face :underline t)))
2809 "Face for hard line breaks."
2810 :group 'markdown-faces)
2812 (defface markdown-comment-face
2813 '((t (:inherit font-lock-comment-face)))
2814 "Face for HTML comments."
2815 :group 'markdown-faces)
2817 (defface markdown-math-face
2818 '((t (:inherit font-lock-string-face)))
2819 "Face for LaTeX expressions."
2820 :group 'markdown-faces)
2822 (defface markdown-metadata-key-face
2823 '((t (:inherit font-lock-variable-name-face)))
2824 "Face for metadata keys."
2825 :group 'markdown-faces)
2827 (defface markdown-metadata-value-face
2828 '((t (:inherit font-lock-string-face)))
2829 "Face for metadata values."
2830 :group 'markdown-faces)
2832 (defface markdown-gfm-checkbox-face
2833 '((t (:inherit font-lock-builtin-face)))
2834 "Face for GFM checkboxes."
2835 :group 'markdown-faces)
2837 (defface markdown-highlight-face
2838 '((t (:inherit highlight)))
2839 "Face for mouse highlighting."
2840 :group 'markdown-faces)
2842 (defface markdown-hr-face
2843 '((t (:inherit markdown-markup-face)))
2844 "Face for horizontal rules."
2845 :group 'markdown-faces)
2847 (defface markdown-html-tag-name-face
2848 '((t (:inherit font-lock-type-face)))
2849 "Face for HTML tag names."
2850 :group 'markdown-faces)
2852 (defface markdown-html-tag-delimiter-face
2853 '((t (:inherit markdown-markup-face)))
2854 "Face for HTML tag delimiters."
2855 :group 'markdown-faces)
2857 (defface markdown-html-attr-name-face
2858 '((t (:inherit font-lock-variable-name-face)))
2859 "Face for HTML attribute names."
2860 :group 'markdown-faces)
2862 (defface markdown-html-attr-value-face
2863 '((t (:inherit font-lock-string-face)))
2864 "Face for HTML attribute values."
2865 :group 'markdown-faces)
2867 (defface markdown-html-entity-face
2868 '((t (:inherit font-lock-variable-name-face)))
2869 "Face for HTML entities."
2870 :group 'markdown-faces)
2872 (defcustom markdown-header-scaling nil
2873 "Whether to use variable-height faces for headers.
2874 When non-nil, `markdown-header-face' will inherit from
2875 `variable-pitch' and the scaling values in
2876 `markdown-header-scaling-values' will be applied to
2877 headers of levels one through six respectively."
2878 :type 'boolean
2879 :initialize 'custom-initialize-default
2880 :set (lambda (symbol value)
2881 (set-default symbol value)
2882 (markdown-update-header-faces value))
2883 :group 'markdown-faces
2884 :package-version '(markdown-mode . "2.2"))
2886 (defcustom markdown-header-scaling-values
2887 '(2.0 1.7 1.4 1.1 1.0 1.0)
2888 "List of scaling values for headers of level one through six.
2889 Used when `markdown-header-scaling' is non-nil."
2890 :type 'list
2891 :initialize 'custom-initialize-default
2892 :set (lambda (symbol value)
2893 (set-default symbol value)
2894 (markdown-update-header-faces markdown-header-scaling value))
2895 :group 'markdown-faces)
2897 (defun markdown-make-header-faces ()
2898 "Build the faces used for Markdown headers."
2899 (let ((inherit-faces '(font-lock-function-name-face)))
2900 (when markdown-header-scaling
2901 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2902 (defface markdown-header-face
2903 `((t (:inherit ,inherit-faces :weight bold)))
2904 "Base face for headers."
2905 :group 'markdown-faces))
2906 (dotimes (num 6)
2907 (let* ((num1 (1+ num))
2908 (face-name (intern (format "markdown-header-face-%s" num1)))
2909 (scale (if markdown-header-scaling
2910 (float (nth num markdown-header-scaling-values))
2911 1.0)))
2912 (eval
2913 `(defface ,face-name
2914 '((t (:inherit markdown-header-face :height ,scale)))
2915 (format "Face for level %s headers.
2916 You probably don't want to customize this face directly. Instead
2917 you can customize the base face `markdown-header-face' or the
2918 variable-height variable `markdown-header-scaling'." ,num1)
2919 :group 'markdown-faces)))))
2921 (markdown-make-header-faces)
2923 (defun markdown-update-header-faces (&optional scaling scaling-values)
2924 "Update header faces, depending on if header SCALING is desired.
2925 If so, use given list of SCALING-VALUES relative to the baseline
2926 size of `markdown-header-face'."
2927 (dotimes (num 6)
2928 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
2929 (scale (cond ((not scaling) 1.0)
2930 (scaling-values (float (nth num scaling-values)))
2931 (t (float (nth num markdown-header-scaling-values))))))
2932 (unless (get face-name 'saved-face) ; Don't update customized faces
2933 (set-face-attribute face-name nil :height scale)))))
2935 (defun markdown-syntactic-face (state)
2936 "Return font-lock face for characters with given STATE.
2937 See `font-lock-syntactic-face-function' for details."
2938 (let ((in-comment (nth 4 state)))
2939 (cond
2940 (in-comment 'markdown-comment-face)
2941 (t nil))))
2943 (defcustom markdown-list-item-bullets
2944 '("●" "◎" "○" "◆" "◇" "►" "•")
2945 "List of bullets to use for unordered lists.
2946 It can contain any number of symbols, which will be repeated.
2947 Depending on your font, some reasonable choices are:
2948 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
2949 :group 'markdown
2950 :type '(repeat (string :tag "Bullet character"))
2951 :package-version '(markdown-mode . "2.3"))
2953 (defun markdown--footnote-marker-properties ()
2954 "Return a font-lock facespec expression for footnote marker text."
2955 `(face markdown-footnote-marker-face
2956 ,@(when markdown-hide-markup
2957 `(display ,markdown-footnote-display))))
2959 (defun markdown--pandoc-inline-footnote-properties ()
2960 "Return a font-lock facespec expression for Pandoc inline footnote text."
2961 `(face markdown-footnote-text-face
2962 ,@(when markdown-hide-markup
2963 `(display ,markdown-footnote-display))))
2965 (defvar markdown-mode-font-lock-keywords-basic
2966 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
2967 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
2968 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
2969 (2 markdown-markup-face)
2970 (3 markdown-metadata-value-face)))
2971 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
2972 (2 markdown-markup-properties nil t)
2973 (3 markdown-language-keyword-properties nil t)
2974 (4 markdown-language-info-properties nil t)
2975 (5 markdown-markup-properties nil t)))
2976 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
2977 (markdown-fontify-gfm-code-blocks)
2978 (markdown-fontify-tables)
2979 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
2980 (2 markdown-markup-properties nil t)
2981 (3 markdown-language-keyword-properties nil t)
2982 (4 markdown-language-info-properties nil t)
2983 (5 markdown-markup-properties nil t)))
2984 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
2985 (markdown-fontify-fenced-code-blocks)
2986 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
2987 (markdown-fontify-headings)
2988 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
2989 (2 markdown-markup-face)
2990 (3 markdown-metadata-value-face)))
2991 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
2992 (2 markdown-markup-face)
2993 (3 markdown-metadata-value-face)))
2994 (markdown-fontify-hrs)
2995 (markdown-match-code . ((1 markdown-markup-properties prepend)
2996 (2 markdown-inline-code-face prepend)
2997 (3 markdown-markup-properties prepend)))
2998 (,markdown-regex-kbd . ((1 markdown-markup-properties)
2999 (2 markdown-inline-code-face)
3000 (3 markdown-markup-properties)))
3001 (markdown-fontify-angle-uris)
3002 (,markdown-regex-email . 'markdown-plain-url-face)
3003 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
3004 (2 'markdown-html-tag-name-face t)
3005 (3 'markdown-html-tag-delimiter-face t)
3006 ;; Anchored matcher for HTML tag attributes
3007 (,markdown-regex-html-attr
3008 ;; Before searching, move past tag
3009 ;; name; set limit at tag close.
3010 (progn
3011 (goto-char (match-end 2)) (match-end 3))
3013 . ((1 'markdown-html-attr-name-face)
3014 (3 'markdown-html-tag-delimiter-face nil t)
3015 (4 'markdown-html-attr-value-face nil t)))))
3016 (,markdown-regex-html-entity . 'markdown-html-entity-face)
3017 (markdown-fontify-list-items)
3018 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
3019 (2 (markdown--footnote-marker-properties)) ; label
3020 (3 markdown-markup-properties))) ; ]
3021 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
3022 (2 markdown-markup-properties) ; [
3023 (3 (markdown--pandoc-inline-footnote-properties)) ; text
3024 (4 markdown-markup-properties))) ; ]
3025 (markdown-match-includes . ((1 markdown-markup-properties)
3026 (2 markdown-markup-properties nil t)
3027 (3 markdown-include-title-properties nil t)
3028 (4 markdown-markup-properties nil t)
3029 (5 markdown-markup-properties)
3030 (6 'markdown-url-face)
3031 (7 markdown-markup-properties)))
3032 (markdown-fontify-inline-links)
3033 (markdown-fontify-reference-links)
3034 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
3035 (2 markdown-reference-face) ; label
3036 (3 markdown-markup-face) ; ]
3037 (4 markdown-markup-face) ; :
3038 (5 markdown-url-face) ; url
3039 (6 markdown-link-title-face))) ; "title" (optional)
3040 (markdown-fontify-plain-uris)
3041 ;; Math mode $..$
3042 (markdown-match-math-single . ((1 markdown-markup-face prepend)
3043 (2 markdown-math-face append)
3044 (3 markdown-markup-face prepend)))
3045 ;; Math mode $$..$$
3046 (markdown-match-math-double . ((1 markdown-markup-face prepend)
3047 (2 markdown-math-face append)
3048 (3 markdown-markup-face prepend)))
3049 ;; Math mode \[..\] and \\[..\\]
3050 (markdown-match-math-display . ((1 markdown-markup-face prepend)
3051 (3 markdown-math-face append)
3052 (4 markdown-markup-face prepend)))
3053 (markdown-match-bold . ((1 markdown-markup-properties prepend)
3054 (2 markdown-bold-face append)
3055 (3 markdown-markup-properties prepend)))
3056 (markdown-match-italic . ((1 markdown-markup-properties prepend)
3057 (2 markdown-italic-face append)
3058 (3 markdown-markup-properties prepend)))
3059 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
3060 (4 markdown-strike-through-face)
3061 (5 markdown-markup-properties)))
3062 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
3063 (markdown-fontify-sub-superscripts)
3064 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
3065 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
3066 (markdown-fontify-blockquotes)
3067 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
3068 "Syntax highlighting for Markdown files.")
3070 ;; Footnotes
3071 (defvar markdown-footnote-counter 0
3072 "Counter for footnote numbers.")
3073 (make-variable-buffer-local 'markdown-footnote-counter)
3075 (defconst markdown-footnote-chars
3076 "[[:alnum:]-]"
3077 "Regular expression matching any character that is allowed in a footnote identifier.")
3079 (defconst markdown-regex-footnote-definition
3080 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
3081 "Regular expression matching a footnote definition, capturing the label.")
3084 ;;; Compatibility =============================================================
3086 (defun markdown-replace-regexp-in-string (regexp rep string)
3087 "Replace ocurrences of REGEXP with REP in STRING.
3088 This is a compatibility wrapper to provide `replace-regexp-in-string'
3089 in XEmacs 21."
3090 (if (featurep 'xemacs)
3091 (replace-in-string string regexp rep)
3092 (replace-regexp-in-string regexp rep string)))
3094 ;; `markdown-use-region-p' is a compatibility function which checks
3095 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
3096 (eval-and-compile
3097 (cond
3098 ;; Emacs 24 and newer
3099 ((fboundp 'use-region-p)
3100 (defalias 'markdown-use-region-p 'use-region-p))
3101 ;; XEmacs
3102 ((fboundp 'region-active-p)
3103 (defalias 'markdown-use-region-p 'region-active-p))))
3105 ;; Use new names for outline-mode functions in Emacs 25 and later.
3106 (eval-and-compile
3107 (defalias 'markdown-hide-sublevels
3108 (if (fboundp 'outline-hide-sublevels)
3109 'outline-hide-sublevels
3110 'hide-sublevels))
3111 (defalias 'markdown-show-all
3112 (if (fboundp 'outline-show-all)
3113 'outline-show-all
3114 'show-all))
3115 (defalias 'markdown-hide-body
3116 (if (fboundp 'outline-hide-body)
3117 'outline-hide-body
3118 'hide-body))
3119 (defalias 'markdown-show-children
3120 (if (fboundp 'outline-show-children)
3121 'outline-show-children
3122 'show-children))
3123 (defalias 'markdown-show-subtree
3124 (if (fboundp 'outline-show-subtree)
3125 'outline-show-subtree
3126 'show-subtree))
3127 (defalias 'markdown-hide-subtree
3128 (if (fboundp 'outline-hide-subtree)
3129 'outline-hide-subtree
3130 'hide-subtree)))
3132 ;; Provide directory-name-p to Emacs 24
3133 (defsubst markdown-directory-name-p (name)
3134 "Return non-nil if NAME ends with a directory separator character.
3135 Taken from `directory-name-p' from Emacs 25 and provided here for
3136 backwards compatibility."
3137 (let ((len (length name))
3138 (lastc ?.))
3139 (if (> len 0)
3140 (setq lastc (aref name (1- len))))
3141 (or (= lastc ?/)
3142 (and (memq system-type '(windows-nt ms-dos))
3143 (= lastc ?\\)))))
3145 ;; Provide a function to find files recursively in Emacs 24.
3146 (defalias 'markdown-directory-files-recursively
3147 (if (fboundp 'directory-files-recursively)
3148 'directory-files-recursively
3149 (lambda (dir regexp)
3150 "Return list of all files under DIR that have file names matching REGEXP.
3151 This function works recursively. Files are returned in \"depth first\"
3152 order, and files from each directory are sorted in alphabetical order.
3153 Each file name appears in the returned list in its absolute form.
3154 Based on `directory-files-recursively' from Emacs 25 and provided
3155 here for backwards compatibility."
3156 (let ((result nil)
3157 (files nil)
3158 ;; When DIR is "/", remote file names like "/method:" could
3159 ;; also be offered. We shall suppress them.
3160 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3161 (dolist (file (sort (file-name-all-completions "" dir)
3162 'string<))
3163 (unless (member file '("./" "../"))
3164 (if (markdown-directory-name-p file)
3165 (let* ((leaf (substring file 0 (1- (length file))))
3166 (full-file (expand-file-name leaf dir)))
3167 (setq result
3168 (nconc result (markdown-directory-files-recursively
3169 full-file regexp))))
3170 (when (string-match-p regexp file)
3171 (push (expand-file-name file dir) files)))))
3172 (nconc result (nreverse files))))))
3174 (defun markdown-flyspell-check-word-p ()
3175 "Return t if `flyspell' should check word just before point.
3176 Used for `flyspell-generic-check-word-predicate'."
3177 (save-excursion
3178 (goto-char (1- (point)))
3179 (not (or (markdown-code-block-at-point-p)
3180 (markdown-inline-code-at-point-p)
3181 (markdown-in-comment-p)
3182 (let ((faces (get-text-property (point) 'face)))
3183 (if (listp faces)
3184 (or (memq 'markdown-reference-face faces)
3185 (memq 'markdown-markup-face faces)
3186 (memq 'markdown-plain-url-face faces)
3187 (memq 'markdown-inline-code-face faces)
3188 (memq 'markdown-url-face faces))
3189 (memq faces '(markdown-reference-face
3190 markdown-markup-face
3191 markdown-plain-url-face
3192 markdown-inline-code-face
3193 markdown-url-face))))))))
3195 (defun markdown-font-lock-ensure ()
3196 "Provide `font-lock-ensure' in Emacs 24."
3197 (if (fboundp 'font-lock-ensure)
3198 (font-lock-ensure)
3199 (with-no-warnings
3200 ;; Suppress warning about non-interactive use of
3201 ;; `font-lock-fontify-buffer' in Emacs 25.
3202 (font-lock-fontify-buffer))))
3205 ;;; Markdown Parsing Functions ================================================
3207 (define-obsolete-function-alias
3208 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
3209 (define-obsolete-function-alias
3210 'markdown-prev-line-blank 'markdown-prev-line-blank-p "v2.4")
3211 (define-obsolete-function-alias
3212 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
3213 (define-obsolete-function-alias
3214 'markdown-new-baseline 'markdown-new-baseline-p "v2.4")
3216 (defun markdown-cur-line-blank-p ()
3217 "Return t if the current line is blank and nil otherwise."
3218 (save-excursion
3219 (beginning-of-line)
3220 (looking-at-p "^\\s *$")))
3222 (defun markdown-prev-line-blank-p ()
3223 "Return t if the previous line is blank and nil otherwise.
3224 If we are at the first line, then consider the previous line to be blank."
3225 (or (= (line-beginning-position) (point-min))
3226 (save-excursion
3227 (forward-line -1)
3228 (markdown-cur-line-blank-p))))
3230 (defun markdown-next-line-blank-p ()
3231 "Return t if the next line is blank and nil otherwise.
3232 If we are at the last line, then consider the next line to be blank."
3233 (or (= (line-end-position) (point-max))
3234 (save-excursion
3235 (forward-line 1)
3236 (markdown-cur-line-blank-p))))
3238 (defun markdown-prev-line-indent ()
3239 "Return the number of leading whitespace characters in the previous line.
3240 Return 0 if the current line is the first line in the buffer."
3241 (save-excursion
3242 (if (= (line-beginning-position) (point-min))
3244 (forward-line -1)
3245 (current-indentation))))
3247 (defun markdown-next-line-indent ()
3248 "Return the number of leading whitespace characters in the next line.
3249 Return 0 if line is the last line in the buffer."
3250 (save-excursion
3251 (if (= (line-end-position) (point-max))
3253 (forward-line 1)
3254 (current-indentation))))
3256 (defun markdown-cur-non-list-indent ()
3257 "Return beginning position of list item text (not including the list marker).
3258 Return nil if the current line is not the beginning of a list item."
3259 (save-match-data
3260 (save-excursion
3261 (beginning-of-line)
3262 (when (re-search-forward markdown-regex-list (line-end-position) t)
3263 (current-column)))))
3265 (defun markdown-prev-non-list-indent ()
3266 "Return position of the first non-list-marker on the previous line."
3267 (save-excursion
3268 (forward-line -1)
3269 (markdown-cur-non-list-indent)))
3271 (defun markdown-new-baseline-p ()
3272 "Determine if the current line begins a new baseline level."
3273 (save-excursion
3274 (beginning-of-line)
3275 (or (looking-at-p markdown-regex-header)
3276 (looking-at-p markdown-regex-hr)
3277 (and (null (markdown-cur-non-list-indent))
3278 (= (current-indentation) 0)
3279 (markdown-prev-line-blank-p)))))
3281 (defun markdown-search-backward-baseline ()
3282 "Search backward baseline point with no indentation and not a list item."
3283 (end-of-line)
3284 (let (stop)
3285 (while (not (or stop (bobp)))
3286 (re-search-backward markdown-regex-block-separator-noindent nil t)
3287 (when (match-end 2)
3288 (goto-char (match-end 2))
3289 (cond
3290 ((markdown-new-baseline-p)
3291 (setq stop t))
3292 ((looking-at-p markdown-regex-list)
3293 (setq stop nil))
3294 (t (setq stop t)))))))
3296 (defun markdown-update-list-levels (marker indent levels)
3297 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3298 Here, MARKER is a string representing the type of list, INDENT is an integer
3299 giving the indentation, in spaces, of the current block, and LEVELS is a
3300 list of the indentation levels of parent list items. When LEVELS is nil,
3301 it means we are at baseline (not inside of a nested list)."
3302 (cond
3303 ;; New list item at baseline.
3304 ((and marker (null levels))
3305 (setq levels (list indent)))
3306 ;; List item with greater indentation (four or more spaces).
3307 ;; Increase list level.
3308 ((and marker (>= indent (+ (car levels) 4)))
3309 (setq levels (cons indent levels)))
3310 ;; List item with greater or equal indentation (less than four spaces).
3311 ;; Do not increase list level.
3312 ((and marker (>= indent (car levels)))
3313 levels)
3314 ;; Lesser indentation level.
3315 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3316 ;; indentation could move back more than one list level). Note
3317 ;; that this block need not be the beginning of list item.
3318 ((< indent (car levels))
3319 (while (and (> (length levels) 1)
3320 (< indent (+ (cadr levels) 4)))
3321 (setq levels (cdr levels)))
3322 levels)
3323 ;; Otherwise, do nothing.
3324 (t levels)))
3326 (defun markdown-calculate-list-levels ()
3327 "Calculate list levels at point.
3328 Return a list of the form (n1 n2 n3 ...) where n1 is the
3329 indentation of the deepest nested list item in the branch of
3330 the list at the point, n2 is the indentation of the parent
3331 list item, and so on. The depth of the list item is therefore
3332 the length of the returned list. If the point is not at or
3333 immediately after a list item, return nil."
3334 (save-excursion
3335 (let ((first (point)) levels indent pre-regexp)
3336 ;; Find a baseline point with zero list indentation
3337 (markdown-search-backward-baseline)
3338 ;; Search for all list items between baseline and LOC
3339 (while (and (< (point) first)
3340 (re-search-forward markdown-regex-list first t))
3341 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3342 (beginning-of-line)
3343 (cond
3344 ;; Make sure this is not a header or hr
3345 ((markdown-new-baseline-p) (setq levels nil))
3346 ;; Make sure this is not a line from a pre block
3347 ((looking-at-p pre-regexp))
3348 ;; If not, then update levels
3350 (setq indent (current-indentation))
3351 (setq levels (markdown-update-list-levels (match-string 2)
3352 indent levels))))
3353 (end-of-line))
3354 levels)))
3356 (defun markdown-prev-list-item (level)
3357 "Search backward from point for a list item with indentation LEVEL.
3358 Set point to the beginning of the item, and return point, or nil
3359 upon failure."
3360 (let (bounds indent prev)
3361 (setq prev (point))
3362 (forward-line -1)
3363 (setq indent (current-indentation))
3364 (while
3365 (cond
3366 ;; List item
3367 ((and (looking-at-p markdown-regex-list)
3368 (setq bounds (markdown-cur-list-item-bounds)))
3369 (cond
3370 ;; Stop and return point at item of equal indentation
3371 ((= (nth 3 bounds) level)
3372 (setq prev (point))
3373 nil)
3374 ;; Stop and return nil at item with lesser indentation
3375 ((< (nth 3 bounds) level)
3376 (setq prev nil)
3377 nil)
3378 ;; Stop at beginning of buffer
3379 ((bobp) (setq prev nil))
3380 ;; Continue at item with greater indentation
3381 ((> (nth 3 bounds) level) t)))
3382 ;; Stop at beginning of buffer
3383 ((bobp) (setq prev nil))
3384 ;; Continue if current line is blank
3385 ((markdown-cur-line-blank-p) t)
3386 ;; Continue while indentation is the same or greater
3387 ((>= indent level) t)
3388 ;; Stop if current indentation is less than list item
3389 ;; and the next is blank
3390 ((and (< indent level)
3391 (markdown-next-line-blank-p))
3392 (setq prev nil))
3393 ;; Stop at a header
3394 ((looking-at-p markdown-regex-header) (setq prev nil))
3395 ;; Stop at a horizontal rule
3396 ((looking-at-p markdown-regex-hr) (setq prev nil))
3397 ;; Otherwise, continue.
3398 (t t))
3399 (forward-line -1)
3400 (setq indent (current-indentation)))
3401 prev))
3403 (defun markdown-next-list-item (level)
3404 "Search forward from point for the next list item with indentation LEVEL.
3405 Set point to the beginning of the item, and return point, or nil
3406 upon failure."
3407 (let (bounds indent next)
3408 (setq next (point))
3409 (if (looking-at markdown-regex-header-setext)
3410 (goto-char (match-end 0)))
3411 (forward-line)
3412 (setq indent (current-indentation))
3413 (while
3414 (cond
3415 ;; Stop at end of the buffer.
3416 ((eobp) nil)
3417 ;; Continue if the current line is blank
3418 ((markdown-cur-line-blank-p) t)
3419 ;; List item
3420 ((and (looking-at-p markdown-regex-list)
3421 (setq bounds (markdown-cur-list-item-bounds)))
3422 (cond
3423 ;; Continue at item with greater indentation
3424 ((> (nth 3 bounds) level) t)
3425 ;; Stop and return point at item of equal indentation
3426 ((= (nth 3 bounds) level)
3427 (setq next (point))
3428 nil)
3429 ;; Stop and return nil at item with lesser indentation
3430 ((< (nth 3 bounds) level)
3431 (setq next nil)
3432 nil)))
3433 ;; Continue while indentation is the same or greater
3434 ((>= indent level) t)
3435 ;; Stop if current indentation is less than list item
3436 ;; and the previous line was blank.
3437 ((and (< indent level)
3438 (markdown-prev-line-blank-p))
3439 (setq next nil))
3440 ;; Stop at a header
3441 ((looking-at-p markdown-regex-header) (setq next nil))
3442 ;; Stop at a horizontal rule
3443 ((looking-at-p markdown-regex-hr) (setq next nil))
3444 ;; Otherwise, continue.
3445 (t t))
3446 (forward-line)
3447 (setq indent (current-indentation)))
3448 next))
3450 (defun markdown-cur-list-item-end (level)
3451 "Move to end of list item with pre-marker indentation LEVEL.
3452 Return the point at the end when a list item was found at the
3453 original point. If the point is not in a list item, do nothing."
3454 (let (indent)
3455 (forward-line)
3456 (setq indent (current-indentation))
3457 (while
3458 (cond
3459 ;; Stop at end of the buffer.
3460 ((eobp) nil)
3461 ;; Continue if the current line is blank
3462 ((markdown-cur-line-blank-p) t)
3463 ;; Continue while indentation is the same or greater
3464 ((>= indent level) t)
3465 ;; Stop if current indentation is less than list item
3466 ;; and the previous line was blank.
3467 ((and (< indent level)
3468 (markdown-prev-line-blank-p))
3469 nil)
3470 ;; Stop at a new list item of the same or lesser indentation
3471 ((looking-at-p markdown-regex-list) nil)
3472 ;; Stop at a header
3473 ((looking-at-p markdown-regex-header) nil)
3474 ;; Stop at a horizontal rule
3475 ((looking-at-p markdown-regex-hr) nil)
3476 ;; Otherwise, continue.
3477 (t t))
3478 (forward-line)
3479 (setq indent (current-indentation)))
3480 ;; Don't skip over whitespace for empty list items (marker and
3481 ;; whitespace only), just move to end of whitespace.
3482 (save-match-data
3483 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3484 (goto-char (match-end 3))
3485 (skip-syntax-backward "-")))
3486 (point)))
3488 (defun markdown-cur-list-item-bounds (&optional matched)
3489 "Return bounds of list item at point (possibly already MATCHED).
3490 Return a list of the following form:
3492 (begin end indent nonlist-indent marker checkbox)
3494 The named components are:
3496 - begin: Position of beginning of list item, including leading indentation.
3497 - end: Position of the end of the list item, including list item text.
3498 - indent: Number of characters of indentation before list marker (an integer).
3499 - nonlist-indent: Number characters of indentation, list
3500 marker, and whitespace following list marker (an integer).
3501 - marker: String containing the list marker and following whitespace
3502 (e.g., \"- \" or \"* \").
3503 - checkbox: String containing the GFM checkbox portion, if any,
3504 including any trailing whitespace before the text
3505 begins (e.g., \"[x] \").
3507 As an example, for the following unordered list item
3509 - item
3511 the returned list would be
3513 (1 14 3 5 \"- \" nil)
3515 If the point is not inside a list item, return nil.
3516 Leave match data intact for `markdown-regex-list'."
3517 (save-excursion
3518 (let ((cur (point)))
3519 (end-of-line)
3520 (when (or matched (re-search-backward markdown-regex-list nil t))
3521 (let* ((begin (match-beginning 0))
3522 (indent (length (match-string-no-properties 1)))
3523 (nonlist-indent (length (match-string 0)))
3524 (marker (concat (match-string-no-properties 2)
3525 (match-string-no-properties 3)))
3526 (checkbox (progn (goto-char (match-end 0))
3527 (when (looking-at "\\[[xX ]\\]\\s-*")
3528 (match-string-no-properties 0))))
3529 (end (markdown-cur-list-item-end nonlist-indent)))
3530 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3531 (list begin end indent nonlist-indent marker checkbox)))))))
3533 (defun markdown-list-item-at-point-p ()
3534 "Return t if there is a list item at the point and nil otherwise."
3535 (save-match-data (markdown-cur-list-item-bounds)))
3537 (defun markdown-prev-list-item-bounds ()
3538 "Return bounds of previous item in the same list of any level.
3539 The return value has the same form as that of
3540 `markdown-cur-list-item-bounds'."
3541 (save-excursion
3542 (let ((cur-bounds (markdown-cur-list-item-bounds))
3543 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3544 stop)
3545 (when cur-bounds
3546 (goto-char (nth 0 cur-bounds))
3547 (while (and (not stop) (not (bobp))
3548 (re-search-backward markdown-regex-list
3549 beginning-of-list t))
3550 (unless (or (looking-at markdown-regex-hr)
3551 (markdown-code-block-at-point-p))
3552 (setq stop (point))))
3553 (markdown-cur-list-item-bounds)))))
3555 (defun markdown-next-list-item-bounds ()
3556 "Return bounds of next item in the same list of any level.
3557 The return value has the same form as that of
3558 `markdown-cur-list-item-bounds'."
3559 (save-excursion
3560 (let ((cur-bounds (markdown-cur-list-item-bounds))
3561 (end-of-list (save-excursion (markdown-end-of-list)))
3562 stop)
3563 (when cur-bounds
3564 (goto-char (nth 0 cur-bounds))
3565 (end-of-line)
3566 (while (and (not stop) (not (eobp))
3567 (re-search-forward markdown-regex-list
3568 end-of-list t))
3569 (unless (or (looking-at markdown-regex-hr)
3570 (markdown-code-block-at-point-p))
3571 (setq stop (point))))
3572 (when stop
3573 (markdown-cur-list-item-bounds))))))
3575 (defun markdown-beginning-of-list ()
3576 "Move point to beginning of list at point, if any."
3577 (interactive)
3578 (let ((orig-point (point))
3579 (list-begin (save-excursion
3580 (markdown-search-backward-baseline)
3581 ;; Stop at next list item, regardless of the indentation.
3582 (markdown-next-list-item (point-max))
3583 (when (looking-at markdown-regex-list)
3584 (point)))))
3585 (when (and list-begin (<= list-begin orig-point))
3586 (goto-char list-begin))))
3588 (defun markdown-end-of-list ()
3589 "Move point to end of list at point, if any."
3590 (interactive)
3591 (let ((start (point))
3592 (end (save-excursion
3593 (when (markdown-beginning-of-list)
3594 ;; Items can't have nonlist-indent <= 1, so this
3595 ;; moves past all list items.
3596 (markdown-next-list-item 1)
3597 (skip-syntax-backward "-")
3598 (unless (eobp) (forward-char 1))
3599 (point)))))
3600 (when (and end (>= end start))
3601 (goto-char end))))
3603 (defun markdown-up-list ()
3604 "Move point to beginning of parent list item."
3605 (interactive)
3606 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3607 (when cur-bounds
3608 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3609 (let ((up-bounds (markdown-cur-list-item-bounds)))
3610 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3611 (point))))))
3613 (defun markdown-bounds-of-thing-at-point (thing)
3614 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3615 Does not include trailing newlines when THING is 'line. Handles the
3616 end of buffer case by setting both endpoints equal to the value of
3617 `point-max', since an empty region will trigger empty markup insertion.
3618 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3619 (let* ((bounds (bounds-of-thing-at-point thing))
3620 (a (car bounds))
3621 (b (cdr bounds)))
3622 (when bounds
3623 (when (eq thing 'line)
3624 (cond ((and (eobp) (markdown-cur-line-blank-p))
3625 (setq a b))
3626 ((char-equal (char-before b) ?\^J)
3627 (setq b (1- b)))))
3628 (cons a b))))
3630 (defun markdown-reference-definition (reference)
3631 "Find out whether Markdown REFERENCE is defined.
3632 REFERENCE should not include the square brackets.
3633 When REFERENCE is defined, return a list of the form (text start end)
3634 containing the definition text itself followed by the start and end
3635 locations of the text. Otherwise, return nil.
3636 Leave match data for `markdown-regex-reference-definition'
3637 intact additional processing."
3638 (let ((reference (downcase reference)))
3639 (save-excursion
3640 (goto-char (point-min))
3641 (catch 'found
3642 (while (re-search-forward markdown-regex-reference-definition nil t)
3643 (when (string= reference (downcase (match-string-no-properties 2)))
3644 (throw 'found
3645 (list (match-string-no-properties 5)
3646 (match-beginning 5) (match-end 5)))))))))
3648 (defun markdown-get-defined-references ()
3649 "Return a list of all defined reference labels (not including square brackets)."
3650 (save-excursion
3651 (goto-char (point-min))
3652 (let (refs)
3653 (while (re-search-forward markdown-regex-reference-definition nil t)
3654 (let ((target (match-string-no-properties 2)))
3655 (cl-pushnew target refs :test #'equal)))
3656 (reverse refs))))
3658 (defun markdown-get-used-uris ()
3659 "Return a list of all used URIs in the buffer."
3660 (save-excursion
3661 (goto-char (point-min))
3662 (let (uris)
3663 (while (re-search-forward
3664 (concat "\\(?:" markdown-regex-link-inline
3665 "\\|" markdown-regex-angle-uri
3666 "\\|" markdown-regex-uri
3667 "\\|" markdown-regex-email
3668 "\\)")
3669 nil t)
3670 (unless (or (markdown-inline-code-at-point-p)
3671 (markdown-code-block-at-point-p))
3672 (cl-pushnew (or (match-string-no-properties 6)
3673 (match-string-no-properties 10)
3674 (match-string-no-properties 12)
3675 (match-string-no-properties 13))
3676 uris :test #'equal)))
3677 (reverse uris))))
3679 (defun markdown-inline-code-at-pos (pos)
3680 "Return non-nil if there is an inline code fragment at POS.
3681 Return nil otherwise. Set match data according to
3682 `markdown-match-code' upon success.
3683 This function searches the block for a code fragment that
3684 contains the point using `markdown-match-code'. We do this
3685 because `thing-at-point-looking-at' does not work reliably with
3686 `markdown-regex-code'.
3688 The match data is set as follows:
3689 Group 1 matches the opening backquotes.
3690 Group 2 matches the code fragment itself, without backquotes.
3691 Group 3 matches the closing backquotes."
3692 (save-excursion
3693 (goto-char pos)
3694 (let ((old-point (point))
3695 (end-of-block (progn (markdown-end-of-text-block) (point)))
3696 found)
3697 (markdown-beginning-of-text-block)
3698 (while (and (markdown-match-code end-of-block)
3699 (setq found t)
3700 (< (match-end 0) old-point)))
3701 (and found ; matched something
3702 (<= (match-beginning 0) old-point) ; match contains old-point
3703 (>= (match-end 0) old-point)))))
3705 (defun markdown-inline-code-at-pos-p (pos)
3706 "Return non-nil if there is an inline code fragment at POS.
3707 Like `markdown-inline-code-at-pos`, but preserves match data."
3708 (save-match-data (markdown-inline-code-at-pos pos)))
3710 (defun markdown-inline-code-at-point ()
3711 "Return non-nil if the point is at an inline code fragment.
3712 See `markdown-inline-code-at-pos' for details."
3713 (markdown-inline-code-at-pos (point)))
3715 (defun markdown-inline-code-at-point-p ()
3716 "Return non-nil if there is inline code at the point.
3717 This is a predicate function counterpart to
3718 `markdown-inline-code-at-point' which does not modify the match
3719 data. See `markdown-code-block-at-point-p' for code blocks."
3720 (save-match-data (markdown-inline-code-at-pos (point))))
3722 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3724 (defun markdown-code-block-at-pos (pos)
3725 "Return match data list if there is a code block at POS.
3726 Uses text properties at the beginning of the line position.
3727 This includes pre blocks, tilde-fenced code blocks, and GFM
3728 quoted code blocks. Return nil otherwise."
3729 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3730 (or (get-text-property pos 'markdown-pre)
3731 (markdown-get-enclosing-fenced-block-construct pos)
3732 ;; polymode removes text properties set by markdown-mode, so
3733 ;; check if `poly-markdown-mode' is active and whether the
3734 ;; `chunkmode' property is non-nil at POS.
3735 (and (bound-and-true-p poly-markdown-mode)
3736 (get-text-property pos 'chunkmode))))
3738 ;; Function was renamed to emphasize that it does not modify match-data.
3739 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3741 (defun markdown-code-block-at-point-p ()
3742 "Return non-nil if there is a code block at the point.
3743 This includes pre blocks, tilde-fenced code blocks, and GFM
3744 quoted code blocks. This function does not modify the match
3745 data. See `markdown-inline-code-at-point-p' for inline code."
3746 (save-match-data (markdown-code-block-at-pos (point))))
3748 (defun markdown-heading-at-point ()
3749 "Return non-nil if there is a heading at the point.
3750 Set match data for `markdown-regex-header'."
3751 (let ((match-data (get-text-property (point) 'markdown-heading)))
3752 (when match-data
3753 (set-match-data match-data)
3754 t)))
3756 (defun markdown-pipe-at-bol-p ()
3757 "Return non-nil if the line begins with a pipe symbol.
3758 This may be useful for tables and Pandoc's line_blocks extension."
3759 (char-equal (char-after (point-at-bol)) ?|))
3762 ;;; Markdown Font Lock Matching Functions =====================================
3764 (defun markdown-range-property-any (begin end prop prop-values)
3765 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3766 Also returns t if PROP is a list containing one of the PROP-VALUES.
3767 Return nil otherwise."
3768 (let (props)
3769 (catch 'found
3770 (dolist (loc (number-sequence begin end))
3771 (when (setq props (get-text-property loc prop))
3772 (cond ((listp props)
3773 ;; props is a list, check for membership
3774 (dolist (val prop-values)
3775 (when (memq val props) (throw 'found loc))))
3777 ;; props is a scalar, check for equality
3778 (dolist (val prop-values)
3779 (when (eq val props) (throw 'found loc))))))))))
3781 (defun markdown-range-properties-exist (begin end props)
3782 (cl-loop
3783 for loc in (number-sequence begin end)
3784 with result = nil
3785 while (not
3786 (setq result
3787 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3788 finally return result))
3790 (defun markdown-match-inline-generic (regex last &optional faceless)
3791 "Match inline REGEX from the point to LAST.
3792 When FACELESS is non-nil, do not return matches where faces have been applied."
3793 (when (re-search-forward regex last t)
3794 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3795 (face (and faceless (text-property-not-all
3796 (match-beginning 0) (match-end 0) 'face nil))))
3797 (cond
3798 ;; In code block: move past it and recursively search again
3799 (bounds
3800 (when (< (goto-char (cl-second bounds)) last)
3801 (markdown-match-inline-generic regex last faceless)))
3802 ;; When faces are found in the match range, skip over the match and
3803 ;; recursively search again.
3804 (face
3805 (when (< (goto-char (match-end 0)) last)
3806 (markdown-match-inline-generic regex last faceless)))
3807 ;; Keep match data and return t when in bounds.
3809 (<= (match-end 0) last))))))
3811 (defun markdown-match-code (last)
3812 "Match inline code fragments from point to LAST."
3813 (unless (bobp)
3814 (backward-char 1))
3815 (when (markdown-match-inline-generic markdown-regex-code last)
3816 (let ((begin (match-beginning 1))
3817 (end (match-end 1))
3818 (open-begin (match-beginning 2))
3819 (open-end (match-end 2))
3820 (code-begin (match-beginning 3))
3821 (code-end (match-end 3))
3822 (close-begin (match-beginning 4))
3823 (close-end (match-end 4)))
3824 (if (or (markdown-in-comment-p begin)
3825 (markdown-in-comment-p end)
3826 (markdown-code-block-at-pos begin))
3827 (progn (goto-char (min (1+ begin) last))
3828 (when (< (point) last)
3829 (markdown-match-code last)))
3830 (set-match-data (list begin end
3831 open-begin open-end
3832 code-begin code-end
3833 close-begin close-end))
3834 t))))
3836 (defun markdown-match-bold (last)
3837 "Match inline bold from the point to LAST."
3838 (when (markdown-match-inline-generic markdown-regex-bold last)
3839 (let ((begin (match-beginning 2))
3840 (end (match-end 2)))
3841 (if (or (markdown-inline-code-at-pos-p begin)
3842 (markdown-inline-code-at-pos-p end)
3843 (markdown-in-comment-p)
3844 (markdown-range-property-any
3845 begin begin 'face '(markdown-url-face
3846 markdown-plain-url-face))
3847 (markdown-range-property-any
3848 begin end 'face '(markdown-math-face)))
3849 (progn (goto-char (min (1+ begin) last))
3850 (when (< (point) last)
3851 (markdown-match-italic last)))
3852 (set-match-data (list (match-beginning 2) (match-end 2)
3853 (match-beginning 3) (match-end 3)
3854 (match-beginning 4) (match-end 4)
3855 (match-beginning 5) (match-end 5)))
3856 t))))
3858 (defun markdown-match-italic (last)
3859 "Match inline italics from the point to LAST."
3860 (let ((regex (if (eq major-mode 'gfm-mode)
3861 markdown-regex-gfm-italic markdown-regex-italic)))
3862 (when (markdown-match-inline-generic regex last)
3863 (let ((begin (match-beginning 1))
3864 (end (match-end 1)))
3865 (if (or (markdown-inline-code-at-pos-p begin)
3866 (markdown-inline-code-at-pos-p end)
3867 (markdown-in-comment-p)
3868 (markdown-range-property-any
3869 begin begin 'face '(markdown-url-face
3870 markdown-plain-url-face))
3871 (markdown-range-property-any
3872 begin end 'face '(markdown-bold-face
3873 markdown-list-face
3874 markdown-math-face)))
3875 (progn (goto-char (min (1+ begin) last))
3876 (when (< (point) last)
3877 (markdown-match-italic last)))
3878 (set-match-data (list (match-beginning 1) (match-end 1)
3879 (match-beginning 2) (match-end 2)
3880 (match-beginning 3) (match-end 3)
3881 (match-beginning 4) (match-end 4)))
3882 t)))))
3884 (defun markdown-match-math-generic (regex last)
3885 "Match REGEX from point to LAST.
3886 REGEX is either `markdown-regex-math-inline-single' for matching
3887 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3888 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3889 (let ((begin (match-beginning 1)) (end (match-end 1)))
3890 (prog1
3891 (if (or (markdown-range-property-any
3892 begin end 'face (list markdown-inline-code-face
3893 markdown-bold-face))
3894 (markdown-range-properties-exist
3895 begin end
3896 (markdown-get-fenced-block-middle-properties)))
3897 (markdown-match-math-generic regex last)
3899 (goto-char (1+ (match-end 0)))))))
3901 (defun markdown-match-list-items (last)
3902 "Match list items from point to LAST."
3903 (when (markdown-match-inline-generic markdown-regex-list last)
3904 (let ((begin (match-beginning 2))
3905 (end (match-end 2)))
3906 (if (or (markdown-range-property-any
3907 begin end 'face (list markdown-inline-code-face
3908 markdown-bold-face
3909 markdown-math-face))
3910 (markdown-range-properties-exist begin end '(markdown-hr))
3911 (markdown-in-comment-p))
3912 (progn (goto-char (min (1+ (match-end 0)) last))
3913 (markdown-match-list-items last))
3914 (set-match-data (list (match-beginning 0) (match-end 0)
3915 (match-beginning 1) (match-end 1)
3916 (match-beginning 2) (match-end 2)))
3917 (goto-char (1+ (match-end 0)))))))
3919 (defun markdown-match-math-single (last)
3920 "Match single quoted $..$ math from point to LAST."
3921 (markdown-match-math-generic markdown-regex-math-inline-single last))
3923 (defun markdown-match-math-double (last)
3924 "Match double quoted $$..$$ math from point to LAST."
3925 (markdown-match-math-generic markdown-regex-math-inline-double last))
3927 (defun markdown-match-math-display (last)
3928 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
3929 (markdown-match-math-generic markdown-regex-math-display last))
3931 (defun markdown-match-propertized-text (property last)
3932 "Match text with PROPERTY from point to LAST.
3933 Restore match data previously stored in PROPERTY."
3934 (let ((saved (get-text-property (point) property))
3935 pos)
3936 (unless saved
3937 (setq pos (next-single-char-property-change (point) property nil last))
3938 (setq saved (get-text-property pos property)))
3939 (when saved
3940 (set-match-data saved)
3941 ;; Step at least one character beyond point. Otherwise
3942 ;; `font-lock-fontify-keywords-region' infloops.
3943 (goto-char (min (1+ (max (match-end 0) (point)))
3944 (point-max)))
3945 saved)))
3947 (defun markdown-match-pre-blocks (last)
3948 "Match preformatted blocks from point to LAST.
3949 Use data stored in 'markdown-pre text property during syntax
3950 analysis."
3951 (markdown-match-propertized-text 'markdown-pre last))
3953 (defun markdown-match-gfm-code-blocks (last)
3954 "Match GFM quoted code blocks from point to LAST.
3955 Use data stored in 'markdown-gfm-code text property during syntax
3956 analysis."
3957 (markdown-match-propertized-text 'markdown-gfm-code last))
3959 (defun markdown-match-gfm-open-code-blocks (last)
3960 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
3962 (defun markdown-match-gfm-close-code-blocks (last)
3963 (markdown-match-propertized-text 'markdown-gfm-block-end last))
3965 (defun markdown-match-fenced-code-blocks (last)
3966 "Match fenced code blocks from the point to LAST."
3967 (markdown-match-propertized-text 'markdown-fenced-code last))
3969 (defun markdown-match-fenced-start-code-block (last)
3970 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
3972 (defun markdown-match-fenced-end-code-block (last)
3973 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
3975 (defun markdown-match-blockquotes (last)
3976 "Match blockquotes from point to LAST.
3977 Use data stored in 'markdown-blockquote text property during syntax
3978 analysis."
3979 (markdown-match-propertized-text 'markdown-blockquote last))
3981 (defun markdown-match-hr (last)
3982 "Match horizontal rules comments from the point to LAST."
3983 (markdown-match-propertized-text 'markdown-hr last))
3985 (defun markdown-match-comments (last)
3986 "Match HTML comments from the point to LAST."
3987 (when (and (skip-syntax-forward "^<" last))
3988 (let ((beg (point)))
3989 (when (and (skip-syntax-forward "^>" last) (< (point) last))
3990 (forward-char)
3991 (set-match-data (list beg (point)))
3992 t))))
3994 (defun markdown-match-generic-links (last ref)
3995 "Match inline links from point to LAST.
3996 When REF is non-nil, match reference links instead of standard
3997 links with URLs."
3998 ;; Search for the next potential link (not in a code block).
3999 (while (and (progn
4000 ;; Clear match data to test for a match after functions returns.
4001 (set-match-data nil)
4002 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
4003 ;; Keep searching if this is in a code block, inline
4004 ;; code, or a comment, or if it is include syntax.
4005 (or (markdown-code-block-at-point-p)
4006 (markdown-inline-code-at-pos-p (match-beginning 0))
4007 (markdown-inline-code-at-pos-p (match-end 0))
4008 (markdown-in-comment-p)
4009 (and (char-equal (char-after (point-at-bol)) ?<)
4010 (char-equal (char-after (1+ (point-at-bol))) ?<)))
4011 (< (point) last)))
4012 ;; Match opening exclamation point (optional) and left bracket.
4013 (when (match-beginning 2)
4014 (let* ((bang (match-beginning 1))
4015 (first-begin (match-beginning 2))
4016 ;; Find end of block to prevent matching across blocks.
4017 (end-of-block (save-excursion
4018 (progn
4019 (goto-char (match-beginning 2))
4020 (markdown-end-of-text-block)
4021 (point))))
4022 ;; Move over balanced expressions to closing right bracket.
4023 ;; Catch unbalanced expression errors and return nil.
4024 (first-end (condition-case nil
4025 (and (goto-char first-begin)
4026 (scan-sexps (point) 1))
4027 (error nil)))
4028 ;; Continue with point at CONT-POINT upon failure.
4029 (cont-point (min (1+ first-begin) last))
4030 second-begin second-end url-begin url-end
4031 title-begin title-end)
4032 ;; When bracket found, in range, and followed by a left paren/bracket...
4033 (when (and first-end (< first-end end-of-block) (goto-char first-end)
4034 (char-equal (char-after (point)) (if ref ?\[ ?\()))
4035 ;; Scan across balanced expressions for closing parenthesis/bracket.
4036 (setq second-begin (point)
4037 second-end (condition-case nil
4038 (scan-sexps (point) 1)
4039 (error nil)))
4040 ;; Check that closing parenthesis/bracket is in range.
4041 (if (and second-end (<= second-end end-of-block) (<= second-end last))
4042 (progn
4043 ;; Search for (optional) title inside closing parenthesis
4044 (when (and (not ref) (search-forward "\"" second-end t))
4045 (setq title-begin (1- (point))
4046 title-end (and (goto-char second-end)
4047 (search-backward "\"" (1+ title-begin) t))
4048 title-end (and title-end (1+ title-end))))
4049 ;; Store URL/reference range
4050 (setq url-begin (1+ second-begin)
4051 url-end (1- (or title-begin second-end)))
4052 ;; Set match data, move point beyond link, and return
4053 (set-match-data
4054 (list (or bang first-begin) second-end ; 0 - all
4055 bang (and bang (1+ bang)) ; 1 - bang
4056 first-begin (1+ first-begin) ; 2 - markup
4057 (1+ first-begin) (1- first-end) ; 3 - link text
4058 (1- first-end) first-end ; 4 - markup
4059 second-begin (1+ second-begin) ; 5 - markup
4060 url-begin url-end ; 6 - url/reference
4061 title-begin title-end ; 7 - title
4062 (1- second-end) second-end)) ; 8 - markup
4063 ;; Nullify cont-point and leave point at end and
4064 (setq cont-point nil)
4065 (goto-char second-end))
4066 ;; If no closing parenthesis in range, update continuation point
4067 (setq cont-point (min end-of-block second-begin))))
4068 (cond
4069 ;; On failure, continue searching at cont-point
4070 ((and cont-point (< cont-point last))
4071 (goto-char cont-point)
4072 (markdown-match-generic-links last ref))
4073 ;; No more text, return nil
4074 ((and cont-point (= cont-point last))
4075 nil)
4076 ;; Return t if a match occurred
4077 (t t)))))
4079 (defun markdown-match-inline-links (last)
4080 "Match standard inline links from point to LAST."
4081 (markdown-match-generic-links last nil))
4083 (defun markdown-match-reference-links (last)
4084 "Match inline reference links from point to LAST."
4085 (markdown-match-generic-links last t))
4087 (defun markdown-match-angle-uris (last)
4088 "Match angle bracket URIs from point to LAST."
4089 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
4090 (goto-char (1+ (match-end 0)))))
4092 (defun markdown-match-plain-uris (last)
4093 "Match plain URIs from point to LAST."
4094 (when (markdown-match-inline-generic markdown-regex-uri last t)
4095 (goto-char (1+ (match-end 0)))))
4097 (defvar markdown-conditional-search-function #'re-search-forward
4098 "Conditional search function used in `markdown-search-until-condition'.
4099 Made into a variable to allow for dynamic let-binding.")
4101 (defun markdown-search-until-condition (condition &rest args)
4102 (let (ret)
4103 (while (and (not ret) (apply markdown-conditional-search-function args))
4104 (setq ret (funcall condition)))
4105 ret))
4107 (defun markdown-match-generic-metadata
4108 (regexp last &optional block-begin-re block-end-re)
4109 "Match metadata declarations specified by REGEXP from point to LAST.
4110 These declarations must appear inside a metadata block specified
4111 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
4112 expression denoting the beginning of a metadata block. If it is
4113 nil, we assume metadata can only appear at the beginning of the
4114 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
4115 the end of a metadata block. If it is nil, assume blocks end with
4116 a blank line or the end of the buffer. There may be at most one such
4117 block in a file. Subsequent blocks will be ignored."
4118 (let* ((first (point))
4119 (begin-re (or block-begin-re "\\`"))
4120 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
4122 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4123 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4124 ;; (block-begin (or prev-block-begin next-block-begin))
4126 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4127 (re-search-forward begin-re last t))
4128 (match-end 0)))
4130 (block-end (and block-begin (goto-char block-begin)
4131 (re-search-forward end-re nil t))))
4132 (cond
4133 ;; Don't match declarations if there is no metadata block or if
4134 ;; the point is beyond the block. Move point to point-max to
4135 ;; prevent additional searches and return return nil since nothing
4136 ;; was found.
4137 ((or (null block-begin) (and block-end (> first block-end)))
4138 (goto-char (point-max))
4139 nil)
4140 ;; No declarations to match if a block was found but not in
4141 ;; range. Move point to LAST, to resume there, and return nil.
4142 ((> block-begin last)
4143 (goto-char last)
4144 nil)
4145 ;; If a block was found that begins before LAST and ends after
4146 ;; point, search for declarations inside it.
4148 ;; If the starting is before the beginning of the block, start
4149 ;; there. Otherwise, move back to FIRST.
4150 (goto-char (if (< first block-begin) block-begin first))
4151 (if (re-search-forward regexp (min last block-end) t)
4152 ;; If a metadata declaration is found, set match-data and return t.
4153 (let ((key-beginning (match-beginning 1))
4154 (key-end (match-end 1))
4155 (markup-begin (match-beginning 2))
4156 (markup-end (match-end 2))
4157 (value-beginning (match-beginning 3)))
4158 (set-match-data (list key-beginning (point) ; complete metadata
4159 key-beginning key-end ; key
4160 markup-begin markup-end ; markup
4161 value-beginning (point))) ; value
4163 ;; Otherwise, move the point to last and return nil
4164 (goto-char last)
4165 nil)))))
4167 (defun markdown-match-declarative-metadata (last)
4168 "Match declarative metadata from the point to LAST."
4169 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4171 (defun markdown-match-pandoc-metadata (last)
4172 "Match Pandoc metadata from the point to LAST."
4173 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4175 (defun markdown-match-yaml-metadata-begin (last)
4176 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4178 (defun markdown-match-yaml-metadata-end (last)
4179 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4181 (defun markdown-match-yaml-metadata-key (last)
4182 (markdown-match-propertized-text 'markdown-metadata-key last))
4184 (defun markdown-match-wiki-link (last)
4185 "Match wiki links from point to LAST."
4186 (when (and markdown-enable-wiki-links
4187 (not markdown-wiki-link-fontify-missing)
4188 (markdown-match-inline-generic markdown-regex-wiki-link last))
4189 (let ((begin (match-beginning 1)) (end (match-end 1)))
4190 (if (or (markdown-in-comment-p begin)
4191 (markdown-in-comment-p end)
4192 (markdown-inline-code-at-pos-p begin)
4193 (markdown-inline-code-at-pos-p end)
4194 (markdown-code-block-at-pos begin))
4195 (progn (goto-char (min (1+ begin) last))
4196 (when (< (point) last)
4197 (markdown-match-wiki-link last)))
4198 (set-match-data (list begin end))
4199 t))))
4201 (defun markdown-match-inline-attributes (last)
4202 "Match inline attributes from point to LAST."
4203 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4204 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4205 (markdown-inline-code-at-pos-p (match-end 0))
4206 (markdown-in-comment-p))
4207 t)))
4209 (defun markdown-match-leanpub-sections (last)
4210 "Match Leanpub section markers from point to LAST."
4211 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4212 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4213 (markdown-inline-code-at-pos-p (match-end 0))
4214 (markdown-in-comment-p))
4215 t)))
4217 (defun markdown-match-includes (last)
4218 "Match include statements from point to LAST.
4219 Sets match data for the following seven groups:
4220 Group 1: opening two angle brackets
4221 Group 2: opening title delimiter (optional)
4222 Group 3: title text (optional)
4223 Group 4: closing title delimiter (optional)
4224 Group 5: opening filename delimiter
4225 Group 6: filename
4226 Group 7: closing filename delimiter"
4227 (when (markdown-match-inline-generic markdown-regex-include last)
4228 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4229 (markdown-in-comment-p (match-end 0))
4230 (markdown-code-block-at-pos (match-beginning 0))))))
4231 (cond
4232 ;; Parentheses and maybe square brackets, but no curly braces:
4233 ;; match optional title in square brackets and file in parentheses.
4234 ((and valid (match-beginning 5)
4235 (not (match-beginning 8)))
4236 (set-match-data (list (match-beginning 1) (match-end 7)
4237 (match-beginning 1) (match-end 1)
4238 (match-beginning 2) (match-end 2)
4239 (match-beginning 3) (match-end 3)
4240 (match-beginning 4) (match-end 4)
4241 (match-beginning 5) (match-end 5)
4242 (match-beginning 6) (match-end 6)
4243 (match-beginning 7) (match-end 7))))
4244 ;; Only square brackets present: match file in square brackets.
4245 ((and valid (match-beginning 2)
4246 (not (match-beginning 5))
4247 (not (match-beginning 7)))
4248 (set-match-data (list (match-beginning 1) (match-end 4)
4249 (match-beginning 1) (match-end 1)
4250 nil nil
4251 nil nil
4252 nil nil
4253 (match-beginning 2) (match-end 2)
4254 (match-beginning 3) (match-end 3)
4255 (match-beginning 4) (match-end 4))))
4256 ;; Only curly braces present: match file in curly braces.
4257 ((and valid (match-beginning 8)
4258 (not (match-beginning 2))
4259 (not (match-beginning 5)))
4260 (set-match-data (list (match-beginning 1) (match-end 10)
4261 (match-beginning 1) (match-end 1)
4262 nil nil
4263 nil nil
4264 nil nil
4265 (match-beginning 8) (match-end 8)
4266 (match-beginning 9) (match-end 9)
4267 (match-beginning 10) (match-end 10))))
4269 ;; Not a valid match, move to next line and search again.
4270 (forward-line)
4271 (when (< (point) last)
4272 (setq valid (markdown-match-includes last)))))
4273 valid)))
4275 (defun markdown-match-html-tag (last)
4276 "Match HTML tags from point to LAST."
4277 (when (and markdown-enable-html
4278 (markdown-match-inline-generic markdown-regex-html-tag last t))
4279 (set-match-data (list (match-beginning 0) (match-end 0)
4280 (match-beginning 1) (match-end 1)
4281 (match-beginning 2) (match-end 2)
4282 (match-beginning 9) (match-end 9)))
4286 ;;; Markdown Font Fontification Functions =====================================
4288 (defun markdown--first-displayable (seq)
4289 "Return the first displayable character or string in SEQ.
4290 SEQ may be an atom or a sequence."
4291 (let ((seq (if (listp seq) seq (list seq))))
4292 (cond ((stringp (car seq))
4293 (cl-find-if
4294 (lambda (str)
4295 (and (mapcar #'char-displayable-p (string-to-list str))))
4296 seq))
4297 ((characterp (car seq))
4298 (cl-find-if #'char-displayable-p seq)))))
4300 (defun markdown--marginalize-string (level)
4301 "Generate atx markup string of given LEVEL for left margin."
4302 (let ((margin-left-space-count
4303 (- markdown-marginalize-headers-margin-width level)))
4304 (concat (make-string margin-left-space-count ? )
4305 (make-string level ?#))))
4307 (defun markdown-marginalize-update-current ()
4308 "Update the window configuration to create a left margin."
4309 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4310 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4311 (let* ((header-delimiter-font-width
4312 (window-font-width nil 'markdown-header-delimiter-face))
4313 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4314 header-delimiter-font-width))
4315 (margin-char-width (/ margin-pixel-width (default-font-width))))
4316 (set-window-margins nil margin-char-width))
4317 ;; As a fallback, simply set margin based on character count.
4318 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4320 (defun markdown-fontify-headings (last)
4321 "Add text properties to headings from point to LAST."
4322 (when (markdown-match-propertized-text 'markdown-heading last)
4323 (let* ((level (markdown-outline-level))
4324 (heading-face
4325 (intern (format "markdown-header-face-%d" level)))
4326 (heading-props `(face ,heading-face))
4327 (left-markup-props
4328 `(face markdown-header-delimiter-face
4329 ,@(cond
4330 (markdown-hide-markup
4331 `(display ""))
4332 (markdown-marginalize-headers
4333 `(display ((margin left-margin)
4334 ,(markdown--marginalize-string level)))))))
4335 (right-markup-props
4336 `(face markdown-header-delimiter-face
4337 ,@(when markdown-hide-markup `(display ""))))
4338 (rule-props `(face markdown-header-rule-face
4339 ,@(when markdown-hide-markup `(display "")))))
4340 (if (match-end 1)
4341 ;; Setext heading
4342 (progn (add-text-properties
4343 (match-beginning 1) (match-end 1) heading-props)
4344 (if (= level 1)
4345 (add-text-properties
4346 (match-beginning 2) (match-end 2) rule-props)
4347 (add-text-properties
4348 (match-beginning 3) (match-end 3) rule-props)))
4349 ;; atx heading
4350 (add-text-properties
4351 (match-beginning 4) (match-end 4) left-markup-props)
4352 (add-text-properties
4353 (match-beginning 5) (match-end 5) heading-props)
4354 (when (match-end 6)
4355 (add-text-properties
4356 (match-beginning 6) (match-end 6) right-markup-props))))
4359 (defun markdown-fontify-tables (last)
4360 (when (and (re-search-forward "|" last t)
4361 (markdown-table-at-point-p))
4362 (font-lock-append-text-property
4363 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
4364 'face 'markdown-table-face)
4365 (forward-line 1)
4368 (defun markdown-fontify-blockquotes (last)
4369 "Apply font-lock properties to blockquotes from point to LAST."
4370 (when (markdown-match-blockquotes last)
4371 (let ((display-string
4372 (markdown--first-displayable markdown-blockquote-display-char)))
4373 (add-text-properties
4374 (match-beginning 1) (match-end 1)
4375 (if markdown-hide-markup
4376 `(face markdown-blockquote-face display ,display-string)
4377 `(face markdown-markup-face)))
4378 (font-lock-append-text-property
4379 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4380 t)))
4382 (defun markdown-fontify-list-items (last)
4383 "Apply font-lock properties to list markers from point to LAST."
4384 (when (markdown-match-list-items last)
4385 (let* ((indent (length (match-string-no-properties 1)))
4386 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4387 (bullet (nth (mod level (length markdown-list-item-bullets))
4388 markdown-list-item-bullets)))
4389 (add-text-properties
4390 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4391 (when markdown-hide-markup
4392 (cond
4393 ;; Unordered lists
4394 ((string-match-p "[\\*\\+-]" (match-string 2))
4395 (add-text-properties
4396 (match-beginning 2) (match-end 2) `(display ,bullet)))
4397 ;; Definition lists
4398 ((string-equal ":" (match-string 2))
4399 (let ((display-string
4400 (char-to-string (markdown--first-displayable
4401 markdown-definition-display-char))))
4402 (add-text-properties (match-beginning 2) (match-end 2)
4403 `(display ,display-string)))))))
4406 (defun markdown-fontify-hrs (last)
4407 "Add text properties to horizontal rules from point to LAST."
4408 (when (markdown-match-hr last)
4409 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4410 (add-text-properties
4411 (match-beginning 0) (match-end 0)
4412 `(face markdown-hr-face
4413 font-lock-multiline t
4414 ,@(when (and markdown-hide-markup hr-char)
4415 `(display ,(make-string
4416 (window-body-width) hr-char)))))
4417 t)))
4419 (defun markdown-fontify-sub-superscripts (last)
4420 "Apply text properties to sub- and superscripts from point to LAST."
4421 (when (markdown-search-until-condition
4422 (lambda () (and (not (markdown-code-block-at-point-p))
4423 (not (markdown-inline-code-at-point-p))
4424 (not (markdown-in-comment-p))))
4425 markdown-regex-sub-superscript last t)
4426 (let* ((subscript-p (string= (match-string 2) "~"))
4427 (props
4428 (if subscript-p
4429 (car markdown-sub-superscript-display)
4430 (cdr markdown-sub-superscript-display)))
4431 (mp (list 'face 'markdown-markup-face
4432 'invisible 'markdown-markup)))
4433 (when markdown-hide-markup
4434 (put-text-property (match-beginning 3) (match-end 3)
4435 'display props))
4436 (add-text-properties (match-beginning 2) (match-end 2) mp)
4437 (add-text-properties (match-beginning 4) (match-end 4) mp)
4438 t)))
4441 ;;; Syntax Table ==============================================================
4443 (defvar markdown-mode-syntax-table
4444 (let ((tab (make-syntax-table text-mode-syntax-table)))
4445 (modify-syntax-entry ?\" "." tab)
4446 tab)
4447 "Syntax table for `markdown-mode'.")
4450 ;;; Element Insertion =========================================================
4452 (defun markdown-ensure-blank-line-before ()
4453 "If previous line is not already blank, insert a blank line before point."
4454 (unless (bolp) (insert "\n"))
4455 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4457 (defun markdown-ensure-blank-line-after ()
4458 "If following line is not already blank, insert a blank line after point.
4459 Return the point where it was originally."
4460 (save-excursion
4461 (unless (eolp) (insert "\n"))
4462 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4464 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4465 "Insert the strings S1 and S2, wrapping around region or THING.
4466 If a region is specified by the optional BEG and END arguments,
4467 wrap the strings S1 and S2 around that region.
4468 If there is an active region, wrap the strings S1 and S2 around
4469 the region. If there is not an active region but the point is at
4470 THING, wrap that thing (which defaults to word). Otherwise, just
4471 insert S1 and S2 and place the point in between. Return the
4472 bounds of the entire wrapped string, or nil if nothing was wrapped
4473 and S1 and S2 were only inserted."
4474 (let (a b bounds new-point)
4475 (cond
4476 ;; Given region
4477 ((and beg end)
4478 (setq a beg
4479 b end
4480 new-point (+ (point) (length s1))))
4481 ;; Active region
4482 ((markdown-use-region-p)
4483 (setq a (region-beginning)
4484 b (region-end)
4485 new-point (+ (point) (length s1))))
4486 ;; Thing (word) at point
4487 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4488 (setq a (car bounds)
4489 b (cdr bounds)
4490 new-point (+ (point) (length s1))))
4491 ;; No active region and no word
4493 (setq a (point)
4494 b (point))))
4495 (goto-char b)
4496 (insert s2)
4497 (goto-char a)
4498 (insert s1)
4499 (when new-point (goto-char new-point))
4500 (if (= a b)
4502 (setq b (+ b (length s1) (length s2)))
4503 (cons a b))))
4505 (defun markdown-point-after-unwrap (cur prefix suffix)
4506 "Return desired position of point after an unwrapping operation.
4507 CUR gives the position of the point before the operation.
4508 Additionally, two cons cells must be provided. PREFIX gives the
4509 bounds of the prefix string and SUFFIX gives the bounds of the
4510 suffix string."
4511 (cond ((< cur (cdr prefix)) (car prefix))
4512 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4513 ((<= cur (cdr suffix))
4514 (- cur (+ (- (cdr prefix) (car prefix))
4515 (- cur (car suffix)))))
4516 (t cur)))
4518 (defun markdown-unwrap-thing-at-point (regexp all text)
4519 "Remove prefix and suffix of thing at point and reposition the point.
4520 When the thing at point matches REGEXP, replace the subexpression
4521 ALL with the string in subexpression TEXT. Reposition the point
4522 in an appropriate location accounting for the removal of prefix
4523 and suffix strings. Return new bounds of string from group TEXT.
4524 When REGEXP is nil, assumes match data is already set."
4525 (when (or (null regexp)
4526 (thing-at-point-looking-at regexp))
4527 (let ((cur (point))
4528 (prefix (cons (match-beginning all) (match-beginning text)))
4529 (suffix (cons (match-end text) (match-end all)))
4530 (bounds (cons (match-beginning text) (match-end text))))
4531 ;; Replace the thing at point
4532 (replace-match (match-string text) t t nil all)
4533 ;; Reposition the point
4534 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4535 ;; Adjust bounds
4536 (setq bounds (cons (car prefix)
4537 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4539 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4540 "Remove prefix and suffix of all things in region from BEG to END.
4541 When a thing in the region matches REGEXP, replace the
4542 subexpression ALL with the string in subexpression TEXT.
4543 Return a cons cell containing updated bounds for the region."
4544 (save-excursion
4545 (goto-char beg)
4546 (let ((removed 0) len-all len-text)
4547 (while (re-search-forward regexp (- end removed) t)
4548 (setq len-all (length (match-string-no-properties all)))
4549 (setq len-text (length (match-string-no-properties text)))
4550 (setq removed (+ removed (- len-all len-text)))
4551 (replace-match (match-string text) t t nil all))
4552 (cons beg (- end removed)))))
4554 (defun markdown-insert-hr (arg)
4555 "Insert or replace a horizonal rule.
4556 By default, use the first element of `markdown-hr-strings'. When
4557 ARG is non-nil, as when given a prefix, select a different
4558 element as follows. When prefixed with \\[universal-argument],
4559 use the last element of `markdown-hr-strings' instead. When
4560 prefixed with an integer from 1 to the length of
4561 `markdown-hr-strings', use the element in that position instead."
4562 (interactive "*P")
4563 (when (thing-at-point-looking-at markdown-regex-hr)
4564 (delete-region (match-beginning 0) (match-end 0)))
4565 (markdown-ensure-blank-line-before)
4566 (cond ((equal arg '(4))
4567 (insert (car (reverse markdown-hr-strings))))
4568 ((and (integerp arg) (> arg 0)
4569 (<= arg (length markdown-hr-strings)))
4570 (insert (nth (1- arg) markdown-hr-strings)))
4572 (insert (car markdown-hr-strings))))
4573 (markdown-ensure-blank-line-after))
4575 (defun markdown-insert-bold ()
4576 "Insert markup to make a region or word bold.
4577 If there is an active region, make the region bold. If the point
4578 is at a non-bold word, make the word bold. If the point is at a
4579 bold word or phrase, remove the bold markup. Otherwise, simply
4580 insert bold delimiters and place the point in between them."
4581 (interactive)
4582 (let ((delim (if markdown-bold-underscore "__" "**")))
4583 (if (markdown-use-region-p)
4584 ;; Active region
4585 (let ((bounds (markdown-unwrap-things-in-region
4586 (region-beginning) (region-end)
4587 markdown-regex-bold 2 4)))
4588 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4589 ;; Bold markup removal, bold word at point, or empty markup insertion
4590 (if (thing-at-point-looking-at markdown-regex-bold)
4591 (markdown-unwrap-thing-at-point nil 2 4)
4592 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4594 (defun markdown-insert-italic ()
4595 "Insert markup to make a region or word italic.
4596 If there is an active region, make the region italic. If the point
4597 is at a non-italic word, make the word italic. If the point is at an
4598 italic word or phrase, remove the italic markup. Otherwise, simply
4599 insert italic delimiters and place the point in between them."
4600 (interactive)
4601 (let ((delim (if markdown-italic-underscore "_" "*")))
4602 (if (markdown-use-region-p)
4603 ;; Active region
4604 (let ((bounds (markdown-unwrap-things-in-region
4605 (region-beginning) (region-end)
4606 markdown-regex-italic 1 3)))
4607 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4608 ;; Italic markup removal, italic word at point, or empty markup insertion
4609 (if (thing-at-point-looking-at markdown-regex-italic)
4610 (markdown-unwrap-thing-at-point nil 1 3)
4611 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4613 (defun markdown-insert-strike-through ()
4614 "Insert markup to make a region or word strikethrough.
4615 If there is an active region, make the region strikethrough. If the point
4616 is at a non-bold word, make the word strikethrough. If the point is at a
4617 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4618 simply insert bold delimiters and place the point in between them."
4619 (interactive)
4620 (let ((delim "~~"))
4621 (if (markdown-use-region-p)
4622 ;; Active region
4623 (let ((bounds (markdown-unwrap-things-in-region
4624 (region-beginning) (region-end)
4625 markdown-regex-strike-through 2 4)))
4626 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4627 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4628 (if (thing-at-point-looking-at markdown-regex-strike-through)
4629 (markdown-unwrap-thing-at-point nil 2 4)
4630 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4632 (defun markdown-insert-code ()
4633 "Insert markup to make a region or word an inline code fragment.
4634 If there is an active region, make the region an inline code
4635 fragment. If the point is at a word, make the word an inline
4636 code fragment. Otherwise, simply insert code delimiters and
4637 place the point in between them."
4638 (interactive)
4639 (if (markdown-use-region-p)
4640 ;; Active region
4641 (let ((bounds (markdown-unwrap-things-in-region
4642 (region-beginning) (region-end)
4643 markdown-regex-code 1 3)))
4644 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4645 ;; Code markup removal, code markup for word, or empty markup insertion
4646 (if (markdown-inline-code-at-point)
4647 (markdown-unwrap-thing-at-point nil 0 2)
4648 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4650 (defun markdown-insert-kbd ()
4651 "Insert markup to wrap region or word in <kbd> tags.
4652 If there is an active region, use the region. If the point is at
4653 a word, use the word. Otherwise, simply insert <kbd> tags and
4654 place the point in between them."
4655 (interactive)
4656 (if (markdown-use-region-p)
4657 ;; Active region
4658 (let ((bounds (markdown-unwrap-things-in-region
4659 (region-beginning) (region-end)
4660 markdown-regex-kbd 0 2)))
4661 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4662 ;; Markup removal, markup for word, or empty markup insertion
4663 (if (thing-at-point-looking-at markdown-regex-kbd)
4664 (markdown-unwrap-thing-at-point nil 0 2)
4665 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4667 (defun markdown-insert-inline-link (text url &optional title)
4668 "Insert an inline link with TEXT pointing to URL.
4669 Optionally, the user can provide a TITLE."
4670 (let ((cur (point)))
4671 (setq title (and title (concat " \"" title "\"")))
4672 (insert (concat "[" text "](" url title ")"))
4673 (cond ((not text) (goto-char (+ 1 cur)))
4674 ((not url) (goto-char (+ 3 (length text) cur))))))
4676 (defun markdown-insert-inline-image (text url &optional title)
4677 "Insert an inline link with alt TEXT pointing to URL.
4678 Optionally, also provide a TITLE."
4679 (let ((cur (point)))
4680 (setq title (and title (concat " \"" title "\"")))
4681 (insert (concat "![" text "](" url title ")"))
4682 (cond ((not text) (goto-char (+ 2 cur)))
4683 ((not url) (goto-char (+ 4 (length text) cur))))))
4685 (defun markdown-insert-reference-link (text label &optional url title)
4686 "Insert a reference link and, optionally, a reference definition.
4687 The link TEXT will be inserted followed by the optional LABEL.
4688 If a URL is given, also insert a definition for the reference
4689 LABEL according to `markdown-reference-location'. If a TITLE is
4690 given, it will be added to the end of the reference definition
4691 and will be used to populate the title attribute when converted
4692 to XHTML. If URL is nil, insert only the link portion (for
4693 example, when a reference label is already defined)."
4694 (insert (concat "[" text "][" label "]"))
4695 (when url
4696 (markdown-insert-reference-definition
4697 (if (string-equal label "") text label)
4698 url title)))
4700 (defun markdown-insert-reference-image (text label &optional url title)
4701 "Insert a reference image and, optionally, a reference definition.
4702 The alt TEXT will be inserted followed by the optional LABEL.
4703 If a URL is given, also insert a definition for the reference
4704 LABEL according to `markdown-reference-location'. If a TITLE is
4705 given, it will be added to the end of the reference definition
4706 and will be used to populate the title attribute when converted
4707 to XHTML. If URL is nil, insert only the link portion (for
4708 example, when a reference label is already defined)."
4709 (insert (concat "![" text "][" label "]"))
4710 (when url
4711 (markdown-insert-reference-definition
4712 (if (string-equal label "") text label)
4713 url title)))
4715 (defun markdown-insert-reference-definition (label &optional url title)
4716 "Add definition for reference LABEL with URL and TITLE.
4717 LABEL is a Markdown reference label without square brackets.
4718 URL and TITLE are optional. When given, the TITLE will
4719 be used to populate the title attribute when converted to XHTML."
4720 ;; END specifies where to leave the point upon return
4721 (let ((end (point)))
4722 (cl-case markdown-reference-location
4723 (end (goto-char (point-max)))
4724 (immediately (markdown-end-of-text-block))
4725 (subtree (markdown-end-of-subtree))
4726 (header (markdown-end-of-defun)))
4727 ;; Skip backwards over local variables. This logic is similar to the one
4728 ;; used in ‘hack-local-variables’.
4729 (when (and enable-local-variables (eobp))
4730 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4731 (when (let ((case-fold-search t))
4732 (search-forward "Local Variables:" nil :move))
4733 (beginning-of-line 0)
4734 (when (eq (char-before) ?\n) (backward-char))))
4735 (unless (or (markdown-cur-line-blank-p)
4736 (thing-at-point-looking-at markdown-regex-reference-definition))
4737 (insert "\n"))
4738 (insert "\n[" label "]: ")
4739 (if url
4740 (insert url)
4741 ;; When no URL is given, leave point at END following the colon
4742 (setq end (point)))
4743 (when (> (length title) 0)
4744 (insert " \"" title "\""))
4745 (unless (looking-at-p "\n")
4746 (insert "\n"))
4747 (goto-char end)
4748 (when url
4749 (message
4750 (markdown--substitute-command-keys
4751 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4752 label))))
4754 (define-obsolete-function-alias
4755 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4756 (define-obsolete-function-alias
4757 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4759 (defun markdown--insert-link-or-image (image)
4760 "Interactively insert new or update an existing link or image.
4761 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4762 This is an internal function called by
4763 `markdown-insert-link' and `markdown-insert-image'."
4764 (cl-multiple-value-bind (begin end text uri ref title)
4765 (if (markdown-use-region-p)
4766 ;; Use region as either link text or URL as appropriate.
4767 (let ((region (buffer-substring-no-properties
4768 (region-beginning) (region-end))))
4769 (if (string-match markdown-regex-uri region)
4770 ;; Region contains a URL; use it as such.
4771 (list (region-beginning) (region-end)
4772 nil (match-string 0 region) nil nil)
4773 ;; Region doesn't contain a URL, so use it as text.
4774 (list (region-beginning) (region-end)
4775 region nil nil nil)))
4776 ;; Extract and use properties of existing link, if any.
4777 (markdown-link-at-pos (point)))
4778 (let* ((ref (when ref (concat "[" ref "]")))
4779 (defined-refs (append
4780 (mapcar (lambda (ref) (concat "[" ref "]"))
4781 (markdown-get-defined-references))))
4782 (used-uris (markdown-get-used-uris))
4783 (uri-or-ref (completing-read
4784 "URL or [reference]: "
4785 (append defined-refs used-uris)
4786 nil nil (or uri ref)))
4787 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4788 (match-string 1 uri-or-ref))
4789 ((string-equal "" uri-or-ref)
4790 "")))
4791 (uri (unless ref uri-or-ref))
4792 (text-prompt (if image
4793 "Alt text: "
4794 (if ref
4795 "Link text: "
4796 "Link text (blank for plain URL): ")))
4797 (text (read-string text-prompt text))
4798 (text (if (= (length text) 0) nil text))
4799 (plainp (and uri (not text)))
4800 (implicitp (string-equal ref ""))
4801 (ref (if implicitp text ref))
4802 (definedp (and ref (markdown-reference-definition ref)))
4803 (ref-url (unless (or uri definedp)
4804 (completing-read "Reference URL: " used-uris)))
4805 (title (unless (or plainp definedp)
4806 (read-string "Title (tooltip text, optional): " title)))
4807 (title (if (= (length title) 0) nil title)))
4808 (when (and image implicitp)
4809 (user-error "Reference required: implicit image references are invalid"))
4810 (when (and begin end)
4811 (delete-region begin end))
4812 (cond
4813 ((and (not image) uri text)
4814 (markdown-insert-inline-link text uri title))
4815 ((and image uri text)
4816 (markdown-insert-inline-image text uri title))
4817 ((and ref text)
4818 (if image
4819 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4820 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4821 (unless definedp
4822 (markdown-insert-reference-definition ref ref-url title)))
4823 ((and (not image) uri)
4824 (markdown-insert-uri uri))))))
4826 (defun markdown-insert-link ()
4827 "Insert new or update an existing link, with interactive prompts.
4828 If the point is at an existing link or URL, update the link text,
4829 URL, reference label, and/or title. Otherwise, insert a new link.
4830 The type of link inserted (inline, reference, or plain URL)
4831 depends on which values are provided:
4833 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4834 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4835 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4836 * If only a URL is given, insert a plain link: <URL>.
4838 In other words, to create an implicit reference link, leave the
4839 URL prompt empty and to create a plain URL link, leave the link
4840 text empty.
4842 If there is an active region, use the text as the default URL, if
4843 it seems to be a URL, or link text value otherwise.
4845 If a given reference is not defined, this function will
4846 additionally prompt for the URL and optional title. In this case,
4847 the reference definition is placed at the location determined by
4848 `markdown-reference-location'.
4850 Through updating the link, this function can be used to convert a
4851 link of one type (inline, reference, or plain) to another type by
4852 selectively adding or removing information via the prompts."
4853 (interactive)
4854 (markdown--insert-link-or-image nil))
4856 (defun markdown-insert-image ()
4857 "Insert new or update an existing image, with interactive prompts.
4858 If the point is at an existing image, update the alt text, URL,
4859 reference label, and/or title. Otherwise, insert a new image.
4860 The type of image inserted (inline or reference) depends on which
4861 values are provided:
4863 * If a URL and ALT-TEXT are given, insert an inline image:
4864 ![ALT-TEXT](URL).
4865 * If [REF] and ALT-TEXT are given, insert a reference image:
4866 ![ALT-TEXT][REF].
4868 If there is an active region, use the text as the default URL, if
4869 it seems to be a URL, or alt text value otherwise.
4871 If a given reference is not defined, this function will
4872 additionally prompt for the URL and optional title. In this case,
4873 the reference definition is placed at the location determined by
4874 `markdown-reference-location'.
4876 Through updating the image, this function can be used to convert an
4877 image of one type (inline or reference) to another type by
4878 selectively adding or removing information via the prompts."
4879 (interactive)
4880 (markdown--insert-link-or-image t))
4882 (defun markdown-insert-uri (&optional uri)
4883 "Insert markup for an inline URI.
4884 If there is an active region, use it as the URI. If the point is
4885 at a URI, wrap it with angle brackets. If the point is at an
4886 inline URI, remove the angle brackets. Otherwise, simply insert
4887 angle brackets place the point between them."
4888 (interactive)
4889 (if (markdown-use-region-p)
4890 ;; Active region
4891 (let ((bounds (markdown-unwrap-things-in-region
4892 (region-beginning) (region-end)
4893 markdown-regex-angle-uri 0 2)))
4894 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4895 ;; Markup removal, URI at point, new URI, or empty markup insertion
4896 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4897 (markdown-unwrap-thing-at-point nil 0 2)
4898 (if uri
4899 (insert "<" uri ">")
4900 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4902 (defun markdown-insert-wiki-link ()
4903 "Insert a wiki link of the form [[WikiLink]].
4904 If there is an active region, use the region as the link text.
4905 If the point is at a word, use the word as the link text. If
4906 there is no active region and the point is not at word, simply
4907 insert link markup."
4908 (interactive)
4909 (if (markdown-use-region-p)
4910 ;; Active region
4911 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4912 ;; Markup removal, wiki link at at point, or empty markup insertion
4913 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4914 (if (or markdown-wiki-link-alias-first
4915 (null (match-string 5)))
4916 (markdown-unwrap-thing-at-point nil 1 3)
4917 (markdown-unwrap-thing-at-point nil 1 5))
4918 (markdown-wrap-or-insert "[[" "]]"))))
4920 (defun markdown-remove-header ()
4921 "Remove header markup if point is at a header.
4922 Return bounds of remaining header text if a header was removed
4923 and nil otherwise."
4924 (interactive "*")
4925 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
4926 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
4928 (defun markdown-insert-header (&optional level text setext)
4929 "Insert or replace header markup.
4930 The level of the header is specified by LEVEL and header text is
4931 given by TEXT. LEVEL must be an integer from 1 and 6, and the
4932 default value is 1.
4933 When TEXT is nil, the header text is obtained as follows.
4934 If there is an active region, it is used as the header text.
4935 Otherwise, the current line will be used as the header text.
4936 If there is not an active region and the point is at a header,
4937 remove the header markup and replace with level N header.
4938 Otherwise, insert empty header markup and place the point in
4939 between.
4940 The style of the header will be atx (hash marks) unless
4941 SETEXT is non-nil, in which case a setext-style (underlined)
4942 header will be inserted."
4943 (interactive "p\nsHeader text: ")
4944 (setq level (min (max (or level 1) 1) (if setext 2 6)))
4945 ;; Determine header text if not given
4946 (when (null text)
4947 (if (markdown-use-region-p)
4948 ;; Active region
4949 (setq text (delete-and-extract-region (region-beginning) (region-end)))
4950 ;; No active region
4951 (markdown-remove-header)
4952 (setq text (delete-and-extract-region
4953 (line-beginning-position) (line-end-position)))
4954 (when (and setext (string-match-p "^[ \t]*$" text))
4955 (setq text (read-string "Header text: "))))
4956 (setq text (markdown-compress-whitespace-string text)))
4957 ;; Insertion with given text
4958 (markdown-ensure-blank-line-before)
4959 (let (hdr)
4960 (cond (setext
4961 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
4962 (insert text "\n" hdr))
4964 (setq hdr (make-string level ?#))
4965 (insert hdr " " text)
4966 (when (null markdown-asymmetric-header) (insert " " hdr)))))
4967 (markdown-ensure-blank-line-after)
4968 ;; Leave point at end of text
4969 (cond (setext
4970 (backward-char (1+ (string-width text))))
4971 ((null markdown-asymmetric-header)
4972 (backward-char (1+ level)))))
4974 (defun markdown-insert-header-dwim (&optional arg setext)
4975 "Insert or replace header markup.
4976 The level and type of the header are determined automatically by
4977 the type and level of the previous header, unless a prefix
4978 argument is given via ARG.
4979 With a numeric prefix valued 1 to 6, insert a header of the given
4980 level, with the type being determined automatically (note that
4981 only level 1 or 2 setext headers are possible).
4983 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
4984 promote the heading by one level.
4985 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
4986 demote the heading by one level.
4987 When SETEXT is non-nil, prefer setext-style headers when
4988 possible (levels one and two).
4990 When there is an active region, use it for the header text. When
4991 the point is at an existing header, change the type and level
4992 according to the rules above.
4993 Otherwise, if the line is not empty, create a header using the
4994 text on the current line as the header text.
4995 Finally, if the point is on a blank line, insert empty header
4996 markup (atx) or prompt for text (setext).
4997 See `markdown-insert-header' for more details about how the
4998 header text is determined."
4999 (interactive "*P")
5000 (let (level)
5001 (save-excursion
5002 (when (or (thing-at-point-looking-at markdown-regex-header)
5003 (re-search-backward markdown-regex-header nil t))
5004 ;; level of current or previous header
5005 (setq level (markdown-outline-level))
5006 ;; match group 1 indicates a setext header
5007 (setq setext (match-end 1))))
5008 ;; check prefix argument
5009 (cond
5010 ((and (equal arg '(4)) level (> level 1)) ;; C-u
5011 (cl-decf level))
5012 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
5013 (cl-incf level))
5014 (arg ;; numeric prefix
5015 (setq level (prefix-numeric-value arg))))
5016 ;; setext headers must be level one or two
5017 (and level (setq setext (and setext (<= level 2))))
5018 ;; insert the heading
5019 (markdown-insert-header level nil setext)))
5021 (defun markdown-insert-header-setext-dwim (&optional arg)
5022 "Insert or replace header markup, with preference for setext.
5023 See `markdown-insert-header-dwim' for details, including how ARG is handled."
5024 (interactive "*P")
5025 (markdown-insert-header-dwim arg t))
5027 (defun markdown-insert-header-atx-1 ()
5028 "Insert a first level atx-style (hash mark) header.
5029 See `markdown-insert-header'."
5030 (interactive "*")
5031 (markdown-insert-header 1 nil nil))
5033 (defun markdown-insert-header-atx-2 ()
5034 "Insert a level two atx-style (hash mark) header.
5035 See `markdown-insert-header'."
5036 (interactive "*")
5037 (markdown-insert-header 2 nil nil))
5039 (defun markdown-insert-header-atx-3 ()
5040 "Insert a level three atx-style (hash mark) header.
5041 See `markdown-insert-header'."
5042 (interactive "*")
5043 (markdown-insert-header 3 nil nil))
5045 (defun markdown-insert-header-atx-4 ()
5046 "Insert a level four atx-style (hash mark) header.
5047 See `markdown-insert-header'."
5048 (interactive "*")
5049 (markdown-insert-header 4 nil nil))
5051 (defun markdown-insert-header-atx-5 ()
5052 "Insert a level five atx-style (hash mark) header.
5053 See `markdown-insert-header'."
5054 (interactive "*")
5055 (markdown-insert-header 5 nil nil))
5057 (defun markdown-insert-header-atx-6 ()
5058 "Insert a sixth level atx-style (hash mark) header.
5059 See `markdown-insert-header'."
5060 (interactive "*")
5061 (markdown-insert-header 6 nil nil))
5063 (defun markdown-insert-header-setext-1 ()
5064 "Insert a setext-style (underlined) first-level header.
5065 See `markdown-insert-header'."
5066 (interactive "*")
5067 (markdown-insert-header 1 nil t))
5069 (defun markdown-insert-header-setext-2 ()
5070 "Insert a setext-style (underlined) second-level header.
5071 See `markdown-insert-header'."
5072 (interactive "*")
5073 (markdown-insert-header 2 nil t))
5075 (defun markdown-blockquote-indentation (loc)
5076 "Return string containing necessary indentation for a blockquote at LOC.
5077 Also see `markdown-pre-indentation'."
5078 (save-excursion
5079 (goto-char loc)
5080 (let* ((list-level (length (markdown-calculate-list-levels)))
5081 (indent ""))
5082 (dotimes (_ list-level indent)
5083 (setq indent (concat indent " "))))))
5085 (defun markdown-insert-blockquote ()
5086 "Start a blockquote section (or blockquote the region).
5087 If Transient Mark mode is on and a region is active, it is used as
5088 the blockquote text."
5089 (interactive)
5090 (if (markdown-use-region-p)
5091 (markdown-blockquote-region (region-beginning) (region-end))
5092 (markdown-ensure-blank-line-before)
5093 (insert (markdown-blockquote-indentation (point)) "> ")
5094 (markdown-ensure-blank-line-after)))
5096 (defun markdown-block-region (beg end prefix)
5097 "Format the region using a block prefix.
5098 Arguments BEG and END specify the beginning and end of the
5099 region. The characters PREFIX will appear at the beginning
5100 of each line."
5101 (save-excursion
5102 (let* ((end-marker (make-marker))
5103 (beg-marker (make-marker))
5104 (prefix-without-trailing-whitespace
5105 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
5106 ;; Ensure blank line after and remove extra whitespace
5107 (goto-char end)
5108 (skip-syntax-backward "-")
5109 (set-marker end-marker (point))
5110 (delete-horizontal-space)
5111 (markdown-ensure-blank-line-after)
5112 ;; Ensure blank line before and remove extra whitespace
5113 (goto-char beg)
5114 (skip-syntax-forward "-")
5115 (delete-horizontal-space)
5116 (markdown-ensure-blank-line-before)
5117 (set-marker beg-marker (point))
5118 ;; Insert PREFIX before each line
5119 (goto-char beg-marker)
5120 (while (and (< (line-beginning-position) end-marker)
5121 (not (eobp)))
5122 ;; Don’t insert trailing whitespace.
5123 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
5124 (forward-line)))))
5126 (defun markdown-blockquote-region (beg end)
5127 "Blockquote the region.
5128 Arguments BEG and END specify the beginning and end of the region."
5129 (interactive "*r")
5130 (markdown-block-region
5131 beg end (concat (markdown-blockquote-indentation
5132 (max (point-min) (1- beg))) "> ")))
5134 (defun markdown-pre-indentation (loc)
5135 "Return string containing necessary whitespace for a pre block at LOC.
5136 Also see `markdown-blockquote-indentation'."
5137 (save-excursion
5138 (goto-char loc)
5139 (let* ((list-level (length (markdown-calculate-list-levels)))
5140 indent)
5141 (dotimes (_ (1+ list-level) indent)
5142 (setq indent (concat indent " "))))))
5144 (defun markdown-insert-pre ()
5145 "Start a preformatted section (or apply to the region).
5146 If Transient Mark mode is on and a region is active, it is marked
5147 as preformatted text."
5148 (interactive)
5149 (if (markdown-use-region-p)
5150 (markdown-pre-region (region-beginning) (region-end))
5151 (markdown-ensure-blank-line-before)
5152 (insert (markdown-pre-indentation (point)))
5153 (markdown-ensure-blank-line-after)))
5155 (defun markdown-pre-region (beg end)
5156 "Format the region as preformatted text.
5157 Arguments BEG and END specify the beginning and end of the region."
5158 (interactive "*r")
5159 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5160 (markdown-block-region beg end indent)))
5162 (defun markdown-electric-backquote (arg)
5163 "Insert a backquote.
5164 The numeric prefix argument ARG says how many times to repeat the insertion.
5165 Call `markdown-insert-gfm-code-block' interactively
5166 if three backquotes inserted at the beginning of line."
5167 (interactive "*P")
5168 (self-insert-command (prefix-numeric-value arg))
5169 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5170 (replace-match "")
5171 (call-interactively #'markdown-insert-gfm-code-block)))
5173 (defconst markdown-gfm-recognized-languages
5174 ;; To reproduce/update, evaluate the let-form in
5175 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5176 ;; but with appropriate use of a keyboard macro, indenting and filling it
5177 ;; properly is pretty fast.
5178 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5179 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5180 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5181 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5182 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5183 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5184 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5185 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5186 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5187 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5188 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5189 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5190 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5191 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5192 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5193 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5194 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5195 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5196 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5197 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5198 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5199 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5200 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5201 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5202 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5203 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5204 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5205 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5206 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5207 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5208 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5209 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5210 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5211 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5212 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5213 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5214 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5215 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5216 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5217 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5218 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5219 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5220 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5221 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5222 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5223 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5224 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5225 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5226 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5227 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5228 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5229 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5230 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5231 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5232 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5233 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5234 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5235 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5236 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5237 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5238 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5239 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5240 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5241 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5242 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5243 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5244 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5245 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5246 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5247 "Language specifiers recognized by GitHub's syntax highlighting features.")
5249 (defvar markdown-gfm-used-languages nil
5250 "Language names used in GFM code blocks.")
5251 (make-variable-buffer-local 'markdown-gfm-used-languages)
5253 (defun markdown-trim-whitespace (str)
5254 (markdown-replace-regexp-in-string
5255 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5257 (defun markdown-clean-language-string (str)
5258 (markdown-replace-regexp-in-string
5259 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5261 (defun markdown-validate-language-string (widget)
5262 (let ((str (widget-value widget)))
5263 (unless (string= str (markdown-clean-language-string str))
5264 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5265 widget)))
5267 (defun markdown-gfm-get-corpus ()
5268 "Create corpus of recognized GFM code block languages for the given buffer."
5269 (let ((given-corpus (append markdown-gfm-additional-languages
5270 markdown-gfm-recognized-languages)))
5271 (append
5272 markdown-gfm-used-languages
5273 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5274 given-corpus))))
5276 (defun markdown-gfm-add-used-language (lang)
5277 "Clean LANG and add to list of used languages."
5278 (setq markdown-gfm-used-languages
5279 (cons lang (remove lang markdown-gfm-used-languages))))
5281 (defcustom markdown-spaces-after-code-fence 1
5282 "Number of space characters to insert after a code fence.
5283 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5284 opening code fence and an info string."
5285 :group 'markdown
5286 :type 'integer
5287 :safe #'natnump
5288 :package-version '(markdown-mode . "2.3"))
5290 (defun markdown-insert-gfm-code-block (&optional lang edit)
5291 "Insert GFM code block for language LANG.
5292 If LANG is nil, the language will be queried from user. If a
5293 region is active, wrap this region with the markup instead. If
5294 the region boundaries are not on empty lines, these are added
5295 automatically in order to have the correct markup. When EDIT is
5296 non-nil (e.g., when \\[universal-argument] is given), edit the
5297 code block in an indirect buffer after insertion."
5298 (interactive
5299 (list (let ((completion-ignore-case nil))
5300 (condition-case nil
5301 (markdown-clean-language-string
5302 (completing-read
5303 "Programming language: "
5304 (markdown-gfm-get-corpus)
5305 nil 'confirm (car markdown-gfm-used-languages)
5306 'markdown-gfm-language-history))
5307 (quit "")))
5308 current-prefix-arg))
5309 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5310 (when (> (length lang) 0)
5311 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5312 lang)))
5313 (if (markdown-use-region-p)
5314 (let* ((b (region-beginning)) (e (region-end)) end
5315 (indent (progn (goto-char b) (current-indentation))))
5316 (goto-char e)
5317 ;; if we're on a blank line, don't newline, otherwise the ```
5318 ;; should go on its own line
5319 (unless (looking-back "\n" nil)
5320 (newline))
5321 (indent-to indent)
5322 (insert "```")
5323 (markdown-ensure-blank-line-after)
5324 (setq end (point))
5325 (goto-char b)
5326 ;; if we're on a blank line, insert the quotes here, otherwise
5327 ;; add a new line first
5328 (unless (looking-at-p "\n")
5329 (newline)
5330 (forward-line -1))
5331 (markdown-ensure-blank-line-before)
5332 (indent-to indent)
5333 (insert "```" lang)
5334 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5335 (let ((indent (current-indentation)) start)
5336 (delete-horizontal-space :backward-only)
5337 (markdown-ensure-blank-line-before)
5338 (indent-to indent)
5339 (setq start (point))
5340 (insert "```" lang "\n")
5341 (indent-to indent)
5342 (unless edit (insert ?\n))
5343 (indent-to indent)
5344 (insert "```")
5345 (markdown-ensure-blank-line-after)
5346 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5347 (end-of-line 0)
5348 (when edit (markdown-edit-code-block))))
5350 (defun markdown-code-block-lang (&optional pos-prop)
5351 "Return the language name for a GFM or tilde fenced code block.
5352 The beginning of the block may be described by POS-PROP,
5353 a cons of (pos . prop) giving the position and property
5354 at the beginning of the block."
5355 (or pos-prop
5356 (setq pos-prop
5357 (markdown-max-of-seq
5358 #'car
5359 (cl-remove-if
5360 #'null
5361 (cl-mapcar
5362 #'markdown-find-previous-prop
5363 (markdown-get-fenced-block-begin-properties))))))
5364 (when pos-prop
5365 (goto-char (car pos-prop))
5366 (set-match-data (get-text-property (point) (cdr pos-prop)))
5367 ;; Note: Hard-coded group number assumes tilde
5368 ;; and GFM fenced code regexp groups agree.
5369 (let ((begin (match-beginning 3))
5370 (end (match-end 3)))
5371 (when (and begin end)
5372 ;; Fix language strings beginning with periods, like ".ruby".
5373 (when (eq (char-after begin) ?.)
5374 (setq begin (1+ begin)))
5375 (buffer-substring-no-properties begin end)))))
5377 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5378 (with-current-buffer (or buffer (current-buffer))
5379 (save-excursion
5380 (goto-char (point-min))
5381 (cl-loop
5382 with prop = 'markdown-gfm-block-begin
5383 for pos-prop = (markdown-find-next-prop prop)
5384 while pos-prop
5385 for lang = (markdown-code-block-lang pos-prop)
5386 do (progn (when lang (markdown-gfm-add-used-language lang))
5387 (goto-char (next-single-property-change (point) prop)))))))
5390 ;;; Footnotes ==================================================================
5392 (defun markdown-footnote-counter-inc ()
5393 "Increment `markdown-footnote-counter' and return the new value."
5394 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5395 (save-excursion
5396 (goto-char (point-min))
5397 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5398 (point-max) t)
5399 (let ((fn (string-to-number (match-string 1))))
5400 (when (> fn markdown-footnote-counter)
5401 (setq markdown-footnote-counter fn))))))
5402 (cl-incf markdown-footnote-counter))
5404 (defun markdown-insert-footnote ()
5405 "Insert footnote with a new number and move point to footnote definition."
5406 (interactive)
5407 (let ((fn (markdown-footnote-counter-inc)))
5408 (insert (format "[^%d]" fn))
5409 (markdown-footnote-text-find-new-location)
5410 (markdown-ensure-blank-line-before)
5411 (unless (markdown-cur-line-blank-p)
5412 (insert "\n"))
5413 (insert (format "[^%d]: " fn))
5414 (markdown-ensure-blank-line-after)))
5416 (defun markdown-footnote-text-find-new-location ()
5417 "Position the point at the proper location for a new footnote text."
5418 (cond
5419 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5420 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5421 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5422 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5424 (defun markdown-footnote-kill ()
5425 "Kill the footnote at point.
5426 The footnote text is killed (and added to the kill ring), the
5427 footnote marker is deleted. Point has to be either at the
5428 footnote marker or in the footnote text."
5429 (interactive)
5430 (let ((marker-pos nil)
5431 (skip-deleting-marker nil)
5432 (starting-footnote-text-positions
5433 (markdown-footnote-text-positions)))
5434 (when starting-footnote-text-positions
5435 ;; We're starting in footnote text, so mark our return position and jump
5436 ;; to the marker if possible.
5437 (let ((marker-pos (markdown-footnote-find-marker
5438 (cl-first starting-footnote-text-positions))))
5439 (if marker-pos
5440 (goto-char (1- marker-pos))
5441 ;; If there isn't a marker, we still want to kill the text.
5442 (setq skip-deleting-marker t))))
5443 ;; Either we didn't start in the text, or we started in the text and jumped
5444 ;; to the marker. We want to assume we're at the marker now and error if
5445 ;; we're not.
5446 (unless skip-deleting-marker
5447 (let ((marker (markdown-footnote-delete-marker)))
5448 (unless marker
5449 (error "Not at a footnote"))
5450 ;; Even if we knew the text position before, it changed when we deleted
5451 ;; the label.
5452 (setq marker-pos (cl-second marker))
5453 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5454 (unless new-text-pos
5455 (error "No text for footnote `%s'" (cl-first marker)))
5456 (goto-char new-text-pos))))
5457 (let ((pos (markdown-footnote-kill-text)))
5458 (goto-char (if starting-footnote-text-positions
5460 marker-pos)))))
5462 (defun markdown-footnote-delete-marker ()
5463 "Delete a footnote marker at point.
5464 Returns a list (ID START) containing the footnote ID and the
5465 start position of the marker before deletion. If no footnote
5466 marker was deleted, this function returns NIL."
5467 (let ((marker (markdown-footnote-marker-positions)))
5468 (when marker
5469 (delete-region (cl-second marker) (cl-third marker))
5470 (butlast marker))))
5472 (defun markdown-footnote-kill-text ()
5473 "Kill footnote text at point.
5474 Returns the start position of the footnote text before deletion,
5475 or NIL if point was not inside a footnote text.
5477 The killed text is placed in the kill ring (without the footnote
5478 number)."
5479 (let ((fn (markdown-footnote-text-positions)))
5480 (when fn
5481 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5482 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5483 (kill-new (match-string 1 text))
5484 (when (and (markdown-cur-line-blank-p)
5485 (markdown-prev-line-blank-p)
5486 (not (bobp)))
5487 (delete-region (1- (point)) (point)))
5488 (cl-second fn)))))
5490 (defun markdown-footnote-goto-text ()
5491 "Jump to the text of the footnote at point."
5492 (interactive)
5493 (let ((fn (car (markdown-footnote-marker-positions))))
5494 (unless fn
5495 (user-error "Not at a footnote marker"))
5496 (let ((new-pos (markdown-footnote-find-text fn)))
5497 (unless new-pos
5498 (error "No definition found for footnote `%s'" fn))
5499 (goto-char new-pos))))
5501 (defun markdown-footnote-return ()
5502 "Return from a footnote to its footnote number in the main text."
5503 (interactive)
5504 (let ((fn (save-excursion
5505 (car (markdown-footnote-text-positions)))))
5506 (unless fn
5507 (user-error "Not in a footnote"))
5508 (let ((new-pos (markdown-footnote-find-marker fn)))
5509 (unless new-pos
5510 (error "Footnote marker `%s' not found" fn))
5511 (goto-char new-pos))))
5513 (defun markdown-footnote-find-marker (id)
5514 "Find the location of the footnote marker with ID.
5515 The actual buffer position returned is the position directly
5516 following the marker's closing bracket. If no marker is found,
5517 NIL is returned."
5518 (save-excursion
5519 (goto-char (point-min))
5520 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5521 (skip-chars-backward "^]")
5522 (point))))
5524 (defun markdown-footnote-find-text (id)
5525 "Find the location of the text of footnote ID.
5526 The actual buffer position returned is the position of the first
5527 character of the text, after the footnote's identifier. If no
5528 footnote text is found, NIL is returned."
5529 (save-excursion
5530 (goto-char (point-min))
5531 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5532 (skip-chars-forward "[ \t]")
5533 (point))))
5535 (defun markdown-footnote-marker-positions ()
5536 "Return the position and ID of the footnote marker point is on.
5537 The return value is a list (ID START END). If point is not on a
5538 footnote, NIL is returned."
5539 ;; first make sure we're at a footnote marker
5540 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5541 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5542 (save-excursion
5543 ;; move point between [ and ^:
5544 (if (looking-at-p "\\[")
5545 (forward-char 1)
5546 (skip-chars-backward "^["))
5547 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5548 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5550 (defun markdown-footnote-text-positions ()
5551 "Return the start and end positions of the footnote text point is in.
5552 The exact return value is a list of three elements: (ID START END).
5553 The start position is the position of the opening bracket
5554 of the footnote id. The end position is directly after the
5555 newline that ends the footnote. If point is not in a footnote,
5556 NIL is returned instead."
5557 (save-excursion
5558 (let (result)
5559 (move-beginning-of-line 1)
5560 ;; Try to find the label. If we haven't found the label and we're at a blank
5561 ;; or indented line, back up if possible.
5562 (while (and
5563 (not (and (looking-at markdown-regex-footnote-definition)
5564 (setq result (list (match-string 1) (point)))))
5565 (and (not (bobp))
5566 (or (markdown-cur-line-blank-p)
5567 (>= (current-indentation) 4))))
5568 (forward-line -1))
5569 (when result
5570 ;; Advance if there is a next line that is either blank or indented.
5571 ;; (Need to check if we're on the last line, because
5572 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5573 (while (and (/= (line-end-position) (point-max))
5574 (or (markdown-next-line-blank-p)
5575 (>= (markdown-next-line-indent) 4)))
5576 (forward-line))
5577 ;; Move back while the current line is blank.
5578 (while (markdown-cur-line-blank-p)
5579 (forward-line -1))
5580 ;; Advance to capture this line and a single trailing newline (if there
5581 ;; is one).
5582 (forward-line)
5583 (append result (list (point)))))))
5586 ;;; Element Removal ===========================================================
5588 (defun markdown-kill-thing-at-point ()
5589 "Kill thing at point and add important text, without markup, to kill ring.
5590 Possible things to kill include (roughly in order of precedence):
5591 inline code, headers, horizonal rules, links (add link text to
5592 kill ring), images (add alt text to kill ring), angle uri, email
5593 addresses, bold, italics, reference definition (add URI to kill
5594 ring), footnote markers and text (kill both marker and text, add
5595 text to kill ring), and list items."
5596 (interactive "*")
5597 (let (val)
5598 (cond
5599 ;; Inline code
5600 ((markdown-inline-code-at-point)
5601 (kill-new (match-string 2))
5602 (delete-region (match-beginning 0) (match-end 0)))
5603 ;; ATX header
5604 ((thing-at-point-looking-at markdown-regex-header-atx)
5605 (kill-new (match-string 2))
5606 (delete-region (match-beginning 0) (match-end 0)))
5607 ;; Setext header
5608 ((thing-at-point-looking-at markdown-regex-header-setext)
5609 (kill-new (match-string 1))
5610 (delete-region (match-beginning 0) (match-end 0)))
5611 ;; Horizonal rule
5612 ((thing-at-point-looking-at markdown-regex-hr)
5613 (kill-new (match-string 0))
5614 (delete-region (match-beginning 0) (match-end 0)))
5615 ;; Inline link or image (add link or alt text to kill ring)
5616 ((thing-at-point-looking-at markdown-regex-link-inline)
5617 (kill-new (match-string 3))
5618 (delete-region (match-beginning 0) (match-end 0)))
5619 ;; Reference link or image (add link or alt text to kill ring)
5620 ((thing-at-point-looking-at markdown-regex-link-reference)
5621 (kill-new (match-string 3))
5622 (delete-region (match-beginning 0) (match-end 0)))
5623 ;; Angle URI (add URL to kill ring)
5624 ((thing-at-point-looking-at markdown-regex-angle-uri)
5625 (kill-new (match-string 2))
5626 (delete-region (match-beginning 0) (match-end 0)))
5627 ;; Email address in angle brackets (add email address to kill ring)
5628 ((thing-at-point-looking-at markdown-regex-email)
5629 (kill-new (match-string 1))
5630 (delete-region (match-beginning 0) (match-end 0)))
5631 ;; Wiki link (add alias text to kill ring)
5632 ((and markdown-enable-wiki-links
5633 (thing-at-point-looking-at markdown-regex-wiki-link))
5634 (kill-new (markdown-wiki-link-alias))
5635 (delete-region (match-beginning 1) (match-end 1)))
5636 ;; Bold
5637 ((thing-at-point-looking-at markdown-regex-bold)
5638 (kill-new (match-string 4))
5639 (delete-region (match-beginning 2) (match-end 2)))
5640 ;; Italics
5641 ((thing-at-point-looking-at markdown-regex-italic)
5642 (kill-new (match-string 3))
5643 (delete-region (match-beginning 1) (match-end 1)))
5644 ;; Strikethrough
5645 ((thing-at-point-looking-at markdown-regex-strike-through)
5646 (kill-new (match-string 4))
5647 (delete-region (match-beginning 2) (match-end 2)))
5648 ;; Footnote marker (add footnote text to kill ring)
5649 ((thing-at-point-looking-at markdown-regex-footnote)
5650 (markdown-footnote-kill))
5651 ;; Footnote text (add footnote text to kill ring)
5652 ((setq val (markdown-footnote-text-positions))
5653 (markdown-footnote-kill))
5654 ;; Reference definition (add URL to kill ring)
5655 ((thing-at-point-looking-at markdown-regex-reference-definition)
5656 (kill-new (match-string 5))
5657 (delete-region (match-beginning 0) (match-end 0)))
5658 ;; List item
5659 ((setq val (markdown-cur-list-item-bounds))
5660 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5662 (user-error "Nothing found at point to kill")))))
5665 ;;; Indentation ====================================================================
5667 (defun markdown-indent-find-next-position (cur-pos positions)
5668 "Return the position after the index of CUR-POS in POSITIONS.
5669 Positions are calculated by `markdown-calc-indents'."
5670 (while (and positions
5671 (not (equal cur-pos (car positions))))
5672 (setq positions (cdr positions)))
5673 (or (cadr positions) 0))
5675 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5676 'markdown-outdent-find-next-position "v2.3")
5678 (defun markdown-outdent-find-next-position (cur-pos positions)
5679 "Return the maximal element that precedes CUR-POS from POSITIONS.
5680 Positions are calculated by `markdown-calc-indents'."
5681 (let ((result 0))
5682 (dolist (i positions)
5683 (when (< i cur-pos)
5684 (setq result (max result i))))
5685 result))
5687 (defun markdown-indent-line ()
5688 "Indent the current line using some heuristics.
5689 If the _previous_ command was either `markdown-enter-key' or
5690 `markdown-cycle', then we should cycle to the next
5691 reasonable indentation position. Otherwise, we could have been
5692 called directly by `markdown-enter-key', by an initial call of
5693 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5694 these cases, indent to the default position.
5695 Positions are calculated by `markdown-calc-indents'."
5696 (interactive)
5697 (let ((positions (markdown-calc-indents))
5698 (point-pos (current-column))
5699 (_ (back-to-indentation))
5700 (cur-pos (current-column)))
5701 (if (not (equal this-command 'markdown-cycle))
5702 (indent-line-to (car positions))
5703 (setq positions (sort (delete-dups positions) '<))
5704 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5705 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5706 (indent-line-to next-pos)
5707 (move-to-column new-point-pos)))))
5709 (defun markdown-calc-indents ()
5710 "Return a list of indentation columns to cycle through.
5711 The first element in the returned list should be considered the
5712 default indentation level. This function does not worry about
5713 duplicate positions, which are handled up by calling functions."
5714 (let (pos prev-line-pos positions)
5716 ;; Indentation of previous line
5717 (setq prev-line-pos (markdown-prev-line-indent))
5718 (setq positions (cons prev-line-pos positions))
5720 ;; Indentation of previous non-list-marker text
5721 (when (setq pos (markdown-prev-non-list-indent))
5722 (setq positions (cons pos positions)))
5724 ;; Indentation required for a pre block in current context
5725 (setq pos (length (markdown-pre-indentation (point))))
5726 (setq positions (cons pos positions))
5728 ;; Indentation of the previous line + tab-width
5729 (if prev-line-pos
5730 (setq positions (cons (+ prev-line-pos tab-width) positions))
5731 (setq positions (cons tab-width positions)))
5733 ;; Indentation of the previous line - tab-width
5734 (if (and prev-line-pos (> prev-line-pos tab-width))
5735 (setq positions (cons (- prev-line-pos tab-width) positions)))
5737 ;; Indentation of all preceeding list markers (when in a list)
5738 (when (setq pos (markdown-calculate-list-levels))
5739 (setq positions (append pos positions)))
5741 ;; First column
5742 (setq positions (cons 0 positions))
5744 ;; Return reversed list
5745 (reverse positions)))
5747 (defun markdown-enter-key ()
5748 "Handle RET depending on the context.
5749 If the point is at a table, move to the next row. Otherwise,
5750 indent according to value of `markdown-indent-on-enter'.
5751 When it is nil, simply call `newline'. Otherwise, indent the next line
5752 following RET using `markdown-indent-line'. Furthermore, when it
5753 is set to 'indent-and-new-item and the point is in a list item,
5754 start a new item with the same indentation. If the point is in an
5755 empty list item, remove it (so that pressing RET twice when in a
5756 list simply adds a blank line)."
5757 (interactive)
5758 (cond
5759 ;; Table
5760 ((markdown-table-at-point-p)
5761 (call-interactively #'markdown-table-next-row))
5762 ;; Indent non-table text
5763 (markdown-indent-on-enter
5764 (let (bounds)
5765 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5766 (setq bounds (markdown-cur-list-item-bounds)))
5767 (let ((beg (cl-first bounds))
5768 (end (cl-second bounds))
5769 (length (cl-fourth bounds)))
5770 ;; Point is in a list item
5771 (if (= (- end beg) length)
5772 ;; Delete blank list
5773 (progn
5774 (delete-region beg end)
5775 (newline)
5776 (markdown-indent-line))
5777 (call-interactively #'markdown-insert-list-item)))
5778 ;; Point is not in a list
5779 (newline)
5780 (markdown-indent-line))))
5781 ;; Insert a raw newline
5782 (t (newline))))
5784 (define-obsolete-function-alias 'markdown-exdent-or-delete
5785 'markdown-outdent-or-delete "v2.3")
5787 (defun markdown-outdent-or-delete (arg)
5788 "Handle BACKSPACE by cycling through indentation points.
5789 When BACKSPACE is pressed, if there is only whitespace
5790 before the current point, then outdent the line one level.
5791 Otherwise, do normal delete by repeating
5792 `backward-delete-char-untabify' ARG times."
5793 (interactive "*p")
5794 (if (use-region-p)
5795 (backward-delete-char-untabify arg)
5796 (let ((cur-pos (current-column))
5797 (start-of-indention (save-excursion
5798 (back-to-indentation)
5799 (current-column)))
5800 (positions (markdown-calc-indents)))
5801 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5802 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5803 (backward-delete-char-untabify arg)))))
5805 (defun markdown-find-leftmost-column (beg end)
5806 "Find the leftmost column in the region from BEG to END."
5807 (let ((mincol 1000))
5808 (save-excursion
5809 (goto-char beg)
5810 (while (< (point) end)
5811 (back-to-indentation)
5812 (unless (looking-at-p "[ \t]*$")
5813 (setq mincol (min mincol (current-column))))
5814 (forward-line 1)
5816 mincol))
5818 (defun markdown-indent-region (beg end arg)
5819 "Indent the region from BEG to END using some heuristics.
5820 When ARG is non-nil, outdent the region instead.
5821 See `markdown-indent-line' and `markdown-indent-line'."
5822 (interactive "*r\nP")
5823 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5824 (leftmostcol (markdown-find-leftmost-column beg end))
5825 (next-pos (if arg
5826 (markdown-outdent-find-next-position leftmostcol positions)
5827 (markdown-indent-find-next-position leftmostcol positions))))
5828 (indent-rigidly beg end (- next-pos leftmostcol))
5829 (setq deactivate-mark nil)))
5831 (define-obsolete-function-alias 'markdown-exdent-region
5832 'markdown-outdent-region "v2.3")
5834 (defun markdown-outdent-region (beg end)
5835 "Call `markdown-indent-region' on region from BEG to END with prefix."
5836 (interactive "*r")
5837 (markdown-indent-region beg end t))
5840 ;;; Markup Completion =========================================================
5842 (defconst markdown-complete-alist
5843 '((markdown-regex-header-atx . markdown-complete-atx)
5844 (markdown-regex-header-setext . markdown-complete-setext)
5845 (markdown-regex-hr . markdown-complete-hr))
5846 "Association list of form (regexp . function) for markup completion.")
5848 (defun markdown-incomplete-atx-p ()
5849 "Return t if ATX header markup is incomplete and nil otherwise.
5850 Assumes match data is available for `markdown-regex-header-atx'.
5851 Checks that the number of trailing hash marks equals the number of leading
5852 hash marks, that there is only a single space before and after the text,
5853 and that there is no extraneous whitespace in the text."
5855 ;; Number of starting and ending hash marks differs
5856 (not (= (length (match-string 1)) (length (match-string 3))))
5857 ;; When the header text is not empty...
5858 (and (> (length (match-string 2)) 0)
5859 ;; ...if there are extra leading, trailing, or interior spaces
5860 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5861 (not (= (match-beginning 3) (1+ (match-end 2))))
5862 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5863 ;; When the header text is empty...
5864 (and (= (length (match-string 2)) 0)
5865 ;; ...if there are too many or too few spaces
5866 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5868 (defun markdown-complete-atx ()
5869 "Complete and normalize ATX headers.
5870 Add or remove hash marks to the end of the header to match the
5871 beginning. Ensure that there is only a single space between hash
5872 marks and header text. Removes extraneous whitespace from header text.
5873 Assumes match data is available for `markdown-regex-header-atx'.
5874 Return nil if markup was complete and non-nil if markup was completed."
5875 (when (markdown-incomplete-atx-p)
5876 (let* ((new-marker (make-marker))
5877 (new-marker (set-marker new-marker (match-end 2))))
5878 ;; Hash marks and spacing at end
5879 (goto-char (match-end 2))
5880 (delete-region (match-end 2) (match-end 3))
5881 (insert " " (match-string 1))
5882 ;; Remove extraneous whitespace from title
5883 (replace-match (markdown-compress-whitespace-string (match-string 2))
5884 t t nil 2)
5885 ;; Spacing at beginning
5886 (goto-char (match-end 1))
5887 (delete-region (match-end 1) (match-beginning 2))
5888 (insert " ")
5889 ;; Leave point at end of text
5890 (goto-char new-marker))))
5892 (defun markdown-incomplete-setext-p ()
5893 "Return t if setext header markup is incomplete and nil otherwise.
5894 Assumes match data is available for `markdown-regex-header-setext'.
5895 Checks that length of underline matches text and that there is no
5896 extraneous whitespace in the text."
5897 (or (not (= (length (match-string 1)) (length (match-string 2))))
5898 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5900 (defun markdown-complete-setext ()
5901 "Complete and normalize setext headers.
5902 Add or remove underline characters to match length of header
5903 text. Removes extraneous whitespace from header text. Assumes
5904 match data is available for `markdown-regex-header-setext'.
5905 Return nil if markup was complete and non-nil if markup was completed."
5906 (when (markdown-incomplete-setext-p)
5907 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5908 (char (char-after (match-beginning 2)))
5909 (level (if (char-equal char ?-) 2 1)))
5910 (goto-char (match-beginning 0))
5911 (delete-region (match-beginning 0) (match-end 0))
5912 (markdown-insert-header level text t)
5913 t)))
5915 (defun markdown-incomplete-hr-p ()
5916 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5917 Assumes match data is available for `markdown-regex-hr'."
5918 (not (member (match-string 0) markdown-hr-strings)))
5920 (defun markdown-complete-hr ()
5921 "Complete horizontal rules.
5922 If horizontal rule string is a member of `markdown-hr-strings',
5923 do nothing. Otherwise, replace with the car of
5924 `markdown-hr-strings'.
5925 Assumes match data is available for `markdown-regex-hr'.
5926 Return nil if markup was complete and non-nil if markup was completed."
5927 (when (markdown-incomplete-hr-p)
5928 (replace-match (car markdown-hr-strings))
5931 (defun markdown-complete ()
5932 "Complete markup of object near point or in region when active.
5933 Handle all objects in `markdown-complete-alist', in order.
5934 See `markdown-complete-at-point' and `markdown-complete-region'."
5935 (interactive "*")
5936 (if (markdown-use-region-p)
5937 (markdown-complete-region (region-beginning) (region-end))
5938 (markdown-complete-at-point)))
5940 (defun markdown-complete-at-point ()
5941 "Complete markup of object near point.
5942 Handle all elements of `markdown-complete-alist' in order."
5943 (interactive "*")
5944 (let ((list markdown-complete-alist) found changed)
5945 (while list
5946 (let ((regexp (eval (caar list)))
5947 (function (cdar list)))
5948 (setq list (cdr list))
5949 (when (thing-at-point-looking-at regexp)
5950 (setq found t)
5951 (setq changed (funcall function))
5952 (setq list nil))))
5953 (if found
5954 (or changed (user-error "Markup at point is complete"))
5955 (user-error "Nothing to complete at point"))))
5957 (defun markdown-complete-region (beg end)
5958 "Complete markup of objects in region from BEG to END.
5959 Handle all objects in `markdown-complete-alist', in order. Each
5960 match is checked to ensure that a previous regexp does not also
5961 match."
5962 (interactive "*r")
5963 (let ((end-marker (set-marker (make-marker) end))
5964 previous)
5965 (dolist (element markdown-complete-alist)
5966 (let ((regexp (eval (car element)))
5967 (function (cdr element)))
5968 (goto-char beg)
5969 (while (re-search-forward regexp end-marker 'limit)
5970 (when (match-string 0)
5971 ;; Make sure this is not a match for any of the preceding regexps.
5972 ;; This prevents mistaking an HR for a Setext subheading.
5973 (let (match)
5974 (save-match-data
5975 (dolist (prev-regexp previous)
5976 (or match (setq match (looking-back prev-regexp nil)))))
5977 (unless match
5978 (save-excursion (funcall function))))))
5979 (cl-pushnew regexp previous :test #'equal)))
5980 previous))
5982 (defun markdown-complete-buffer ()
5983 "Complete markup for all objects in the current buffer."
5984 (interactive "*")
5985 (markdown-complete-region (point-min) (point-max)))
5988 ;;; Markup Cycling ============================================================
5990 (defun markdown-cycle-atx (arg &optional remove)
5991 "Cycle ATX header markup.
5992 Promote header (decrease level) when ARG is 1 and demote
5993 header (increase level) if arg is -1. When REMOVE is non-nil,
5994 remove the header when the level reaches zero and stop cycling
5995 when it reaches six. Otherwise, perform a proper cycling through
5996 levels one through six. Assumes match data is available for
5997 `markdown-regex-header-atx'."
5998 (let* ((old-level (length (match-string 1)))
5999 (new-level (+ old-level arg))
6000 (text (match-string 2)))
6001 (when (not remove)
6002 (setq new-level (% new-level 6))
6003 (setq new-level (cond ((= new-level 0) 6)
6004 ((< new-level 0) (+ new-level 6))
6005 (t new-level))))
6006 (cond
6007 ((= new-level 0)
6008 (markdown-unwrap-thing-at-point nil 0 2))
6009 ((<= new-level 6)
6010 (goto-char (match-beginning 0))
6011 (delete-region (match-beginning 0) (match-end 0))
6012 (markdown-insert-header new-level text nil)))))
6014 (defun markdown-cycle-setext (arg &optional remove)
6015 "Cycle setext header markup.
6016 Promote header (increase level) when ARG is 1 and demote
6017 header (decrease level or remove) if arg is -1. When demoting a
6018 level-two setext header, replace with a level-three atx header.
6019 When REMOVE is non-nil, remove the header when the level reaches
6020 zero. Otherwise, cycle back to a level six atx header. Assumes
6021 match data is available for `markdown-regex-header-setext'."
6022 (let* ((char (char-after (match-beginning 2)))
6023 (old-level (if (char-equal char ?=) 1 2))
6024 (new-level (+ old-level arg)))
6025 (when (and (not remove) (= new-level 0))
6026 (setq new-level 6))
6027 (cond
6028 ((= new-level 0)
6029 (markdown-unwrap-thing-at-point nil 0 1))
6030 ((<= new-level 2)
6031 (markdown-insert-header new-level nil t))
6032 ((<= new-level 6)
6033 (markdown-insert-header new-level nil nil)))))
6035 (defun markdown-cycle-hr (arg &optional remove)
6036 "Cycle string used for horizontal rule from `markdown-hr-strings'.
6037 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
6038 backwards (promote). When REMOVE is non-nil, remove the hr instead
6039 of cycling when the end of the list is reached.
6040 Assumes match data is available for `markdown-regex-hr'."
6041 (let* ((strings (if (= arg -1)
6042 (reverse markdown-hr-strings)
6043 markdown-hr-strings))
6044 (tail (member (match-string 0) strings))
6045 (new (or (cadr tail)
6046 (if remove
6047 (if (= arg 1)
6049 (car tail))
6050 (car strings)))))
6051 (replace-match new)))
6053 (defun markdown-cycle-bold ()
6054 "Cycle bold markup between underscores and asterisks.
6055 Assumes match data is available for `markdown-regex-bold'."
6056 (save-excursion
6057 (let* ((old-delim (match-string 3))
6058 (new-delim (if (string-equal old-delim "**") "__" "**")))
6059 (replace-match new-delim t t nil 3)
6060 (replace-match new-delim t t nil 5))))
6062 (defun markdown-cycle-italic ()
6063 "Cycle italic markup between underscores and asterisks.
6064 Assumes match data is available for `markdown-regex-italic'."
6065 (save-excursion
6066 (let* ((old-delim (match-string 2))
6067 (new-delim (if (string-equal old-delim "*") "_" "*")))
6068 (replace-match new-delim t t nil 2)
6069 (replace-match new-delim t t nil 4))))
6072 ;;; Keymap ====================================================================
6074 (defun markdown--style-map-prompt ()
6075 "Return a formatted prompt for Markdown markup insertion."
6076 (when markdown-enable-prefix-prompts
6077 (concat
6078 "Markdown: "
6079 (propertize "bold" 'face 'markdown-bold-face) ", "
6080 (propertize "italic" 'face 'markdown-italic-face) ", "
6081 (propertize "code" 'face 'markdown-inline-code-face) ", "
6082 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
6083 (propertize "pre" 'face 'markdown-pre-face) ", "
6084 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
6085 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
6086 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
6087 (propertize "- = hr" 'face 'markdown-hr-face) ", "
6088 "C-h = more")))
6090 (defun markdown--command-map-prompt ()
6091 "Return prompt for Markdown buffer-wide commands."
6092 (when markdown-enable-prefix-prompts
6093 (concat
6094 "Command: "
6095 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
6096 (propertize "p" 'face 'markdown-bold-face) "review, "
6097 (propertize "o" 'face 'markdown-bold-face) "pen, "
6098 (propertize "e" 'face 'markdown-bold-face) "xport, "
6099 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
6100 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
6101 "C-h = more")))
6103 (defvar markdown-mode-style-map
6104 (let ((map (make-keymap (markdown--style-map-prompt))))
6105 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
6106 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
6107 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
6108 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
6109 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
6110 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
6111 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
6112 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
6113 (define-key map (kbd "b") 'markdown-insert-bold)
6114 (define-key map (kbd "c") 'markdown-insert-code)
6115 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
6116 (define-key map (kbd "f") 'markdown-insert-footnote)
6117 (define-key map (kbd "h") 'markdown-insert-header-dwim)
6118 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
6119 (define-key map (kbd "i") 'markdown-insert-italic)
6120 (define-key map (kbd "k") 'markdown-insert-kbd)
6121 (define-key map (kbd "l") 'markdown-insert-link)
6122 (define-key map (kbd "p") 'markdown-insert-pre)
6123 (define-key map (kbd "P") 'markdown-pre-region)
6124 (define-key map (kbd "q") 'markdown-insert-blockquote)
6125 (define-key map (kbd "s") 'markdown-insert-strike-through)
6126 (define-key map (kbd "Q") 'markdown-blockquote-region)
6127 (define-key map (kbd "w") 'markdown-insert-wiki-link)
6128 (define-key map (kbd "-") 'markdown-insert-hr)
6129 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
6130 ;; Deprecated keys that may be removed in a future version
6131 (define-key map (kbd "e") 'markdown-insert-italic)
6132 map)
6133 "Keymap for Markdown text styling commands.")
6135 (defvar markdown-mode-command-map
6136 (let ((map (make-keymap (markdown--command-map-prompt))))
6137 (define-key map (kbd "m") 'markdown-other-window)
6138 (define-key map (kbd "p") 'markdown-preview)
6139 (define-key map (kbd "e") 'markdown-export)
6140 (define-key map (kbd "v") 'markdown-export-and-preview)
6141 (define-key map (kbd "o") 'markdown-open)
6142 (define-key map (kbd "l") 'markdown-live-preview-mode)
6143 (define-key map (kbd "w") 'markdown-kill-ring-save)
6144 (define-key map (kbd "c") 'markdown-check-refs)
6145 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6146 (define-key map (kbd "]") 'markdown-complete-buffer)
6147 (define-key map (kbd "^") 'markdown-table-sort-lines)
6148 (define-key map (kbd "|") 'markdown-table-convert-region)
6149 (define-key map (kbd "t") 'markdown-table-transpose)
6150 map)
6151 "Keymap for Markdown buffer-wide commands.")
6153 (defvar markdown-mode-map
6154 (let ((map (make-keymap)))
6155 ;; Markup insertion & removal
6156 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6157 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6158 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6159 ;; Promotion, demotion, and cycling
6160 (define-key map (kbd "C-c C--") 'markdown-promote)
6161 (define-key map (kbd "C-c C-=") 'markdown-demote)
6162 (define-key map (kbd "C-c C-]") 'markdown-complete)
6163 ;; Following and doing things
6164 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6165 (define-key map (kbd "C-c C-d") 'markdown-do)
6166 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6167 ;; Indentation
6168 (define-key map (kbd "C-m") 'markdown-enter-key)
6169 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6170 (define-key map (kbd "C-c >") 'markdown-indent-region)
6171 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6172 ;; Visibility cycling
6173 (define-key map (kbd "TAB") 'markdown-cycle)
6174 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6175 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6176 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6177 ;; Heading and list navigation
6178 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6179 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6180 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6181 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6182 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6183 ;; Buffer-wide commands
6184 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6185 ;; Subtree, list, and table editing
6186 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6187 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6188 (define-key map (kbd "C-c <left>") 'markdown-promote)
6189 (define-key map (kbd "C-c <right>") 'markdown-demote)
6190 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6191 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6192 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6193 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6194 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6195 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6196 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6197 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6198 ;; Paragraphs (Markdown context aware)
6199 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6200 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6201 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6202 ;; Blocks (one or more paragraphs)
6203 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6204 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6205 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6206 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6207 ;; Pages (top-level sections)
6208 (define-key map [remap backward-page] 'markdown-backward-page)
6209 (define-key map [remap forward-page] 'markdown-forward-page)
6210 (define-key map [remap mark-page] 'markdown-mark-page)
6211 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6212 ;; Link Movement
6213 (define-key map (kbd "M-n") 'markdown-next-link)
6214 (define-key map (kbd "M-p") 'markdown-previous-link)
6215 ;; Toggling functionality
6216 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6217 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6218 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6219 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6220 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6221 ;; Alternative keys (in case of problems with the arrow keys)
6222 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6223 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6224 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6225 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6226 ;; Deprecated keys that may be removed in a future version
6227 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
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 r") 'markdown-insert-link) ;; C-c C-l
6230 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6231 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6232 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6233 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6234 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6235 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6236 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6237 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6238 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6239 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6240 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6241 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6242 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6243 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6244 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6245 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6246 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6247 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6248 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6249 map)
6250 "Keymap for Markdown major mode.")
6252 (defvar markdown-mode-mouse-map
6253 (let ((map (make-sparse-keymap)))
6254 (define-key map [follow-link] 'mouse-face)
6255 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6256 map)
6257 "Keymap for following links with mouse.")
6259 (defvar gfm-mode-map
6260 (let ((map (make-sparse-keymap)))
6261 (set-keymap-parent map markdown-mode-map)
6262 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6263 (define-key map "`" 'markdown-electric-backquote)
6264 map)
6265 "Keymap for `gfm-mode'.
6266 See also `markdown-mode-map'.")
6269 ;;; Menu ==================================================================
6271 (easy-menu-define markdown-mode-menu markdown-mode-map
6272 "Menu for Markdown mode"
6273 '("Markdown"
6274 "---"
6275 ("Movement"
6276 ["Jump" markdown-do]
6277 ["Follow Link" markdown-follow-thing-at-point]
6278 ["Next Link" markdown-next-link]
6279 ["Previous Link" markdown-previous-link]
6280 "---"
6281 ["Next Heading or List Item" markdown-outline-next]
6282 ["Previous Heading or List Item" markdown-outline-previous]
6283 ["Next at Same Level" markdown-outline-next-same-level]
6284 ["Previous at Same Level" markdown-outline-previous-same-level]
6285 ["Up to Parent" markdown-outline-up]
6286 "---"
6287 ["Forward Paragraph" markdown-forward-paragraph]
6288 ["Backward Paragraph" markdown-backward-paragraph]
6289 ["Forward Block" markdown-forward-block]
6290 ["Backward Block" markdown-backward-block])
6291 ("Show & Hide"
6292 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6293 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6294 "---"
6295 ["Narrow to Region" narrow-to-region]
6296 ["Narrow to Block" markdown-narrow-to-block]
6297 ["Narrow to Section" narrow-to-defun]
6298 ["Narrow to Subtree" markdown-narrow-to-subtree]
6299 ["Widen" widen (buffer-narrowed-p)]
6300 "---"
6301 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6302 :keys "C-c C-x C-m"
6303 :style radio
6304 :selected markdown-hide-markup])
6305 "---"
6306 ("Headings & Structure"
6307 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6308 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6309 ("Specific Heading (atx)"
6310 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6311 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6312 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6313 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6314 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6315 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6316 ("Specific Heading (Setext)"
6317 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6318 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6319 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6320 "---"
6321 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6322 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6323 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6324 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6325 ("Region & Mark"
6326 ["Indent Region" markdown-indent-region]
6327 ["Outdent Region" markdown-outdent-region]
6328 "--"
6329 ["Mark Paragraph" mark-paragraph]
6330 ["Mark Block" markdown-mark-block]
6331 ["Mark Section" mark-defun]
6332 ["Mark Subtree" markdown-mark-subtree])
6333 ("Lists"
6334 ["Insert List Item" markdown-insert-list-item]
6335 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6336 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6337 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6338 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6339 ["Renumber List" markdown-cleanup-list-numbers]
6340 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6341 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6342 ("Links & Images"
6343 ["Insert Link" markdown-insert-link]
6344 ["Insert Image" markdown-insert-image]
6345 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6346 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6347 "---"
6348 ["Check References" markdown-check-refs]
6349 ["Toggle URL Hiding" markdown-toggle-url-hiding
6350 :style radio
6351 :selected markdown-hide-urls]
6352 ["Toggle Inline Images" markdown-toggle-inline-images
6353 :keys "C-c C-x C-i"
6354 :style radio
6355 :selected markdown-inline-image-overlays]
6356 ["Toggle Wiki Links" markdown-toggle-wiki-links
6357 :style radio
6358 :selected markdown-enable-wiki-links])
6359 ("Styles"
6360 ["Bold" markdown-insert-bold]
6361 ["Italic" markdown-insert-italic]
6362 ["Code" markdown-insert-code]
6363 ["Strikethrough" markdown-insert-strike-through]
6364 ["Keyboard" markdown-insert-kbd]
6365 "---"
6366 ["Blockquote" markdown-insert-blockquote]
6367 ["Preformatted" markdown-insert-pre]
6368 ["GFM Code Block" markdown-insert-gfm-code-block]
6369 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6370 "---"
6371 ["Blockquote Region" markdown-blockquote-region]
6372 ["Preformatted Region" markdown-pre-region]
6373 "---"
6374 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6375 :style radio
6376 :selected markdown-fontify-code-blocks-natively]
6377 ["LaTeX Math Support" markdown-toggle-math
6378 :style radio
6379 :selected markdown-enable-math])
6380 "---"
6381 ("Preview & Export"
6382 ["Compile" markdown-other-window]
6383 ["Preview" markdown-preview]
6384 ["Export" markdown-export]
6385 ["Export & View" markdown-export-and-preview]
6386 ["Open" markdown-open]
6387 ["Live Export" markdown-live-preview-mode
6388 :style radio
6389 :selected markdown-live-preview-mode]
6390 ["Kill ring save" markdown-kill-ring-save])
6391 ("Markup Completion and Cycling"
6392 ["Complete Markup" markdown-complete]
6393 ["Promote Element" markdown-promote :keys "C-c C--"]
6394 ["Demote Element" markdown-demote :keys "C-c C-="])
6395 "---"
6396 ["Kill Element" markdown-kill-thing-at-point]
6397 "---"
6398 ("Documentation"
6399 ["Version" markdown-show-version]
6400 ["Homepage" markdown-mode-info]
6401 ["Describe Mode" (describe-function 'markdown-mode)]
6402 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6405 ;;; imenu =====================================================================
6407 (defun markdown-imenu-create-nested-index ()
6408 "Create and return a nested imenu index alist for the current buffer.
6409 See `imenu-create-index-function' and `imenu--index-alist' for details."
6410 (let* ((root '(nil . nil))
6411 cur-alist
6412 (cur-level 0)
6413 (empty-heading "-")
6414 (self-heading ".")
6415 hashes pos level heading)
6416 (save-excursion
6417 (goto-char (point-min))
6418 (while (re-search-forward markdown-regex-header (point-max) t)
6419 (unless (markdown-code-block-at-point-p)
6420 (cond
6421 ((match-string-no-properties 2) ;; level 1 setext
6422 (setq heading (match-string-no-properties 1))
6423 (setq pos (match-beginning 1)
6424 level 1))
6425 ((match-string-no-properties 3) ;; level 2 setext
6426 (setq heading (match-string-no-properties 1))
6427 (setq pos (match-beginning 1)
6428 level 2))
6429 ((setq hashes (markdown-trim-whitespace
6430 (match-string-no-properties 4)))
6431 (setq heading (match-string-no-properties 5)
6432 pos (match-beginning 4)
6433 level (length hashes))))
6434 (let ((alist (list (cons heading pos))))
6435 (cond
6436 ((= cur-level level) ; new sibling
6437 (setcdr cur-alist alist)
6438 (setq cur-alist alist))
6439 ((< cur-level level) ; first child
6440 (dotimes (_ (- level cur-level 1))
6441 (setq alist (list (cons empty-heading alist))))
6442 (if cur-alist
6443 (let* ((parent (car cur-alist))
6444 (self-pos (cdr parent)))
6445 (setcdr parent (cons (cons self-heading self-pos) alist)))
6446 (setcdr root alist)) ; primogenitor
6447 (setq cur-alist alist)
6448 (setq cur-level level))
6449 (t ; new sibling of an ancestor
6450 (let ((sibling-alist (last (cdr root))))
6451 (dotimes (_ (1- level))
6452 (setq sibling-alist (last (cdar sibling-alist))))
6453 (setcdr sibling-alist alist)
6454 (setq cur-alist alist))
6455 (setq cur-level level))))))
6456 (cdr root))))
6458 (defun markdown-imenu-create-flat-index ()
6459 "Create and return a flat imenu index alist for the current buffer.
6460 See `imenu-create-index-function' and `imenu--index-alist' for details."
6461 (let* ((empty-heading "-") index heading pos)
6462 (save-excursion
6463 (goto-char (point-min))
6464 (while (re-search-forward markdown-regex-header (point-max) t)
6465 (when (and (not (markdown-code-block-at-point-p))
6466 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6467 (cond
6468 ((setq heading (match-string-no-properties 1))
6469 (setq pos (match-beginning 1)))
6470 ((setq heading (match-string-no-properties 5))
6471 (setq pos (match-beginning 4))))
6472 (or (> (length heading) 0)
6473 (setq heading empty-heading))
6474 (setq index (append index (list (cons heading pos))))))
6475 index)))
6478 ;;; References ================================================================
6480 (defun markdown-reference-goto-definition ()
6481 "Jump to the definition of the reference at point or create it."
6482 (interactive)
6483 (when (thing-at-point-looking-at markdown-regex-link-reference)
6484 (let* ((text (match-string-no-properties 3))
6485 (reference (match-string-no-properties 6))
6486 (target (downcase (if (string= reference "") text reference)))
6487 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6488 (if loc
6489 (goto-char loc)
6490 (goto-char (match-beginning 0))
6491 (markdown-insert-reference-definition target)))))
6493 (defun markdown-reference-find-links (reference)
6494 "Return a list of all links for REFERENCE.
6495 REFERENCE should not include the surrounding square brackets.
6496 Elements of the list have the form (text start line), where
6497 text is the link text, start is the location at the beginning of
6498 the link, and line is the line number on which the link appears."
6499 (let* ((ref-quote (regexp-quote reference))
6500 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6501 ref-quote ref-quote))
6502 links)
6503 (save-excursion
6504 (goto-char (point-min))
6505 (while (re-search-forward regexp nil t)
6506 (let* ((text (or (match-string-no-properties 1)
6507 (match-string-no-properties 2)))
6508 (start (match-beginning 0))
6509 (line (markdown-line-number-at-pos)))
6510 (cl-pushnew (list text start line) links :test #'equal))))
6511 links))
6513 (defun markdown-get-undefined-refs ()
6514 "Return a list of undefined Markdown references.
6515 Result is an alist of pairs (reference . occurrences), where
6516 occurrences is itself another alist of pairs (label . line-number).
6517 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6518 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6519 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6520 (let ((missing))
6521 (save-excursion
6522 (goto-char (point-min))
6523 (while
6524 (re-search-forward markdown-regex-link-reference nil t)
6525 (let* ((text (match-string-no-properties 3))
6526 (reference (match-string-no-properties 6))
6527 (target (downcase (if (string= reference "") text reference))))
6528 (unless (markdown-reference-definition target)
6529 (let ((entry (assoc target missing)))
6530 (if (not entry)
6531 (cl-pushnew
6532 (cons target (list (cons text (markdown-line-number-at-pos))))
6533 missing :test #'equal)
6534 (setcdr entry
6535 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6536 (reverse missing))))
6538 (defconst markdown-reference-check-buffer
6539 "*Undefined references for %buffer%*"
6540 "Pattern for name of buffer for listing undefined references.
6541 The string %buffer% will be replaced by the corresponding
6542 `markdown-mode' buffer name.")
6544 (defun markdown-reference-check-buffer (&optional buffer-name)
6545 "Name and return buffer for reference checking.
6546 BUFFER-NAME is the name of the main buffer being visited."
6547 (or buffer-name (setq buffer-name (buffer-name)))
6548 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6549 "%buffer%" buffer-name
6550 markdown-reference-check-buffer))))
6551 (with-current-buffer refbuf
6552 (when view-mode
6553 (View-exit-and-edit))
6554 (use-local-map button-buffer-map)
6555 (erase-buffer))
6556 refbuf))
6558 (defconst markdown-reference-links-buffer
6559 "*Reference links for %buffer%*"
6560 "Pattern for name of buffer for listing references.
6561 The string %buffer% will be replaced by the corresponding buffer name.")
6563 (defun markdown-reference-links-buffer (&optional buffer-name)
6564 "Name, setup, and return a buffer for listing links.
6565 BUFFER-NAME is the name of the main buffer being visited."
6566 (or buffer-name (setq buffer-name (buffer-name)))
6567 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6568 "%buffer%" buffer-name
6569 markdown-reference-links-buffer))))
6570 (with-current-buffer linkbuf
6571 (when view-mode
6572 (View-exit-and-edit))
6573 (use-local-map button-buffer-map)
6574 (erase-buffer))
6575 linkbuf))
6577 ;; Add an empty Markdown reference definition to buffer
6578 ;; specified in the 'target-buffer property. The reference name is
6579 ;; the button's label.
6580 (define-button-type 'markdown-undefined-reference-button
6581 'help-echo "mouse-1, RET: create definition for undefined reference"
6582 'follow-link t
6583 'face 'bold
6584 'action (lambda (b)
6585 (let ((buffer (button-get b 'target-buffer))
6586 (line (button-get b 'target-line))
6587 (label (button-label b)))
6588 (switch-to-buffer-other-window buffer)
6589 (goto-char (point-min))
6590 (forward-line line)
6591 (markdown-insert-reference-definition label)
6592 (markdown-check-refs t))))
6594 ;; Jump to line in buffer specified by 'target-buffer property.
6595 ;; Line number is button's 'line property.
6596 (define-button-type 'markdown-goto-line-button
6597 'help-echo "mouse-1, RET: go to line"
6598 'follow-link t
6599 'face 'italic
6600 'action (lambda (b)
6601 (message (button-get b 'buffer))
6602 (switch-to-buffer-other-window (button-get b 'target-buffer))
6603 ;; use call-interactively to silence compiler
6604 (let ((current-prefix-arg (button-get b 'target-line)))
6605 (call-interactively 'goto-line))))
6607 ;; Jumps to a particular link at location given by 'target-char
6608 ;; property in buffer given by 'target-buffer property.
6609 (define-button-type 'markdown-location-button
6610 'help-echo "mouse-1, RET: jump to location of link"
6611 'follow-link t
6612 'face 'bold
6613 'action (lambda (b)
6614 (let ((target (button-get b 'target-buffer))
6615 (loc (button-get b 'target-char)))
6616 (kill-buffer-and-window)
6617 (switch-to-buffer target)
6618 (goto-char loc))))
6620 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6621 "Insert a button for creating REFERENCE in buffer OLDBUF.
6622 REFERENCE should be a list of the form (reference . occurrences),
6623 as by `markdown-get-undefined-refs'."
6624 (let ((label (car reference)))
6625 ;; Create a reference button
6626 (insert-button label
6627 :type 'markdown-undefined-reference-button
6628 'target-buffer oldbuf
6629 'target-line (cdr (car (cdr reference))))
6630 (insert " (")
6631 (dolist (occurrence (cdr reference))
6632 (let ((line (cdr occurrence)))
6633 ;; Create a line number button
6634 (insert-button (number-to-string line)
6635 :type 'markdown-goto-line-button
6636 'target-buffer oldbuf
6637 'target-line line)
6638 (insert " ")))
6639 (delete-char -1)
6640 (insert ")")
6641 (newline)))
6643 (defun markdown-insert-link-button (link oldbuf)
6644 "Insert a button for jumping to LINK in buffer OLDBUF.
6645 LINK should be a list of the form (text char line) containing
6646 the link text, location, and line number."
6647 (let ((label (cl-first link))
6648 (char (cl-second link))
6649 (line (cl-third link)))
6650 ;; Create a reference button
6651 (insert-button label
6652 :type 'markdown-location-button
6653 'target-buffer oldbuf
6654 'target-char char)
6655 (insert (format " (line %d)\n" line))))
6657 (defun markdown-reference-goto-link (&optional reference)
6658 "Jump to the location of the first use of REFERENCE."
6659 (interactive)
6660 (unless reference
6661 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6662 (setq reference (match-string-no-properties 2))
6663 (user-error "No reference definition at point")))
6664 (let ((links (markdown-reference-find-links reference)))
6665 (cond ((= (length links) 1)
6666 (goto-char (cadr (car links))))
6667 ((> (length links) 1)
6668 (let ((oldbuf (current-buffer))
6669 (linkbuf (markdown-reference-links-buffer)))
6670 (with-current-buffer linkbuf
6671 (insert "Links using reference " reference ":\n\n")
6672 (dolist (link (reverse links))
6673 (markdown-insert-link-button link oldbuf)))
6674 (view-buffer-other-window linkbuf)
6675 (goto-char (point-min))
6676 (forward-line 2)))
6678 (error "No links for reference %s" reference)))))
6680 (defun markdown-check-refs (&optional silent)
6681 "Show all undefined Markdown references in current `markdown-mode' buffer.
6682 If SILENT is non-nil, do not message anything when no undefined
6683 references found.
6684 Links which have empty reference definitions are considered to be
6685 defined."
6686 (interactive "P")
6687 (when (not (eq major-mode 'markdown-mode))
6688 (user-error "Not available in current mode"))
6689 (let ((oldbuf (current-buffer))
6690 (refs (markdown-get-undefined-refs))
6691 (refbuf (markdown-reference-check-buffer)))
6692 (if (null refs)
6693 (progn
6694 (when (not silent)
6695 (message "No undefined references found"))
6696 (kill-buffer refbuf))
6697 (with-current-buffer refbuf
6698 (insert "The following references are undefined:\n\n")
6699 (dolist (ref refs)
6700 (markdown-insert-undefined-reference-button ref oldbuf))
6701 (view-buffer-other-window refbuf)
6702 (goto-char (point-min))
6703 (forward-line 2)))))
6706 ;;; Lists =====================================================================
6708 (defun markdown-insert-list-item (&optional arg)
6709 "Insert a new list item.
6710 If the point is inside unordered list, insert a bullet mark. If
6711 the point is inside ordered list, insert the next number followed
6712 by a period. Use the previous list item to determine the amount
6713 of whitespace to place before and after list markers.
6715 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6716 decrease the indentation by one level.
6718 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6719 increase the indentation by one level."
6720 (interactive "p")
6721 (let (bounds cur-indent marker indent new-indent new-loc)
6722 (save-match-data
6723 ;; Look for a list item on current or previous non-blank line
6724 (save-excursion
6725 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6726 (not (bobp))
6727 (markdown-cur-line-blank-p))
6728 (forward-line -1)))
6729 (when bounds
6730 (cond ((save-excursion
6731 (skip-chars-backward " \t")
6732 (looking-at-p markdown-regex-list))
6733 (beginning-of-line)
6734 (insert "\n")
6735 (forward-line -1))
6736 ((not (markdown-cur-line-blank-p))
6737 (newline)))
6738 (setq new-loc (point)))
6739 ;; Look ahead for a list item on next non-blank line
6740 (unless bounds
6741 (save-excursion
6742 (while (and (null bounds)
6743 (not (eobp))
6744 (markdown-cur-line-blank-p))
6745 (forward-line)
6746 (setq bounds (markdown-cur-list-item-bounds))))
6747 (when bounds
6748 (setq new-loc (point))
6749 (unless (markdown-cur-line-blank-p)
6750 (newline))))
6751 (if (not bounds)
6752 ;; When not in a list, start a new unordered one
6753 (progn
6754 (unless (markdown-cur-line-blank-p)
6755 (insert "\n"))
6756 (insert markdown-unordered-list-item-prefix))
6757 ;; Compute indentation and marker for new list item
6758 (setq cur-indent (nth 2 bounds))
6759 (setq marker (nth 4 bounds))
6760 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6761 (when (nth 5 bounds)
6762 (setq marker
6763 (concat marker
6764 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6765 (cond
6766 ;; Dedent: decrement indentation, find previous marker.
6767 ((= arg 4)
6768 (setq indent (max (- cur-indent 4) 0))
6769 (let ((prev-bounds
6770 (save-excursion
6771 (goto-char (nth 0 bounds))
6772 (when (markdown-up-list)
6773 (markdown-cur-list-item-bounds)))))
6774 (when prev-bounds
6775 (setq marker (nth 4 prev-bounds)))))
6776 ;; Indent: increment indentation by 4, use same marker.
6777 ((= arg 16) (setq indent (+ cur-indent 4)))
6778 ;; Same level: keep current indentation and marker.
6779 (t (setq indent cur-indent)))
6780 (setq new-indent (make-string indent 32))
6781 (goto-char new-loc)
6782 (cond
6783 ;; Ordered list
6784 ((string-match-p "[0-9]" marker)
6785 (if (= arg 16) ;; starting a new column indented one more level
6786 (insert (concat new-indent "1. "))
6787 ;; Don't use previous match-data
6788 (set-match-data nil)
6789 ;; travel up to the last item and pick the correct number. If
6790 ;; the argument was nil, "new-indent = cur-indent" is the same,
6791 ;; so we don't need special treatment. Neat.
6792 (save-excursion
6793 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6794 (>= (forward-line -1) 0))))
6795 (let* ((old-prefix (match-string 1))
6796 (old-spacing (match-string 2))
6797 (new-prefix (if old-prefix
6798 (int-to-string (1+ (string-to-number old-prefix)))
6799 "1"))
6800 (space-adjust (- (length old-prefix) (length new-prefix)))
6801 (new-spacing (if (and (match-string 2)
6802 (not (string-match-p "\t" old-spacing))
6803 (< space-adjust 0)
6804 (> space-adjust (- 1 (length (match-string 2)))))
6805 (substring (match-string 2) 0 space-adjust)
6806 (or old-spacing ". "))))
6807 (insert (concat new-indent new-prefix new-spacing)))))
6808 ;; Unordered list, GFM task list, or ordered list with hash mark
6809 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6810 (insert new-indent marker)))))))
6812 (defun markdown-move-list-item-up ()
6813 "Move the current list item up in the list when possible.
6814 In nested lists, move child items with the parent item."
6815 (interactive)
6816 (let (cur prev old)
6817 (when (setq cur (markdown-cur-list-item-bounds))
6818 (setq old (point))
6819 (goto-char (nth 0 cur))
6820 (if (markdown-prev-list-item (nth 3 cur))
6821 (progn
6822 (setq prev (markdown-cur-list-item-bounds))
6823 (condition-case nil
6824 (progn
6825 (transpose-regions (nth 0 prev) (nth 1 prev)
6826 (nth 0 cur) (nth 1 cur) t)
6827 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6828 ;; Catch error in case regions overlap.
6829 (error (goto-char old))))
6830 (goto-char old)))))
6832 (defun markdown-move-list-item-down ()
6833 "Move the current list item down in the list when possible.
6834 In nested lists, move child items with the parent item."
6835 (interactive)
6836 (let (cur next old)
6837 (when (setq cur (markdown-cur-list-item-bounds))
6838 (setq old (point))
6839 (if (markdown-next-list-item (nth 3 cur))
6840 (progn
6841 (setq next (markdown-cur-list-item-bounds))
6842 (condition-case nil
6843 (progn
6844 (transpose-regions (nth 0 cur) (nth 1 cur)
6845 (nth 0 next) (nth 1 next) nil)
6846 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6847 ;; Catch error in case regions overlap.
6848 (error (goto-char old))))
6849 (goto-char old)))))
6851 (defun markdown-demote-list-item (&optional bounds)
6852 "Indent (or demote) the current list item.
6853 Optionally, BOUNDS of the current list item may be provided if available.
6854 In nested lists, demote child items as well."
6855 (interactive)
6856 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6857 (save-excursion
6858 (let ((end-marker (set-marker (make-marker) (nth 1 bounds))))
6859 (goto-char (nth 0 bounds))
6860 (while (< (point) end-marker)
6861 (unless (markdown-cur-line-blank-p)
6862 (insert (make-string markdown-list-indent-width ? )))
6863 (forward-line))))))
6865 (defun markdown-promote-list-item (&optional bounds)
6866 "Unindent (or promote) the current list item.
6867 Optionally, BOUNDS of the current list item may be provided if available.
6868 In nested lists, demote child items as well."
6869 (interactive)
6870 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6871 (save-excursion
6872 (save-match-data
6873 (let ((end-marker (set-marker (make-marker) (nth 1 bounds)))
6874 num regexp)
6875 (goto-char (nth 0 bounds))
6876 (when (looking-at (format "^[ ]\\{1,%d\\}"
6877 markdown-list-indent-width))
6878 (setq num (- (match-end 0) (match-beginning 0)))
6879 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6880 (while (and (< (point) end-marker)
6881 (re-search-forward regexp end-marker t))
6882 (replace-match "" nil nil)
6883 (forward-line))))))))
6885 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6886 "Update the numbering for level PFX (as a string of spaces).
6888 Assume that the previously found match was for a numbered item in
6889 a list."
6890 (let ((cpfx pfx)
6891 (idx 0)
6892 (continue t)
6893 (step t)
6894 (sep nil))
6895 (while (and continue (not (eobp)))
6896 (setq step t)
6897 (cond
6898 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6899 (setq cpfx (match-string-no-properties 1))
6900 (cond
6901 ((string= cpfx pfx)
6902 (save-excursion
6903 (replace-match
6904 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6905 (setq sep nil))
6906 ;; indented a level
6907 ((string< pfx cpfx)
6908 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6909 (setq step nil))
6910 ;; exit the loop
6912 (setq step nil)
6913 (setq continue nil))))
6915 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
6916 (setq cpfx (match-string-no-properties 1))
6917 (cond
6918 ;; reset if separated before
6919 ((string= cpfx pfx) (when sep (setq idx 0)))
6920 ((string< cpfx pfx)
6921 (setq step nil)
6922 (setq continue nil))))
6923 (t (setq sep t)))
6925 (when step
6926 (beginning-of-line)
6927 (setq continue (= (forward-line) 0))))
6928 sep))
6930 (defun markdown-cleanup-list-numbers ()
6931 "Update the numbering of ordered lists."
6932 (interactive)
6933 (save-excursion
6934 (goto-char (point-min))
6935 (markdown-cleanup-list-numbers-level "")))
6938 ;;; Movement ==================================================================
6940 (defun markdown-beginning-of-defun (&optional arg)
6941 "`beginning-of-defun-function' for Markdown.
6942 This is used to find the beginning of the defun and should behave
6943 like ‘beginning-of-defun’, returning non-nil if it found the
6944 beginning of a defun. It moves the point backward, right before a
6945 heading which defines a defun. When ARG is non-nil, repeat that
6946 many times. When ARG is negative, move forward to the ARG-th
6947 following section."
6948 (or arg (setq arg 1))
6949 (when (< arg 0) (end-of-line))
6950 ;; Adjust position for setext headings.
6951 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
6952 (not (= (point) (match-beginning 0)))
6953 (not (markdown-code-block-at-point-p)))
6954 (goto-char (match-end 0)))
6955 (let (found)
6956 ;; Move backward with positive argument.
6957 (while (and (not (bobp)) (> arg 0))
6958 (setq found nil)
6959 (while (and (not found)
6960 (not (bobp))
6961 (re-search-backward markdown-regex-header nil 'move))
6962 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6963 (setq found (match-beginning 0)))
6964 (setq arg (1- arg)))
6965 ;; Move forward with negative argument.
6966 (while (and (not (eobp)) (< arg 0))
6967 (setq found nil)
6968 (while (and (not found)
6969 (not (eobp))
6970 (re-search-forward markdown-regex-header nil 'move))
6971 (when (not (markdown-code-block-at-pos (match-beginning 0))))
6972 (setq found (match-beginning 0)))
6973 (setq arg (1+ arg)))
6974 (when found
6975 (beginning-of-line)
6976 t)))
6978 (defun markdown-end-of-defun ()
6979 "`end-of-defun-function’ for Markdown.
6980 This is used to find the end of the defun at point.
6981 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
6982 so it can assume that point is at the beginning of the defun body.
6983 It should move point to the first position after the defun."
6984 (or (eobp) (forward-char 1))
6985 (let (found)
6986 (while (and (not found)
6987 (not (eobp))
6988 (re-search-forward markdown-regex-header nil 'move))
6989 (when (not (markdown-code-block-at-pos (match-beginning 0)))
6990 (setq found (match-beginning 0))))
6991 (when found
6992 (goto-char found)
6993 (skip-syntax-backward "-"))))
6995 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
6997 (defun markdown-beginning-of-text-block ()
6998 "Move backward to previous beginning of a plain text block.
6999 This function simply looks for blank lines without considering
7000 the surrounding context in light of Markdown syntax. For that, see
7001 `markdown-backward-block'."
7002 (interactive)
7003 (let ((start (point)))
7004 (if (re-search-backward markdown-regex-block-separator nil t)
7005 (goto-char (match-end 0))
7006 (goto-char (point-min)))
7007 (when (and (= start (point)) (not (bobp)))
7008 (forward-line -1)
7009 (if (re-search-backward markdown-regex-block-separator nil t)
7010 (goto-char (match-end 0))
7011 (goto-char (point-min))))))
7013 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
7015 (defun markdown-end-of-text-block ()
7016 "Move forward to next beginning of a plain text block.
7017 This function simply looks for blank lines without considering
7018 the surrounding context in light of Markdown syntax. For that, see
7019 `markdown-forward-block'."
7020 (interactive)
7021 (beginning-of-line)
7022 (skip-syntax-forward "-")
7023 (when (= (point) (point-min))
7024 (forward-char))
7025 (if (re-search-forward markdown-regex-block-separator nil t)
7026 (goto-char (match-end 0))
7027 (goto-char (point-max)))
7028 (skip-syntax-backward "-")
7029 (forward-line))
7031 (defun markdown-backward-paragraph (&optional arg)
7032 "Move the point to the start of the current paragraph.
7033 With argument ARG, do it ARG times; a negative argument ARG = -N
7034 means move forward N blocks."
7035 (interactive "^p")
7036 (or arg (setq arg 1))
7037 (if (< arg 0)
7038 (markdown-forward-paragraph (- arg))
7039 (dotimes (_ arg)
7040 ;; Skip over whitespace in between paragraphs when moving backward.
7041 (skip-syntax-backward "-")
7042 (beginning-of-line)
7043 ;; Skip over code block endings.
7044 (when (markdown-range-properties-exist
7045 (point-at-bol) (point-at-eol)
7046 '(markdown-gfm-block-end
7047 markdown-tilde-fence-end))
7048 (forward-line -1))
7049 ;; Skip over blank lines inside blockquotes.
7050 (while (and (not (eobp))
7051 (looking-at markdown-regex-blockquote)
7052 (= (length (match-string 3)) 0))
7053 (forward-line -1))
7054 ;; Proceed forward based on the type of block of paragraph.
7055 (let (bounds skip)
7056 (cond
7057 ;; Blockquotes
7058 ((looking-at markdown-regex-blockquote)
7059 (while (and (not (bobp))
7060 (looking-at markdown-regex-blockquote)
7061 (> (length (match-string 3)) 0)) ;; not blank
7062 (forward-line -1))
7063 (forward-line))
7064 ;; List items
7065 ((setq bounds (markdown-cur-list-item-bounds))
7066 (goto-char (nth 0 bounds)))
7067 ;; Other
7069 (while (and (not (bobp))
7070 (not skip)
7071 (not (markdown-cur-line-blank-p))
7072 (not (looking-at markdown-regex-blockquote))
7073 (not (markdown-range-properties-exist
7074 (point-at-bol) (point-at-eol)
7075 '(markdown-gfm-block-end
7076 markdown-tilde-fence-end))))
7077 (setq skip (markdown-range-properties-exist
7078 (point-at-bol) (point-at-eol)
7079 '(markdown-gfm-block-begin
7080 markdown-tilde-fence-begin)))
7081 (forward-line -1))
7082 (unless (bobp)
7083 (forward-line 1))))))))
7085 (defun markdown-forward-paragraph (&optional arg)
7086 "Move forward to the next end of a paragraph.
7087 With argument ARG, do it ARG times; a negative argument ARG = -N
7088 means move backward N blocks."
7089 (interactive "^p")
7090 (or arg (setq arg 1))
7091 (if (< arg 0)
7092 (markdown-backward-paragraph (- arg))
7093 (dotimes (_ arg)
7094 ;; Skip whitespace in between paragraphs.
7095 (when (markdown-cur-line-blank-p)
7096 (skip-syntax-forward "-")
7097 (beginning-of-line))
7098 ;; Proceed forward based on the type of block.
7099 (let (bounds skip)
7100 (cond
7101 ;; Blockquotes
7102 ((looking-at markdown-regex-blockquote)
7103 ;; Skip over blank lines inside blockquotes.
7104 (while (and (not (eobp))
7105 (looking-at markdown-regex-blockquote)
7106 (= (length (match-string 3)) 0))
7107 (forward-line))
7108 ;; Move to end of quoted text block
7109 (while (and (not (eobp))
7110 (looking-at markdown-regex-blockquote)
7111 (> (length (match-string 3)) 0)) ;; not blank
7112 (forward-line)))
7113 ;; List items
7114 ((and (markdown-cur-list-item-bounds)
7115 (setq bounds (markdown-next-list-item-bounds)))
7116 (goto-char (nth 0 bounds)))
7117 ;; Other
7119 (forward-line)
7120 (while (and (not (eobp))
7121 (not skip)
7122 (not (markdown-cur-line-blank-p))
7123 (not (looking-at markdown-regex-blockquote))
7124 (not (markdown-range-properties-exist
7125 (point-at-bol) (point-at-eol)
7126 '(markdown-gfm-block-begin
7127 markdown-tilde-fence-begin))))
7128 (setq skip (markdown-range-properties-exist
7129 (point-at-bol) (point-at-eol)
7130 '(markdown-gfm-block-end
7131 markdown-tilde-fence-end)))
7132 (forward-line))))))))
7134 (defun markdown-backward-block (&optional arg)
7135 "Move the point to the start of the current Markdown block.
7136 Moves across complete code blocks, list items, and blockquotes,
7137 but otherwise stops at blank lines, headers, and horizontal
7138 rules. With argument ARG, do it ARG times; a negative argument
7139 ARG = -N means move forward N blocks."
7140 (interactive "^p")
7141 (or arg (setq arg 1))
7142 (if (< arg 0)
7143 (markdown-forward-block (- arg))
7144 (dotimes (_ arg)
7145 ;; Skip over whitespace in between blocks when moving backward,
7146 ;; unless at a block boundary with no whitespace.
7147 (skip-syntax-backward "-")
7148 (beginning-of-line)
7149 ;; Proceed forward based on the type of block.
7150 (cond
7151 ;; Code blocks
7152 ((and (markdown-code-block-at-pos (point)) ;; this line
7153 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7154 (forward-line -1)
7155 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7156 (forward-line -1))
7157 (forward-line))
7158 ;; Headings
7159 ((markdown-heading-at-point)
7160 (goto-char (match-beginning 0)))
7161 ;; Horizontal rules
7162 ((looking-at markdown-regex-hr))
7163 ;; Blockquotes
7164 ((looking-at markdown-regex-blockquote)
7165 (forward-line -1)
7166 (while (and (looking-at markdown-regex-blockquote)
7167 (not (bobp)))
7168 (forward-line -1))
7169 (forward-line))
7170 ;; List items
7171 ((markdown-cur-list-item-bounds)
7172 (markdown-beginning-of-list))
7173 ;; Other
7175 ;; Move forward in case it is a one line regular paragraph.
7176 (unless (markdown-next-line-blank-p)
7177 (forward-line))
7178 (unless (markdown-prev-line-blank-p)
7179 (markdown-backward-paragraph)))))))
7181 (defun markdown-forward-block (&optional arg)
7182 "Move forward to the next end of a Markdown block.
7183 Moves across complete code blocks, list items, and blockquotes,
7184 but otherwise stops at blank lines, headers, and horizontal
7185 rules. With argument ARG, do it ARG times; a negative argument
7186 ARG = -N means move backward N blocks."
7187 (interactive "^p")
7188 (or arg (setq arg 1))
7189 (if (< arg 0)
7190 (markdown-backward-block (- arg))
7191 (dotimes (_ arg)
7192 ;; Skip over whitespace in between blocks when moving forward.
7193 (if (markdown-cur-line-blank-p)
7194 (skip-syntax-forward "-")
7195 (beginning-of-line))
7196 ;; Proceed forward based on the type of block.
7197 (cond
7198 ;; Code blocks
7199 ((markdown-code-block-at-point-p)
7200 (forward-line)
7201 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7202 (forward-line)))
7203 ;; Headings
7204 ((looking-at markdown-regex-header)
7205 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7206 (forward-line))
7207 ;; Horizontal rules
7208 ((looking-at markdown-regex-hr)
7209 (forward-line))
7210 ;; Blockquotes
7211 ((looking-at markdown-regex-blockquote)
7212 (forward-line)
7213 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7214 (forward-line)))
7215 ;; List items
7216 ((markdown-cur-list-item-bounds)
7217 (markdown-end-of-list)
7218 (forward-line))
7219 ;; Other
7220 (t (markdown-forward-paragraph))))
7221 (skip-syntax-backward "-")
7222 (unless (eobp)
7223 (forward-char 1))))
7225 (defun markdown-backward-page (&optional count)
7226 "Move backward to boundary of the current toplevel section.
7227 With COUNT, repeat, or go forward if negative."
7228 (interactive "p")
7229 (or count (setq count 1))
7230 (if (< count 0)
7231 (markdown-forward-page (- count))
7232 (skip-syntax-backward "-")
7233 (or (markdown-back-to-heading-over-code-block t t)
7234 (goto-char (point-min)))
7235 (when (looking-at markdown-regex-header)
7236 (let ((level (markdown-outline-level)))
7237 (when (> level 1) (markdown-up-heading level))
7238 (when (> count 1)
7239 (condition-case nil
7240 (markdown-backward-same-level (1- count))
7241 (error (goto-char (point-min)))))))))
7243 (defun markdown-forward-page (&optional count)
7244 "Move forward to boundary of the current toplevel section.
7245 With COUNT, repeat, or go backward if negative."
7246 (interactive "p")
7247 (or count (setq count 1))
7248 (if (< count 0)
7249 (markdown-backward-page (- count))
7250 (if (markdown-back-to-heading-over-code-block t t)
7251 (let ((level (markdown-outline-level)))
7252 (when (> level 1) (markdown-up-heading level))
7253 (condition-case nil
7254 (markdown-forward-same-level count)
7255 (error (goto-char (point-max)))))
7256 (markdown-next-visible-heading 1))))
7258 (defun markdown-next-link ()
7259 "Jump to next inline, reference, or wiki link.
7260 If successful, return point. Otherwise, return nil.
7261 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7262 (interactive)
7263 (let ((opoint (point)))
7264 (when (or (markdown-link-p) (markdown-wiki-link-p))
7265 ;; At a link already, move past it.
7266 (goto-char (+ (match-end 0) 1)))
7267 ;; Search for the next wiki link and move to the beginning.
7268 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7269 (markdown-code-block-at-point-p)
7270 (< (point) (point-max))))
7271 (if (and (not (eq (point) opoint))
7272 (or (markdown-link-p) (markdown-wiki-link-p)))
7273 ;; Group 1 will move past non-escape character in wiki link regexp.
7274 ;; Go to beginning of group zero for all other link types.
7275 (goto-char (or (match-beginning 1) (match-beginning 0)))
7276 (goto-char opoint)
7277 nil)))
7279 (defun markdown-previous-link ()
7280 "Jump to previous wiki link.
7281 If successful, return point. Otherwise, return nil.
7282 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7283 (interactive)
7284 (let ((opoint (point)))
7285 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7286 (markdown-code-block-at-point-p)
7287 (> (point) (point-min))))
7288 (if (and (not (eq (point) opoint))
7289 (or (markdown-link-p) (markdown-wiki-link-p)))
7290 (goto-char (or (match-beginning 1) (match-beginning 0)))
7291 (goto-char opoint)
7292 nil)))
7295 ;;; Outline ===================================================================
7297 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7298 "Wrapper for `outline-mode' functions to skip false positives.
7299 MOVE-FN is a function and ARG is its argument. For example,
7300 headings inside preformatted code blocks may match
7301 `outline-regexp' but should not be considered as headings.
7302 When ADJUST is non-nil, adjust the point for interactive calls
7303 to avoid leaving the point at invisible markup. This adjustment
7304 generally should only be done for interactive calls, since other
7305 functions may expect the point to be at the beginning of the
7306 regular expression."
7307 (let ((prev -1) (start (point)))
7308 (if arg (funcall move-fn arg) (funcall move-fn))
7309 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7310 (setq prev (point))
7311 (if arg (funcall move-fn arg) (funcall move-fn)))
7312 ;; Adjust point for setext headings and invisible text.
7313 (save-match-data
7314 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7315 (if markdown-hide-markup
7316 ;; Move to beginning of heading text if markup is hidden.
7317 (goto-char (or (match-beginning 1) (match-beginning 5)))
7318 ;; Move to beginning of markup otherwise.
7319 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7320 (if (= (point) start) nil (point))))
7322 (defun markdown-next-visible-heading (arg)
7323 "Move to the next visible heading line of any level.
7324 With argument, repeats or can move backward if negative. ARG is
7325 passed to `outline-next-visible-heading'."
7326 (interactive "p")
7327 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7329 (defun markdown-previous-visible-heading (arg)
7330 "Move to the previous visible heading line of any level.
7331 With argument, repeats or can move backward if negative. ARG is
7332 passed to `outline-previous-visible-heading'."
7333 (interactive "p")
7334 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7336 (defun markdown-next-heading ()
7337 "Move to the next heading line of any level."
7338 (markdown-move-heading-common #'outline-next-heading))
7340 (defun markdown-previous-heading ()
7341 "Move to the previous heading line of any level."
7342 (markdown-move-heading-common #'outline-previous-heading))
7344 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7345 "Move back to the beginning of the previous heading.
7346 Returns t if the point is at a heading, the location if a heading
7347 was found, and nil otherwise.
7348 Only visible heading lines are considered, unless INVISIBLE-OK is
7349 non-nil. Throw an error if there is no previous heading unless
7350 NO-ERROR is non-nil.
7351 Leaves match data intact for `markdown-regex-header'."
7352 (beginning-of-line)
7353 (or (and (markdown-heading-at-point)
7354 (not (markdown-code-block-at-point-p)))
7355 (let (found)
7356 (save-excursion
7357 (while (and (not found)
7358 (re-search-backward markdown-regex-header nil t))
7359 (when (and (or invisible-ok (not (outline-invisible-p)))
7360 (not (markdown-code-block-at-point-p)))
7361 (setq found (point))))
7362 (if (not found)
7363 (unless no-error (user-error "Before first heading"))
7364 (setq found (point))))
7365 (when found (goto-char found)))))
7367 (defun markdown-forward-same-level (arg)
7368 "Move forward to the ARG'th heading at same level as this one.
7369 Stop at the first and last headings of a superior heading."
7370 (interactive "p")
7371 (markdown-back-to-heading-over-code-block)
7372 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7374 (defun markdown-backward-same-level (arg)
7375 "Move backward to the ARG'th heading at same level as this one.
7376 Stop at the first and last headings of a superior heading."
7377 (interactive "p")
7378 (markdown-back-to-heading-over-code-block)
7379 (while (> arg 0)
7380 (let ((point-to-move-to
7381 (save-excursion
7382 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7383 (if point-to-move-to
7384 (progn
7385 (goto-char point-to-move-to)
7386 (setq arg (1- arg)))
7387 (user-error "No previous same-level heading")))))
7389 (defun markdown-up-heading (arg)
7390 "Move to the visible heading line of which the present line is a subheading.
7391 With argument, move up ARG levels."
7392 (interactive "p")
7393 (and (called-interactively-p 'any)
7394 (not (eq last-command 'markdown-up-heading)) (push-mark))
7395 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7397 (defun markdown-back-to-heading (&optional invisible-ok)
7398 "Move to previous heading line, or beg of this line if it's a heading.
7399 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7400 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7402 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7404 (defun markdown-on-heading-p ()
7405 "Return non-nil if point is on a heading line."
7406 (get-text-property (point-at-bol) 'markdown-heading))
7408 (defun markdown-end-of-subtree (&optional invisible-OK)
7409 "Move to the end of the current subtree.
7410 Only visible heading lines are considered, unless INVISIBLE-OK is
7411 non-nil.
7412 Derived from `org-end-of-subtree'."
7413 (markdown-back-to-heading invisible-OK)
7414 (let ((first t)
7415 (level (markdown-outline-level)))
7416 (while (and (not (eobp))
7417 (or first (> (markdown-outline-level) level)))
7418 (setq first nil)
7419 (markdown-next-heading))
7420 (if (memq (preceding-char) '(?\n ?\^M))
7421 (progn
7422 ;; Go to end of line before heading
7423 (forward-char -1)
7424 (if (memq (preceding-char) '(?\n ?\^M))
7425 ;; leave blank line before heading
7426 (forward-char -1)))))
7427 (point))
7429 (defun markdown-outline-fix-visibility ()
7430 "Hide any false positive headings that should not be shown.
7431 For example, headings inside preformatted code blocks may match
7432 `outline-regexp' but should not be shown as headings when cycling.
7433 Also, the ending --- line in metadata blocks appears to be a
7434 setext header, but should not be folded."
7435 (save-excursion
7436 (goto-char (point-min))
7437 ;; Unhide any false positives in metadata blocks
7438 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7439 (let ((body (progn (forward-line)
7440 (markdown-text-property-at-point
7441 'markdown-yaml-metadata-section))))
7442 (when body
7443 (let ((end (progn (goto-char (cl-second body))
7444 (markdown-text-property-at-point
7445 'markdown-yaml-metadata-end))))
7446 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7447 ;; Hide any false positives in code blocks
7448 (unless (outline-on-heading-p)
7449 (outline-next-visible-heading 1))
7450 (while (< (point) (point-max))
7451 (when (markdown-code-block-at-point-p)
7452 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7453 (outline-next-visible-heading 1))))
7455 (defvar markdown-cycle-global-status 1)
7456 (defvar markdown-cycle-subtree-status nil)
7458 (defun markdown-next-preface ()
7459 (let (finish)
7460 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7461 nil 'move))
7462 (unless (markdown-code-block-at-point-p)
7463 (goto-char (match-beginning 0))
7464 (setq finish t))))
7465 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7466 (forward-char -1)))
7468 (defun markdown-show-entry ()
7469 (save-excursion
7470 (outline-back-to-heading t)
7471 (outline-flag-region (1- (point))
7472 (progn
7473 (markdown-next-preface)
7474 (if (= 1 (- (point-max) (point)))
7475 (point-max)
7476 (point)))
7477 nil)))
7479 ;; This function was originally derived from `org-cycle' from org.el.
7480 (defun markdown-cycle (&optional arg)
7481 "Visibility cycling for Markdown mode.
7482 If ARG is t, perform global visibility cycling. If the point is
7483 at an atx-style header, cycle visibility of the corresponding
7484 subtree. Otherwise, indent the current line or insert a tab,
7485 as appropriate, by calling `indent-for-tab-command'."
7486 (interactive "P")
7487 (cond
7489 ;; Global cycling
7490 ((eq arg t)
7491 (cond
7492 ;; Move from overview to contents
7493 ((and (eq last-command this-command)
7494 (eq markdown-cycle-global-status 2))
7495 (markdown-hide-sublevels 1)
7496 (message "CONTENTS")
7497 (setq markdown-cycle-global-status 3)
7498 (markdown-outline-fix-visibility))
7499 ;; Move from contents to all
7500 ((and (eq last-command this-command)
7501 (eq markdown-cycle-global-status 3))
7502 (markdown-show-all)
7503 (message "SHOW ALL")
7504 (setq markdown-cycle-global-status 1))
7505 ;; Defaults to overview
7507 (markdown-hide-body)
7508 (message "OVERVIEW")
7509 (setq markdown-cycle-global-status 2)
7510 (markdown-outline-fix-visibility))))
7512 ;; At a heading: rotate between three different views
7513 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7514 (markdown-back-to-heading)
7515 (let ((goal-column 0) eoh eol eos)
7516 ;; Determine boundaries
7517 (save-excursion
7518 (markdown-back-to-heading)
7519 (save-excursion
7520 (beginning-of-line 2)
7521 (while (and (not (eobp)) ;; this is like `next-line'
7522 (get-char-property (1- (point)) 'invisible))
7523 (beginning-of-line 2)) (setq eol (point)))
7524 (markdown-end-of-heading) (setq eoh (point))
7525 (markdown-end-of-subtree t)
7526 (skip-chars-forward " \t\n")
7527 (beginning-of-line 1) ; in case this is an item
7528 (setq eos (1- (point))))
7529 ;; Find out what to do next and set `this-command'
7530 (cond
7531 ;; Nothing is hidden behind this heading
7532 ((= eos eoh)
7533 (message "EMPTY ENTRY")
7534 (setq markdown-cycle-subtree-status nil))
7535 ;; Entire subtree is hidden in one line: open it
7536 ((>= eol eos)
7537 (markdown-show-entry)
7538 (markdown-show-children)
7539 (message "CHILDREN")
7540 (setq markdown-cycle-subtree-status 'children))
7541 ;; We just showed the children, now show everything.
7542 ((and (eq last-command this-command)
7543 (eq markdown-cycle-subtree-status 'children))
7544 (markdown-show-subtree)
7545 (message "SUBTREE")
7546 (setq markdown-cycle-subtree-status 'subtree))
7547 ;; Default action: hide the subtree.
7549 (markdown-hide-subtree)
7550 (message "FOLDED")
7551 (setq markdown-cycle-subtree-status 'folded)))))
7553 ;; In a table, move forward by one cell
7554 ((markdown-table-at-point-p)
7555 (call-interactively #'markdown-table-forward-cell))
7557 ;; Otherwise, indent as appropriate
7559 (indent-for-tab-command))))
7561 (defun markdown-shifttab ()
7562 "Handle S-TAB keybinding based on context.
7563 When in a table, move backward one cell.
7564 Otherwise, cycle global heading visibility by calling
7565 `markdown-cycle' with argument t."
7566 (interactive)
7567 (cond ((markdown-table-at-point-p)
7568 (call-interactively #'markdown-table-backward-cell))
7569 (t (markdown-cycle t))))
7571 (defun markdown-outline-level ()
7572 "Return the depth to which a statement is nested in the outline."
7573 (cond
7574 ((and (match-beginning 0)
7575 (markdown-code-block-at-pos (match-beginning 0)))
7576 7) ;; Only 6 header levels are defined.
7577 ((match-end 2) 1)
7578 ((match-end 3) 2)
7579 ((match-end 4)
7580 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7582 (defun markdown-promote-subtree (&optional arg)
7583 "Promote the current subtree of ATX headings.
7584 Note that Markdown does not support heading levels higher than
7585 six and therefore level-six headings will not be promoted
7586 further. If ARG is non-nil promote the heading, otherwise
7587 demote."
7588 (interactive "*P")
7589 (save-excursion
7590 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7591 (re-search-backward markdown-regex-header-atx nil t))
7592 (not (markdown-code-block-at-point-p)))
7593 (let ((level (length (match-string 1)))
7594 (promote-or-demote (if arg 1 -1))
7595 (remove 't))
7596 (markdown-cycle-atx promote-or-demote remove)
7597 (catch 'end-of-subtree
7598 (while (and (markdown-next-heading)
7599 (looking-at markdown-regex-header-atx))
7600 ;; Exit if this not a higher level heading; promote otherwise.
7601 (if (and (looking-at markdown-regex-header-atx)
7602 (<= (length (match-string-no-properties 1)) level))
7603 (throw 'end-of-subtree nil)
7604 (markdown-cycle-atx promote-or-demote remove))))))))
7606 (defun markdown-demote-subtree ()
7607 "Demote the current subtree of ATX headings."
7608 (interactive)
7609 (markdown-promote-subtree t))
7611 (defun markdown-move-subtree-up ()
7612 "Move the current subtree of ATX headings up."
7613 (interactive)
7614 (outline-move-subtree-up 1))
7616 (defun markdown-move-subtree-down ()
7617 "Move the current subtree of ATX headings down."
7618 (interactive)
7619 (outline-move-subtree-down 1))
7621 (defun markdown-outline-next ()
7622 "Move to next list item, when in a list, or next visible heading."
7623 (interactive)
7624 (let ((bounds (markdown-next-list-item-bounds)))
7625 (if bounds
7626 (goto-char (nth 0 bounds))
7627 (markdown-next-visible-heading 1))))
7629 (defun markdown-outline-previous ()
7630 "Move to previous list item, when in a list, or previous visible heading."
7631 (interactive)
7632 (let ((bounds (markdown-prev-list-item-bounds)))
7633 (if bounds
7634 (goto-char (nth 0 bounds))
7635 (markdown-previous-visible-heading 1))))
7637 (defun markdown-outline-next-same-level ()
7638 "Move to next list item or heading of same level."
7639 (interactive)
7640 (let ((bounds (markdown-cur-list-item-bounds)))
7641 (if bounds
7642 (markdown-next-list-item (nth 3 bounds))
7643 (markdown-forward-same-level 1))))
7645 (defun markdown-outline-previous-same-level ()
7646 "Move to previous list item or heading of same level."
7647 (interactive)
7648 (let ((bounds (markdown-cur-list-item-bounds)))
7649 (if bounds
7650 (markdown-prev-list-item (nth 3 bounds))
7651 (markdown-backward-same-level 1))))
7653 (defun markdown-outline-up ()
7654 "Move to previous list item, when in a list, or next heading."
7655 (interactive)
7656 (unless (markdown-up-list)
7657 (markdown-up-heading 1)))
7660 ;;; Marking and Narrowing =====================================================
7662 (defun markdown-mark-paragraph ()
7663 "Put mark at end of this block, point at beginning.
7664 The block marked is the one that contains point or follows point.
7666 Interactively, if this command is repeated or (in Transient Mark
7667 mode) if the mark is active, it marks the next block after the
7668 ones already marked."
7669 (interactive)
7670 (if (or (and (eq last-command this-command) (mark t))
7671 (and transient-mark-mode mark-active))
7672 (set-mark
7673 (save-excursion
7674 (goto-char (mark))
7675 (markdown-forward-paragraph)
7676 (point)))
7677 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7678 (end-of-defun-function 'markdown-forward-paragraph))
7679 (mark-defun))))
7681 (defun markdown-mark-block ()
7682 "Put mark at end of this block, point at beginning.
7683 The block marked is the one that contains point or follows point.
7685 Interactively, if this command is repeated or (in Transient Mark
7686 mode) if the mark is active, it marks the next block after the
7687 ones already marked."
7688 (interactive)
7689 (if (or (and (eq last-command this-command) (mark t))
7690 (and transient-mark-mode mark-active))
7691 (set-mark
7692 (save-excursion
7693 (goto-char (mark))
7694 (markdown-forward-block)
7695 (point)))
7696 (let ((beginning-of-defun-function 'markdown-backward-block)
7697 (end-of-defun-function 'markdown-forward-block))
7698 (mark-defun))))
7700 (defun markdown-narrow-to-block ()
7701 "Make text outside current block invisible.
7702 The current block is the one that contains point or follows point."
7703 (interactive)
7704 (let ((beginning-of-defun-function 'markdown-backward-block)
7705 (end-of-defun-function 'markdown-forward-block))
7706 (narrow-to-defun)))
7708 (defun markdown-mark-text-block ()
7709 "Put mark at end of this plain text block, point at beginning.
7710 The block marked is the one that contains point or follows point.
7712 Interactively, if this command is repeated or (in Transient Mark
7713 mode) if the mark is active, it marks the next block after the
7714 ones already marked."
7715 (interactive)
7716 (if (or (and (eq last-command this-command) (mark t))
7717 (and transient-mark-mode mark-active))
7718 (set-mark
7719 (save-excursion
7720 (goto-char (mark))
7721 (markdown-end-of-text-block)
7722 (point)))
7723 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7724 (end-of-defun-function 'markdown-end-of-text-block))
7725 (mark-defun))))
7727 (defun markdown-mark-page ()
7728 "Put mark at end of this top level section, point at beginning.
7729 The top level section marked is the one that contains point or
7730 follows point.
7732 Interactively, if this command is repeated or (in Transient Mark
7733 mode) if the mark is active, it marks the next page after the
7734 ones already marked."
7735 (interactive)
7736 (if (or (and (eq last-command this-command) (mark t))
7737 (and transient-mark-mode mark-active))
7738 (set-mark
7739 (save-excursion
7740 (goto-char (mark))
7741 (markdown-forward-page)
7742 (point)))
7743 (let ((beginning-of-defun-function 'markdown-backward-page)
7744 (end-of-defun-function 'markdown-forward-page))
7745 (mark-defun))))
7747 (defun markdown-narrow-to-page ()
7748 "Make text outside current top level section invisible.
7749 The current section is the one that contains point or follows point."
7750 (interactive)
7751 (let ((beginning-of-defun-function 'markdown-backward-page)
7752 (end-of-defun-function 'markdown-forward-page))
7753 (narrow-to-defun)))
7755 (defun markdown-mark-subtree ()
7756 "Mark the current subtree.
7757 This puts point at the start of the current subtree, and mark at the end."
7758 (interactive)
7759 (let ((beg))
7760 (if (markdown-heading-at-point)
7761 (beginning-of-line)
7762 (markdown-previous-visible-heading 1))
7763 (setq beg (point))
7764 (markdown-end-of-subtree)
7765 (push-mark (point) nil t)
7766 (goto-char beg)))
7768 (defun markdown-narrow-to-subtree ()
7769 "Narrow buffer to the current subtree."
7770 (interactive)
7771 (save-excursion
7772 (save-match-data
7773 (narrow-to-region
7774 (progn (markdown-back-to-heading-over-code-block t) (point))
7775 (progn (markdown-end-of-subtree)
7776 (if (and (markdown-heading-at-point) (not (eobp)))
7777 (backward-char 1))
7778 (point))))))
7781 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7783 (defun markdown-move-up ()
7784 "Move thing at point up.
7785 When in a list item, call `markdown-move-list-item-up'.
7786 When in a table, call `markdown-table-move-row-up'.
7787 Otherwise, move the current heading subtree up with
7788 `markdown-move-subtree-up'."
7789 (interactive)
7790 (cond
7791 ((markdown-list-item-at-point-p)
7792 (call-interactively #'markdown-move-list-item-up))
7793 ((markdown-table-at-point-p)
7794 (call-interactively #'markdown-table-move-row-up))
7796 (call-interactively #'markdown-move-subtree-up))))
7798 (defun markdown-move-down ()
7799 "Move thing at point down.
7800 When in a list item, call `markdown-move-list-item-down'.
7801 Otherwise, move the current heading subtree up with
7802 `markdown-move-subtree-down'."
7803 (interactive)
7804 (cond
7805 ((markdown-list-item-at-point-p)
7806 (call-interactively #'markdown-move-list-item-down))
7807 ((markdown-table-at-point-p)
7808 (call-interactively #'markdown-table-move-row-down))
7810 (call-interactively #'markdown-move-subtree-down))))
7812 (defun markdown-promote ()
7813 "Promote or move element at point to the left.
7814 Depending on the context, this function will promote a heading or
7815 list item at the point, move a table column to the left, or cycle
7816 markup."
7817 (interactive)
7818 (let (bounds)
7819 (cond
7820 ;; Promote atx heading subtree
7821 ((thing-at-point-looking-at markdown-regex-header-atx)
7822 (markdown-promote-subtree))
7823 ;; Promote setext heading
7824 ((thing-at-point-looking-at markdown-regex-header-setext)
7825 (markdown-cycle-setext -1))
7826 ;; Promote horizonal rule
7827 ((thing-at-point-looking-at markdown-regex-hr)
7828 (markdown-cycle-hr -1))
7829 ;; Promote list item
7830 ((setq bounds (markdown-cur-list-item-bounds))
7831 (markdown-promote-list-item bounds))
7832 ;; Move table column to the left
7833 ((markdown-table-at-point-p)
7834 (call-interactively #'markdown-table-move-column-left))
7835 ;; Promote bold
7836 ((thing-at-point-looking-at markdown-regex-bold)
7837 (markdown-cycle-bold))
7838 ;; Promote italic
7839 ((thing-at-point-looking-at markdown-regex-italic)
7840 (markdown-cycle-italic))
7842 (user-error "Nothing to promote at point")))))
7844 (defun markdown-demote ()
7845 "Demote or move element at point to the right.
7846 Depending on the context, this function will demote a heading or
7847 list item at the point, move a table column to the right, or cycle
7848 or remove markup."
7849 (interactive)
7850 (let (bounds)
7851 (cond
7852 ;; Demote atx heading subtree
7853 ((thing-at-point-looking-at markdown-regex-header-atx)
7854 (markdown-demote-subtree))
7855 ;; Demote setext heading
7856 ((thing-at-point-looking-at markdown-regex-header-setext)
7857 (markdown-cycle-setext 1))
7858 ;; Demote horizonal rule
7859 ((thing-at-point-looking-at markdown-regex-hr)
7860 (markdown-cycle-hr 1))
7861 ;; Demote list item
7862 ((setq bounds (markdown-cur-list-item-bounds))
7863 (markdown-demote-list-item bounds))
7864 ;; Move table column to the right
7865 ((markdown-table-at-point-p)
7866 (call-interactively #'markdown-table-move-column-right))
7867 ;; Demote bold
7868 ((thing-at-point-looking-at markdown-regex-bold)
7869 (markdown-cycle-bold))
7870 ;; Demote italic
7871 ((thing-at-point-looking-at markdown-regex-italic)
7872 (markdown-cycle-italic))
7874 (user-error "Nothing to demote at point")))))
7877 ;;; Commands ==================================================================
7879 (defun markdown (&optional output-buffer-name)
7880 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7881 The output buffer name defaults to `markdown-output-buffer-name'.
7882 Return the name of the output buffer used."
7883 (interactive)
7884 (save-window-excursion
7885 (let ((begin-region)
7886 (end-region))
7887 (if (markdown-use-region-p)
7888 (setq begin-region (region-beginning)
7889 end-region (region-end))
7890 (setq begin-region (point-min)
7891 end-region (point-max)))
7893 (unless output-buffer-name
7894 (setq output-buffer-name markdown-output-buffer-name))
7895 (cond
7896 ;; Handle case when `markdown-command' does not read from stdin
7897 ((and (stringp markdown-command) markdown-command-needs-filename)
7898 (if (not buffer-file-name)
7899 (user-error "Must be visiting a file")
7900 (shell-command (concat markdown-command " "
7901 (shell-quote-argument buffer-file-name))
7902 output-buffer-name)))
7903 ;; Pass region to `markdown-command' via stdin
7905 (let ((buf (get-buffer-create output-buffer-name)))
7906 (with-current-buffer buf
7907 (setq buffer-read-only nil)
7908 (erase-buffer))
7909 (if (stringp markdown-command)
7910 (call-process-region begin-region end-region
7911 shell-file-name nil buf nil
7912 shell-command-switch markdown-command)
7913 (funcall markdown-command begin-region end-region buf))))))
7914 output-buffer-name))
7916 (defun markdown-standalone (&optional output-buffer-name)
7917 "Special function to provide standalone HTML output.
7918 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
7919 (interactive)
7920 (setq output-buffer-name (markdown output-buffer-name))
7921 (with-current-buffer output-buffer-name
7922 (set-buffer output-buffer-name)
7923 (unless (markdown-output-standalone-p)
7924 (markdown-add-xhtml-header-and-footer output-buffer-name))
7925 (goto-char (point-min))
7926 (html-mode))
7927 output-buffer-name)
7929 (defun markdown-other-window (&optional output-buffer-name)
7930 "Run `markdown-command' on current buffer and display in other window.
7931 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7932 that name."
7933 (interactive)
7934 (markdown-display-buffer-other-window
7935 (markdown-standalone output-buffer-name)))
7937 (defun markdown-output-standalone-p ()
7938 "Determine whether `markdown-command' output is standalone XHTML.
7939 Standalone XHTML output is identified by an occurrence of
7940 `markdown-xhtml-standalone-regexp' in the first five lines of output."
7941 (save-excursion
7942 (goto-char (point-min))
7943 (save-match-data
7944 (re-search-forward
7945 markdown-xhtml-standalone-regexp
7946 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
7947 t))))
7949 (defun markdown-stylesheet-link-string (stylesheet-path)
7950 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
7951 stylesheet-path
7952 "\" />"))
7954 (defun markdown-add-xhtml-header-and-footer (title)
7955 "Wrap XHTML header and footer with given TITLE around current buffer."
7956 (goto-char (point-min))
7957 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
7958 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
7959 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
7960 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
7961 "<head>\n<title>")
7962 (insert title)
7963 (insert "</title>\n")
7964 (when (> (length markdown-content-type) 0)
7965 (insert
7966 (format
7967 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
7968 markdown-content-type
7969 (or (and markdown-coding-system
7970 (fboundp 'coding-system-get)
7971 (coding-system-get markdown-coding-system
7972 'mime-charset))
7973 (and (fboundp 'coding-system-get)
7974 (coding-system-get buffer-file-coding-system
7975 'mime-charset))
7976 "iso-8859-1"))))
7977 (if (> (length markdown-css-paths) 0)
7978 (insert (mapconcat #'markdown-stylesheet-link-string
7979 markdown-css-paths "\n")))
7980 (when (> (length markdown-xhtml-header-content) 0)
7981 (insert markdown-xhtml-header-content))
7982 (insert "\n</head>\n\n"
7983 "<body>\n\n")
7984 (goto-char (point-max))
7985 (insert "\n"
7986 "</body>\n"
7987 "</html>\n"))
7989 (defun markdown-preview (&optional output-buffer-name)
7990 "Run `markdown-command' on the current buffer and view output in browser.
7991 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
7992 that name."
7993 (interactive)
7994 (browse-url-of-buffer
7995 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
7997 (defun markdown-export-file-name (&optional extension)
7998 "Attempt to generate a filename for Markdown output.
7999 The file extension will be EXTENSION if given, or .html by default.
8000 If the current buffer is visiting a file, we construct a new
8001 output filename based on that filename. Otherwise, return nil."
8002 (when (buffer-file-name)
8003 (unless extension
8004 (setq extension ".html"))
8005 (let ((candidate
8006 (concat
8007 (cond
8008 ((buffer-file-name)
8009 (file-name-sans-extension (buffer-file-name)))
8010 (t (buffer-name)))
8011 extension)))
8012 (cond
8013 ((equal candidate (buffer-file-name))
8014 (concat candidate extension))
8016 candidate)))))
8018 (defun markdown-export (&optional output-file)
8019 "Run Markdown on the current buffer, save to file, and return the filename.
8020 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
8021 generated by `markdown-export-file-name', which will be constructed using the
8022 current filename, but with the extension removed and replaced with .html."
8023 (interactive)
8024 (unless output-file
8025 (setq output-file (markdown-export-file-name ".html")))
8026 (when output-file
8027 (let* ((init-buf (current-buffer))
8028 (init-point (point))
8029 (init-buf-string (buffer-string))
8030 (output-buffer (find-file-noselect output-file))
8031 (output-buffer-name (buffer-name output-buffer)))
8032 (run-hooks 'markdown-before-export-hook)
8033 (markdown-standalone output-buffer-name)
8034 (with-current-buffer output-buffer
8035 (run-hooks 'markdown-after-export-hook)
8036 (save-buffer)
8037 (when markdown-export-kill-buffer (kill-buffer)))
8038 ;; if modified, restore initial buffer
8039 (when (buffer-modified-p init-buf)
8040 (erase-buffer)
8041 (insert init-buf-string)
8042 (save-buffer)
8043 (goto-char init-point))
8044 output-file)))
8046 (defun markdown-export-and-preview ()
8047 "Export to XHTML using `markdown-export' and browse the resulting file."
8048 (interactive)
8049 (browse-url-of-file (markdown-export)))
8051 (defvar markdown-live-preview-buffer nil
8052 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
8053 (make-variable-buffer-local 'markdown-live-preview-buffer)
8055 (defvar markdown-live-preview-source-buffer nil
8056 "Source buffer from which current buffer was generated.
8057 This is the inverse of `markdown-live-preview-buffer'.")
8058 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
8060 (defvar markdown-live-preview-currently-exporting nil)
8062 (defun markdown-live-preview-get-filename ()
8063 "Standardize the filename exported by `markdown-live-preview-export'."
8064 (markdown-export-file-name ".html"))
8066 (defun markdown-live-preview-window-eww (file)
8067 "Preview FILE with eww.
8068 To be used with `markdown-live-preview-window-function'."
8069 (if (require 'eww nil t)
8070 (progn
8071 (eww-open-file file)
8072 (get-buffer "*eww*"))
8073 (error "EWW is not present or not loaded on this version of Emacs")))
8075 (defun markdown-visual-lines-between-points (beg end)
8076 (save-excursion
8077 (goto-char beg)
8078 (cl-loop with count = 0
8079 while (progn (end-of-visual-line)
8080 (and (< (point) end) (line-move-visual 1 t)))
8081 do (cl-incf count)
8082 finally return count)))
8084 (defun markdown-live-preview-window-serialize (buf)
8085 "Get window point and scroll data for all windows displaying BUF."
8086 (when (buffer-live-p buf)
8087 (with-current-buffer buf
8088 (mapcar
8089 (lambda (win)
8090 (with-selected-window win
8091 (let* ((start (window-start))
8092 (pt (window-point))
8093 (pt-or-sym (cond ((= pt (point-min)) 'min)
8094 ((= pt (point-max)) 'max)
8095 (t pt)))
8096 (diff (markdown-visual-lines-between-points
8097 start pt)))
8098 (list win pt-or-sym diff))))
8099 (get-buffer-window-list buf)))))
8101 (defun markdown-get-point-back-lines (pt num-lines)
8102 (save-excursion
8103 (goto-char pt)
8104 (line-move-visual (- num-lines) t)
8105 ;; in testing, can occasionally overshoot the number of lines to traverse
8106 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
8107 (when (> actual-num-lines num-lines)
8108 (line-move-visual (- actual-num-lines num-lines) t)))
8109 (point)))
8111 (defun markdown-live-preview-window-deserialize (window-posns)
8112 "Apply window point and scroll data from WINDOW-POSNS.
8113 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
8114 (cl-destructuring-bind (win pt-or-sym diff) window-posns
8115 (when (window-live-p win)
8116 (with-current-buffer markdown-live-preview-buffer
8117 (set-window-buffer win (current-buffer))
8118 (cl-destructuring-bind (actual-pt actual-diff)
8119 (cl-case pt-or-sym
8120 (min (list (point-min) 0))
8121 (max (list (point-max) diff))
8122 (t (list pt-or-sym diff)))
8123 (set-window-start
8124 win (markdown-get-point-back-lines actual-pt actual-diff))
8125 (set-window-point win actual-pt))))))
8127 (defun markdown-live-preview-export ()
8128 "Export to XHTML using `markdown-export'.
8129 Browse the resulting file within Emacs using
8130 `markdown-live-preview-window-function' Return the buffer
8131 displaying the rendered output."
8132 (interactive)
8133 (let ((filename (markdown-live-preview-get-filename)))
8134 (when filename
8135 (let* ((markdown-live-preview-currently-exporting t)
8136 (cur-buf (current-buffer))
8137 (export-file (markdown-export filename))
8138 ;; get positions in all windows currently displaying output buffer
8139 (window-data
8140 (markdown-live-preview-window-serialize
8141 markdown-live-preview-buffer)))
8142 (save-window-excursion
8143 (let ((output-buffer
8144 (funcall markdown-live-preview-window-function export-file)))
8145 (with-current-buffer output-buffer
8146 (setq markdown-live-preview-source-buffer cur-buf)
8147 (add-hook 'kill-buffer-hook
8148 #'markdown-live-preview-remove-on-kill t t))
8149 (with-current-buffer cur-buf
8150 (setq markdown-live-preview-buffer output-buffer))))
8151 (with-current-buffer cur-buf
8152 ;; reset all windows displaying output buffer to where they were,
8153 ;; now with the new output
8154 (mapc #'markdown-live-preview-window-deserialize window-data)
8155 ;; delete html editing buffer
8156 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8157 (when (and export-file (file-exists-p export-file)
8158 (eq markdown-live-preview-delete-export
8159 'delete-on-export))
8160 (delete-file export-file))
8161 markdown-live-preview-buffer)))))
8163 (defun markdown-live-preview-remove ()
8164 (when (buffer-live-p markdown-live-preview-buffer)
8165 (kill-buffer markdown-live-preview-buffer))
8166 (setq markdown-live-preview-buffer nil)
8167 ;; if set to 'delete-on-export, the output has already been deleted
8168 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8169 (let ((outfile-name (markdown-live-preview-get-filename)))
8170 (when (and outfile-name (file-exists-p outfile-name))
8171 (delete-file outfile-name)))))
8173 (defun markdown-get-other-window ()
8174 "Find another window to display preview or output content."
8175 (cond
8176 ((memq markdown-split-window-direction '(vertical below))
8177 (or (window-in-direction 'below) (split-window-vertically)))
8178 ((memq markdown-split-window-direction '(horizontal right))
8179 (or (window-in-direction 'right) (split-window-horizontally)))
8180 (t (split-window-sensibly (get-buffer-window)))))
8182 (defun markdown-display-buffer-other-window (buf)
8183 "Display preview or output buffer BUF in another window."
8184 (let ((cur-buf (current-buffer))
8185 (window (markdown-get-other-window)))
8186 (set-window-buffer window buf)
8187 (set-buffer cur-buf)))
8189 (defun markdown-live-preview-if-markdown ()
8190 (when (and (derived-mode-p 'markdown-mode)
8191 markdown-live-preview-mode)
8192 (unless markdown-live-preview-currently-exporting
8193 (if (buffer-live-p markdown-live-preview-buffer)
8194 (markdown-live-preview-export)
8195 (markdown-display-buffer-other-window
8196 (markdown-live-preview-export))))))
8198 (defun markdown-live-preview-remove-on-kill ()
8199 (cond ((and (derived-mode-p 'markdown-mode)
8200 markdown-live-preview-mode)
8201 (markdown-live-preview-remove))
8202 (markdown-live-preview-source-buffer
8203 (with-current-buffer markdown-live-preview-source-buffer
8204 (setq markdown-live-preview-buffer nil))
8205 (setq markdown-live-preview-source-buffer nil))))
8207 (defun markdown-live-preview-switch-to-output ()
8208 "Switch to output buffer."
8209 (interactive)
8210 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8211 output buffer in another window."
8212 (if markdown-live-preview-mode
8213 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8214 (markdown-live-preview-mode))
8216 (defun markdown-live-preview-re-export ()
8217 "Re export source buffer."
8218 (interactive)
8219 "If the current buffer is a buffer displaying the exported version of a
8220 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8221 update this buffer's contents."
8222 (when markdown-live-preview-source-buffer
8223 (with-current-buffer markdown-live-preview-source-buffer
8224 (markdown-live-preview-export))))
8226 (defun markdown-open ()
8227 "Open file for the current buffer with `markdown-open-command'."
8228 (interactive)
8229 (unless markdown-open-command
8230 (user-error "Variable `markdown-open-command' must be set"))
8231 (if (stringp markdown-open-command)
8232 (if (not buffer-file-name)
8233 (user-error "Must be visiting a file")
8234 (save-buffer)
8235 (call-process markdown-open-command nil 0 nil buffer-file-name))
8236 (funcall markdown-open-command))
8237 nil)
8239 (defun markdown-kill-ring-save ()
8240 "Run Markdown on file and store output in the kill ring."
8241 (interactive)
8242 (save-window-excursion
8243 (markdown)
8244 (with-current-buffer markdown-output-buffer-name
8245 (kill-ring-save (point-min) (point-max)))))
8248 ;;; Links =====================================================================
8250 (defun markdown-link-p ()
8251 "Return non-nil when `point' is at a non-wiki link.
8252 See `markdown-wiki-link-p' for more information."
8253 (let ((case-fold-search nil))
8254 (and (not (markdown-wiki-link-p))
8255 (not (markdown-code-block-at-point-p))
8256 (or (thing-at-point-looking-at markdown-regex-link-inline)
8257 (thing-at-point-looking-at markdown-regex-link-reference)
8258 (thing-at-point-looking-at markdown-regex-uri)
8259 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8261 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8263 (defun markdown-link-at-pos (pos)
8264 "Return properties of link or image at position POS.
8265 Value is a list of elements describing the link:
8266 0. beginning position
8267 1. end position
8268 2. link text
8269 3. URL
8270 4. reference label
8271 5. title text
8272 6. bang (nil or \"!\")"
8273 (save-excursion
8274 (goto-char pos)
8275 (let (begin end text url reference title bang)
8276 (cond
8277 ;; Inline or reference image or link at point.
8278 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8279 (thing-at-point-looking-at markdown-regex-link-reference))
8280 (setq bang (match-string-no-properties 1)
8281 begin (match-beginning 0)
8282 end (match-end 0)
8283 text (match-string-no-properties 3))
8284 (if (char-equal (char-after (match-beginning 5)) ?\[)
8285 ;; Reference link
8286 (setq reference (match-string-no-properties 6))
8287 ;; Inline link
8288 (setq url (match-string-no-properties 6))
8289 (when (match-end 7)
8290 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8291 ;; Angle bracket URI at point.
8292 ((thing-at-point-looking-at markdown-regex-angle-uri)
8293 (setq begin (match-beginning 0)
8294 end (match-end 0)
8295 url (match-string-no-properties 2)))
8296 ;; Plain URI at point.
8297 ((thing-at-point-looking-at markdown-regex-uri)
8298 (setq begin (match-beginning 0)
8299 end (match-end 0)
8300 url (match-string-no-properties 1))))
8301 (list begin end text url reference title bang))))
8303 (defun markdown-link-url ()
8304 "Return the URL part of the regular (non-wiki) link at point.
8305 Works with both inline and reference style links, and with images.
8306 If point is not at a link or the link reference is not defined
8307 returns nil."
8308 (let* ((values (markdown-link-at-pos (point)))
8309 (text (nth 2 values))
8310 (url (nth 3 values))
8311 (ref (nth 4 values)))
8312 (or url (and ref (car (markdown-reference-definition
8313 (downcase (if (string= ref "") text ref))))))))
8315 (defun markdown-follow-link-at-point ()
8316 "Open the current non-wiki link.
8317 If the link is a complete URL, open in browser with `browse-url'.
8318 Otherwise, open with `find-file' after stripping anchor and/or query string.
8319 Translate filenames using `markdown-filename-translate-function'."
8320 (interactive)
8321 (if (markdown-link-p)
8322 (let* ((url (markdown-link-url))
8323 (struct (url-generic-parse-url url))
8324 (full (url-fullness struct))
8325 (file url))
8326 ;; Parse URL, determine fullness, strip query string
8327 (if (fboundp 'url-path-and-query)
8328 (setq file (car (url-path-and-query struct)))
8329 (when (and (setq file (url-filename struct))
8330 (string-match "\\?" file))
8331 (setq file (substring file 0 (match-beginning 0)))))
8332 ;; Open full URLs in browser, files in Emacs
8333 (if full
8334 (browse-url url)
8335 (when (and file (> (length file) 0))
8336 (find-file (funcall markdown-translate-filename-function file)))))
8337 (user-error "Point is not at a Markdown link or URL")))
8339 (defun markdown-fontify-inline-links (last)
8340 "Add text properties to next inline link from point to LAST."
8341 (when (markdown-match-generic-links last nil)
8342 (let* ((link-start (match-beginning 3))
8343 (link-end (match-end 3))
8344 (url-start (match-beginning 6))
8345 (url-end (match-end 6))
8346 (url (match-string-no-properties 6))
8347 (title-start (match-beginning 7))
8348 (title-end (match-end 7))
8349 (title (match-string-no-properties 7))
8350 ;; Markup part
8351 (mp (list 'face 'markdown-markup-face
8352 'invisible 'markdown-markup
8353 'rear-nonsticky t
8354 'font-lock-multiline t))
8355 ;; Link part
8356 (lp (list 'keymap markdown-mode-mouse-map
8357 'face markdown-link-face
8358 'mouse-face 'markdown-highlight-face
8359 'font-lock-multiline t
8360 'help-echo (if title (concat title "\n" url) url)))
8361 ;; URL part
8362 (up (list 'keymap markdown-mode-mouse-map
8363 'face 'markdown-url-face
8364 'invisible 'markdown-markup
8365 'mouse-face 'markdown-highlight-face
8366 'font-lock-multiline t))
8367 ;; URL composition character
8368 (url-char (markdown--first-displayable markdown-url-compose-char))
8369 ;; Title part
8370 (tp (list 'face 'markdown-link-title-face
8371 'invisible 'markdown-markup
8372 'font-lock-multiline t)))
8373 (dolist (g '(1 2 4 5 8))
8374 (when (match-end g)
8375 (add-text-properties (match-beginning g) (match-end g) mp)))
8376 (when link-start (add-text-properties link-start link-end lp))
8377 (when url-start (add-text-properties url-start url-end up))
8378 (when title-start (add-text-properties url-end title-end tp))
8379 (when (and markdown-hide-urls url-start)
8380 (compose-region url-start (or title-end url-end) url-char))
8381 t)))
8383 (defun markdown-fontify-reference-links (last)
8384 "Add text properties to next reference link from point to LAST."
8385 (when (markdown-match-generic-links last t)
8386 (let* ((link-start (match-beginning 3))
8387 (link-end (match-end 3))
8388 (ref-start (match-beginning 6))
8389 (ref-end (match-end 6))
8390 ;; Markup part
8391 (mp (list 'face 'markdown-markup-face
8392 'invisible 'markdown-markup
8393 'rear-nonsticky t
8394 'font-lock-multiline t))
8395 ;; Link part
8396 (lp (list 'keymap markdown-mode-mouse-map
8397 'face markdown-link-face
8398 'mouse-face 'markdown-highlight-face
8399 'font-lock-multiline t
8400 'help-echo (lambda (_ __ pos)
8401 (save-match-data
8402 (save-excursion
8403 (goto-char pos)
8404 (or (markdown-link-url)
8405 "Undefined reference"))))))
8406 ;; URL composition character
8407 (url-char (markdown--first-displayable markdown-url-compose-char))
8408 ;; Reference part
8409 (rp (list 'face 'markdown-reference-face
8410 'invisible 'markdown-markup
8411 'font-lock-multiline t)))
8412 (dolist (g '(1 2 4 5 8))
8413 (when (match-end g)
8414 (add-text-properties (match-beginning g) (match-end g) mp)))
8415 (when link-start (add-text-properties link-start link-end lp))
8416 (when ref-start (add-text-properties ref-start ref-end rp)
8417 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8418 (compose-region ref-start ref-end url-char)))
8419 t)))
8421 (defun markdown-fontify-angle-uris (last)
8422 "Add text properties to angle URIs from point to LAST."
8423 (when (markdown-match-angle-uris last)
8424 (let* ((url-start (match-beginning 2))
8425 (url-end (match-end 2))
8426 ;; Markup part
8427 (mp (list 'face 'markdown-markup-face
8428 'invisible 'markdown-markup
8429 'rear-nonsticky t
8430 'font-lock-multiline t))
8431 ;; URI part
8432 (up (list 'keymap markdown-mode-mouse-map
8433 'face 'markdown-plain-url-face
8434 'mouse-face 'markdown-highlight-face
8435 'font-lock-multiline t)))
8436 (dolist (g '(1 3))
8437 (add-text-properties (match-beginning g) (match-end g) mp))
8438 (add-text-properties url-start url-end up)
8439 t)))
8441 (defun markdown-fontify-plain-uris (last)
8442 "Add text properties to plain URLs from point to LAST."
8443 (when (markdown-match-plain-uris last)
8444 (let* ((start (match-beginning 0))
8445 (end (match-end 0))
8446 (props (list 'keymap markdown-mode-mouse-map
8447 'face 'markdown-plain-url-face
8448 'mouse-face 'markdown-highlight-face
8449 'rear-nonsticky t
8450 'font-lock-multiline t)))
8451 (add-text-properties start end props)
8452 t)))
8454 (defun markdown-toggle-url-hiding (&optional arg)
8455 "Toggle the display or hiding of URLs.
8456 With a prefix argument ARG, enable URL hiding if ARG is positive,
8457 and disable it otherwise."
8458 (interactive (list (or current-prefix-arg 'toggle)))
8459 (setq markdown-hide-urls
8460 (if (eq arg 'toggle)
8461 (not markdown-hide-urls)
8462 (> (prefix-numeric-value arg) 0)))
8463 (if markdown-hide-urls
8464 (message "markdown-mode URL hiding enabled")
8465 (message "markdown-mode URL hiding disabled"))
8466 (markdown-reload-extensions))
8469 ;;; WikiLink Following/Markup =================================================
8471 (defun markdown-wiki-link-p ()
8472 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8473 A true wiki link name matches `markdown-regex-wiki-link' but does
8474 not match the current file name after conversion. This modifies
8475 the data returned by `match-data'. Note that the potential wiki
8476 link name must be available via `match-string'."
8477 (when markdown-enable-wiki-links
8478 (let ((case-fold-search nil))
8479 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8480 (not (markdown-code-block-at-point-p))
8481 (or (not buffer-file-name)
8482 (not (string-equal (buffer-file-name)
8483 (markdown-convert-wiki-link-to-filename
8484 (markdown-wiki-link-link)))))))))
8486 (defun markdown-wiki-link-link ()
8487 "Return the link part of the wiki link using current match data.
8488 The location of the link component depends on the value of
8489 `markdown-wiki-link-alias-first'."
8490 (if markdown-wiki-link-alias-first
8491 (or (match-string-no-properties 5) (match-string-no-properties 3))
8492 (match-string-no-properties 3)))
8494 (defun markdown-wiki-link-alias ()
8495 "Return the alias or text part of the wiki link using current match data.
8496 The location of the alias component depends on the value of
8497 `markdown-wiki-link-alias-first'."
8498 (if markdown-wiki-link-alias-first
8499 (match-string-no-properties 3)
8500 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8502 (defun markdown-convert-wiki-link-to-filename (name)
8503 "Generate a filename from the wiki link NAME.
8504 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8505 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8506 and [[test test]] both map to Test-test.ext. Look in the current
8507 directory first, then in subdirectories if
8508 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8509 in parent directories if
8510 `markdown-wiki-link-search-parent-directories' is non-nil."
8511 (let* ((basename (markdown-replace-regexp-in-string
8512 "[[:space:]\n]" markdown-link-space-sub-char name))
8513 (basename (if (eq major-mode 'gfm-mode)
8514 (concat (upcase (substring basename 0 1))
8515 (downcase (substring basename 1 nil)))
8516 basename))
8517 directory extension default candidates dir)
8518 (when buffer-file-name
8519 (setq directory (file-name-directory buffer-file-name)
8520 extension (file-name-extension buffer-file-name)))
8521 (setq default (concat basename
8522 (when extension (concat "." extension))))
8523 (cond
8524 ;; Look in current directory first.
8525 ((or (null buffer-file-name)
8526 (file-exists-p default))
8527 default)
8528 ;; Possibly search in subdirectories, next.
8529 ((and markdown-wiki-link-search-subdirectories
8530 (setq candidates
8531 (markdown-directory-files-recursively
8532 directory (concat "^" default "$"))))
8533 (car candidates))
8534 ;; Possibly search in parent directories as a last resort.
8535 ((and markdown-wiki-link-search-parent-directories
8536 (setq dir (locate-dominating-file directory default)))
8537 (concat dir default))
8538 ;; If nothing is found, return default in current directory.
8539 (t default))))
8541 (defun markdown-follow-wiki-link (name &optional other)
8542 "Follow the wiki link NAME.
8543 Convert the name to a file name and call `find-file'. Ensure that
8544 the new buffer remains in `markdown-mode'. Open the link in another
8545 window when OTHER is non-nil."
8546 (let ((filename (markdown-convert-wiki-link-to-filename name))
8547 (wp (when buffer-file-name
8548 (file-name-directory buffer-file-name))))
8549 (if (not wp)
8550 (user-error "Must be visiting a file")
8551 (when other (other-window 1))
8552 (let ((default-directory wp))
8553 (find-file filename)))
8554 (when (not (eq major-mode 'markdown-mode))
8555 (markdown-mode))))
8557 (defun markdown-follow-wiki-link-at-point (&optional arg)
8558 "Find Wiki Link at point.
8559 With prefix argument ARG, open the file in other window.
8560 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8561 (interactive "P")
8562 (if (markdown-wiki-link-p)
8563 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8564 (user-error "Point is not at a Wiki Link")))
8566 (defun markdown-highlight-wiki-link (from to face)
8567 "Highlight the wiki link in the region between FROM and TO using FACE."
8568 (put-text-property from to 'font-lock-face face))
8570 (defun markdown-unfontify-region-wiki-links (from to)
8571 "Remove wiki link faces from the region specified by FROM and TO."
8572 (interactive "*r")
8573 (let ((modified (buffer-modified-p)))
8574 (remove-text-properties from to '(font-lock-face markdown-link-face))
8575 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8576 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8577 ;; undo that if it wasn't originally marked modified
8578 (set-buffer-modified-p modified)))
8580 (defun markdown-fontify-region-wiki-links (from to)
8581 "Search region given by FROM and TO for wiki links and fontify them.
8582 If a wiki link is found check to see if the backing file exists
8583 and highlight accordingly."
8584 (goto-char from)
8585 (save-match-data
8586 (while (re-search-forward markdown-regex-wiki-link to t)
8587 (when (not (markdown-code-block-at-point-p))
8588 (let ((highlight-beginning (match-beginning 1))
8589 (highlight-end (match-end 1))
8590 (file-name
8591 (markdown-convert-wiki-link-to-filename
8592 (markdown-wiki-link-link))))
8593 (if (condition-case nil (file-exists-p file-name) (error nil))
8594 (markdown-highlight-wiki-link
8595 highlight-beginning highlight-end markdown-link-face)
8596 (markdown-highlight-wiki-link
8597 highlight-beginning highlight-end markdown-missing-link-face)))))))
8599 (defun markdown-extend-changed-region (from to)
8600 "Extend region given by FROM and TO so that we can fontify all links.
8601 The region is extended to the first newline before and the first
8602 newline after."
8603 ;; start looking for the first new line before 'from
8604 (goto-char from)
8605 (re-search-backward "\n" nil t)
8606 (let ((new-from (point-min))
8607 (new-to (point-max)))
8608 (if (not (= (point) from))
8609 (setq new-from (point)))
8610 ;; do the same thing for the first new line after 'to
8611 (goto-char to)
8612 (re-search-forward "\n" nil t)
8613 (if (not (= (point) to))
8614 (setq new-to (point)))
8615 (cl-values new-from new-to)))
8617 (defun markdown-check-change-for-wiki-link (from to)
8618 "Check region between FROM and TO for wiki links and re-fontify as needed."
8619 (interactive "*r")
8620 (let* ((modified (buffer-modified-p))
8621 (buffer-undo-list t)
8622 (inhibit-read-only t)
8623 (inhibit-point-motion-hooks t)
8624 deactivate-mark
8625 buffer-file-truename)
8626 (unwind-protect
8627 (save-excursion
8628 (save-match-data
8629 (save-restriction
8630 ;; Extend the region to fontify so that it starts
8631 ;; and ends at safe places.
8632 (cl-multiple-value-bind (new-from new-to)
8633 (markdown-extend-changed-region from to)
8634 (goto-char new-from)
8635 ;; Only refontify when the range contains text with a
8636 ;; wiki link face or if the wiki link regexp matches.
8637 (when (or (markdown-range-property-any
8638 new-from new-to 'font-lock-face
8639 (list markdown-link-face
8640 markdown-missing-link-face))
8641 (re-search-forward
8642 markdown-regex-wiki-link new-to t))
8643 ;; Unfontify existing fontification (start from scratch)
8644 (markdown-unfontify-region-wiki-links new-from new-to)
8645 ;; Now do the fontification.
8646 (markdown-fontify-region-wiki-links new-from new-to))))))
8647 (and (not modified)
8648 (buffer-modified-p)
8649 (set-buffer-modified-p nil)))))
8651 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8652 "Check region between FROM and TO for wiki links and re-fontify as needed.
8653 Designed to be used with the `after-change-functions' hook."
8654 (markdown-check-change-for-wiki-link from to))
8656 (defun markdown-fontify-buffer-wiki-links ()
8657 "Refontify all wiki links in the buffer."
8658 (interactive)
8659 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8662 ;;; Following & Doing =========================================================
8664 (defun markdown-follow-thing-at-point (arg)
8665 "Follow thing at point if possible, such as a reference link or wiki link.
8666 Opens inline and reference links in a browser. Opens wiki links
8667 to other files in the current window, or the another window if
8668 ARG is non-nil.
8669 See `markdown-follow-link-at-point' and
8670 `markdown-follow-wiki-link-at-point'."
8671 (interactive "P")
8672 (cond ((markdown-link-p)
8673 (markdown-follow-link-at-point))
8674 ((markdown-wiki-link-p)
8675 (markdown-follow-wiki-link-at-point arg))
8677 (user-error "Nothing to follow at point"))))
8679 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8681 (defun markdown-do ()
8682 "Do something sensible based on context at point.
8683 Jumps between reference links and definitions; between footnote
8684 markers and footnote text."
8685 (interactive)
8686 (cond
8687 ;; Footnote definition
8688 ((markdown-footnote-text-positions)
8689 (markdown-footnote-return))
8690 ;; Footnote marker
8691 ((markdown-footnote-marker-positions)
8692 (markdown-footnote-goto-text))
8693 ;; Reference link
8694 ((thing-at-point-looking-at markdown-regex-link-reference)
8695 (markdown-reference-goto-definition))
8696 ;; Reference definition
8697 ((thing-at-point-looking-at markdown-regex-reference-definition)
8698 (markdown-reference-goto-link (match-string-no-properties 2)))
8699 ;; GFM task list item
8700 ((markdown-gfm-task-list-item-at-point)
8701 (markdown-toggle-gfm-checkbox))
8702 ;; Align table
8703 ((markdown-table-at-point-p)
8704 (call-interactively #'markdown-table-align))
8705 ;; Otherwise
8707 (markdown-insert-gfm-checkbox))))
8710 ;;; Miscellaneous =============================================================
8712 (defun markdown-compress-whitespace-string (str)
8713 "Compress whitespace in STR and return result.
8714 Leading and trailing whitespace is removed. Sequences of multiple
8715 spaces, tabs, and newlines are replaced with single spaces."
8716 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8717 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8719 (defun markdown--substitute-command-keys (string)
8720 "Like `substitute-command-keys' but, but prefers control characters.
8721 First pass STRING to `substitute-command-keys' and then
8722 substitute `C-i` for `TAB` and `C-m` for `RET`."
8723 (replace-regexp-in-string
8724 "\\<TAB\\>" "C-i"
8725 (replace-regexp-in-string
8726 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8728 (defun markdown-line-number-at-pos (&optional pos)
8729 "Return (narrowed) buffer line number at position POS.
8730 If POS is nil, use current buffer location.
8731 This is an exact copy of `line-number-at-pos' for use in emacs21."
8732 (let ((opoint (or pos (point))) start)
8733 (save-excursion
8734 (goto-char (point-min))
8735 (setq start (point))
8736 (goto-char opoint)
8737 (forward-line 0)
8738 (1+ (count-lines start (point))))))
8740 (defun markdown-inside-link-p ()
8741 "Return t if point is within a link."
8742 (save-match-data
8743 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8745 (defun markdown-line-is-reference-definition-p ()
8746 "Return whether the current line is a (non-footnote) reference defition."
8747 (save-excursion
8748 (move-beginning-of-line 1)
8749 (and (looking-at-p markdown-regex-reference-definition)
8750 (not (looking-at-p "[ \t]*\\[^")))))
8752 (defun markdown-adaptive-fill-function ()
8753 "Return prefix for filling paragraph or nil if not determined."
8754 (cond
8755 ;; List item inside blockquote
8756 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8757 (markdown-replace-regexp-in-string
8758 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8759 ;; Blockquote
8760 ((looking-at markdown-regex-blockquote)
8761 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8762 ;; List items
8763 ((looking-at markdown-regex-list)
8764 (match-string-no-properties 0))
8765 ;; Footnote definition
8766 ((looking-at-p markdown-regex-footnote-definition)
8767 " ") ; four spaces
8768 ;; No match
8769 (t nil)))
8771 (defun markdown-fill-paragraph (&optional justify)
8772 "Fill paragraph at or after point.
8773 This function is like \\[fill-paragraph], but it skips Markdown
8774 code blocks. If the point is in a code block, or just before one,
8775 do not fill. Otherwise, call `fill-paragraph' as usual. If
8776 JUSTIFY is non-nil, justify text as well. Since this function
8777 handles filling itself, it always returns t so that
8778 `fill-paragraph' doesn't run."
8779 (interactive "P")
8780 (unless (or (markdown-code-block-at-point-p)
8781 (save-excursion
8782 (back-to-indentation)
8783 (skip-syntax-forward "-")
8784 (markdown-code-block-at-point-p)))
8785 (fill-paragraph justify))
8788 (make-obsolete 'markdown-fill-forward-paragraph-function
8789 'markdown-fill-forward-paragraph "v2.3")
8791 (defun markdown-fill-forward-paragraph (&optional arg)
8792 "Function used by `fill-paragraph' to move over ARG paragraphs.
8793 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8794 It is called with a single argument specifying the number of
8795 paragraphs to move. Just like `forward-paragraph', it should
8796 return the number of paragraphs left to move."
8797 (or arg (setq arg 1))
8798 (if (> arg 0)
8799 ;; With positive ARG, move across ARG non-code-block paragraphs,
8800 ;; one at a time. When passing a code block, don't decrement ARG.
8801 (while (and (not (eobp))
8802 (> arg 0)
8803 (= (forward-paragraph 1) 0)
8804 (or (markdown-code-block-at-pos (point-at-bol 0))
8805 (setq arg (1- arg)))))
8806 ;; Move backward by one paragraph with negative ARG (always -1).
8807 (let ((start (point)))
8808 (setq arg (forward-paragraph arg))
8809 (while (and (not (eobp))
8810 (progn (move-to-left-margin) (not (eobp)))
8811 (looking-at-p paragraph-separate))
8812 (forward-line 1))
8813 (cond
8814 ;; Move point past whitespace following list marker.
8815 ((looking-at markdown-regex-list)
8816 (goto-char (match-end 0)))
8817 ;; Move point past whitespace following pipe at beginning of line
8818 ;; to handle Pandoc line blocks.
8819 ((looking-at "^|\\s-*")
8820 (goto-char (match-end 0)))
8821 ;; Return point if the paragraph passed was a code block.
8822 ((markdown-code-block-at-pos (point-at-bol 2))
8823 (goto-char start)))))
8824 arg)
8826 (defun markdown--inhibit-electric-quote ()
8827 "Function added to `electric-quote-inhibit-functions'.
8828 Return non-nil if the quote has been inserted inside a code block
8829 or span."
8830 (let ((pos (1- (point))))
8831 (or (markdown-inline-code-at-pos pos)
8832 (markdown-code-block-at-pos pos))))
8835 ;;; Extension Framework =======================================================
8837 (defun markdown-reload-extensions ()
8838 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8839 (interactive)
8840 (when (member major-mode '(markdown-mode gfm-mode))
8841 ;; Refontify buffer
8842 (if (eval-when-compile (fboundp 'font-lock-flush))
8843 ;; Use font-lock-flush in Emacs >= 25.1
8844 (font-lock-flush)
8845 ;; Backwards compatibility for Emacs 24.3-24.5
8846 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8847 (font-lock-refresh-defaults)))
8848 ;; Add or remove hooks related to extensions
8849 (markdown-setup-wiki-link-hooks)))
8851 (defun markdown-handle-local-variables ()
8852 "Run in `hack-local-variables-hook' to update font lock rules.
8853 Checks to see if there is actually a ‘markdown-mode’ file local variable
8854 before regenerating font-lock rules for extensions."
8855 (when (and (boundp 'file-local-variables-alist)
8856 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8857 (assoc 'markdown-enable-math file-local-variables-alist)))
8858 (when (assoc 'markdown-enable-math file-local-variables-alist)
8859 (markdown-toggle-math markdown-enable-math))
8860 (markdown-reload-extensions)))
8863 ;;; Wiki Links ================================================================
8865 (defun markdown-toggle-wiki-links (&optional arg)
8866 "Toggle support for wiki links.
8867 With a prefix argument ARG, enable wiki link support if ARG is positive,
8868 and disable it otherwise."
8869 (interactive (list (or current-prefix-arg 'toggle)))
8870 (setq markdown-enable-wiki-links
8871 (if (eq arg 'toggle)
8872 (not markdown-enable-wiki-links)
8873 (> (prefix-numeric-value arg) 0)))
8874 (if markdown-enable-wiki-links
8875 (message "markdown-mode wiki link support enabled")
8876 (message "markdown-mode wiki link support disabled"))
8877 (markdown-reload-extensions))
8879 (defun markdown-setup-wiki-link-hooks ()
8880 "Add or remove hooks for fontifying wiki links.
8881 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8882 ;; Anytime text changes make sure it gets fontified correctly
8883 (if (and markdown-enable-wiki-links
8884 markdown-wiki-link-fontify-missing)
8885 (add-hook 'after-change-functions
8886 'markdown-check-change-for-wiki-link-after-change t t)
8887 (remove-hook 'after-change-functions
8888 'markdown-check-change-for-wiki-link-after-change t))
8889 ;; If we left the buffer there is a really good chance we were
8890 ;; creating one of the wiki link documents. Make sure we get
8891 ;; refontified when we come back.
8892 (if (and markdown-enable-wiki-links
8893 markdown-wiki-link-fontify-missing)
8894 (progn
8895 (add-hook 'window-configuration-change-hook
8896 'markdown-fontify-buffer-wiki-links t t)
8897 (markdown-fontify-buffer-wiki-links))
8898 (remove-hook 'window-configuration-change-hook
8899 'markdown-fontify-buffer-wiki-links t)
8900 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8903 ;;; Math Support ==============================================================
8905 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8907 (defconst markdown-mode-font-lock-keywords-math
8908 (list
8909 ;; Equation reference (eq:foo)
8910 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
8911 (2 markdown-reference-face)
8912 (3 markdown-markup-face)))
8913 ;; Equation reference \eqref{foo}
8914 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
8915 (2 markdown-reference-face)
8916 (3 markdown-markup-face))))
8917 "Font lock keywords to add and remove when toggling math support.")
8919 (defun markdown-toggle-math (&optional arg)
8920 "Toggle support for inline and display LaTeX math expressions.
8921 With a prefix argument ARG, enable math mode if ARG is positive,
8922 and disable it otherwise. If called from Lisp, enable the mode
8923 if ARG is omitted or nil."
8924 (interactive (list (or current-prefix-arg 'toggle)))
8925 (setq markdown-enable-math
8926 (if (eq arg 'toggle)
8927 (not markdown-enable-math)
8928 (> (prefix-numeric-value arg) 0)))
8929 (if markdown-enable-math
8930 (progn
8931 (font-lock-add-keywords
8932 'markdown-mode markdown-mode-font-lock-keywords-math)
8933 (message "markdown-mode math support enabled"))
8934 (font-lock-remove-keywords
8935 'markdown-mode markdown-mode-font-lock-keywords-math)
8936 (message "markdown-mode math support disabled"))
8937 (markdown-reload-extensions))
8940 ;;; GFM Checkboxes ============================================================
8942 (define-button-type 'markdown-gfm-checkbox-button
8943 'follow-link t
8944 'face 'markdown-gfm-checkbox-face
8945 'mouse-face 'markdown-highlight-face
8946 'action #'markdown-toggle-gfm-checkbox-button)
8948 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
8949 "Return non-nil if there is a GFM task list item at the point.
8950 Optionally, the list item BOUNDS may be given if available, as
8951 returned by `markdown-cur-list-item-bounds'. When a task list item
8952 is found, the return value is the same value returned by
8953 `markdown-cur-list-item-bounds'."
8954 (unless bounds
8955 (setq bounds (markdown-cur-list-item-bounds)))
8956 (> (length (nth 5 bounds)) 0))
8958 (defun markdown-insert-gfm-checkbox ()
8959 "Add GFM checkbox at point.
8960 Returns t if added.
8961 Returns nil if non-applicable."
8962 (interactive)
8963 (let ((bounds (markdown-cur-list-item-bounds)))
8964 (if bounds
8965 (unless (cl-sixth bounds)
8966 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
8967 (markup "[ ] "))
8968 (if (< pos (point))
8969 (save-excursion
8970 (goto-char pos)
8971 (insert markup))
8972 (goto-char pos)
8973 (insert markup))
8975 (unless (save-excursion
8976 (back-to-indentation)
8977 (or (markdown-list-item-at-point-p)
8978 (markdown-heading-at-point)
8979 (markdown-in-comment-p)
8980 (markdown-code-block-at-point-p)))
8981 (let ((pos (save-excursion
8982 (back-to-indentation)
8983 (point)))
8984 (markup (concat (or (save-excursion
8985 (beginning-of-line 0)
8986 (cl-fifth (markdown-cur-list-item-bounds)))
8987 markdown-unordered-list-item-prefix)
8988 "[ ] ")))
8989 (if (< pos (point))
8990 (save-excursion
8991 (goto-char pos)
8992 (insert markup))
8993 (goto-char pos)
8994 (insert markup))
8995 t)))))
8997 (defun markdown-toggle-gfm-checkbox ()
8998 "Toggle GFM checkbox at point.
8999 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
9000 Returns nil if there is no task list item at the point."
9001 (interactive)
9002 (save-match-data
9003 (save-excursion
9004 (let ((bounds (markdown-cur-list-item-bounds)))
9005 (when bounds
9006 ;; Move to beginning of task list item
9007 (goto-char (cl-first bounds))
9008 ;; Advance to column of first non-whitespace after marker
9009 (forward-char (cl-fourth bounds))
9010 (cond ((looking-at "\\[ \\]")
9011 (replace-match
9012 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
9013 nil t)
9014 (match-string-no-properties 0))
9015 ((looking-at "\\[[xX]\\]")
9016 (replace-match "[ ]" nil t)
9017 (match-string-no-properties 0))))))))
9019 (defun markdown-toggle-gfm-checkbox-button (button)
9020 "Toggle GFM checkbox BUTTON on click."
9021 (save-match-data
9022 (save-excursion
9023 (goto-char (button-start button))
9024 (markdown-toggle-gfm-checkbox))))
9026 (defun markdown-make-gfm-checkboxes-buttons (start end)
9027 "Make GFM checkboxes buttons in region between START and END."
9028 (save-excursion
9029 (goto-char start)
9030 (let ((case-fold-search t))
9031 (save-excursion
9032 (while (re-search-forward markdown-regex-gfm-checkbox end t)
9033 (make-button (match-beginning 1) (match-end 1)
9034 :type 'markdown-gfm-checkbox-button))))))
9036 ;; Called when any modification is made to buffer text.
9037 (defun markdown-gfm-checkbox-after-change-function (beg end _)
9038 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
9039 BEG and END are the limits of scanned region."
9040 (save-excursion
9041 (save-match-data
9042 ;; Rescan between start of line from `beg' and start of line after `end'.
9043 (markdown-make-gfm-checkboxes-buttons
9044 (progn (goto-char beg) (beginning-of-line) (point))
9045 (progn (goto-char end) (forward-line 1) (point))))))
9047 (defun markdown-remove-gfm-checkbox-overlays ()
9048 "Remove all GFM checkbox overlays in buffer."
9049 (save-excursion
9050 (save-restriction
9051 (widen)
9052 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
9055 ;;; Display inline image =================================================
9057 (defvar markdown-inline-image-overlays nil)
9058 (make-variable-buffer-local 'markdown-inline-image-overlays)
9060 (defun markdown-remove-inline-images ()
9061 "Remove inline image overlays from image links in the buffer.
9062 This can be toggled with `markdown-toggle-inline-images'
9063 or \\[markdown-toggle-inline-images]."
9064 (interactive)
9065 (mapc #'delete-overlay markdown-inline-image-overlays)
9066 (setq markdown-inline-image-overlays nil))
9068 (defun markdown-display-inline-images ()
9069 "Add inline image overlays to image links in the buffer.
9070 This can be toggled with `markdown-toggle-inline-images'
9071 or \\[markdown-toggle-inline-images]."
9072 (interactive)
9073 (unless (display-images-p)
9074 (error "Cannot show images"))
9075 (save-excursion
9076 (save-restriction
9077 (widen)
9078 (goto-char (point-min))
9079 (while (re-search-forward markdown-regex-link-inline nil t)
9080 (let ((start (match-beginning 0))
9081 (end (match-end 0))
9082 (file (match-string-no-properties 6)))
9083 (when (file-exists-p file)
9084 (let* ((abspath (if (file-name-absolute-p file)
9085 file
9086 (concat default-directory file)))
9087 (image
9088 (if (and markdown-max-image-size
9089 (image-type-available-p 'imagemagick))
9090 (create-image
9091 abspath 'imagemagick nil
9092 :max-width (car markdown-max-image-size)
9093 :max-height (cdr markdown-max-image-size))
9094 (create-image abspath))))
9095 (when image
9096 (let ((ov (make-overlay start end)))
9097 (overlay-put ov 'display image)
9098 (overlay-put ov 'face 'default)
9099 (push ov markdown-inline-image-overlays))))))))))
9101 (defun markdown-toggle-inline-images ()
9102 "Toggle inline image overlays in the buffer."
9103 (interactive)
9104 (if markdown-inline-image-overlays
9105 (markdown-remove-inline-images)
9106 (markdown-display-inline-images)))
9109 ;;; GFM Code Block Fontification ==============================================
9111 (defcustom markdown-fontify-code-blocks-natively nil
9112 "When non-nil, fontify code in code blocks using the native major mode.
9113 This only works for fenced code blocks where the language is
9114 specified where we can automatically determine the appropriate
9115 mode to use. The language to mode mapping may be customized by
9116 setting the variable `markdown-code-lang-modes'."
9117 :group 'markdown
9118 :type 'boolean
9119 :safe 'booleanp
9120 :package-version '(markdown-mode . "2.3"))
9122 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
9123 "Toggle the native fontification of code blocks.
9124 With a prefix argument ARG, enable if ARG is positive,
9125 and disable otherwise."
9126 (interactive (list (or current-prefix-arg 'toggle)))
9127 (setq markdown-fontify-code-blocks-natively
9128 (if (eq arg 'toggle)
9129 (not markdown-fontify-code-blocks-natively)
9130 (> (prefix-numeric-value arg) 0)))
9131 (if markdown-fontify-code-blocks-natively
9132 (message "markdown-mode native code block fontification enabled")
9133 (message "markdown-mode native code block fontification disabled"))
9134 (markdown-reload-extensions))
9136 ;; This is based on `org-src-lang-modes' from org-src.el
9137 (defcustom markdown-code-lang-modes
9138 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
9139 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
9140 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
9141 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9142 ("bash" . sh-mode))
9143 "Alist mapping languages to their major mode.
9144 The key is the language name, the value is the major mode. For
9145 many languages this is simple, but for language where this is not
9146 the case, this variable provides a way to simplify things on the
9147 user side. For example, there is no ocaml-mode in Emacs, but the
9148 mode to use is `tuareg-mode'."
9149 :group 'markdown
9150 :type '(repeat
9151 (cons
9152 (string "Language name")
9153 (symbol "Major mode")))
9154 :package-version '(markdown-mode . "2.3"))
9156 (defun markdown-get-lang-mode (lang)
9157 "Return major mode that should be used for LANG.
9158 LANG is a string, and the returned major mode is a symbol."
9159 (cl-find-if
9160 'fboundp
9161 (list (cdr (assoc lang markdown-code-lang-modes))
9162 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9163 (intern (concat lang "-mode"))
9164 (intern (concat (downcase lang) "-mode")))))
9166 (defun markdown-fontify-code-blocks-generic (matcher last)
9167 "Add text properties to next code block from point to LAST.
9168 Use matching function MATCHER."
9169 (when (funcall matcher last)
9170 (save-excursion
9171 (save-match-data
9172 (let* ((start (match-beginning 0))
9173 (end (match-end 0))
9174 ;; Find positions outside opening and closing backquotes.
9175 (bol-prev (progn (goto-char start)
9176 (if (bolp) (point-at-bol 0) (point-at-bol))))
9177 (eol-next (progn (goto-char end)
9178 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9179 lang)
9180 (if (and markdown-fontify-code-blocks-natively
9181 (setq lang (markdown-code-block-lang)))
9182 (markdown-fontify-code-block-natively lang start end)
9183 (add-text-properties start end '(face markdown-pre-face)))
9184 ;; Set background for block as well as opening and closing lines.
9185 (font-lock-append-text-property
9186 bol-prev eol-next 'face 'markdown-code-face)
9187 ;; Set invisible property for lines before and after, including newline.
9188 (add-text-properties bol-prev start '(invisible markdown-markup))
9189 (add-text-properties end eol-next '(invisible markdown-markup)))))
9192 (defun markdown-fontify-gfm-code-blocks (last)
9193 "Add text properties to next GFM code block from point to LAST."
9194 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9196 (defun markdown-fontify-fenced-code-blocks (last)
9197 "Add text properties to next tilde fenced code block from point to LAST."
9198 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9200 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9201 (defun markdown-fontify-code-block-natively (lang start end)
9202 "Fontify given GFM or fenced code block.
9203 This function is called by Emacs for automatic fontification when
9204 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9205 language used in the block. START and END specify the block
9206 position."
9207 (let ((lang-mode (markdown-get-lang-mode lang)))
9208 (when (fboundp lang-mode)
9209 (let ((string (buffer-substring-no-properties start end))
9210 (modified (buffer-modified-p))
9211 (markdown-buffer (current-buffer)) pos next)
9212 (remove-text-properties start end '(face nil))
9213 (with-current-buffer
9214 (get-buffer-create
9215 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9216 ;; Make sure that modification hooks are not inhibited in
9217 ;; the org-src-fontification buffer in case we're called
9218 ;; from `jit-lock-function' (Bug#25132).
9219 (let ((inhibit-modification-hooks nil))
9220 (delete-region (point-min) (point-max))
9221 (insert string " ")) ;; so there's a final property change
9222 (unless (eq major-mode lang-mode) (funcall lang-mode))
9223 (markdown-font-lock-ensure)
9224 (setq pos (point-min))
9225 (while (setq next (next-single-property-change pos 'face))
9226 (let ((val (get-text-property pos 'face)))
9227 (when val
9228 (put-text-property
9229 (+ start (1- pos)) (1- (+ start next)) 'face
9230 val markdown-buffer)))
9231 (setq pos next)))
9232 (add-text-properties
9233 start end
9234 '(font-lock-fontified t fontified t font-lock-multiline t))
9235 (set-buffer-modified-p modified)))))
9237 (require 'edit-indirect nil t)
9238 (defvar edit-indirect-guess-mode-function)
9239 (defvar edit-indirect-after-commit-functions)
9241 (defun markdown--edit-indirect-after-commit-function (_beg end)
9242 "Ensure trailing newlines at the END of code blocks."
9243 (goto-char end)
9244 (unless (eq (char-before) ?\n)
9245 (insert "\n")))
9247 (defun markdown-edit-code-block ()
9248 "Edit Markdown code block in an indirect buffer."
9249 (interactive)
9250 (save-excursion
9251 (if (fboundp 'edit-indirect-region)
9252 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9253 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9254 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9255 (if (and begin end)
9256 (let* ((lang (markdown-code-block-lang))
9257 (mode (or (and lang (markdown-get-lang-mode lang))
9258 markdown-edit-code-block-default-mode))
9259 (edit-indirect-guess-mode-function
9260 (lambda (_parent-buffer _beg _end)
9261 (funcall mode))))
9262 (edit-indirect-region begin end 'display-buffer))
9263 (user-error "Not inside a GFM or tilde fenced code block")))
9264 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9265 (progn (package-refresh-contents)
9266 (package-install 'edit-indirect)
9267 (markdown-edit-code-block))))))
9270 ;;; Table Editing
9272 ;; These functions were originally adapted from `org-table.el'.
9274 ;; General helper functions
9276 (defmacro markdown--with-gensyms (symbols &rest body)
9277 (declare (debug (sexp body)) (indent 1))
9278 `(let ,(mapcar (lambda (s)
9279 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9280 symbols)
9281 ,@body))
9283 (defun markdown--split-string (string &optional separators)
9284 "Splits STRING into substrings at SEPARATORS.
9285 SEPARATORS is a regular expression. If nil it defaults to
9286 `split-string-default-separators'. This version returns no empty
9287 strings if there are matches at the beginning and end of string."
9288 (let ((start 0) notfirst list)
9289 (while (and (string-match
9290 (or separators split-string-default-separators)
9291 string
9292 (if (and notfirst
9293 (= start (match-beginning 0))
9294 (< start (length string)))
9295 (1+ start) start))
9296 (< (match-beginning 0) (length string)))
9297 (setq notfirst t)
9298 (or (eq (match-beginning 0) 0)
9299 (and (eq (match-beginning 0) (match-end 0))
9300 (eq (match-beginning 0) start))
9301 (push (substring string start (match-beginning 0)) list))
9302 (setq start (match-end 0)))
9303 (or (eq start (length string))
9304 (push (substring string start) list))
9305 (nreverse list)))
9307 (defun markdown--string-width (s)
9308 "Return width of string S.
9309 This version ignores characters with invisibility property
9310 `markdown-markup'."
9311 (let (b)
9312 (when (or (eq t buffer-invisibility-spec)
9313 (member 'markdown-markup buffer-invisibility-spec))
9314 (while (setq b (text-property-any
9315 0 (length s)
9316 'invisible 'markdown-markup s))
9317 (setq s (concat
9318 (substring s 0 b)
9319 (substring s (or (next-single-property-change
9320 b 'invisible s)
9321 (length s))))))))
9322 (string-width s))
9324 (defun markdown--remove-invisible-markup (s)
9325 "Remove Markdown markup from string S.
9326 This version removes characters with invisibility property
9327 `markdown-markup'."
9328 (let (b)
9329 (while (setq b (text-property-any
9330 0 (length s)
9331 'invisible 'markdown-markup s))
9332 (setq s (concat
9333 (substring s 0 b)
9334 (substring s (or (next-single-property-change
9335 b 'invisible s)
9336 (length s)))))))
9339 ;; Functions for maintaining tables
9341 (defvar markdown-table-at-point-p-function nil
9342 "Function to decide if point is inside a table.
9344 The indirection serves to differentiate between standard markdown
9345 tables and gfm tables which are less strict about the markup.")
9347 (defconst markdown-table-line-regexp "^[ \t]*|"
9348 "Regexp matching any line inside a table.")
9350 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9351 "Regexp matching hline inside a table.")
9353 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9354 "Regexp matching dline inside a table.")
9356 (defun markdown-table-at-point-p ()
9357 "Return non-nil when point is inside a table."
9358 (if (functionp markdown-table-at-point-p-function)
9359 (funcall markdown-table-at-point-p-function)
9360 (markdown--table-at-point-p)))
9362 (defun markdown--table-at-point-p ()
9363 "Return non-nil when point is inside a table."
9364 (save-excursion
9365 (beginning-of-line)
9366 (and (looking-at-p markdown-table-line-regexp)
9367 (not (markdown-code-block-at-point-p)))))
9369 (defconst gfm-table-line-regexp "^.?*|"
9370 "Regexp matching any line inside a table.")
9372 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
9373 "Regexp matching hline inside a table.")
9375 ;; GFM simplified tables syntax is as follows:
9376 ;; - A header line for the column names, this is any text
9377 ;; separated by `|'.
9378 ;; - Followed by a string -|-|- ..., the number of dashes is optional
9379 ;; but must be higher than 1. The number of separators should match
9380 ;; the number of columns.
9381 ;; - Followed by the rows of data, which has the same format as the
9382 ;; header line.
9383 ;; Example:
9385 ;; foo | bar
9386 ;; ------|---------
9387 ;; bar | baz
9388 ;; bar | baz
9389 (defun gfm--table-at-point-p ()
9390 "Return non-nil when point is inside a gfm-compatible table."
9391 (or (markdown--table-at-point-p)
9392 (save-excursion
9393 (beginning-of-line)
9394 (when (looking-at-p gfm-table-line-regexp)
9395 ;; we might be at the first line of the table, check if the
9396 ;; line below is the hline
9397 (or (save-excursion
9398 (forward-line 1)
9399 (looking-at-p gfm-table-hline-regexp))
9400 ;; go up to find the header
9401 (catch 'done
9402 (while (looking-at-p gfm-table-line-regexp)
9403 (when (looking-at-p gfm-table-hline-regexp)
9404 (throw 'done t))
9405 (forward-line -1))
9406 nil))))))
9408 (defun markdown-table-hline-at-point-p ()
9409 "Return non-nil when point is on a hline in a table.
9410 This function assumes point is on a table."
9411 (save-excursion
9412 (beginning-of-line)
9413 (looking-at-p markdown-table-hline-regexp)))
9415 (defun markdown-table-begin ()
9416 "Find the beginning of the table and return its position.
9417 This function assumes point is on a table."
9418 (save-excursion
9419 (while (and (not (bobp))
9420 (markdown-table-at-point-p))
9421 (forward-line -1))
9422 (unless (eobp)
9423 (forward-line 1))
9424 (point)))
9426 (defun markdown-table-end ()
9427 "Find the end of the table and return its position.
9428 This function assumes point is on a table."
9429 (save-excursion
9430 (while (and (not (eobp))
9431 (markdown-table-at-point-p))
9432 (forward-line 1))
9433 (point)))
9435 (defun markdown-table-get-dline ()
9436 "Return index of the table data line at point.
9437 This function assumes point is on a table."
9438 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9439 (save-excursion
9440 (goto-char (markdown-table-begin))
9441 (while (and (re-search-forward
9442 markdown-table-dline-regexp end t)
9443 (setq cnt (1+ cnt))
9444 (< (point-at-eol) pos))))
9445 cnt))
9447 (defun markdown-table-get-column ()
9448 "Return table column at point.
9449 This function assumes point is on a table."
9450 (let ((pos (point)) (cnt 0))
9451 (save-excursion
9452 (beginning-of-line)
9453 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9454 cnt))
9456 (defun markdown-table-get-cell (&optional n)
9457 "Return the content of the cell in column N of current row.
9458 N defaults to column at point. This function assumes point is on
9459 a table."
9460 (and n (markdown-table-goto-column n))
9461 (skip-chars-backward "^|\n") (backward-char 1)
9462 (if (looking-at "|[^|\r\n]*")
9463 (let* ((pos (match-beginning 0))
9464 (val (buffer-substring (1+ pos) (match-end 0))))
9465 (goto-char (min (point-at-eol) (+ 2 pos)))
9466 ;; Trim whitespaces
9467 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9468 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9469 (forward-char 1) ""))
9471 (defun markdown-table-goto-dline (n)
9472 "Go to the Nth data line in the table at point.
9473 Return t when the line exists, nil otherwise. This function
9474 assumes point is on a table."
9475 (goto-char (markdown-table-begin))
9476 (let ((end (markdown-table-end)) (cnt 0))
9477 (while (and (re-search-forward
9478 markdown-table-dline-regexp end t)
9479 (< (setq cnt (1+ cnt)) n)))
9480 (= cnt n)))
9482 (defun markdown-table-goto-column (n &optional on-delim)
9483 "Go to the Nth column in the table line at point.
9484 With optional argument ON-DELIM, stop with point before the left
9485 delimiter of the cell. If there are less than N cells, just go
9486 beyond the last delimiter. This function assumes point is on a
9487 table."
9488 (beginning-of-line 1)
9489 (when (> n 0)
9490 (while (and (> (setq n (1- n)) -1)
9491 (search-forward "|" (point-at-eol) t)))
9492 (if on-delim
9493 (backward-char 1)
9494 (when (looking-at " ") (forward-char 1)))))
9496 (defmacro markdown-table-save-cell (&rest body)
9497 "Save cell at point, execute BODY and restore cell.
9498 This function assumes point is on a table."
9499 (declare (debug (body)))
9500 (markdown--with-gensyms (line column)
9501 `(let ((,line (copy-marker (line-beginning-position)))
9502 (,column (markdown-table-get-column)))
9503 (unwind-protect
9504 (progn ,@body)
9505 (goto-char ,line)
9506 (markdown-table-goto-column ,column)
9507 (set-marker ,line nil)))))
9509 (defun markdown-table-blank-line (s)
9510 "Convert a table line S into a line with blank cells."
9511 (if (string-match "^[ \t]*|-" s)
9512 (setq s (mapconcat
9513 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9514 s ""))
9515 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9516 (setq s (replace-match
9517 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9518 t t s)))
9521 (defun markdown-table-colfmt (fmtspec)
9522 "Process column alignment specifier FMTSPEC for tables."
9523 (when (stringp fmtspec)
9524 (mapcar (lambda (x)
9525 (cond ((string-match-p "^:.*:$" x) 'c)
9526 ((string-match-p "^:" x) 'l)
9527 ((string-match-p ":$" x) 'r)
9528 (t 'd)))
9529 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9531 (defun markdown-table-align ()
9532 "Align table at point.
9533 This function assumes point is on a table."
9534 (interactive)
9535 (let ((begin (markdown-table-begin))
9536 (end (copy-marker (markdown-table-end))))
9537 (markdown-table-save-cell
9538 (goto-char begin)
9539 (let* (fmtspec
9540 ;; Store table indent
9541 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9542 ;; Split table in lines and save column format specifier
9543 (lines (mapcar (lambda (l)
9544 (if (string-match-p "\\`[ \t]*|[-:]" l)
9545 (progn (setq fmtspec (or fmtspec l)) nil) l))
9546 (markdown--split-string (buffer-substring begin end) "\n")))
9547 ;; Split lines in cells
9548 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9549 (remq nil lines)))
9550 ;; Calculate maximum number of cells in a line
9551 (maxcells (if cells
9552 (apply #'max (mapcar #'length cells))
9553 (user-error "Empty table")))
9554 ;; Empty cells to fill short lines
9555 (emptycells (make-list maxcells "")) maxwidths)
9556 ;; Calculate maximum width for each column
9557 (dotimes (i maxcells)
9558 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9559 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9560 maxwidths)))
9561 (setq maxwidths (nreverse maxwidths))
9562 ;; Process column format specifier
9563 (setq fmtspec (markdown-table-colfmt fmtspec))
9564 ;; Compute formats needed for output of table lines
9565 (let ((hfmt (concat indent "|"))
9566 (rfmt (concat indent "|"))
9567 hfmt1 rfmt1 fmt)
9568 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9569 (setq fmt (pop fmtspec))
9570 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9571 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9572 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9573 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9574 (setq rfmt (concat rfmt (format rfmt1 width)))
9575 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9576 ;; Replace modified lines only
9577 (dolist (line lines)
9578 (let ((line (if line
9579 (apply #'format rfmt (append (pop cells) emptycells))
9580 hfmt))
9581 (previous (buffer-substring (point) (line-end-position))))
9582 (if (equal previous line)
9583 (forward-line)
9584 (insert line "\n")
9585 (delete-region (point) (line-beginning-position 2))))))
9586 (set-marker end nil)))))
9588 (defun markdown-table-insert-row (&optional arg)
9589 "Insert a new row above the row at point into the table.
9590 With optional argument ARG, insert below the current row."
9591 (interactive "P")
9592 (unless (markdown-table-at-point-p)
9593 (user-error "Not at a table"))
9594 (let* ((line (buffer-substring
9595 (line-beginning-position) (line-end-position)))
9596 (new (markdown-table-blank-line line)))
9597 (beginning-of-line (if arg 2 1))
9598 (unless (bolp) (insert "\n"))
9599 (insert-before-markers new "\n")
9600 (beginning-of-line 0)
9601 (re-search-forward "| ?" (line-end-position) t)))
9603 (defun markdown-table-delete-row ()
9604 "Delete row or horizontal line at point from the table."
9605 (interactive)
9606 (unless (markdown-table-at-point-p)
9607 (user-error "Not at a table"))
9608 (let ((col (current-column)))
9609 (kill-region (point-at-bol)
9610 (min (1+ (point-at-eol)) (point-max)))
9611 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9612 (move-to-column col)))
9614 (defun markdown-table-move-row (&optional up)
9615 "Move table line at point down.
9616 With optional argument UP, move it up."
9617 (interactive "P")
9618 (unless (markdown-table-at-point-p)
9619 (user-error "Not at a table"))
9620 (let* ((col (current-column)) (pos (point))
9621 (tonew (if up 0 2)) txt)
9622 (beginning-of-line tonew)
9623 (unless (markdown-table-at-point-p)
9624 (goto-char pos) (user-error "Cannot move row further"))
9625 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9626 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9627 (delete-region (point) (1+ (point-at-eol)))
9628 (beginning-of-line tonew)
9629 (insert txt) (beginning-of-line 0)
9630 (move-to-column col)))
9632 (defun markdown-table-move-row-up ()
9633 "Move table row at point up."
9634 (interactive)
9635 (markdown-table-move-row 'up))
9637 (defun markdown-table-move-row-down ()
9638 "Move table row at point down."
9639 (interactive)
9640 (markdown-table-move-row nil))
9642 (defun markdown-table-insert-column ()
9643 "Insert a new table column."
9644 (interactive)
9645 (unless (markdown-table-at-point-p)
9646 (user-error "Not at a table"))
9647 (let* ((col (max 1 (markdown-table-get-column)))
9648 (begin (markdown-table-begin))
9649 (end (copy-marker (markdown-table-end))))
9650 (markdown-table-save-cell
9651 (goto-char begin)
9652 (while (< (point) end)
9653 (markdown-table-goto-column col t)
9654 (if (markdown-table-hline-at-point-p)
9655 (insert "|---")
9656 (insert "| "))
9657 (forward-line)))
9658 (set-marker end nil)
9659 (markdown-table-align)))
9661 (defun markdown-table-delete-column ()
9662 "Delete column at point from table."
9663 (interactive)
9664 (unless (markdown-table-at-point-p)
9665 (user-error "Not at a table"))
9666 (let ((col (markdown-table-get-column))
9667 (begin (markdown-table-begin))
9668 (end (copy-marker (markdown-table-end))))
9669 (markdown-table-save-cell
9670 (goto-char begin)
9671 (while (< (point) end)
9672 (markdown-table-goto-column col t)
9673 (and (looking-at "|[^|\n]+|")
9674 (replace-match "|"))
9675 (forward-line)))
9676 (set-marker end nil)
9677 (markdown-table-goto-column (max 1 (1- col)))
9678 (markdown-table-align)))
9680 (defun markdown-table-move-column (&optional left)
9681 "Move table column at point to the right.
9682 With optional argument LEFT, move it to the left."
9683 (interactive "P")
9684 (unless (markdown-table-at-point-p)
9685 (user-error "Not at a table"))
9686 (let* ((col (markdown-table-get-column))
9687 (col1 (if left (1- col) col))
9688 (colpos (if left (1- col) (1+ col)))
9689 (begin (markdown-table-begin))
9690 (end (copy-marker (markdown-table-end))))
9691 (when (and left (= col 1))
9692 (user-error "Cannot move column further left"))
9693 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9694 (user-error "Cannot move column further right"))
9695 (markdown-table-save-cell
9696 (goto-char begin)
9697 (while (< (point) end)
9698 (markdown-table-goto-column col1 t)
9699 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9700 (replace-match "|\\2|\\1|"))
9701 (forward-line)))
9702 (set-marker end nil)
9703 (markdown-table-goto-column colpos)
9704 (markdown-table-align)))
9706 (defun markdown-table-move-column-left ()
9707 "Move table column at point to the left."
9708 (interactive)
9709 (markdown-table-move-column 'left))
9711 (defun markdown-table-move-column-right ()
9712 "Move table column at point to the right."
9713 (interactive)
9714 (markdown-table-move-column nil))
9716 (defun markdown-table-next-row ()
9717 "Go to the next row (same column) in the table.
9718 Create new table lines if required."
9719 (interactive)
9720 (unless (markdown-table-at-point-p)
9721 (user-error "Not at a table"))
9722 (if (or (looking-at "[ \t]*$")
9723 (save-excursion (skip-chars-backward " \t") (bolp)))
9724 (newline)
9725 (markdown-table-align)
9726 (let ((col (markdown-table-get-column)))
9727 (beginning-of-line 2)
9728 (if (or (not (markdown-table-at-point-p))
9729 (markdown-table-hline-at-point-p))
9730 (progn
9731 (beginning-of-line 0)
9732 (markdown-table-insert-row 'below)))
9733 (markdown-table-goto-column col)
9734 (skip-chars-backward "^|\n\r")
9735 (when (looking-at " ") (forward-char 1)))))
9737 (defun markdown-table-forward-cell ()
9738 "Go to the next cell in the table.
9739 Create new table lines if required."
9740 (interactive)
9741 (unless (markdown-table-at-point-p)
9742 (user-error "Not at a table"))
9743 (markdown-table-align)
9744 (let ((end (markdown-table-end)))
9745 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9746 (condition-case nil
9747 (progn
9748 (re-search-forward "|" end)
9749 (if (looking-at "[ \t]*$")
9750 (re-search-forward "|" end))
9751 (if (and (looking-at "[-:]")
9752 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9753 (goto-char (match-beginning 1)))
9754 (if (looking-at "[-:]")
9755 (progn
9756 (beginning-of-line 0)
9757 (markdown-table-insert-row 'below))
9758 (when (looking-at " ") (forward-char 1))))
9759 (error (markdown-table-insert-row 'below)))))
9761 (defun markdown-table-backward-cell ()
9762 "Go to the previous cell in the table."
9763 (interactive)
9764 (unless (markdown-table-at-point-p)
9765 (user-error "Not at a table"))
9766 (markdown-table-align)
9767 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9768 (condition-case nil
9769 (progn
9770 (re-search-backward "|" (markdown-table-begin))
9771 (re-search-backward "|" (markdown-table-begin)))
9772 (error (user-error "Cannot move to previous table cell")))
9773 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9774 (re-search-backward "|" (markdown-table-begin)))
9775 (when (looking-at "| ?") (goto-char (match-end 0))))
9777 (defun markdown-table-transpose ()
9778 "Transpose table at point.
9779 Horizontal separator lines will be eliminated."
9780 (interactive)
9781 (unless (markdown-table-at-point-p)
9782 (user-error "Not at a table"))
9783 (let* ((table (buffer-substring-no-properties
9784 (markdown-table-begin) (markdown-table-end)))
9785 ;; Convert table to a Lisp structure
9786 (table (delq nil
9787 (mapcar
9788 (lambda (x)
9789 (unless (string-match-p
9790 markdown-table-hline-regexp x)
9791 (markdown--split-string x "\\s-*|\\s-*")))
9792 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9793 (dline_old (markdown-table-get-dline))
9794 (col_old (markdown-table-get-column))
9795 (contents (mapcar (lambda (_)
9796 (let ((tp table))
9797 (mapcar
9798 (lambda (_)
9799 (prog1
9800 (pop (car tp))
9801 (setq tp (cdr tp))))
9802 table)))
9803 (car table))))
9804 (goto-char (markdown-table-begin))
9805 (re-search-forward "|") (backward-char)
9806 (delete-region (point) (markdown-table-end))
9807 (insert (mapconcat
9808 (lambda(x)
9809 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9810 contents ""))
9811 (markdown-table-goto-dline col_old)
9812 (markdown-table-goto-column dline_old))
9813 (markdown-table-align))
9815 (defun markdown-table-sort-lines (&optional sorting-type)
9816 "Sort table lines according to the column at point.
9818 The position of point indicates the column to be used for
9819 sorting, and the range of lines is the range between the nearest
9820 horizontal separator lines, or the entire table of no such lines
9821 exist. If point is before the first column, user will be prompted
9822 for the sorting column. If there is an active region, the mark
9823 specifies the first line and the sorting column, while point
9824 should be in the last line to be included into the sorting.
9826 The command then prompts for the sorting type which can be
9827 alphabetically or numerically. Sorting in reverse order is also
9828 possible.
9830 If SORTING-TYPE is specified when this function is called from a
9831 Lisp program, no prompting will take place. SORTING-TYPE must be
9832 a character, any of (?a ?A ?n ?N) where the capital letters
9833 indicate that sorting should be done in reverse order."
9834 (interactive)
9835 (unless (markdown-table-at-point-p)
9836 (user-error "Not at a table"))
9837 ;; Set sorting type and column used for sorting
9838 (let ((column (let ((c (markdown-table-get-column)))
9839 (cond ((> c 0) c)
9840 ((called-interactively-p 'any)
9841 (read-number "Use column N for sorting: "))
9842 (t 1))))
9843 (sorting-type
9844 (or sorting-type
9845 (read-char-exclusive
9846 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9847 (save-restriction
9848 ;; Narrow buffer to appropriate sorting area
9849 (if (region-active-p)
9850 (narrow-to-region
9851 (save-excursion
9852 (progn
9853 (goto-char (region-beginning)) (line-beginning-position)))
9854 (save-excursion
9855 (progn
9856 (goto-char (region-end)) (line-end-position))))
9857 (let ((start (markdown-table-begin))
9858 (end (markdown-table-end)))
9859 (narrow-to-region
9860 (save-excursion
9861 (if (re-search-backward
9862 markdown-table-hline-regexp start t)
9863 (line-beginning-position 2)
9864 start))
9865 (if (save-excursion (re-search-forward
9866 markdown-table-hline-regexp end t))
9867 (match-beginning 0)
9868 end))))
9869 ;; Determine arguments for `sort-subr'
9870 (let* ((extract-key-from-cell
9871 (cl-case sorting-type
9872 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9873 ((?n ?N) #'string-to-number)
9874 (t (user-error "Invalid sorting type: %c" sorting-type))))
9875 (predicate
9876 (cl-case sorting-type
9877 ((?n ?N) #'<)
9878 ((?a ?A) #'string<))))
9879 ;; Sort selected area
9880 (goto-char (point-min))
9881 (sort-subr (memq sorting-type '(?A ?N))
9882 (lambda ()
9883 (forward-line)
9884 (while (and (not (eobp))
9885 (not (looking-at
9886 markdown-table-dline-regexp)))
9887 (forward-line)))
9888 #'end-of-line
9889 (lambda ()
9890 (funcall extract-key-from-cell
9891 (markdown-table-get-cell column)))
9893 predicate)
9894 (goto-char (point-min))))))
9896 (defun markdown-table-convert-region (begin end &optional separator)
9897 "Convert region from BEGIN to END to table with SEPARATOR.
9899 If every line contains at least one TAB character, the function
9900 assumes that the material is tab separated (TSV). If every line
9901 contains a comma, comma-separated values (CSV) are assumed. If
9902 not, lines are split at whitespace into cells.
9904 You can use a prefix argument to force a specific separator:
9905 \\[universal-argument] once forces CSV, \\[universal-argument]
9906 twice forces TAB, and \\[universal-argument] three times will
9907 prompt for a regular expression to match the separator, and a
9908 numeric argument N indicates that at least N consecutive
9909 spaces, or alternatively a TAB should be used as the separator."
9911 (interactive "r\nP")
9912 (let* ((begin (min begin end)) (end (max begin end)) re)
9913 (goto-char begin) (beginning-of-line 1)
9914 (setq begin (point-marker))
9915 (goto-char end)
9916 (if (bolp) (backward-char 1) (end-of-line 1))
9917 (setq end (point-marker))
9918 (when (equal separator '(64))
9919 (setq separator (read-regexp "Regexp for cell separator: ")))
9920 (unless separator
9921 ;; Get the right cell separator
9922 (goto-char begin)
9923 (setq separator
9924 (cond
9925 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
9926 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
9927 (t 1))))
9928 (goto-char begin)
9929 (if (equal separator '(4))
9930 ;; Parse CSV
9931 (while (< (point) end)
9932 (cond
9933 ((looking-at "^") (insert "| "))
9934 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
9935 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
9936 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
9937 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
9938 ((looking-at "[ \t]*,") (replace-match " | "))
9939 (t (beginning-of-line 2))))
9940 (setq re
9941 (cond
9942 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
9943 ((equal separator '(16)) "^\\|\t")
9944 ((integerp separator)
9945 (if (< separator 1)
9946 (user-error "Cell separator must contain one or more spaces")
9947 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
9948 ((stringp separator) (format "^ *\\|%s" separator))
9949 (t (error "Invalid cell separator"))))
9950 (while (re-search-forward re end t) (replace-match "| " t t)))
9951 (goto-char begin)
9952 (markdown-table-align)))
9955 ;;; ElDoc Support
9957 (defun markdown-eldoc-function ()
9958 "Return a helpful string when appropriate based on context.
9959 * Report URL when point is at a hidden URL.
9960 * Report language name when point is a code block with hidden markup."
9961 (cond
9962 ;; Hidden URL or reference for inline link
9963 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
9964 (thing-at-point-looking-at markdown-regex-link-reference))
9965 (or markdown-hide-urls markdown-hide-markup))
9966 (let* ((imagep (string-equal (match-string 1) "!"))
9967 (edit-keys (markdown--substitute-command-keys
9968 (if imagep
9969 "\\[markdown-insert-image]"
9970 "\\[markdown-insert-link]")))
9971 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
9972 (referencep (string-equal (match-string 5) "["))
9973 (object (if referencep "reference" "URL")))
9974 (format "Hidden %s (%s to edit): %s" object edit-str
9975 (if referencep
9976 (concat
9977 (propertize "[" 'face 'markdown-markup-face)
9978 (propertize (match-string-no-properties 6)
9979 'face 'markdown-reference-face)
9980 (propertize "]" 'face 'markdown-markup-face))
9981 (propertize (match-string-no-properties 6)
9982 'face 'markdown-url-face)))))
9983 ;; Hidden language name for fenced code blocks
9984 ((and (markdown-code-block-at-point-p)
9985 (not (get-text-property (point) 'markdown-pre))
9986 markdown-hide-markup)
9987 (let ((lang (save-excursion (markdown-code-block-lang))))
9988 (unless lang (setq lang "[unspecified]"))
9989 (format "Hidden code block language: %s (%s to toggle markup)"
9990 (propertize lang 'face 'markdown-language-keyword-face)
9991 (markdown--substitute-command-keys
9992 "\\[markdown-toggle-markup-hiding]"))))))
9995 ;;; Mode Definition ==========================================================
9997 (defun markdown-show-version ()
9998 "Show the version number in the minibuffer."
9999 (interactive)
10000 (message "markdown-mode, version %s" markdown-mode-version))
10002 (defun markdown-mode-info ()
10003 "Open the `markdown-mode' homepage."
10004 (interactive)
10005 (browse-url "https://jblevins.org/projects/markdown-mode/"))
10007 ;;;###autoload
10008 (define-derived-mode markdown-mode text-mode "Markdown"
10009 "Major mode for editing Markdown files."
10010 ;; Natural Markdown tab width
10011 (setq tab-width 4)
10012 ;; Comments
10013 (setq-local comment-start "<!-- ")
10014 (setq-local comment-end " -->")
10015 (setq-local comment-start-skip "<!--[ \t]*")
10016 (setq-local comment-column 0)
10017 (setq-local comment-auto-fill-only-comments nil)
10018 (setq-local comment-use-syntax t)
10019 ;; Syntax
10020 (add-hook 'syntax-propertize-extend-region-functions
10021 #'markdown-syntax-propertize-extend-region)
10022 (add-hook 'jit-lock-after-change-extend-region-functions
10023 #'markdown-font-lock-extend-region-function t t)
10024 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
10025 ;; Font lock.
10026 (setq-local font-lock-defaults nil)
10027 (setq-local font-lock-multiline t)
10028 (setq-local font-lock-extra-managed-props
10029 (append font-lock-extra-managed-props
10030 '(composition display invisible)))
10031 (if markdown-hide-markup
10032 (add-to-invisibility-spec 'markdown-markup)
10033 (remove-from-invisibility-spec 'markdown-markup))
10034 (setq font-lock-defaults
10035 '(markdown-mode-font-lock-keywords-basic
10036 nil nil nil nil
10037 (font-lock-syntactic-face-function . markdown-syntactic-face)))
10038 ;; Wiki links
10039 (markdown-setup-wiki-link-hooks)
10040 ;; Math mode
10041 (when markdown-enable-math (markdown-toggle-math t))
10042 ;; Add a buffer-local hook to reload after file-local variables are read
10043 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
10044 ;; For imenu support
10045 (setq imenu-create-index-function
10046 (if markdown-nested-imenu-heading-index
10047 #'markdown-imenu-create-nested-index
10048 #'markdown-imenu-create-flat-index))
10049 ;; For menu support in XEmacs
10050 (easy-menu-add markdown-mode-menu markdown-mode-map)
10051 ;; Defun movement
10052 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
10053 (setq-local end-of-defun-function #'markdown-end-of-defun)
10054 ;; Paragraph filling
10055 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
10056 (setq-local paragraph-start
10057 ;; Should match start of lines that start or separate paragraphs
10058 (mapconcat #'identity
10060 "\f" ; starts with a literal line-feed
10061 "[ \t\f]*$" ; space-only line
10062 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10063 "[ \t]*[*+-][ \t]+" ; unordered list item
10064 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
10065 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
10066 "[ \t]*:[ \t]+" ; definition
10067 "^|" ; table or Pandoc line block
10069 "\\|"))
10070 (setq-local paragraph-separate
10071 ;; Should match lines that separate paragraphs without being
10072 ;; part of any paragraph:
10073 (mapconcat #'identity
10074 '("[ \t\f]*$" ; space-only line
10075 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10076 ;; The following is not ideal, but the Fill customization
10077 ;; options really only handle paragraph-starting prefixes,
10078 ;; not paragraph-ending suffixes:
10079 ".* $" ; line ending in two spaces
10080 "^#+"
10081 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
10082 "\\|"))
10083 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
10084 (setq-local adaptive-fill-regexp "\\s-*")
10085 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
10086 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
10087 ;; Outline mode
10088 (setq-local outline-regexp markdown-regex-header)
10089 (setq-local outline-level #'markdown-outline-level)
10090 ;; Cause use of ellipses for invisible text.
10091 (add-to-invisibility-spec '(outline . t))
10092 ;; ElDoc support
10093 (if (eval-when-compile (fboundp 'add-function))
10094 (add-function :before-until (local 'eldoc-documentation-function)
10095 #'markdown-eldoc-function)
10096 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
10097 ;; Inhibiting line-breaking:
10098 ;; Separating out each condition into a separate function so that users can
10099 ;; override if desired (with remove-hook)
10100 (add-hook 'fill-nobreak-predicate
10101 #'markdown-line-is-reference-definition-p nil t)
10102 (add-hook 'fill-nobreak-predicate
10103 #'markdown-pipe-at-bol-p nil t)
10105 ;; Indentation
10106 (setq-local indent-line-function markdown-indent-function)
10108 ;; Flyspell
10109 (setq-local flyspell-generic-check-word-predicate
10110 #'markdown-flyspell-check-word-p)
10112 ;; Electric quoting
10113 (add-hook 'electric-quote-inhibit-functions
10114 #'markdown--inhibit-electric-quote nil :local)
10116 ;; Backwards compatibility with markdown-css-path
10117 (when (boundp 'markdown-css-path)
10118 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
10119 (add-to-list 'markdown-css-paths markdown-css-path))
10121 ;; Prepare hooks for XEmacs compatibility
10122 (when (featurep 'xemacs)
10123 (make-local-hook 'after-change-functions)
10124 (make-local-hook 'font-lock-extend-region-functions)
10125 (make-local-hook 'window-configuration-change-hook))
10127 ;; Make checkboxes buttons
10128 (when markdown-make-gfm-checkboxes-buttons
10129 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
10130 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
10131 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
10133 ;; edit-indirect
10134 (add-hook 'edit-indirect-after-commit-functions
10135 #'markdown--edit-indirect-after-commit-function
10136 nil 'local)
10138 ;; Marginalized headings
10139 (when markdown-marginalize-headers
10140 (add-hook 'window-configuration-change-hook
10141 #'markdown-marginalize-update-current nil t))
10143 ;; add live preview export hook
10144 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
10145 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
10147 ;;;###autoload
10148 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
10149 ;;;###autoload
10150 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
10153 ;;; GitHub Flavored Markdown Mode ============================================
10155 (defvar gfm-mode-hook nil
10156 "Hook run when entering GFM mode.")
10158 (defvar gfm-font-lock-keywords
10159 ;; Basic Markdown features (excluding possibly overridden ones)
10160 markdown-mode-font-lock-keywords-basic
10161 "Default highlighting expressions for GitHub Flavored Markdown mode.")
10163 ;;;###autoload
10164 (define-derived-mode gfm-mode markdown-mode "GFM"
10165 "Major mode for editing GitHub Flavored Markdown files."
10166 (setq markdown-link-space-sub-char "-")
10167 (setq markdown-wiki-link-search-subdirectories t)
10168 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
10169 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
10170 ;; do the initial link fontification
10171 (markdown-gfm-parse-buffer-for-languages))
10174 ;;; Live Preview Mode ============================================
10175 (define-minor-mode markdown-live-preview-mode
10176 "Toggle native previewing on save for a specific markdown file."
10177 :lighter " MD-Preview"
10178 (if markdown-live-preview-mode
10179 (if (markdown-live-preview-get-filename)
10180 (markdown-display-buffer-other-window (markdown-live-preview-export))
10181 (markdown-live-preview-mode -1)
10182 (user-error "Buffer %s does not visit a file" (current-buffer)))
10183 (markdown-live-preview-remove)))
10186 (provide 'markdown-mode)
10188 ;; Local Variables:
10189 ;; indent-tabs-mode: nil
10190 ;; coding: utf-8
10191 ;; End:
10192 ;;; markdown-mode.el ends here