Perform syntax propertization before hooks run
[markdown-mode.git] / markdown-mode.el
blobddc48935d034aede460666f653348144210616b2
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--append-list-item-bounds (marker indent cur-bounds bounds)
2017 "Update list item BOUNDS given list MARKER, block INDENT, and CUR-BOUNDS.
2018 Here, MARKER is a string representing the type of list and INDENT
2019 is an integer giving the indentation, in spaces, of the current
2020 block. CUR-BOUNDS is a list of the form returned by
2021 `markdown-cur-list-item-bounds' and BOUNDS is a list of bounds
2022 values for parent list items. When BOUNDS is nil, it means we are
2023 at baseline (not inside of a nested list)."
2024 (let ((prev-indent (or (cl-third (car bounds)) 0)))
2025 (cond
2026 ;; New list item at baseline.
2027 ((and marker (null bounds))
2028 (list cur-bounds))
2029 ;; List item with greater indentation (four or more spaces).
2030 ;; Increase list level by consing CUR-BOUNDS onto BOUNDS.
2031 ((and marker (>= indent (+ prev-indent 4)))
2032 (cons cur-bounds bounds))
2033 ;; List item with greater or equal indentation (less than four spaces).
2034 ;; Keep list level the same by replacing the car of BOUNDS.
2035 ((and marker (>= indent prev-indent))
2036 (cons cur-bounds (cdr bounds)))
2037 ;; Lesser indentation level.
2038 ;; Pop appropriate number of elements off BOUNDS list (e.g., lesser
2039 ;; indentation could move back more than one list level). Note
2040 ;; that this block need not be the beginning of list item.
2041 ((< indent prev-indent)
2042 (while (and (> (length bounds) 1)
2043 (setq prev-indent (cl-third (cadr bounds)))
2044 (< indent (+ prev-indent 4)))
2045 (setq bounds (cdr bounds)))
2046 (cons cur-bounds bounds))
2047 ;; Otherwise, do nothing.
2048 (t bounds))))
2050 (defun markdown-syntax-propertize-list-items (start end)
2051 "Propertize list items from START to END.
2052 Stores nested list item information in the `markdown-list-item'
2053 text property to make later syntax analysis easier. The value of
2054 this property is a list with elements of the form (begin . end)
2055 giving the bounds of the current and parent list items."
2056 (save-excursion
2057 (goto-char start)
2058 (let (bounds level pre-regexp)
2059 ;; Find a baseline point with zero list indentation
2060 (markdown-search-backward-baseline)
2061 ;; Search for all list items between baseline and END
2062 (while (and (< (point) end)
2063 (re-search-forward markdown-regex-list end t))
2064 ;; Level of list nesting
2065 (setq level (length bounds))
2066 ;; Pre blocks need to be indented one level past the list level
2067 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ level)))
2068 (beginning-of-line)
2069 (cond
2070 ;; Reset at headings, horizontal rules, and top-level blank lines.
2071 ;; Propertize baseline when in range.
2072 ((markdown-new-baseline-p)
2073 (setq bounds nil))
2074 ;; Make sure this is not a line from a pre block
2075 ((looking-at-p pre-regexp))
2076 ;; If not, then update levels and propertize list item when in range.
2078 (let* ((indent (current-indentation))
2079 (cur-bounds (markdown-cur-list-item-bounds 'matched))
2080 (first (cl-first cur-bounds))
2081 (last (cl-second cur-bounds))
2082 (marker (cl-fifth cur-bounds)))
2083 (setq bounds (markdown--append-list-item-bounds
2084 marker indent cur-bounds bounds))
2085 (when (<= start (point) end)
2086 (put-text-property first last 'markdown-list-item bounds)))))
2087 (end-of-line)))))
2089 (defun markdown-syntax-propertize-pre-blocks (start end)
2090 "Match preformatted text blocks from START to END."
2091 (save-excursion
2092 (goto-char start)
2093 (let ((levels (markdown-calculate-list-levels))
2094 indent pre-regexp close-regexp open close)
2095 (while (and (< (point) end) (not close))
2096 ;; Search for a region with sufficient indentation
2097 (if (null levels)
2098 (setq indent 1)
2099 (setq indent (1+ (length levels))))
2100 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
2101 (setq close-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
2103 (cond
2104 ;; If not at the beginning of a line, move forward
2105 ((not (bolp)) (forward-line))
2106 ;; Move past blank lines
2107 ((markdown-cur-line-blank-p) (forward-line))
2108 ;; At headers and horizontal rules, reset levels
2109 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
2110 ;; If the current line has sufficient indentation, mark out pre block
2111 ;; The opening should be preceded by a blank line.
2112 ((and (looking-at pre-regexp)
2113 (markdown-prev-line-blank-p))
2114 (setq open (match-beginning 0))
2115 (while (and (or (looking-at-p pre-regexp) (markdown-cur-line-blank-p))
2116 (not (eobp)))
2117 (forward-line))
2118 (skip-syntax-backward "-")
2119 (setq close (point)))
2120 ;; If current line has a list marker, update levels, move to end of block
2121 ((looking-at markdown-regex-list)
2122 (setq levels (markdown-update-list-levels
2123 (match-string 2) (current-indentation) levels))
2124 (markdown-end-of-text-block))
2125 ;; If this is the end of the indentation level, adjust levels accordingly.
2126 ;; Only match end of indentation level if levels is not the empty list.
2127 ((and (car levels) (looking-at-p close-regexp))
2128 (setq levels (markdown-update-list-levels
2129 nil (current-indentation) levels))
2130 (markdown-end-of-text-block))
2131 (t (markdown-end-of-text-block))))
2133 (when (and open close)
2134 ;; Set text property data
2135 (put-text-property open close 'markdown-pre (list open close))
2136 ;; Recursively search again
2137 (markdown-syntax-propertize-pre-blocks (point) end)))))
2139 (defconst markdown-fenced-block-pairs
2140 `(((,markdown-regex-tilde-fence-begin markdown-tilde-fence-begin)
2141 (markdown-make-tilde-fence-regex markdown-tilde-fence-end)
2142 markdown-fenced-code)
2143 ((markdown-get-yaml-metadata-start-border markdown-yaml-metadata-begin)
2144 (markdown-get-yaml-metadata-end-border markdown-yaml-metadata-end)
2145 markdown-yaml-metadata-section)
2146 ((,markdown-regex-gfm-code-block-open markdown-gfm-block-begin)
2147 (,markdown-regex-gfm-code-block-close markdown-gfm-block-end)
2148 markdown-gfm-code))
2149 "Mapping of regular expressions to \"fenced-block\" constructs.
2150 These constructs are distinguished by having a distinctive start
2151 and end pattern, both of which take up an entire line of text,
2152 but no special pattern to identify text within the fenced
2153 blocks (unlike blockquotes and indented-code sections).
2155 Each element within this list takes the form:
2157 ((START-REGEX-OR-FUN START-PROPERTY)
2158 (END-REGEX-OR-FUN END-PROPERTY)
2159 MIDDLE-PROPERTY)
2161 Each *-REGEX-OR-FUN element can be a regular expression as a string, or a
2162 function which evaluates to same. Functions for START-REGEX-OR-FUN accept no
2163 arguments, but functions for END-REGEX-OR-FUN accept a single numerical argument
2164 which is the length of the first group of the START-REGEX-OR-FUN match, which
2165 can be ignored if unnecessary. `markdown-maybe-funcall-regexp' is used to
2166 evaluate these into \"real\" regexps.
2168 The *-PROPERTY elements are the text properties applied to each part of the
2169 block construct when it is matched using
2170 `markdown-syntax-propertize-fenced-block-constructs'. START-PROPERTY is applied
2171 to the text matching START-REGEX-OR-FUN, END-PROPERTY to END-REGEX-OR-FUN, and
2172 MIDDLE-PROPERTY to the text in between the two. The value of *-PROPERTY is the
2173 `match-data' when the regexp was matched to the text. In the case of
2174 MIDDLE-PROPERTY, the value is a false match data of the form '(begin end), with
2175 begin and end set to the edges of the \"middle\" text. This makes fontification
2176 easier.")
2178 (defun markdown-text-property-at-point (prop)
2179 (get-text-property (point) prop))
2181 (defsubst markdown-maybe-funcall-regexp (object &optional arg)
2182 (cond ((functionp object)
2183 (if arg (funcall object arg) (funcall object)))
2184 ((stringp object) object)
2185 (t (error "Object cannot be turned into regex"))))
2187 (defsubst markdown-get-start-fence-regexp ()
2188 "Return regexp to find all \"start\" sections of fenced block constructs.
2189 Which construct is actually contained in the match must be found separately."
2190 (mapconcat
2191 #'identity
2192 (mapcar (lambda (entry) (markdown-maybe-funcall-regexp (caar entry)))
2193 markdown-fenced-block-pairs)
2194 "\\|"))
2196 (defun markdown-get-fenced-block-begin-properties ()
2197 (cl-mapcar (lambda (entry) (cl-cadar entry)) markdown-fenced-block-pairs))
2199 (defun markdown-get-fenced-block-end-properties ()
2200 (cl-mapcar (lambda (entry) (cl-cadadr entry)) markdown-fenced-block-pairs))
2202 (defun markdown-get-fenced-block-middle-properties ()
2203 (cl-mapcar #'cl-third markdown-fenced-block-pairs))
2205 (defun markdown-find-previous-prop (prop &optional lim)
2206 "Find previous place where property PROP is non-nil, up to LIM.
2207 Return a cons of (pos . property). pos is point if point contains
2208 non-nil PROP."
2209 (let ((res
2210 (if (get-text-property (point) prop) (point)
2211 (previous-single-property-change
2212 (point) prop nil (or lim (point-min))))))
2213 (when (and (not (get-text-property res prop))
2214 (> res (point-min))
2215 (get-text-property (1- res) prop))
2216 (cl-decf res))
2217 (when (and res (get-text-property res prop)) (cons res prop))))
2219 (defun markdown-find-next-prop (prop &optional lim)
2220 "Find next place where property PROP is non-nil, up to LIM.
2221 Return a cons of (POS . PROPERTY) where POS is point if point
2222 contains non-nil PROP."
2223 (let ((res
2224 (if (get-text-property (point) prop) (point)
2225 (next-single-property-change
2226 (point) prop nil (or lim (point-max))))))
2227 (when (and res (get-text-property res prop)) (cons res prop))))
2229 (defun markdown-min-of-seq (map-fn seq)
2230 "Apply MAP-FN to SEQ and return element of SEQ with minimum value of MAP-FN."
2231 (cl-loop for el in seq
2232 with min = 1.0e+INF ; infinity
2233 with min-el = nil
2234 do (let ((res (funcall map-fn el)))
2235 (when (< res min)
2236 (setq min res)
2237 (setq min-el el)))
2238 finally return min-el))
2240 (defun markdown-max-of-seq (map-fn seq)
2241 "Apply MAP-FN to SEQ and return element of SEQ with maximum value of MAP-FN."
2242 (cl-loop for el in seq
2243 with max = -1.0e+INF ; negative infinity
2244 with max-el = nil
2245 do (let ((res (funcall map-fn el)))
2246 (when (and res (> res max))
2247 (setq max res)
2248 (setq max-el el)))
2249 finally return max-el))
2251 (defun markdown-find-previous-block ()
2252 "Find previous block.
2253 Detect whether `markdown-syntax-propertize-fenced-block-constructs' was
2254 unable to propertize the entire block, but was able to propertize the beginning
2255 of the block. If so, return a cons of (pos . property) where the beginning of
2256 the block was propertized."
2257 (let ((start-pt (point))
2258 (closest-open
2259 (markdown-max-of-seq
2260 #'car
2261 (cl-remove-if
2262 #'null
2263 (cl-mapcar
2264 #'markdown-find-previous-prop
2265 (markdown-get-fenced-block-begin-properties))))))
2266 (when closest-open
2267 (let* ((length-of-open-match
2268 (let ((match-d
2269 (get-text-property (car closest-open) (cdr closest-open))))
2270 (- (cl-fourth match-d) (cl-third match-d))))
2271 (end-regexp
2272 (markdown-maybe-funcall-regexp
2273 (cl-caadr
2274 (cl-find-if
2275 (lambda (entry) (eq (cl-cadar entry) (cdr closest-open)))
2276 markdown-fenced-block-pairs))
2277 length-of-open-match))
2278 (end-prop-loc
2279 (save-excursion
2280 (save-match-data
2281 (goto-char (car closest-open))
2282 (and (re-search-forward end-regexp start-pt t)
2283 (match-beginning 0))))))
2284 (and (not end-prop-loc) closest-open)))))
2286 (defun markdown-get-fenced-block-from-start (prop)
2287 "Return limits of an enclosing fenced block from its start, using PROP.
2288 Return value is a list usable as `match-data'."
2289 (catch 'no-rest-of-block
2290 (let* ((correct-entry
2291 (cl-find-if
2292 (lambda (entry) (eq (cl-cadar entry) prop))
2293 markdown-fenced-block-pairs))
2294 (begin-of-begin (cl-first (markdown-text-property-at-point prop)))
2295 (middle-prop (cl-third correct-entry))
2296 (end-prop (cl-cadadr correct-entry))
2297 (end-of-end
2298 (save-excursion
2299 (goto-char (match-end 0)) ; end of begin
2300 (unless (eobp) (forward-char))
2301 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2302 (if (not mid-prop-v) ; no middle
2303 (progn
2304 ;; try to find end by advancing one
2305 (let ((end-prop-v
2306 (markdown-text-property-at-point end-prop)))
2307 (if end-prop-v (cl-second end-prop-v)
2308 (throw 'no-rest-of-block nil))))
2309 (set-match-data mid-prop-v)
2310 (goto-char (match-end 0)) ; end of middle
2311 (beginning-of-line) ; into end
2312 (cl-second (markdown-text-property-at-point end-prop)))))))
2313 (list begin-of-begin end-of-end))))
2315 (defun markdown-get-fenced-block-from-middle (prop)
2316 "Return limits of an enclosing fenced block from its middle, using PROP.
2317 Return value is a list usable as `match-data'."
2318 (let* ((correct-entry
2319 (cl-find-if
2320 (lambda (entry) (eq (cl-third entry) prop))
2321 markdown-fenced-block-pairs))
2322 (begin-prop (cl-cadar correct-entry))
2323 (begin-of-begin
2324 (save-excursion
2325 (goto-char (match-beginning 0))
2326 (unless (bobp) (forward-line -1))
2327 (beginning-of-line)
2328 (cl-first (markdown-text-property-at-point begin-prop))))
2329 (end-prop (cl-cadadr correct-entry))
2330 (end-of-end
2331 (save-excursion
2332 (goto-char (match-end 0))
2333 (beginning-of-line)
2334 (cl-second (markdown-text-property-at-point end-prop)))))
2335 (list begin-of-begin end-of-end)))
2337 (defun markdown-get-fenced-block-from-end (prop)
2338 "Return limits of an enclosing fenced block from its end, using PROP.
2339 Return value is a list usable as `match-data'."
2340 (let* ((correct-entry
2341 (cl-find-if
2342 (lambda (entry) (eq (cl-cadadr entry) prop))
2343 markdown-fenced-block-pairs))
2344 (end-of-end (cl-second (markdown-text-property-at-point prop)))
2345 (middle-prop (cl-third correct-entry))
2346 (begin-prop (cl-cadar correct-entry))
2347 (begin-of-begin
2348 (save-excursion
2349 (goto-char (match-beginning 0)) ; beginning of end
2350 (unless (bobp) (backward-char)) ; into middle
2351 (let ((mid-prop-v (markdown-text-property-at-point middle-prop)))
2352 (if (not mid-prop-v)
2353 (progn
2354 (beginning-of-line)
2355 (cl-first (markdown-text-property-at-point begin-prop)))
2356 (set-match-data mid-prop-v)
2357 (goto-char (match-beginning 0)) ; beginning of middle
2358 (unless (bobp) (forward-line -1)) ; into beginning
2359 (beginning-of-line)
2360 (cl-first (markdown-text-property-at-point begin-prop)))))))
2361 (list begin-of-begin end-of-end)))
2363 (defun markdown-get-enclosing-fenced-block-construct (&optional pos)
2364 "Get \"fake\" match data for block enclosing POS.
2365 Returns fake match data which encloses the start, middle, and end
2366 of the block construct enclosing POS, if it exists. Used in
2367 `markdown-code-block-at-pos'."
2368 (save-excursion
2369 (when pos (goto-char pos))
2370 (beginning-of-line)
2371 (car
2372 (cl-remove-if
2373 #'null
2374 (cl-mapcar
2375 (lambda (fun-and-prop)
2376 (cl-destructuring-bind (fun prop) fun-and-prop
2377 (when prop
2378 (save-match-data
2379 (set-match-data (markdown-text-property-at-point prop))
2380 (funcall fun prop)))))
2381 `((markdown-get-fenced-block-from-start
2382 ,(cl-find-if
2383 #'markdown-text-property-at-point
2384 (markdown-get-fenced-block-begin-properties)))
2385 (markdown-get-fenced-block-from-middle
2386 ,(cl-find-if
2387 #'markdown-text-property-at-point
2388 (markdown-get-fenced-block-middle-properties)))
2389 (markdown-get-fenced-block-from-end
2390 ,(cl-find-if
2391 #'markdown-text-property-at-point
2392 (markdown-get-fenced-block-end-properties)))))))))
2394 (defun markdown-propertize-end-match (reg end fence-spec middle-begin)
2395 "Get match for REG up to END, if exists, and propertize appropriately.
2396 FENCE-SPEC is an entry in `markdown-fenced-block-pairs' and
2397 MIDDLE-BEGIN is the start of the \"middle\" section of the block."
2398 (when (re-search-forward reg end t)
2399 (let ((close-begin (match-beginning 0)) ; Start of closing line.
2400 (close-end (match-end 0)) ; End of closing line.
2401 (close-data (match-data t))) ; Match data for closing line.
2402 ;; Propertize middle section of fenced block.
2403 (put-text-property middle-begin close-begin
2404 (cl-third fence-spec)
2405 (list middle-begin close-begin))
2406 ;; If the block is a YAML block, propertize the declarations inside
2407 (markdown-syntax-propertize-yaml-metadata middle-begin close-begin)
2408 ;; Propertize closing line of fenced block.
2409 (put-text-property close-begin close-end
2410 (cl-cadadr fence-spec) close-data))))
2412 (defun markdown-syntax-propertize-fenced-block-constructs (start end)
2413 "Propertize according to `markdown-fenced-block-pairs' from START to END.
2414 If unable to propertize an entire block (if the start of a block is within START
2415 and END, but the end of the block is not), propertize the start section of a
2416 block, then in a subsequent call propertize both middle and end by finding the
2417 start which was previously propertized."
2418 (let ((start-reg (markdown-get-start-fence-regexp)))
2419 (save-excursion
2420 (goto-char start)
2421 ;; start from previous unclosed block, if exists
2422 (let ((prev-begin-block (markdown-find-previous-block)))
2423 (when prev-begin-block
2424 (let* ((correct-entry
2425 (cl-find-if (lambda (entry)
2426 (eq (cdr prev-begin-block) (cl-cadar entry)))
2427 markdown-fenced-block-pairs))
2428 (enclosed-text-start (1+ (car prev-begin-block)))
2429 (start-length
2430 (save-excursion
2431 (goto-char (car prev-begin-block))
2432 (string-match
2433 (markdown-maybe-funcall-regexp
2434 (caar correct-entry))
2435 (buffer-substring
2436 (point-at-bol) (point-at-eol)))
2437 (- (match-end 1) (match-beginning 1))))
2438 (end-reg (markdown-maybe-funcall-regexp
2439 (cl-caadr correct-entry) start-length)))
2440 (markdown-propertize-end-match
2441 end-reg end correct-entry enclosed-text-start))))
2442 ;; find all new blocks within region
2443 (while (re-search-forward start-reg end t)
2444 ;; we assume the opening constructs take up (only) an entire line,
2445 ;; so we re-check the current line
2446 (let* ((cur-line (buffer-substring (point-at-bol) (point-at-eol)))
2447 ;; find entry in `markdown-fenced-block-pairs' corresponding
2448 ;; to regex which was matched
2449 (correct-entry
2450 (cl-find-if
2451 (lambda (fenced-pair)
2452 (string-match-p
2453 (markdown-maybe-funcall-regexp (caar fenced-pair))
2454 cur-line))
2455 markdown-fenced-block-pairs))
2456 (enclosed-text-start
2457 (save-excursion (1+ (point-at-eol))))
2458 (end-reg
2459 (markdown-maybe-funcall-regexp
2460 (cl-caadr correct-entry)
2461 (if (and (match-beginning 1) (match-end 1))
2462 (- (match-end 1) (match-beginning 1))
2463 0))))
2464 ;; get correct match data
2465 (save-excursion
2466 (beginning-of-line)
2467 (re-search-forward
2468 (markdown-maybe-funcall-regexp (caar correct-entry))
2469 (point-at-eol)))
2470 ;; mark starting, even if ending is outside of region
2471 (put-text-property (match-beginning 0) (match-end 0)
2472 (cl-cadar correct-entry) (match-data t))
2473 (markdown-propertize-end-match
2474 end-reg end correct-entry enclosed-text-start))))))
2476 (defun markdown-syntax-propertize-blockquotes (start end)
2477 "Match blockquotes from START to END."
2478 (save-excursion
2479 (goto-char start)
2480 (while (and (re-search-forward markdown-regex-blockquote end t)
2481 (not (markdown-code-block-at-pos (match-beginning 0))))
2482 (put-text-property (match-beginning 0) (match-end 0)
2483 'markdown-blockquote
2484 (match-data t)))))
2486 (defun markdown-syntax-propertize-hrs (start end)
2487 "Match horizontal rules from START to END."
2488 (save-excursion
2489 (goto-char start)
2490 (while (re-search-forward markdown-regex-hr end t)
2491 (unless (or (markdown-on-heading-p)
2492 (markdown-code-block-at-point-p))
2493 (put-text-property (match-beginning 0) (match-end 0)
2494 'markdown-hr
2495 (match-data t))))))
2497 (defun markdown-syntax-propertize-yaml-metadata (start end)
2498 "Propertize elements inside YAML metadata blocks from START to END.
2499 Assumes region from START and END is already known to be the interior
2500 region of a YAML metadata block as propertized by
2501 `markdown-syntax-propertize-fenced-block-constructs'."
2502 (save-excursion
2503 (goto-char start)
2504 (cl-loop
2505 while (re-search-forward markdown-regex-declarative-metadata end t)
2506 do (progn
2507 (put-text-property (match-beginning 1) (match-end 1)
2508 'markdown-metadata-key (match-data t))
2509 (put-text-property (match-beginning 2) (match-end 2)
2510 'markdown-metadata-markup (match-data t))
2511 (put-text-property (match-beginning 3) (match-end 3)
2512 'markdown-metadata-value (match-data t))))))
2514 (defun markdown-syntax-propertize-headings (start end)
2515 "Match headings of type SYMBOL with REGEX from START to END."
2516 (goto-char start)
2517 (while (re-search-forward markdown-regex-header end t)
2518 (unless (markdown-code-block-at-pos (match-beginning 0))
2519 (put-text-property
2520 (match-beginning 0) (match-end 0) 'markdown-heading
2521 (match-data t))
2522 (put-text-property
2523 (match-beginning 0) (match-end 0)
2524 (cond ((match-string-no-properties 2) 'markdown-heading-1-setext)
2525 ((match-string-no-properties 3) 'markdown-heading-2-setext)
2526 (t (let ((atx-level (length (markdown-trim-whitespace
2527 (match-string-no-properties 4)))))
2528 (intern (format "markdown-heading-%d-atx" atx-level)))))
2529 (match-data t)))))
2531 (defun markdown-syntax-propertize-comments (start end)
2532 "Match HTML comments from the START to END."
2533 (let* ((in-comment (markdown-in-comment-p)))
2534 (goto-char start)
2535 (cond
2536 ;; Comment start
2537 ((and (not in-comment)
2538 (re-search-forward markdown-regex-comment-start end t)
2539 (not (markdown-inline-code-at-point-p))
2540 (not (markdown-code-block-at-point-p)))
2541 (let ((open-beg (match-beginning 0)))
2542 (put-text-property open-beg (1+ open-beg)
2543 'syntax-table (string-to-syntax "<"))
2544 (markdown-syntax-propertize-comments
2545 (min (1+ (match-end 0)) end (point-max)) end)))
2546 ;; Comment end
2547 ((and in-comment
2548 (re-search-forward markdown-regex-comment-end end t))
2549 (put-text-property (1- (match-end 0)) (match-end 0)
2550 'syntax-table (string-to-syntax ">"))
2551 (markdown-syntax-propertize-comments
2552 (min (1+ (match-end 0)) end (point-max)) end))
2553 ;; Nothing found
2554 (t nil))))
2556 (defvar markdown--syntax-properties
2557 (list 'markdown-tilde-fence-begin nil
2558 'markdown-tilde-fence-end nil
2559 'markdown-fenced-code nil
2560 'markdown-yaml-metadata-begin nil
2561 'markdown-yaml-metadata-end nil
2562 'markdown-yaml-metadata-section nil
2563 'markdown-gfm-block-begin nil
2564 'markdown-gfm-block-end nil
2565 'markdown-gfm-code nil
2566 'markdown-list-item nil
2567 'markdown-pre nil
2568 'markdown-blockquote nil
2569 'markdown-hr nil
2570 'markdown-heading nil
2571 'markdown-heading-1-setext nil
2572 'markdown-heading-2-setext nil
2573 'markdown-heading-1-atx nil
2574 'markdown-heading-2-atx nil
2575 'markdown-heading-3-atx nil
2576 'markdown-heading-4-atx nil
2577 'markdown-heading-5-atx nil
2578 'markdown-heading-6-atx nil
2579 'markdown-metadata-key nil
2580 'markdown-metadata-value nil
2581 'markdown-metadata-markup nil)
2582 "Property list of all Markdown syntactic properties.")
2584 (defun markdown-syntax-propertize (start end)
2585 "Function used as `syntax-propertize-function'.
2586 START and END delimit region to propertize."
2587 (with-silent-modifications
2588 (save-excursion
2589 (remove-text-properties start end markdown--syntax-properties)
2590 (markdown-syntax-propertize-fenced-block-constructs start end)
2591 (markdown-syntax-propertize-list-items start end)
2592 (markdown-syntax-propertize-pre-blocks start end)
2593 (markdown-syntax-propertize-blockquotes start end)
2594 (markdown-syntax-propertize-headings start end)
2595 (markdown-syntax-propertize-hrs start end)
2596 (markdown-syntax-propertize-comments start end))))
2599 ;;; Markup Hiding
2601 (defconst markdown-markup-properties
2602 '(face markdown-markup-face invisible markdown-markup)
2603 "List of properties and values to apply to markup.")
2605 (defconst markdown-language-keyword-properties
2606 '(face markdown-language-keyword-face invisible markdown-markup)
2607 "List of properties and values to apply to code block language names.")
2609 (defconst markdown-language-info-properties
2610 '(face markdown-language-info-face invisible markdown-markup)
2611 "List of properties and values to apply to code block language info strings.")
2613 (defconst markdown-include-title-properties
2614 '(face markdown-link-title-face invisible markdown-markup)
2615 "List of properties and values to apply to included code titles.")
2617 (defcustom markdown-hide-markup nil
2618 "Determines whether markup in the buffer will be hidden.
2619 When set to nil, all markup is displayed in the buffer as it
2620 appears in the file. An exception is when `markdown-hide-urls'
2621 is non-nil.
2622 Set this to a non-nil value to turn this feature on by default.
2623 You can interactively toggle the value of this variable with
2624 `markdown-toggle-markup-hiding', \\[markdown-toggle-markup-hiding],
2625 or from the Markdown > Show & Hide menu.
2627 Markup hiding works by adding text properties to positions in the
2628 buffer---either the `invisible' property or the `display' property
2629 in cases where alternative glyphs are used (e.g., list bullets).
2630 This does not, however, affect printing or other output.
2631 Functions such as `htmlfontify-buffer' and `ps-print-buffer' will
2632 not honor these text properties. For printing, it would be better
2633 to first convert to HTML or PDF (e.g,. using Pandoc)."
2634 :group 'markdown
2635 :type 'boolean
2636 :safe 'booleanp
2637 :package-version '(markdown-mode . "2.3"))
2638 (make-variable-buffer-local 'markdown-hide-markup)
2640 (defun markdown-toggle-markup-hiding (&optional arg)
2641 "Toggle the display or hiding of markup.
2642 With a prefix argument ARG, enable markup hiding if ARG is positive,
2643 and disable it otherwise.
2644 See `markdown-hide-markup' for additional details."
2645 (interactive (list (or current-prefix-arg 'toggle)))
2646 (setq markdown-hide-markup
2647 (if (eq arg 'toggle)
2648 (not markdown-hide-markup)
2649 (> (prefix-numeric-value arg) 0)))
2650 (if markdown-hide-markup
2651 (progn (add-to-invisibility-spec 'markdown-markup)
2652 (message "markdown-mode markup hiding enabled"))
2653 (progn (remove-from-invisibility-spec 'markdown-markup)
2654 (message "markdown-mode markup hiding disabled")))
2655 (markdown-reload-extensions))
2658 ;;; Font Lock =================================================================
2660 (require 'font-lock)
2662 (defvar markdown-italic-face 'markdown-italic-face
2663 "Face name to use for italic text.")
2665 (defvar markdown-bold-face 'markdown-bold-face
2666 "Face name to use for bold text.")
2668 (defvar markdown-strike-through-face 'markdown-strike-through-face
2669 "Face name to use for strike-through text.")
2671 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
2672 "Face name to use as a base for header delimiters.")
2674 (defvar markdown-header-rule-face 'markdown-header-rule-face
2675 "Face name to use as a base for header rules.")
2677 (defvar markdown-header-face 'markdown-header-face
2678 "Face name to use as a base for headers.")
2680 (defvar markdown-header-face-1 'markdown-header-face-1
2681 "Face name to use for level-1 headers.")
2683 (defvar markdown-header-face-2 'markdown-header-face-2
2684 "Face name to use for level-2 headers.")
2686 (defvar markdown-header-face-3 'markdown-header-face-3
2687 "Face name to use for level-3 headers.")
2689 (defvar markdown-header-face-4 'markdown-header-face-4
2690 "Face name to use for level-4 headers.")
2692 (defvar markdown-header-face-5 'markdown-header-face-5
2693 "Face name to use for level-5 headers.")
2695 (defvar markdown-header-face-6 'markdown-header-face-6
2696 "Face name to use for level-6 headers.")
2698 (defvar markdown-inline-code-face 'markdown-inline-code-face
2699 "Face name to use for inline code.")
2701 (defvar markdown-list-face 'markdown-list-face
2702 "Face name to use for list markers.")
2704 (defvar markdown-blockquote-face 'markdown-blockquote-face
2705 "Face name to use for blockquote.")
2707 (defvar markdown-pre-face 'markdown-pre-face
2708 "Face name to use for preformatted text.")
2710 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
2711 "Face name to use for programming language identifiers.")
2713 (defvar markdown-language-info-face 'markdown-language-info-face
2714 "Face name to use for programming info strings.")
2716 (defvar markdown-link-face 'markdown-link-face
2717 "Face name to use for links.")
2719 (defvar markdown-missing-link-face 'markdown-missing-link-face
2720 "Face name to use for links where the linked file does not exist.")
2722 (defvar markdown-reference-face 'markdown-reference-face
2723 "Face name to use for reference.")
2725 (defvar markdown-footnote-marker-face 'markdown-footnote-marker-face
2726 "Face name to use for footnote markers.")
2728 (defvar markdown-url-face 'markdown-url-face
2729 "Face name to use for URLs.")
2731 (defvar markdown-link-title-face 'markdown-link-title-face
2732 "Face name to use for reference link titles.")
2734 (defvar markdown-line-break-face 'markdown-line-break-face
2735 "Face name to use for hard line breaks.")
2737 (defvar markdown-comment-face 'markdown-comment-face
2738 "Face name to use for HTML comments.")
2740 (defvar markdown-math-face 'markdown-math-face
2741 "Face name to use for LaTeX expressions.")
2743 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
2744 "Face name to use for metadata keys.")
2746 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
2747 "Face name to use for metadata values.")
2749 (defvar markdown-gfm-checkbox-face 'markdown-gfm-checkbox-face
2750 "Face name to use for GFM checkboxes.")
2752 (defvar markdown-highlight-face 'markdown-highlight-face
2753 "Face name to use for mouse highlighting.")
2755 (defvar markdown-markup-face 'markdown-markup-face
2756 "Face name to use for markup elements.")
2758 (defgroup markdown-faces nil
2759 "Faces used in Markdown Mode"
2760 :group 'markdown
2761 :group 'faces)
2763 (defface markdown-italic-face
2764 '((t (:inherit italic)))
2765 "Face for italic text."
2766 :group 'markdown-faces)
2768 (defface markdown-bold-face
2769 '((t (:inherit bold)))
2770 "Face for bold text."
2771 :group 'markdown-faces)
2773 (defface markdown-strike-through-face
2774 '((t (:strike-through t)))
2775 "Face for strike-through text."
2776 :group 'markdown-faces)
2778 (defface markdown-markup-face
2779 '((t (:inherit shadow :slant normal :weight normal)))
2780 "Face for markup elements."
2781 :group 'markdown-faces)
2783 (defface markdown-header-rule-face
2784 '((t (:inherit markdown-markup-face)))
2785 "Base face for headers rules."
2786 :group 'markdown-faces)
2788 (defface markdown-header-delimiter-face
2789 '((t (:inherit markdown-markup-face)))
2790 "Base face for headers hash delimiter."
2791 :group 'markdown-faces)
2793 (defface markdown-list-face
2794 '((t (:inherit markdown-markup-face)))
2795 "Face for list item markers."
2796 :group 'markdown-faces)
2798 (defface markdown-blockquote-face
2799 '((t (:inherit font-lock-doc-face)))
2800 "Face for blockquote sections."
2801 :group 'markdown-faces)
2803 (defface markdown-code-face
2804 '((t (:inherit fixed-pitch)))
2805 "Face for inline code, pre blocks, and fenced code blocks.
2806 This may be used, for example, to add a contrasting background to
2807 inline code fragments and code blocks."
2808 :group 'markdown-faces)
2810 (defface markdown-inline-code-face
2811 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2812 "Face for inline code."
2813 :group 'markdown-faces)
2815 (defface markdown-pre-face
2816 '((t (:inherit (markdown-code-face font-lock-constant-face))))
2817 "Face for preformatted text."
2818 :group 'markdown-faces)
2820 (defface markdown-table-face
2821 '((t (:inherit (markdown-code-face))))
2822 "Face for tables."
2823 :group 'markdown-faces)
2825 (defface markdown-language-keyword-face
2826 '((t (:inherit font-lock-type-face)))
2827 "Face for programming language identifiers."
2828 :group 'markdown-faces)
2830 (defface markdown-language-info-face
2831 '((t (:inherit font-lock-string-face)))
2832 "Face for programming language info strings."
2833 :group 'markdown-faces)
2835 (defface markdown-link-face
2836 '((t (:inherit link)))
2837 "Face for links."
2838 :group 'markdown-faces)
2840 (defface markdown-missing-link-face
2841 '((t (:inherit font-lock-warning-face)))
2842 "Face for missing links."
2843 :group 'markdown-faces)
2845 (defface markdown-reference-face
2846 '((t (:inherit markdown-markup-face)))
2847 "Face for link references."
2848 :group 'markdown-faces)
2850 (define-obsolete-face-alias 'markdown-footnote-face
2851 'markdown-footnote-marker-face "v2.3")
2853 (defface markdown-footnote-marker-face
2854 '((t (:inherit markdown-markup-face)))
2855 "Face for footnote markers."
2856 :group 'markdown-faces)
2858 (defface markdown-footnote-text-face
2859 '((t (:inherit font-lock-comment-face)))
2860 "Face for footnote text."
2861 :group 'markdown-faces)
2863 (defface markdown-url-face
2864 '((t (:inherit font-lock-string-face)))
2865 "Face for URLs that are part of markup.
2866 For example, this applies to URLs in inline links:
2867 [link text](http://example.com/)."
2868 :group 'markdown-faces)
2870 (defface markdown-plain-url-face
2871 '((t (:inherit markdown-link-face)))
2872 "Face for URLs that are also links.
2873 For example, this applies to plain angle bracket URLs:
2874 <http://example.com/>."
2875 :group 'markdown-faces)
2877 (defface markdown-link-title-face
2878 '((t (:inherit font-lock-comment-face)))
2879 "Face for reference link titles."
2880 :group 'markdown-faces)
2882 (defface markdown-line-break-face
2883 '((t (:inherit font-lock-constant-face :underline t)))
2884 "Face for hard line breaks."
2885 :group 'markdown-faces)
2887 (defface markdown-comment-face
2888 '((t (:inherit font-lock-comment-face)))
2889 "Face for HTML comments."
2890 :group 'markdown-faces)
2892 (defface markdown-math-face
2893 '((t (:inherit font-lock-string-face)))
2894 "Face for LaTeX expressions."
2895 :group 'markdown-faces)
2897 (defface markdown-metadata-key-face
2898 '((t (:inherit font-lock-variable-name-face)))
2899 "Face for metadata keys."
2900 :group 'markdown-faces)
2902 (defface markdown-metadata-value-face
2903 '((t (:inherit font-lock-string-face)))
2904 "Face for metadata values."
2905 :group 'markdown-faces)
2907 (defface markdown-gfm-checkbox-face
2908 '((t (:inherit font-lock-builtin-face)))
2909 "Face for GFM checkboxes."
2910 :group 'markdown-faces)
2912 (defface markdown-highlight-face
2913 '((t (:inherit highlight)))
2914 "Face for mouse highlighting."
2915 :group 'markdown-faces)
2917 (defface markdown-hr-face
2918 '((t (:inherit markdown-markup-face)))
2919 "Face for horizontal rules."
2920 :group 'markdown-faces)
2922 (defface markdown-html-tag-name-face
2923 '((t (:inherit font-lock-type-face)))
2924 "Face for HTML tag names."
2925 :group 'markdown-faces)
2927 (defface markdown-html-tag-delimiter-face
2928 '((t (:inherit markdown-markup-face)))
2929 "Face for HTML tag delimiters."
2930 :group 'markdown-faces)
2932 (defface markdown-html-attr-name-face
2933 '((t (:inherit font-lock-variable-name-face)))
2934 "Face for HTML attribute names."
2935 :group 'markdown-faces)
2937 (defface markdown-html-attr-value-face
2938 '((t (:inherit font-lock-string-face)))
2939 "Face for HTML attribute values."
2940 :group 'markdown-faces)
2942 (defface markdown-html-entity-face
2943 '((t (:inherit font-lock-variable-name-face)))
2944 "Face for HTML entities."
2945 :group 'markdown-faces)
2947 (defcustom markdown-header-scaling nil
2948 "Whether to use variable-height faces for headers.
2949 When non-nil, `markdown-header-face' will inherit from
2950 `variable-pitch' and the scaling values in
2951 `markdown-header-scaling-values' will be applied to
2952 headers of levels one through six respectively."
2953 :type 'boolean
2954 :initialize 'custom-initialize-default
2955 :set (lambda (symbol value)
2956 (set-default symbol value)
2957 (markdown-update-header-faces value))
2958 :group 'markdown-faces
2959 :package-version '(markdown-mode . "2.2"))
2961 (defcustom markdown-header-scaling-values
2962 '(2.0 1.7 1.4 1.1 1.0 1.0)
2963 "List of scaling values for headers of level one through six.
2964 Used when `markdown-header-scaling' is non-nil."
2965 :type 'list
2966 :initialize 'custom-initialize-default
2967 :set (lambda (symbol value)
2968 (set-default symbol value)
2969 (markdown-update-header-faces markdown-header-scaling value))
2970 :group 'markdown-faces)
2972 (defun markdown-make-header-faces ()
2973 "Build the faces used for Markdown headers."
2974 (let ((inherit-faces '(font-lock-function-name-face)))
2975 (when markdown-header-scaling
2976 (setq inherit-faces (cons 'variable-pitch inherit-faces)))
2977 (defface markdown-header-face
2978 `((t (:inherit ,inherit-faces :weight bold)))
2979 "Base face for headers."
2980 :group 'markdown-faces))
2981 (dotimes (num 6)
2982 (let* ((num1 (1+ num))
2983 (face-name (intern (format "markdown-header-face-%s" num1)))
2984 (scale (if markdown-header-scaling
2985 (float (nth num markdown-header-scaling-values))
2986 1.0)))
2987 (eval
2988 `(defface ,face-name
2989 '((t (:inherit markdown-header-face :height ,scale)))
2990 (format "Face for level %s headers.
2991 You probably don't want to customize this face directly. Instead
2992 you can customize the base face `markdown-header-face' or the
2993 variable-height variable `markdown-header-scaling'." ,num1)
2994 :group 'markdown-faces)))))
2996 (markdown-make-header-faces)
2998 (defun markdown-update-header-faces (&optional scaling scaling-values)
2999 "Update header faces, depending on if header SCALING is desired.
3000 If so, use given list of SCALING-VALUES relative to the baseline
3001 size of `markdown-header-face'."
3002 (dotimes (num 6)
3003 (let* ((face-name (intern (format "markdown-header-face-%s" (1+ num))))
3004 (scale (cond ((not scaling) 1.0)
3005 (scaling-values (float (nth num scaling-values)))
3006 (t (float (nth num markdown-header-scaling-values))))))
3007 (unless (get face-name 'saved-face) ; Don't update customized faces
3008 (set-face-attribute face-name nil :height scale)))))
3010 (defun markdown-syntactic-face (state)
3011 "Return font-lock face for characters with given STATE.
3012 See `font-lock-syntactic-face-function' for details."
3013 (let ((in-comment (nth 4 state)))
3014 (cond
3015 (in-comment 'markdown-comment-face)
3016 (t nil))))
3018 (defcustom markdown-list-item-bullets
3019 '("●" "◎" "○" "◆" "◇" "►" "•")
3020 "List of bullets to use for unordered lists.
3021 It can contain any number of symbols, which will be repeated.
3022 Depending on your font, some reasonable choices are:
3023 ♥ ● ◇ ✚ ✜ ☯ ◆ ♠ ♣ ♦ ❀ ◆ ◖ ▶ ► • ★ ▸."
3024 :group 'markdown
3025 :type '(repeat (string :tag "Bullet character"))
3026 :package-version '(markdown-mode . "2.3"))
3028 (defun markdown--footnote-marker-properties ()
3029 "Return a font-lock facespec expression for footnote marker text."
3030 `(face markdown-footnote-marker-face
3031 ,@(when markdown-hide-markup
3032 `(display ,markdown-footnote-display))))
3034 (defun markdown--pandoc-inline-footnote-properties ()
3035 "Return a font-lock facespec expression for Pandoc inline footnote text."
3036 `(face markdown-footnote-text-face
3037 ,@(when markdown-hide-markup
3038 `(display ,markdown-footnote-display))))
3040 (defvar markdown-mode-font-lock-keywords-basic
3041 `((markdown-match-yaml-metadata-begin . ((1 markdown-markup-face)))
3042 (markdown-match-yaml-metadata-end . ((1 markdown-markup-face)))
3043 (markdown-match-yaml-metadata-key . ((1 markdown-metadata-key-face)
3044 (2 markdown-markup-face)
3045 (3 markdown-metadata-value-face)))
3046 (markdown-match-gfm-open-code-blocks . ((1 markdown-markup-properties)
3047 (2 markdown-markup-properties nil t)
3048 (3 markdown-language-keyword-properties nil t)
3049 (4 markdown-language-info-properties nil t)
3050 (5 markdown-markup-properties nil t)))
3051 (markdown-match-gfm-close-code-blocks . ((0 markdown-markup-properties)))
3052 (markdown-fontify-gfm-code-blocks)
3053 (markdown-fontify-tables)
3054 (markdown-match-fenced-start-code-block . ((1 markdown-markup-properties)
3055 (2 markdown-markup-properties nil t)
3056 (3 markdown-language-keyword-properties nil t)
3057 (4 markdown-language-info-properties nil t)
3058 (5 markdown-markup-properties nil t)))
3059 (markdown-match-fenced-end-code-block . ((0 markdown-markup-properties)))
3060 (markdown-fontify-fenced-code-blocks)
3061 (markdown-match-pre-blocks . ((0 markdown-pre-face)))
3062 (markdown-fontify-headings)
3063 (markdown-match-declarative-metadata . ((1 markdown-metadata-key-face)
3064 (2 markdown-markup-face)
3065 (3 markdown-metadata-value-face)))
3066 (markdown-match-pandoc-metadata . ((1 markdown-markup-face)
3067 (2 markdown-markup-face)
3068 (3 markdown-metadata-value-face)))
3069 (markdown-fontify-hrs)
3070 (markdown-match-code . ((1 markdown-markup-properties prepend)
3071 (2 markdown-inline-code-face prepend)
3072 (3 markdown-markup-properties prepend)))
3073 (,markdown-regex-kbd . ((1 markdown-markup-properties)
3074 (2 markdown-inline-code-face)
3075 (3 markdown-markup-properties)))
3076 (markdown-fontify-angle-uris)
3077 (,markdown-regex-email . 'markdown-plain-url-face)
3078 (markdown-match-html-tag . ((1 'markdown-html-tag-delimiter-face t)
3079 (2 'markdown-html-tag-name-face t)
3080 (3 'markdown-html-tag-delimiter-face t)
3081 ;; Anchored matcher for HTML tag attributes
3082 (,markdown-regex-html-attr
3083 ;; Before searching, move past tag
3084 ;; name; set limit at tag close.
3085 (progn
3086 (goto-char (match-end 2)) (match-end 3))
3088 . ((1 'markdown-html-attr-name-face)
3089 (3 'markdown-html-tag-delimiter-face nil t)
3090 (4 'markdown-html-attr-value-face nil t)))))
3091 (,markdown-regex-html-entity . 'markdown-html-entity-face)
3092 (markdown-fontify-list-items)
3093 (,markdown-regex-footnote . ((1 markdown-markup-properties) ; [^
3094 (2 (markdown--footnote-marker-properties)) ; label
3095 (3 markdown-markup-properties))) ; ]
3096 (,markdown-regex-pandoc-inline-footnote . ((1 markdown-markup-properties) ; ^
3097 (2 markdown-markup-properties) ; [
3098 (3 (markdown--pandoc-inline-footnote-properties)) ; text
3099 (4 markdown-markup-properties))) ; ]
3100 (markdown-match-includes . ((1 markdown-markup-properties)
3101 (2 markdown-markup-properties nil t)
3102 (3 markdown-include-title-properties nil t)
3103 (4 markdown-markup-properties nil t)
3104 (5 markdown-markup-properties)
3105 (6 'markdown-url-face)
3106 (7 markdown-markup-properties)))
3107 (markdown-fontify-inline-links)
3108 (markdown-fontify-reference-links)
3109 (,markdown-regex-reference-definition . ((1 markdown-markup-face) ; [
3110 (2 markdown-reference-face) ; label
3111 (3 markdown-markup-face) ; ]
3112 (4 markdown-markup-face) ; :
3113 (5 markdown-url-face) ; url
3114 (6 markdown-link-title-face))) ; "title" (optional)
3115 (markdown-fontify-plain-uris)
3116 ;; Math mode $..$
3117 (markdown-match-math-single . ((1 markdown-markup-face prepend)
3118 (2 markdown-math-face append)
3119 (3 markdown-markup-face prepend)))
3120 ;; Math mode $$..$$
3121 (markdown-match-math-double . ((1 markdown-markup-face prepend)
3122 (2 markdown-math-face append)
3123 (3 markdown-markup-face prepend)))
3124 ;; Math mode \[..\] and \\[..\\]
3125 (markdown-match-math-display . ((1 markdown-markup-face prepend)
3126 (3 markdown-math-face append)
3127 (4 markdown-markup-face prepend)))
3128 (markdown-match-bold . ((1 markdown-markup-properties prepend)
3129 (2 markdown-bold-face append)
3130 (3 markdown-markup-properties prepend)))
3131 (markdown-match-italic . ((1 markdown-markup-properties prepend)
3132 (2 markdown-italic-face append)
3133 (3 markdown-markup-properties prepend)))
3134 (,markdown-regex-strike-through . ((3 markdown-markup-properties)
3135 (4 markdown-strike-through-face)
3136 (5 markdown-markup-properties)))
3137 (,markdown-regex-line-break . (1 markdown-line-break-face prepend))
3138 (markdown-fontify-sub-superscripts)
3139 (markdown-match-inline-attributes . ((0 markdown-markup-properties prepend)))
3140 (markdown-match-leanpub-sections . ((0 markdown-markup-properties)))
3141 (markdown-fontify-blockquotes)
3142 (markdown-match-wiki-link . ((0 markdown-link-face prepend))))
3143 "Syntax highlighting for Markdown files.")
3145 ;; Footnotes
3146 (defvar markdown-footnote-counter 0
3147 "Counter for footnote numbers.")
3148 (make-variable-buffer-local 'markdown-footnote-counter)
3150 (defconst markdown-footnote-chars
3151 "[[:alnum:]-]"
3152 "Regular expression matching any character that is allowed in a footnote identifier.")
3154 (defconst markdown-regex-footnote-definition
3155 (concat "^ \\{0,3\\}\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:\\(?:[ \t]+\\|$\\)")
3156 "Regular expression matching a footnote definition, capturing the label.")
3159 ;;; Compatibility =============================================================
3161 (defun markdown-replace-regexp-in-string (regexp rep string)
3162 "Replace ocurrences of REGEXP with REP in STRING.
3163 This is a compatibility wrapper to provide `replace-regexp-in-string'
3164 in XEmacs 21."
3165 (if (featurep 'xemacs)
3166 (replace-in-string string regexp rep)
3167 (replace-regexp-in-string regexp rep string)))
3169 ;; `markdown-use-region-p' is a compatibility function which checks
3170 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
3171 (eval-and-compile
3172 (cond
3173 ;; Emacs 24 and newer
3174 ((fboundp 'use-region-p)
3175 (defalias 'markdown-use-region-p 'use-region-p))
3176 ;; XEmacs
3177 ((fboundp 'region-active-p)
3178 (defalias 'markdown-use-region-p 'region-active-p))))
3180 ;; Use new names for outline-mode functions in Emacs 25 and later.
3181 (eval-and-compile
3182 (defalias 'markdown-hide-sublevels
3183 (if (fboundp 'outline-hide-sublevels)
3184 'outline-hide-sublevels
3185 'hide-sublevels))
3186 (defalias 'markdown-show-all
3187 (if (fboundp 'outline-show-all)
3188 'outline-show-all
3189 'show-all))
3190 (defalias 'markdown-hide-body
3191 (if (fboundp 'outline-hide-body)
3192 'outline-hide-body
3193 'hide-body))
3194 (defalias 'markdown-show-children
3195 (if (fboundp 'outline-show-children)
3196 'outline-show-children
3197 'show-children))
3198 (defalias 'markdown-show-subtree
3199 (if (fboundp 'outline-show-subtree)
3200 'outline-show-subtree
3201 'show-subtree))
3202 (defalias 'markdown-hide-subtree
3203 (if (fboundp 'outline-hide-subtree)
3204 'outline-hide-subtree
3205 'hide-subtree)))
3207 ;; Provide directory-name-p to Emacs 24
3208 (defsubst markdown-directory-name-p (name)
3209 "Return non-nil if NAME ends with a directory separator character.
3210 Taken from `directory-name-p' from Emacs 25 and provided here for
3211 backwards compatibility."
3212 (let ((len (length name))
3213 (lastc ?.))
3214 (if (> len 0)
3215 (setq lastc (aref name (1- len))))
3216 (or (= lastc ?/)
3217 (and (memq system-type '(windows-nt ms-dos))
3218 (= lastc ?\\)))))
3220 ;; Provide a function to find files recursively in Emacs 24.
3221 (defalias 'markdown-directory-files-recursively
3222 (if (fboundp 'directory-files-recursively)
3223 'directory-files-recursively
3224 (lambda (dir regexp)
3225 "Return list of all files under DIR that have file names matching REGEXP.
3226 This function works recursively. Files are returned in \"depth first\"
3227 order, and files from each directory are sorted in alphabetical order.
3228 Each file name appears in the returned list in its absolute form.
3229 Based on `directory-files-recursively' from Emacs 25 and provided
3230 here for backwards compatibility."
3231 (let ((result nil)
3232 (files nil)
3233 ;; When DIR is "/", remote file names like "/method:" could
3234 ;; also be offered. We shall suppress them.
3235 (tramp-mode (and tramp-mode (file-remote-p (expand-file-name dir)))))
3236 (dolist (file (sort (file-name-all-completions "" dir)
3237 'string<))
3238 (unless (member file '("./" "../"))
3239 (if (markdown-directory-name-p file)
3240 (let* ((leaf (substring file 0 (1- (length file))))
3241 (full-file (expand-file-name leaf dir)))
3242 (setq result
3243 (nconc result (markdown-directory-files-recursively
3244 full-file regexp))))
3245 (when (string-match-p regexp file)
3246 (push (expand-file-name file dir) files)))))
3247 (nconc result (nreverse files))))))
3249 (defun markdown-flyspell-check-word-p ()
3250 "Return t if `flyspell' should check word just before point.
3251 Used for `flyspell-generic-check-word-predicate'."
3252 (save-excursion
3253 (goto-char (1- (point)))
3254 (not (or (markdown-code-block-at-point-p)
3255 (markdown-inline-code-at-point-p)
3256 (markdown-in-comment-p)
3257 (let ((faces (get-text-property (point) 'face)))
3258 (if (listp faces)
3259 (or (memq 'markdown-reference-face faces)
3260 (memq 'markdown-markup-face faces)
3261 (memq 'markdown-plain-url-face faces)
3262 (memq 'markdown-inline-code-face faces)
3263 (memq 'markdown-url-face faces))
3264 (memq faces '(markdown-reference-face
3265 markdown-markup-face
3266 markdown-plain-url-face
3267 markdown-inline-code-face
3268 markdown-url-face))))))))
3270 (defun markdown-font-lock-ensure ()
3271 "Provide `font-lock-ensure' in Emacs 24."
3272 (if (fboundp 'font-lock-ensure)
3273 (font-lock-ensure)
3274 (with-no-warnings
3275 ;; Suppress warning about non-interactive use of
3276 ;; `font-lock-fontify-buffer' in Emacs 25.
3277 (font-lock-fontify-buffer))))
3280 ;;; Markdown Parsing Functions ================================================
3282 (define-obsolete-function-alias
3283 'markdown-cur-line-blank 'markdown-cur-line-blank-p "v2.4")
3284 (define-obsolete-function-alias
3285 'markdown-prev-line-blank 'markdown-prev-line-blank-p "v2.4")
3286 (define-obsolete-function-alias
3287 'markdown-next-line-blank 'markdown-next-line-blank-p "v2.4")
3288 (define-obsolete-function-alias
3289 'markdown-new-baseline 'markdown-new-baseline-p "v2.4")
3291 (defun markdown-cur-line-blank-p ()
3292 "Return t if the current line is blank and nil otherwise."
3293 (save-excursion
3294 (beginning-of-line)
3295 (looking-at-p "^\\s *$")))
3297 (defun markdown-prev-line-blank-p ()
3298 "Return t if the previous line is blank and nil otherwise.
3299 If we are at the first line, then consider the previous line to be blank."
3300 (or (= (line-beginning-position) (point-min))
3301 (save-excursion
3302 (forward-line -1)
3303 (markdown-cur-line-blank-p))))
3305 (defun markdown-next-line-blank-p ()
3306 "Return t if the next line is blank and nil otherwise.
3307 If we are at the last line, then consider the next line to be blank."
3308 (or (= (line-end-position) (point-max))
3309 (save-excursion
3310 (forward-line 1)
3311 (markdown-cur-line-blank-p))))
3313 (defun markdown-prev-line-indent ()
3314 "Return the number of leading whitespace characters in the previous line.
3315 Return 0 if the current line is the first line in the buffer."
3316 (save-excursion
3317 (if (= (line-beginning-position) (point-min))
3319 (forward-line -1)
3320 (current-indentation))))
3322 (defun markdown-next-line-indent ()
3323 "Return the number of leading whitespace characters in the next line.
3324 Return 0 if line is the last line in the buffer."
3325 (save-excursion
3326 (if (= (line-end-position) (point-max))
3328 (forward-line 1)
3329 (current-indentation))))
3331 (defun markdown-cur-non-list-indent ()
3332 "Return beginning position of list item text (not including the list marker).
3333 Return nil if the current line is not the beginning of a list item."
3334 (save-match-data
3335 (save-excursion
3336 (beginning-of-line)
3337 (when (re-search-forward markdown-regex-list (line-end-position) t)
3338 (current-column)))))
3340 (defun markdown-prev-non-list-indent ()
3341 "Return position of the first non-list-marker on the previous line."
3342 (save-excursion
3343 (forward-line -1)
3344 (markdown-cur-non-list-indent)))
3346 (defun markdown-new-baseline-p ()
3347 "Determine if the current line begins a new baseline level."
3348 (save-excursion
3349 (beginning-of-line)
3350 (or (looking-at-p markdown-regex-header)
3351 (looking-at-p markdown-regex-hr)
3352 (and (null (markdown-cur-non-list-indent))
3353 (= (current-indentation) 0)
3354 (markdown-prev-line-blank-p)))))
3356 (defun markdown-search-backward-baseline ()
3357 "Search backward baseline point with no indentation and not a list item."
3358 (end-of-line)
3359 (let (stop)
3360 (while (not (or stop (bobp)))
3361 (re-search-backward markdown-regex-block-separator-noindent nil t)
3362 (when (match-end 2)
3363 (goto-char (match-end 2))
3364 (cond
3365 ((markdown-new-baseline-p)
3366 (setq stop t))
3367 ((looking-at-p markdown-regex-list)
3368 (setq stop nil))
3369 (t (setq stop t)))))))
3371 (defun markdown-update-list-levels (marker indent levels)
3372 "Update list levels given list MARKER, block INDENT, and current LEVELS.
3373 Here, MARKER is a string representing the type of list, INDENT is an integer
3374 giving the indentation, in spaces, of the current block, and LEVELS is a
3375 list of the indentation levels of parent list items. When LEVELS is nil,
3376 it means we are at baseline (not inside of a nested list)."
3377 (cond
3378 ;; New list item at baseline.
3379 ((and marker (null levels))
3380 (setq levels (list indent)))
3381 ;; List item with greater indentation (four or more spaces).
3382 ;; Increase list level.
3383 ((and marker (>= indent (+ (car levels) 4)))
3384 (setq levels (cons indent levels)))
3385 ;; List item with greater or equal indentation (less than four spaces).
3386 ;; Do not increase list level.
3387 ((and marker (>= indent (car levels)))
3388 levels)
3389 ;; Lesser indentation level.
3390 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
3391 ;; indentation could move back more than one list level). Note
3392 ;; that this block need not be the beginning of list item.
3393 ((< indent (car levels))
3394 (while (and (> (length levels) 1)
3395 (< indent (+ (cadr levels) 4)))
3396 (setq levels (cdr levels)))
3397 levels)
3398 ;; Otherwise, do nothing.
3399 (t levels)))
3401 (defun markdown-calculate-list-levels ()
3402 "Calculate list levels at point.
3403 Return a list of the form (n1 n2 n3 ...) where n1 is the
3404 indentation of the deepest nested list item in the branch of
3405 the list at the point, n2 is the indentation of the parent
3406 list item, and so on. The depth of the list item is therefore
3407 the length of the returned list. If the point is not at or
3408 immediately after a list item, return nil."
3409 (save-excursion
3410 (let ((first (point)) levels indent pre-regexp)
3411 ;; Find a baseline point with zero list indentation
3412 (markdown-search-backward-baseline)
3413 ;; Search for all list items between baseline and LOC
3414 (while (and (< (point) first)
3415 (re-search-forward markdown-regex-list first t))
3416 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
3417 (beginning-of-line)
3418 (cond
3419 ;; Make sure this is not a header or hr
3420 ((markdown-new-baseline-p) (setq levels nil))
3421 ;; Make sure this is not a line from a pre block
3422 ((looking-at-p pre-regexp))
3423 ;; If not, then update levels
3425 (setq indent (current-indentation))
3426 (setq levels (markdown-update-list-levels (match-string 2)
3427 indent levels))))
3428 (end-of-line))
3429 levels)))
3431 (defun markdown-prev-list-item (level)
3432 "Search backward from point for a list item with indentation LEVEL.
3433 Set point to the beginning of the item, and return point, or nil
3434 upon failure."
3435 (let (bounds indent prev)
3436 (setq prev (point))
3437 (forward-line -1)
3438 (setq indent (current-indentation))
3439 (while
3440 (cond
3441 ;; List item
3442 ((and (looking-at-p markdown-regex-list)
3443 (setq bounds (markdown-cur-list-item-bounds)))
3444 (cond
3445 ;; Stop and return point at item of equal indentation
3446 ((= (nth 3 bounds) level)
3447 (setq prev (point))
3448 nil)
3449 ;; Stop and return nil at item with lesser indentation
3450 ((< (nth 3 bounds) level)
3451 (setq prev nil)
3452 nil)
3453 ;; Stop at beginning of buffer
3454 ((bobp) (setq prev nil))
3455 ;; Continue at item with greater indentation
3456 ((> (nth 3 bounds) level) t)))
3457 ;; Stop at beginning of buffer
3458 ((bobp) (setq prev nil))
3459 ;; Continue if current line is blank
3460 ((markdown-cur-line-blank-p) t)
3461 ;; Continue while indentation is the same or greater
3462 ((>= indent level) t)
3463 ;; Stop if current indentation is less than list item
3464 ;; and the next is blank
3465 ((and (< indent level)
3466 (markdown-next-line-blank-p))
3467 (setq prev nil))
3468 ;; Stop at a header
3469 ((looking-at-p markdown-regex-header) (setq prev nil))
3470 ;; Stop at a horizontal rule
3471 ((looking-at-p markdown-regex-hr) (setq prev nil))
3472 ;; Otherwise, continue.
3473 (t t))
3474 (forward-line -1)
3475 (setq indent (current-indentation)))
3476 prev))
3478 (defun markdown-next-list-item (level)
3479 "Search forward from point for the next list item with indentation LEVEL.
3480 Set point to the beginning of the item, and return point, or nil
3481 upon failure."
3482 (let (bounds indent next)
3483 (setq next (point))
3484 (if (looking-at markdown-regex-header-setext)
3485 (goto-char (match-end 0)))
3486 (forward-line)
3487 (setq indent (current-indentation))
3488 (while
3489 (cond
3490 ;; Stop at end of the buffer.
3491 ((eobp) nil)
3492 ;; Continue if the current line is blank
3493 ((markdown-cur-line-blank-p) t)
3494 ;; List item
3495 ((and (looking-at-p markdown-regex-list)
3496 (setq bounds (markdown-cur-list-item-bounds)))
3497 (cond
3498 ;; Continue at item with greater indentation
3499 ((> (nth 3 bounds) level) t)
3500 ;; Stop and return point at item of equal indentation
3501 ((= (nth 3 bounds) level)
3502 (setq next (point))
3503 nil)
3504 ;; Stop and return nil at item with lesser indentation
3505 ((< (nth 3 bounds) level)
3506 (setq next nil)
3507 nil)))
3508 ;; Continue while indentation is the same or greater
3509 ((>= indent level) t)
3510 ;; Stop if current indentation is less than list item
3511 ;; and the previous line was blank.
3512 ((and (< indent level)
3513 (markdown-prev-line-blank-p))
3514 (setq next nil))
3515 ;; Stop at a header
3516 ((looking-at-p markdown-regex-header) (setq next nil))
3517 ;; Stop at a horizontal rule
3518 ((looking-at-p markdown-regex-hr) (setq next nil))
3519 ;; Otherwise, continue.
3520 (t t))
3521 (forward-line)
3522 (setq indent (current-indentation)))
3523 next))
3525 (defun markdown-cur-list-item-end (level)
3526 "Move to end of list item with pre-marker indentation LEVEL.
3527 Return the point at the end when a list item was found at the
3528 original point. If the point is not in a list item, do nothing."
3529 (let (indent)
3530 (forward-line)
3531 (setq indent (current-indentation))
3532 (while
3533 (cond
3534 ;; Stop at end of the buffer.
3535 ((eobp) nil)
3536 ;; Continue if the current line is blank
3537 ((markdown-cur-line-blank-p) t)
3538 ;; Continue while indentation is the same or greater
3539 ((>= indent level) t)
3540 ;; Stop if current indentation is less than list item
3541 ;; and the previous line was blank.
3542 ((and (< indent level)
3543 (markdown-prev-line-blank-p))
3544 nil)
3545 ;; Stop at a new list item of the same or lesser indentation
3546 ((looking-at-p markdown-regex-list) nil)
3547 ;; Stop at a header
3548 ((looking-at-p markdown-regex-header) nil)
3549 ;; Stop at a horizontal rule
3550 ((looking-at-p markdown-regex-hr) nil)
3551 ;; Otherwise, continue.
3552 (t t))
3553 (forward-line)
3554 (setq indent (current-indentation)))
3555 ;; Don't skip over whitespace for empty list items (marker and
3556 ;; whitespace only), just move to end of whitespace.
3557 (save-match-data
3558 (if (looking-back (concat markdown-regex-list "\\s-*") nil)
3559 (goto-char (match-end 3))
3560 (skip-syntax-backward "-")))
3561 (point)))
3563 (defun markdown-cur-list-item-bounds (&optional matched)
3564 "Return bounds of list item at point (possibly already MATCHED).
3565 Return a list of the following form:
3567 (begin end indent nonlist-indent marker checkbox)
3569 The named components are:
3571 - begin: Position of beginning of list item, including leading indentation.
3572 - end: Position of the end of the list item, including list item text.
3573 - indent: Number of characters of indentation before list marker (an integer).
3574 - nonlist-indent: Number characters of indentation, list
3575 marker, and whitespace following list marker (an integer).
3576 - marker: String containing the list marker and following whitespace
3577 (e.g., \"- \" or \"* \").
3578 - checkbox: String containing the GFM checkbox portion, if any,
3579 including any trailing whitespace before the text
3580 begins (e.g., \"[x] \").
3582 As an example, for the following unordered list item
3584 - item
3586 the returned list would be
3588 (1 14 3 5 \"- \" nil)
3590 If the point is not inside a list item, return nil.
3591 Leave match data intact for `markdown-regex-list'."
3592 (save-excursion
3593 (let ((cur (point)))
3594 (end-of-line)
3595 (when (or matched (re-search-backward markdown-regex-list nil t))
3596 (let* ((begin (match-beginning 0))
3597 (indent (length (match-string-no-properties 1)))
3598 (nonlist-indent (length (match-string 0)))
3599 (marker (concat (match-string-no-properties 2)
3600 (match-string-no-properties 3)))
3601 (checkbox (progn (goto-char (match-end 0))
3602 (when (looking-at "\\[[xX ]\\]\\s-*")
3603 (match-string-no-properties 0))))
3604 (end (markdown-cur-list-item-end nonlist-indent)))
3605 (when (and (>= cur begin) (<= cur end) nonlist-indent)
3606 (list begin end indent nonlist-indent marker checkbox)))))))
3608 (defun markdown-list-item-at-point-p ()
3609 "Return t if there is a list item at the point and nil otherwise."
3610 (save-match-data (markdown-cur-list-item-bounds)))
3612 (defun markdown-prev-list-item-bounds ()
3613 "Return bounds of previous item in the same list of any level.
3614 The return value has the same form as that of
3615 `markdown-cur-list-item-bounds'."
3616 (save-excursion
3617 (let ((cur-bounds (markdown-cur-list-item-bounds))
3618 (beginning-of-list (save-excursion (markdown-beginning-of-list)))
3619 stop)
3620 (when cur-bounds
3621 (goto-char (nth 0 cur-bounds))
3622 (while (and (not stop) (not (bobp))
3623 (re-search-backward markdown-regex-list
3624 beginning-of-list t))
3625 (unless (or (looking-at markdown-regex-hr)
3626 (markdown-code-block-at-point-p))
3627 (setq stop (point))))
3628 (markdown-cur-list-item-bounds)))))
3630 (defun markdown-next-list-item-bounds ()
3631 "Return bounds of next item in the same list of any level.
3632 The return value has the same form as that of
3633 `markdown-cur-list-item-bounds'."
3634 (save-excursion
3635 (let ((cur-bounds (markdown-cur-list-item-bounds))
3636 (end-of-list (save-excursion (markdown-end-of-list)))
3637 stop)
3638 (when cur-bounds
3639 (goto-char (nth 0 cur-bounds))
3640 (end-of-line)
3641 (while (and (not stop) (not (eobp))
3642 (re-search-forward markdown-regex-list
3643 end-of-list t))
3644 (unless (or (looking-at markdown-regex-hr)
3645 (markdown-code-block-at-point-p))
3646 (setq stop (point))))
3647 (when stop
3648 (markdown-cur-list-item-bounds))))))
3650 (defun markdown-beginning-of-list ()
3651 "Move point to beginning of list at point, if any."
3652 (interactive)
3653 (let ((orig-point (point))
3654 (list-begin (save-excursion
3655 (markdown-search-backward-baseline)
3656 ;; Stop at next list item, regardless of the indentation.
3657 (markdown-next-list-item (point-max))
3658 (when (looking-at markdown-regex-list)
3659 (point)))))
3660 (when (and list-begin (<= list-begin orig-point))
3661 (goto-char list-begin))))
3663 (defun markdown-end-of-list ()
3664 "Move point to end of list at point, if any."
3665 (interactive)
3666 (let ((start (point))
3667 (end (save-excursion
3668 (when (markdown-beginning-of-list)
3669 ;; Items can't have nonlist-indent <= 1, so this
3670 ;; moves past all list items.
3671 (markdown-next-list-item 1)
3672 (skip-syntax-backward "-")
3673 (unless (eobp) (forward-char 1))
3674 (point)))))
3675 (when (and end (>= end start))
3676 (goto-char end))))
3678 (defun markdown-up-list ()
3679 "Move point to beginning of parent list item."
3680 (interactive)
3681 (let ((cur-bounds (markdown-cur-list-item-bounds)))
3682 (when cur-bounds
3683 (markdown-prev-list-item (1- (nth 3 cur-bounds)))
3684 (let ((up-bounds (markdown-cur-list-item-bounds)))
3685 (when (and up-bounds (< (nth 3 up-bounds) (nth 3 cur-bounds)))
3686 (point))))))
3688 (defun markdown-bounds-of-thing-at-point (thing)
3689 "Call `bounds-of-thing-at-point' for THING with slight modifications.
3690 Does not include trailing newlines when THING is 'line. Handles the
3691 end of buffer case by setting both endpoints equal to the value of
3692 `point-max', since an empty region will trigger empty markup insertion.
3693 Return bounds of form (beg . end) if THING is found, or nil otherwise."
3694 (let* ((bounds (bounds-of-thing-at-point thing))
3695 (a (car bounds))
3696 (b (cdr bounds)))
3697 (when bounds
3698 (when (eq thing 'line)
3699 (cond ((and (eobp) (markdown-cur-line-blank-p))
3700 (setq a b))
3701 ((char-equal (char-before b) ?\^J)
3702 (setq b (1- b)))))
3703 (cons a b))))
3705 (defun markdown-reference-definition (reference)
3706 "Find out whether Markdown REFERENCE is defined.
3707 REFERENCE should not include the square brackets.
3708 When REFERENCE is defined, return a list of the form (text start end)
3709 containing the definition text itself followed by the start and end
3710 locations of the text. Otherwise, return nil.
3711 Leave match data for `markdown-regex-reference-definition'
3712 intact additional processing."
3713 (let ((reference (downcase reference)))
3714 (save-excursion
3715 (goto-char (point-min))
3716 (catch 'found
3717 (while (re-search-forward markdown-regex-reference-definition nil t)
3718 (when (string= reference (downcase (match-string-no-properties 2)))
3719 (throw 'found
3720 (list (match-string-no-properties 5)
3721 (match-beginning 5) (match-end 5)))))))))
3723 (defun markdown-get-defined-references ()
3724 "Return a list of all defined reference labels (not including square brackets)."
3725 (save-excursion
3726 (goto-char (point-min))
3727 (let (refs)
3728 (while (re-search-forward markdown-regex-reference-definition nil t)
3729 (let ((target (match-string-no-properties 2)))
3730 (cl-pushnew target refs :test #'equal)))
3731 (reverse refs))))
3733 (defun markdown-get-used-uris ()
3734 "Return a list of all used URIs in the buffer."
3735 (save-excursion
3736 (goto-char (point-min))
3737 (let (uris)
3738 (while (re-search-forward
3739 (concat "\\(?:" markdown-regex-link-inline
3740 "\\|" markdown-regex-angle-uri
3741 "\\|" markdown-regex-uri
3742 "\\|" markdown-regex-email
3743 "\\)")
3744 nil t)
3745 (unless (or (markdown-inline-code-at-point-p)
3746 (markdown-code-block-at-point-p))
3747 (cl-pushnew (or (match-string-no-properties 6)
3748 (match-string-no-properties 10)
3749 (match-string-no-properties 12)
3750 (match-string-no-properties 13))
3751 uris :test #'equal)))
3752 (reverse uris))))
3754 (defun markdown-inline-code-at-pos (pos)
3755 "Return non-nil if there is an inline code fragment at POS.
3756 Return nil otherwise. Set match data according to
3757 `markdown-match-code' upon success.
3758 This function searches the block for a code fragment that
3759 contains the point using `markdown-match-code'. We do this
3760 because `thing-at-point-looking-at' does not work reliably with
3761 `markdown-regex-code'.
3763 The match data is set as follows:
3764 Group 1 matches the opening backquotes.
3765 Group 2 matches the code fragment itself, without backquotes.
3766 Group 3 matches the closing backquotes."
3767 (save-excursion
3768 (goto-char pos)
3769 (let ((old-point (point))
3770 (end-of-block (progn (markdown-end-of-text-block) (point)))
3771 found)
3772 (markdown-beginning-of-text-block)
3773 (while (and (markdown-match-code end-of-block)
3774 (setq found t)
3775 (< (match-end 0) old-point)))
3776 (and found ; matched something
3777 (<= (match-beginning 0) old-point) ; match contains old-point
3778 (>= (match-end 0) old-point)))))
3780 (defun markdown-inline-code-at-pos-p (pos)
3781 "Return non-nil if there is an inline code fragment at POS.
3782 Like `markdown-inline-code-at-pos`, but preserves match data."
3783 (save-match-data (markdown-inline-code-at-pos pos)))
3785 (defun markdown-inline-code-at-point ()
3786 "Return non-nil if the point is at an inline code fragment.
3787 See `markdown-inline-code-at-pos' for details."
3788 (markdown-inline-code-at-pos (point)))
3790 (defun markdown-inline-code-at-point-p ()
3791 "Return non-nil if there is inline code at the point.
3792 This is a predicate function counterpart to
3793 `markdown-inline-code-at-point' which does not modify the match
3794 data. See `markdown-code-block-at-point-p' for code blocks."
3795 (save-match-data (markdown-inline-code-at-pos (point))))
3797 (make-obsolete 'markdown-code-at-point-p 'markdown-inline-code-at-point-p "v2.2")
3799 (defun markdown-code-block-at-pos (pos)
3800 "Return match data list if there is a code block at POS.
3801 Uses text properties at the beginning of the line position.
3802 This includes pre blocks, tilde-fenced code blocks, and GFM
3803 quoted code blocks. Return nil otherwise."
3804 (setq pos (save-excursion (goto-char pos) (point-at-bol)))
3805 (or (get-text-property pos 'markdown-pre)
3806 (markdown-get-enclosing-fenced-block-construct pos)
3807 ;; polymode removes text properties set by markdown-mode, so
3808 ;; check if `poly-markdown-mode' is active and whether the
3809 ;; `chunkmode' property is non-nil at POS.
3810 (and (bound-and-true-p poly-markdown-mode)
3811 (get-text-property pos 'chunkmode))))
3813 ;; Function was renamed to emphasize that it does not modify match-data.
3814 (defalias 'markdown-code-block-at-point 'markdown-code-block-at-point-p)
3816 (defun markdown-code-block-at-point-p ()
3817 "Return non-nil if there is a code block at the point.
3818 This includes pre blocks, tilde-fenced code blocks, and GFM
3819 quoted code blocks. This function does not modify the match
3820 data. See `markdown-inline-code-at-point-p' for inline code."
3821 (save-match-data (markdown-code-block-at-pos (point))))
3823 (defun markdown-heading-at-point ()
3824 "Return non-nil if there is a heading at the point.
3825 Set match data for `markdown-regex-header'."
3826 (let ((match-data (get-text-property (point) 'markdown-heading)))
3827 (when match-data
3828 (set-match-data match-data)
3829 t)))
3831 (defun markdown-pipe-at-bol-p ()
3832 "Return non-nil if the line begins with a pipe symbol.
3833 This may be useful for tables and Pandoc's line_blocks extension."
3834 (char-equal (char-after (point-at-bol)) ?|))
3837 ;;; Markdown Font Lock Matching Functions =====================================
3839 (defun markdown-range-property-any (begin end prop prop-values)
3840 "Return t if PROP from BEGIN to END is equal to one of the given PROP-VALUES.
3841 Also returns t if PROP is a list containing one of the PROP-VALUES.
3842 Return nil otherwise."
3843 (let (props)
3844 (catch 'found
3845 (dolist (loc (number-sequence begin end))
3846 (when (setq props (get-text-property loc prop))
3847 (cond ((listp props)
3848 ;; props is a list, check for membership
3849 (dolist (val prop-values)
3850 (when (memq val props) (throw 'found loc))))
3852 ;; props is a scalar, check for equality
3853 (dolist (val prop-values)
3854 (when (eq val props) (throw 'found loc))))))))))
3856 (defun markdown-range-properties-exist (begin end props)
3857 (cl-loop
3858 for loc in (number-sequence begin end)
3859 with result = nil
3860 while (not
3861 (setq result
3862 (cl-some (lambda (prop) (get-text-property loc prop)) props)))
3863 finally return result))
3865 (defun markdown-match-inline-generic (regex last &optional faceless)
3866 "Match inline REGEX from the point to LAST.
3867 When FACELESS is non-nil, do not return matches where faces have been applied."
3868 (when (re-search-forward regex last t)
3869 (let ((bounds (markdown-code-block-at-pos (match-beginning 1)))
3870 (face (and faceless (text-property-not-all
3871 (match-beginning 0) (match-end 0) 'face nil))))
3872 (cond
3873 ;; In code block: move past it and recursively search again
3874 (bounds
3875 (when (< (goto-char (cl-second bounds)) last)
3876 (markdown-match-inline-generic regex last faceless)))
3877 ;; When faces are found in the match range, skip over the match and
3878 ;; recursively search again.
3879 (face
3880 (when (< (goto-char (match-end 0)) last)
3881 (markdown-match-inline-generic regex last faceless)))
3882 ;; Keep match data and return t when in bounds.
3884 (<= (match-end 0) last))))))
3886 (defun markdown-match-code (last)
3887 "Match inline code fragments from point to LAST."
3888 (unless (bobp)
3889 (backward-char 1))
3890 (when (markdown-match-inline-generic markdown-regex-code last)
3891 (let ((begin (match-beginning 1))
3892 (end (match-end 1))
3893 (open-begin (match-beginning 2))
3894 (open-end (match-end 2))
3895 (code-begin (match-beginning 3))
3896 (code-end (match-end 3))
3897 (close-begin (match-beginning 4))
3898 (close-end (match-end 4)))
3899 (if (or (markdown-in-comment-p begin)
3900 (markdown-in-comment-p end)
3901 (markdown-code-block-at-pos begin))
3902 (progn (goto-char (min (1+ begin) last))
3903 (when (< (point) last)
3904 (markdown-match-code last)))
3905 (set-match-data (list begin end
3906 open-begin open-end
3907 code-begin code-end
3908 close-begin close-end))
3909 t))))
3911 (defun markdown-match-bold (last)
3912 "Match inline bold from the point to LAST."
3913 (when (markdown-match-inline-generic markdown-regex-bold last)
3914 (let ((begin (match-beginning 2))
3915 (end (match-end 2)))
3916 (if (or (markdown-inline-code-at-pos-p begin)
3917 (markdown-inline-code-at-pos-p end)
3918 (markdown-in-comment-p)
3919 (markdown-range-property-any
3920 begin begin 'face '(markdown-url-face
3921 markdown-plain-url-face))
3922 (markdown-range-property-any
3923 begin end 'face '(markdown-math-face)))
3924 (progn (goto-char (min (1+ begin) last))
3925 (when (< (point) last)
3926 (markdown-match-italic last)))
3927 (set-match-data (list (match-beginning 2) (match-end 2)
3928 (match-beginning 3) (match-end 3)
3929 (match-beginning 4) (match-end 4)
3930 (match-beginning 5) (match-end 5)))
3931 t))))
3933 (defun markdown-match-italic (last)
3934 "Match inline italics from the point to LAST."
3935 (let ((regex (if (eq major-mode 'gfm-mode)
3936 markdown-regex-gfm-italic markdown-regex-italic)))
3937 (when (markdown-match-inline-generic regex last)
3938 (let ((begin (match-beginning 1))
3939 (end (match-end 1)))
3940 (if (or (markdown-inline-code-at-pos-p begin)
3941 (markdown-inline-code-at-pos-p end)
3942 (markdown-in-comment-p)
3943 (markdown-range-property-any
3944 begin begin 'face '(markdown-url-face
3945 markdown-plain-url-face))
3946 (markdown-range-property-any
3947 begin end 'face '(markdown-bold-face
3948 markdown-list-face
3949 markdown-math-face)))
3950 (progn (goto-char (min (1+ begin) last))
3951 (when (< (point) last)
3952 (markdown-match-italic last)))
3953 (set-match-data (list (match-beginning 1) (match-end 1)
3954 (match-beginning 2) (match-end 2)
3955 (match-beginning 3) (match-end 3)
3956 (match-beginning 4) (match-end 4)))
3957 t)))))
3959 (defun markdown-match-math-generic (regex last)
3960 "Match REGEX from point to LAST.
3961 REGEX is either `markdown-regex-math-inline-single' for matching
3962 $..$ or `markdown-regex-math-inline-double' for matching $$..$$."
3963 (when (and markdown-enable-math (markdown-match-inline-generic regex last))
3964 (let ((begin (match-beginning 1)) (end (match-end 1)))
3965 (prog1
3966 (if (or (markdown-range-property-any
3967 begin end 'face (list markdown-inline-code-face
3968 markdown-bold-face))
3969 (markdown-range-properties-exist
3970 begin end
3971 (markdown-get-fenced-block-middle-properties)))
3972 (markdown-match-math-generic regex last)
3974 (goto-char (1+ (match-end 0)))))))
3976 (defun markdown-match-list-items (last)
3977 "Match list items from point to LAST."
3978 (when (markdown-match-inline-generic markdown-regex-list last)
3979 (let ((begin (match-beginning 2))
3980 (end (match-end 2)))
3981 (if (or (markdown-range-property-any
3982 begin end 'face (list markdown-inline-code-face
3983 markdown-bold-face
3984 markdown-math-face))
3985 (markdown-range-properties-exist begin end '(markdown-hr))
3986 (markdown-in-comment-p))
3987 (progn (goto-char (min (1+ (match-end 0)) last))
3988 (markdown-match-list-items last))
3989 (set-match-data (list (match-beginning 0) (match-end 0)
3990 (match-beginning 1) (match-end 1)
3991 (match-beginning 2) (match-end 2)))
3992 (goto-char (1+ (match-end 0)))))))
3994 (defun markdown-match-math-single (last)
3995 "Match single quoted $..$ math from point to LAST."
3996 (markdown-match-math-generic markdown-regex-math-inline-single last))
3998 (defun markdown-match-math-double (last)
3999 "Match double quoted $$..$$ math from point to LAST."
4000 (markdown-match-math-generic markdown-regex-math-inline-double last))
4002 (defun markdown-match-math-display (last)
4003 "Match bracketed display math \[..\] and \\[..\\] from point to LAST."
4004 (markdown-match-math-generic markdown-regex-math-display last))
4006 (defun markdown-match-propertized-text (property last)
4007 "Match text with PROPERTY from point to LAST.
4008 Restore match data previously stored in PROPERTY."
4009 (let ((saved (get-text-property (point) property))
4010 pos)
4011 (unless saved
4012 (setq pos (next-single-char-property-change (point) property nil last))
4013 (setq saved (get-text-property pos property)))
4014 (when saved
4015 (set-match-data saved)
4016 ;; Step at least one character beyond point. Otherwise
4017 ;; `font-lock-fontify-keywords-region' infloops.
4018 (goto-char (min (1+ (max (match-end 0) (point)))
4019 (point-max)))
4020 saved)))
4022 (defun markdown-match-pre-blocks (last)
4023 "Match preformatted blocks from point to LAST.
4024 Use data stored in 'markdown-pre text property during syntax
4025 analysis."
4026 (markdown-match-propertized-text 'markdown-pre last))
4028 (defun markdown-match-gfm-code-blocks (last)
4029 "Match GFM quoted code blocks from point to LAST.
4030 Use data stored in 'markdown-gfm-code text property during syntax
4031 analysis."
4032 (markdown-match-propertized-text 'markdown-gfm-code last))
4034 (defun markdown-match-gfm-open-code-blocks (last)
4035 (markdown-match-propertized-text 'markdown-gfm-block-begin last))
4037 (defun markdown-match-gfm-close-code-blocks (last)
4038 (markdown-match-propertized-text 'markdown-gfm-block-end last))
4040 (defun markdown-match-fenced-code-blocks (last)
4041 "Match fenced code blocks from the point to LAST."
4042 (markdown-match-propertized-text 'markdown-fenced-code last))
4044 (defun markdown-match-fenced-start-code-block (last)
4045 (markdown-match-propertized-text 'markdown-tilde-fence-begin last))
4047 (defun markdown-match-fenced-end-code-block (last)
4048 (markdown-match-propertized-text 'markdown-tilde-fence-end last))
4050 (defun markdown-match-blockquotes (last)
4051 "Match blockquotes from point to LAST.
4052 Use data stored in 'markdown-blockquote text property during syntax
4053 analysis."
4054 (markdown-match-propertized-text 'markdown-blockquote last))
4056 (defun markdown-match-hr (last)
4057 "Match horizontal rules comments from the point to LAST."
4058 (markdown-match-propertized-text 'markdown-hr last))
4060 (defun markdown-match-comments (last)
4061 "Match HTML comments from the point to LAST."
4062 (when (and (skip-syntax-forward "^<" last))
4063 (let ((beg (point)))
4064 (when (and (skip-syntax-forward "^>" last) (< (point) last))
4065 (forward-char)
4066 (set-match-data (list beg (point)))
4067 t))))
4069 (defun markdown-match-generic-links (last ref)
4070 "Match inline links from point to LAST.
4071 When REF is non-nil, match reference links instead of standard
4072 links with URLs."
4073 ;; Search for the next potential link (not in a code block).
4074 (while (and (progn
4075 ;; Clear match data to test for a match after functions returns.
4076 (set-match-data nil)
4077 (re-search-forward "\\(!\\)?\\(\\[\\)" last 'limit))
4078 ;; Keep searching if this is in a code block, inline
4079 ;; code, or a comment, or if it is include syntax.
4080 (or (markdown-code-block-at-point-p)
4081 (markdown-inline-code-at-pos-p (match-beginning 0))
4082 (markdown-inline-code-at-pos-p (match-end 0))
4083 (markdown-in-comment-p)
4084 (and (char-equal (char-after (point-at-bol)) ?<)
4085 (char-equal (char-after (1+ (point-at-bol))) ?<)))
4086 (< (point) last)))
4087 ;; Match opening exclamation point (optional) and left bracket.
4088 (when (match-beginning 2)
4089 (let* ((bang (match-beginning 1))
4090 (first-begin (match-beginning 2))
4091 ;; Find end of block to prevent matching across blocks.
4092 (end-of-block (save-excursion
4093 (progn
4094 (goto-char (match-beginning 2))
4095 (markdown-end-of-text-block)
4096 (point))))
4097 ;; Move over balanced expressions to closing right bracket.
4098 ;; Catch unbalanced expression errors and return nil.
4099 (first-end (condition-case nil
4100 (and (goto-char first-begin)
4101 (scan-sexps (point) 1))
4102 (error nil)))
4103 ;; Continue with point at CONT-POINT upon failure.
4104 (cont-point (min (1+ first-begin) last))
4105 second-begin second-end url-begin url-end
4106 title-begin title-end)
4107 ;; When bracket found, in range, and followed by a left paren/bracket...
4108 (when (and first-end (< first-end end-of-block) (goto-char first-end)
4109 (char-equal (char-after (point)) (if ref ?\[ ?\()))
4110 ;; Scan across balanced expressions for closing parenthesis/bracket.
4111 (setq second-begin (point)
4112 second-end (condition-case nil
4113 (scan-sexps (point) 1)
4114 (error nil)))
4115 ;; Check that closing parenthesis/bracket is in range.
4116 (if (and second-end (<= second-end end-of-block) (<= second-end last))
4117 (progn
4118 ;; Search for (optional) title inside closing parenthesis
4119 (when (and (not ref) (search-forward "\"" second-end t))
4120 (setq title-begin (1- (point))
4121 title-end (and (goto-char second-end)
4122 (search-backward "\"" (1+ title-begin) t))
4123 title-end (and title-end (1+ title-end))))
4124 ;; Store URL/reference range
4125 (setq url-begin (1+ second-begin)
4126 url-end (1- (or title-begin second-end)))
4127 ;; Set match data, move point beyond link, and return
4128 (set-match-data
4129 (list (or bang first-begin) second-end ; 0 - all
4130 bang (and bang (1+ bang)) ; 1 - bang
4131 first-begin (1+ first-begin) ; 2 - markup
4132 (1+ first-begin) (1- first-end) ; 3 - link text
4133 (1- first-end) first-end ; 4 - markup
4134 second-begin (1+ second-begin) ; 5 - markup
4135 url-begin url-end ; 6 - url/reference
4136 title-begin title-end ; 7 - title
4137 (1- second-end) second-end)) ; 8 - markup
4138 ;; Nullify cont-point and leave point at end and
4139 (setq cont-point nil)
4140 (goto-char second-end))
4141 ;; If no closing parenthesis in range, update continuation point
4142 (setq cont-point (min end-of-block second-begin))))
4143 (cond
4144 ;; On failure, continue searching at cont-point
4145 ((and cont-point (< cont-point last))
4146 (goto-char cont-point)
4147 (markdown-match-generic-links last ref))
4148 ;; No more text, return nil
4149 ((and cont-point (= cont-point last))
4150 nil)
4151 ;; Return t if a match occurred
4152 (t t)))))
4154 (defun markdown-match-inline-links (last)
4155 "Match standard inline links from point to LAST."
4156 (markdown-match-generic-links last nil))
4158 (defun markdown-match-reference-links (last)
4159 "Match inline reference links from point to LAST."
4160 (markdown-match-generic-links last t))
4162 (defun markdown-match-angle-uris (last)
4163 "Match angle bracket URIs from point to LAST."
4164 (when (markdown-match-inline-generic markdown-regex-angle-uri last)
4165 (goto-char (1+ (match-end 0)))))
4167 (defun markdown-match-plain-uris (last)
4168 "Match plain URIs from point to LAST."
4169 (when (markdown-match-inline-generic markdown-regex-uri last t)
4170 (goto-char (1+ (match-end 0)))))
4172 (defvar markdown-conditional-search-function #'re-search-forward
4173 "Conditional search function used in `markdown-search-until-condition'.
4174 Made into a variable to allow for dynamic let-binding.")
4176 (defun markdown-search-until-condition (condition &rest args)
4177 (let (ret)
4178 (while (and (not ret) (apply markdown-conditional-search-function args))
4179 (setq ret (funcall condition)))
4180 ret))
4182 (defun markdown-match-generic-metadata
4183 (regexp last &optional block-begin-re block-end-re)
4184 "Match metadata declarations specified by REGEXP from point to LAST.
4185 These declarations must appear inside a metadata block specified
4186 by BLOCK-BEGIN-RE and BLOCK-END-RE. BLOCK-BEGIN-RE is a regular
4187 expression denoting the beginning of a metadata block. If it is
4188 nil, we assume metadata can only appear at the beginning of the
4189 buffer. Similarly, BLOCK-END-RE is a regular expression denoting
4190 the end of a metadata block. If it is nil, assume blocks end with
4191 a blank line or the end of the buffer. There may be at most one such
4192 block in a file. Subsequent blocks will be ignored."
4193 (let* ((first (point))
4194 (begin-re (or block-begin-re "\\`"))
4195 (end-re (or block-end-re "\n[ \t]*\n\\|\n\\'\\|\\'"))
4197 ;; (prev-block-begin (when (re-search-backward begin-re (point-min) t) (match-end 0)))
4198 ;; (next-block-begin (when (re-search-forward begin-re last t) (match-end 0)))
4199 ;; (block-begin (or prev-block-begin next-block-begin))
4201 (block-begin (when (or (re-search-backward begin-re (point-min) t)
4202 (re-search-forward begin-re last t))
4203 (match-end 0)))
4205 (block-end (and block-begin (goto-char block-begin)
4206 (re-search-forward end-re nil t))))
4207 (cond
4208 ;; Don't match declarations if there is no metadata block or if
4209 ;; the point is beyond the block. Move point to point-max to
4210 ;; prevent additional searches and return return nil since nothing
4211 ;; was found.
4212 ((or (null block-begin) (and block-end (> first block-end)))
4213 (goto-char (point-max))
4214 nil)
4215 ;; No declarations to match if a block was found but not in
4216 ;; range. Move point to LAST, to resume there, and return nil.
4217 ((> block-begin last)
4218 (goto-char last)
4219 nil)
4220 ;; If a block was found that begins before LAST and ends after
4221 ;; point, search for declarations inside it.
4223 ;; If the starting is before the beginning of the block, start
4224 ;; there. Otherwise, move back to FIRST.
4225 (goto-char (if (< first block-begin) block-begin first))
4226 (if (re-search-forward regexp (min last block-end) t)
4227 ;; If a metadata declaration is found, set match-data and return t.
4228 (let ((key-beginning (match-beginning 1))
4229 (key-end (match-end 1))
4230 (markup-begin (match-beginning 2))
4231 (markup-end (match-end 2))
4232 (value-beginning (match-beginning 3)))
4233 (set-match-data (list key-beginning (point) ; complete metadata
4234 key-beginning key-end ; key
4235 markup-begin markup-end ; markup
4236 value-beginning (point))) ; value
4238 ;; Otherwise, move the point to last and return nil
4239 (goto-char last)
4240 nil)))))
4242 (defun markdown-match-declarative-metadata (last)
4243 "Match declarative metadata from the point to LAST."
4244 (markdown-match-generic-metadata markdown-regex-declarative-metadata last))
4246 (defun markdown-match-pandoc-metadata (last)
4247 "Match Pandoc metadata from the point to LAST."
4248 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
4250 (defun markdown-match-yaml-metadata-begin (last)
4251 (markdown-match-propertized-text 'markdown-yaml-metadata-begin last))
4253 (defun markdown-match-yaml-metadata-end (last)
4254 (markdown-match-propertized-text 'markdown-yaml-metadata-end last))
4256 (defun markdown-match-yaml-metadata-key (last)
4257 (markdown-match-propertized-text 'markdown-metadata-key last))
4259 (defun markdown-match-wiki-link (last)
4260 "Match wiki links from point to LAST."
4261 (when (and markdown-enable-wiki-links
4262 (not markdown-wiki-link-fontify-missing)
4263 (markdown-match-inline-generic markdown-regex-wiki-link last))
4264 (let ((begin (match-beginning 1)) (end (match-end 1)))
4265 (if (or (markdown-in-comment-p begin)
4266 (markdown-in-comment-p end)
4267 (markdown-inline-code-at-pos-p begin)
4268 (markdown-inline-code-at-pos-p end)
4269 (markdown-code-block-at-pos begin))
4270 (progn (goto-char (min (1+ begin) last))
4271 (when (< (point) last)
4272 (markdown-match-wiki-link last)))
4273 (set-match-data (list begin end))
4274 t))))
4276 (defun markdown-match-inline-attributes (last)
4277 "Match inline attributes from point to LAST."
4278 (when (markdown-match-inline-generic markdown-regex-inline-attributes last)
4279 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4280 (markdown-inline-code-at-pos-p (match-end 0))
4281 (markdown-in-comment-p))
4282 t)))
4284 (defun markdown-match-leanpub-sections (last)
4285 "Match Leanpub section markers from point to LAST."
4286 (when (markdown-match-inline-generic markdown-regex-leanpub-sections last)
4287 (unless (or (markdown-inline-code-at-pos-p (match-beginning 0))
4288 (markdown-inline-code-at-pos-p (match-end 0))
4289 (markdown-in-comment-p))
4290 t)))
4292 (defun markdown-match-includes (last)
4293 "Match include statements from point to LAST.
4294 Sets match data for the following seven groups:
4295 Group 1: opening two angle brackets
4296 Group 2: opening title delimiter (optional)
4297 Group 3: title text (optional)
4298 Group 4: closing title delimiter (optional)
4299 Group 5: opening filename delimiter
4300 Group 6: filename
4301 Group 7: closing filename delimiter"
4302 (when (markdown-match-inline-generic markdown-regex-include last)
4303 (let ((valid (not (or (markdown-in-comment-p (match-beginning 0))
4304 (markdown-in-comment-p (match-end 0))
4305 (markdown-code-block-at-pos (match-beginning 0))))))
4306 (cond
4307 ;; Parentheses and maybe square brackets, but no curly braces:
4308 ;; match optional title in square brackets and file in parentheses.
4309 ((and valid (match-beginning 5)
4310 (not (match-beginning 8)))
4311 (set-match-data (list (match-beginning 1) (match-end 7)
4312 (match-beginning 1) (match-end 1)
4313 (match-beginning 2) (match-end 2)
4314 (match-beginning 3) (match-end 3)
4315 (match-beginning 4) (match-end 4)
4316 (match-beginning 5) (match-end 5)
4317 (match-beginning 6) (match-end 6)
4318 (match-beginning 7) (match-end 7))))
4319 ;; Only square brackets present: match file in square brackets.
4320 ((and valid (match-beginning 2)
4321 (not (match-beginning 5))
4322 (not (match-beginning 7)))
4323 (set-match-data (list (match-beginning 1) (match-end 4)
4324 (match-beginning 1) (match-end 1)
4325 nil nil
4326 nil nil
4327 nil nil
4328 (match-beginning 2) (match-end 2)
4329 (match-beginning 3) (match-end 3)
4330 (match-beginning 4) (match-end 4))))
4331 ;; Only curly braces present: match file in curly braces.
4332 ((and valid (match-beginning 8)
4333 (not (match-beginning 2))
4334 (not (match-beginning 5)))
4335 (set-match-data (list (match-beginning 1) (match-end 10)
4336 (match-beginning 1) (match-end 1)
4337 nil nil
4338 nil nil
4339 nil nil
4340 (match-beginning 8) (match-end 8)
4341 (match-beginning 9) (match-end 9)
4342 (match-beginning 10) (match-end 10))))
4344 ;; Not a valid match, move to next line and search again.
4345 (forward-line)
4346 (when (< (point) last)
4347 (setq valid (markdown-match-includes last)))))
4348 valid)))
4350 (defun markdown-match-html-tag (last)
4351 "Match HTML tags from point to LAST."
4352 (when (and markdown-enable-html
4353 (markdown-match-inline-generic markdown-regex-html-tag last t))
4354 (set-match-data (list (match-beginning 0) (match-end 0)
4355 (match-beginning 1) (match-end 1)
4356 (match-beginning 2) (match-end 2)
4357 (match-beginning 9) (match-end 9)))
4361 ;;; Markdown Font Fontification Functions =====================================
4363 (defun markdown--first-displayable (seq)
4364 "Return the first displayable character or string in SEQ.
4365 SEQ may be an atom or a sequence."
4366 (let ((seq (if (listp seq) seq (list seq))))
4367 (cond ((stringp (car seq))
4368 (cl-find-if
4369 (lambda (str)
4370 (and (mapcar #'char-displayable-p (string-to-list str))))
4371 seq))
4372 ((characterp (car seq))
4373 (cl-find-if #'char-displayable-p seq)))))
4375 (defun markdown--marginalize-string (level)
4376 "Generate atx markup string of given LEVEL for left margin."
4377 (let ((margin-left-space-count
4378 (- markdown-marginalize-headers-margin-width level)))
4379 (concat (make-string margin-left-space-count ? )
4380 (make-string level ?#))))
4382 (defun markdown-marginalize-update-current ()
4383 "Update the window configuration to create a left margin."
4384 ;; Emacs 25 or later is needed for window-font-width and default-font-width.
4385 (if (and (fboundp 'window-font-width) (fboundp 'default-font-width))
4386 (let* ((header-delimiter-font-width
4387 (window-font-width nil 'markdown-header-delimiter-face))
4388 (margin-pixel-width (* markdown-marginalize-headers-margin-width
4389 header-delimiter-font-width))
4390 (margin-char-width (/ margin-pixel-width (default-font-width))))
4391 (set-window-margins nil margin-char-width))
4392 ;; As a fallback, simply set margin based on character count.
4393 (set-window-margins nil markdown-marginalize-headers-margin-width)))
4395 (defun markdown-fontify-headings (last)
4396 "Add text properties to headings from point to LAST."
4397 (when (markdown-match-propertized-text 'markdown-heading last)
4398 (let* ((level (markdown-outline-level))
4399 (heading-face
4400 (intern (format "markdown-header-face-%d" level)))
4401 (heading-props `(face ,heading-face))
4402 (left-markup-props
4403 `(face markdown-header-delimiter-face
4404 ,@(cond
4405 (markdown-hide-markup
4406 `(display ""))
4407 (markdown-marginalize-headers
4408 `(display ((margin left-margin)
4409 ,(markdown--marginalize-string level)))))))
4410 (right-markup-props
4411 `(face markdown-header-delimiter-face
4412 ,@(when markdown-hide-markup `(display ""))))
4413 (rule-props `(face markdown-header-rule-face
4414 ,@(when markdown-hide-markup `(display "")))))
4415 (if (match-end 1)
4416 ;; Setext heading
4417 (progn (add-text-properties
4418 (match-beginning 1) (match-end 1) heading-props)
4419 (if (= level 1)
4420 (add-text-properties
4421 (match-beginning 2) (match-end 2) rule-props)
4422 (add-text-properties
4423 (match-beginning 3) (match-end 3) rule-props)))
4424 ;; atx heading
4425 (add-text-properties
4426 (match-beginning 4) (match-end 4) left-markup-props)
4427 (add-text-properties
4428 (match-beginning 5) (match-end 5) heading-props)
4429 (when (match-end 6)
4430 (add-text-properties
4431 (match-beginning 6) (match-end 6) right-markup-props))))
4434 (defun markdown-fontify-tables (last)
4435 (when (and (re-search-forward "|" last t)
4436 (markdown-table-at-point-p))
4437 (font-lock-append-text-property
4438 (line-beginning-position) (min (1+ (line-end-position)) (point-max))
4439 'face 'markdown-table-face)
4440 (forward-line 1)
4443 (defun markdown-fontify-blockquotes (last)
4444 "Apply font-lock properties to blockquotes from point to LAST."
4445 (when (markdown-match-blockquotes last)
4446 (let ((display-string
4447 (markdown--first-displayable markdown-blockquote-display-char)))
4448 (add-text-properties
4449 (match-beginning 1) (match-end 1)
4450 (if markdown-hide-markup
4451 `(face markdown-blockquote-face display ,display-string)
4452 `(face markdown-markup-face)))
4453 (font-lock-append-text-property
4454 (match-beginning 0) (match-end 0) 'face 'markdown-blockquote-face)
4455 t)))
4457 (defun markdown-fontify-list-items (last)
4458 "Apply font-lock properties to list markers from point to LAST."
4459 (when (markdown-match-list-items last)
4460 (let* ((indent (length (match-string-no-properties 1)))
4461 (level (/ indent 4)) ;; level = 0, 1, 2, ...
4462 (bullet (nth (mod level (length markdown-list-item-bullets))
4463 markdown-list-item-bullets)))
4464 (add-text-properties
4465 (match-beginning 2) (match-end 2) '(face markdown-list-face))
4466 (when markdown-hide-markup
4467 (cond
4468 ;; Unordered lists
4469 ((string-match-p "[\\*\\+-]" (match-string 2))
4470 (add-text-properties
4471 (match-beginning 2) (match-end 2) `(display ,bullet)))
4472 ;; Definition lists
4473 ((string-equal ":" (match-string 2))
4474 (let ((display-string
4475 (char-to-string (markdown--first-displayable
4476 markdown-definition-display-char))))
4477 (add-text-properties (match-beginning 2) (match-end 2)
4478 `(display ,display-string)))))))
4481 (defun markdown-fontify-hrs (last)
4482 "Add text properties to horizontal rules from point to LAST."
4483 (when (markdown-match-hr last)
4484 (let ((hr-char (markdown--first-displayable markdown-hr-display-char)))
4485 (add-text-properties
4486 (match-beginning 0) (match-end 0)
4487 `(face markdown-hr-face
4488 font-lock-multiline t
4489 ,@(when (and markdown-hide-markup hr-char)
4490 `(display ,(make-string
4491 (window-body-width) hr-char)))))
4492 t)))
4494 (defun markdown-fontify-sub-superscripts (last)
4495 "Apply text properties to sub- and superscripts from point to LAST."
4496 (when (markdown-search-until-condition
4497 (lambda () (and (not (markdown-code-block-at-point-p))
4498 (not (markdown-inline-code-at-point-p))
4499 (not (markdown-in-comment-p))))
4500 markdown-regex-sub-superscript last t)
4501 (let* ((subscript-p (string= (match-string 2) "~"))
4502 (props
4503 (if subscript-p
4504 (car markdown-sub-superscript-display)
4505 (cdr markdown-sub-superscript-display)))
4506 (mp (list 'face 'markdown-markup-face
4507 'invisible 'markdown-markup)))
4508 (when markdown-hide-markup
4509 (put-text-property (match-beginning 3) (match-end 3)
4510 'display props))
4511 (add-text-properties (match-beginning 2) (match-end 2) mp)
4512 (add-text-properties (match-beginning 4) (match-end 4) mp)
4513 t)))
4516 ;;; Syntax Table ==============================================================
4518 (defvar markdown-mode-syntax-table
4519 (let ((tab (make-syntax-table text-mode-syntax-table)))
4520 (modify-syntax-entry ?\" "." tab)
4521 tab)
4522 "Syntax table for `markdown-mode'.")
4525 ;;; Element Insertion =========================================================
4527 (defun markdown-ensure-blank-line-before ()
4528 "If previous line is not already blank, insert a blank line before point."
4529 (unless (bolp) (insert "\n"))
4530 (unless (or (bobp) (looking-back "\n\\s-*\n" nil)) (insert "\n")))
4532 (defun markdown-ensure-blank-line-after ()
4533 "If following line is not already blank, insert a blank line after point.
4534 Return the point where it was originally."
4535 (save-excursion
4536 (unless (eolp) (insert "\n"))
4537 (unless (or (eobp) (looking-at-p "\n\\s-*\n")) (insert "\n"))))
4539 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
4540 "Insert the strings S1 and S2, wrapping around region or THING.
4541 If a region is specified by the optional BEG and END arguments,
4542 wrap the strings S1 and S2 around that region.
4543 If there is an active region, wrap the strings S1 and S2 around
4544 the region. If there is not an active region but the point is at
4545 THING, wrap that thing (which defaults to word). Otherwise, just
4546 insert S1 and S2 and place the point in between. Return the
4547 bounds of the entire wrapped string, or nil if nothing was wrapped
4548 and S1 and S2 were only inserted."
4549 (let (a b bounds new-point)
4550 (cond
4551 ;; Given region
4552 ((and beg end)
4553 (setq a beg
4554 b end
4555 new-point (+ (point) (length s1))))
4556 ;; Active region
4557 ((markdown-use-region-p)
4558 (setq a (region-beginning)
4559 b (region-end)
4560 new-point (+ (point) (length s1))))
4561 ;; Thing (word) at point
4562 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
4563 (setq a (car bounds)
4564 b (cdr bounds)
4565 new-point (+ (point) (length s1))))
4566 ;; No active region and no word
4568 (setq a (point)
4569 b (point))))
4570 (goto-char b)
4571 (insert s2)
4572 (goto-char a)
4573 (insert s1)
4574 (when new-point (goto-char new-point))
4575 (if (= a b)
4577 (setq b (+ b (length s1) (length s2)))
4578 (cons a b))))
4580 (defun markdown-point-after-unwrap (cur prefix suffix)
4581 "Return desired position of point after an unwrapping operation.
4582 CUR gives the position of the point before the operation.
4583 Additionally, two cons cells must be provided. PREFIX gives the
4584 bounds of the prefix string and SUFFIX gives the bounds of the
4585 suffix string."
4586 (cond ((< cur (cdr prefix)) (car prefix))
4587 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
4588 ((<= cur (cdr suffix))
4589 (- cur (+ (- (cdr prefix) (car prefix))
4590 (- cur (car suffix)))))
4591 (t cur)))
4593 (defun markdown-unwrap-thing-at-point (regexp all text)
4594 "Remove prefix and suffix of thing at point and reposition the point.
4595 When the thing at point matches REGEXP, replace the subexpression
4596 ALL with the string in subexpression TEXT. Reposition the point
4597 in an appropriate location accounting for the removal of prefix
4598 and suffix strings. Return new bounds of string from group TEXT.
4599 When REGEXP is nil, assumes match data is already set."
4600 (when (or (null regexp)
4601 (thing-at-point-looking-at regexp))
4602 (let ((cur (point))
4603 (prefix (cons (match-beginning all) (match-beginning text)))
4604 (suffix (cons (match-end text) (match-end all)))
4605 (bounds (cons (match-beginning text) (match-end text))))
4606 ;; Replace the thing at point
4607 (replace-match (match-string text) t t nil all)
4608 ;; Reposition the point
4609 (goto-char (markdown-point-after-unwrap cur prefix suffix))
4610 ;; Adjust bounds
4611 (setq bounds (cons (car prefix)
4612 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
4614 (defun markdown-unwrap-things-in-region (beg end regexp all text)
4615 "Remove prefix and suffix of all things in region from BEG to END.
4616 When a thing in the region matches REGEXP, replace the
4617 subexpression ALL with the string in subexpression TEXT.
4618 Return a cons cell containing updated bounds for the region."
4619 (save-excursion
4620 (goto-char beg)
4621 (let ((removed 0) len-all len-text)
4622 (while (re-search-forward regexp (- end removed) t)
4623 (setq len-all (length (match-string-no-properties all)))
4624 (setq len-text (length (match-string-no-properties text)))
4625 (setq removed (+ removed (- len-all len-text)))
4626 (replace-match (match-string text) t t nil all))
4627 (cons beg (- end removed)))))
4629 (defun markdown-insert-hr (arg)
4630 "Insert or replace a horizonal rule.
4631 By default, use the first element of `markdown-hr-strings'. When
4632 ARG is non-nil, as when given a prefix, select a different
4633 element as follows. When prefixed with \\[universal-argument],
4634 use the last element of `markdown-hr-strings' instead. When
4635 prefixed with an integer from 1 to the length of
4636 `markdown-hr-strings', use the element in that position instead."
4637 (interactive "*P")
4638 (when (thing-at-point-looking-at markdown-regex-hr)
4639 (delete-region (match-beginning 0) (match-end 0)))
4640 (markdown-ensure-blank-line-before)
4641 (cond ((equal arg '(4))
4642 (insert (car (reverse markdown-hr-strings))))
4643 ((and (integerp arg) (> arg 0)
4644 (<= arg (length markdown-hr-strings)))
4645 (insert (nth (1- arg) markdown-hr-strings)))
4647 (insert (car markdown-hr-strings))))
4648 (markdown-ensure-blank-line-after))
4650 (defun markdown-insert-bold ()
4651 "Insert markup to make a region or word bold.
4652 If there is an active region, make the region bold. If the point
4653 is at a non-bold word, make the word bold. If the point is at a
4654 bold word or phrase, remove the bold markup. Otherwise, simply
4655 insert bold delimiters and place the point in between them."
4656 (interactive)
4657 (let ((delim (if markdown-bold-underscore "__" "**")))
4658 (if (markdown-use-region-p)
4659 ;; Active region
4660 (let ((bounds (markdown-unwrap-things-in-region
4661 (region-beginning) (region-end)
4662 markdown-regex-bold 2 4)))
4663 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4664 ;; Bold markup removal, bold word at point, or empty markup insertion
4665 (if (thing-at-point-looking-at markdown-regex-bold)
4666 (markdown-unwrap-thing-at-point nil 2 4)
4667 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4669 (defun markdown-insert-italic ()
4670 "Insert markup to make a region or word italic.
4671 If there is an active region, make the region italic. If the point
4672 is at a non-italic word, make the word italic. If the point is at an
4673 italic word or phrase, remove the italic markup. Otherwise, simply
4674 insert italic delimiters and place the point in between them."
4675 (interactive)
4676 (let ((delim (if markdown-italic-underscore "_" "*")))
4677 (if (markdown-use-region-p)
4678 ;; Active region
4679 (let ((bounds (markdown-unwrap-things-in-region
4680 (region-beginning) (region-end)
4681 markdown-regex-italic 1 3)))
4682 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4683 ;; Italic markup removal, italic word at point, or empty markup insertion
4684 (if (thing-at-point-looking-at markdown-regex-italic)
4685 (markdown-unwrap-thing-at-point nil 1 3)
4686 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4688 (defun markdown-insert-strike-through ()
4689 "Insert markup to make a region or word strikethrough.
4690 If there is an active region, make the region strikethrough. If the point
4691 is at a non-bold word, make the word strikethrough. If the point is at a
4692 strikethrough word or phrase, remove the strikethrough markup. Otherwise,
4693 simply insert bold delimiters and place the point in between them."
4694 (interactive)
4695 (let ((delim "~~"))
4696 (if (markdown-use-region-p)
4697 ;; Active region
4698 (let ((bounds (markdown-unwrap-things-in-region
4699 (region-beginning) (region-end)
4700 markdown-regex-strike-through 2 4)))
4701 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
4702 ;; Strikethrough markup removal, strikethrough word at point, or empty markup insertion
4703 (if (thing-at-point-looking-at markdown-regex-strike-through)
4704 (markdown-unwrap-thing-at-point nil 2 4)
4705 (markdown-wrap-or-insert delim delim 'word nil nil)))))
4707 (defun markdown-insert-code ()
4708 "Insert markup to make a region or word an inline code fragment.
4709 If there is an active region, make the region an inline code
4710 fragment. If the point is at a word, make the word an inline
4711 code fragment. Otherwise, simply insert code delimiters and
4712 place the point in between them."
4713 (interactive)
4714 (if (markdown-use-region-p)
4715 ;; Active region
4716 (let ((bounds (markdown-unwrap-things-in-region
4717 (region-beginning) (region-end)
4718 markdown-regex-code 1 3)))
4719 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
4720 ;; Code markup removal, code markup for word, or empty markup insertion
4721 (if (markdown-inline-code-at-point)
4722 (markdown-unwrap-thing-at-point nil 0 2)
4723 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
4725 (defun markdown-insert-kbd ()
4726 "Insert markup to wrap region or word in <kbd> tags.
4727 If there is an active region, use the region. If the point is at
4728 a word, use the word. Otherwise, simply insert <kbd> tags and
4729 place the point in between them."
4730 (interactive)
4731 (if (markdown-use-region-p)
4732 ;; Active region
4733 (let ((bounds (markdown-unwrap-things-in-region
4734 (region-beginning) (region-end)
4735 markdown-regex-kbd 0 2)))
4736 (markdown-wrap-or-insert "<kbd>" "</kbd>" nil (car bounds) (cdr bounds)))
4737 ;; Markup removal, markup for word, or empty markup insertion
4738 (if (thing-at-point-looking-at markdown-regex-kbd)
4739 (markdown-unwrap-thing-at-point nil 0 2)
4740 (markdown-wrap-or-insert "<kbd>" "</kbd>" 'word nil nil))))
4742 (defun markdown-insert-inline-link (text url &optional title)
4743 "Insert an inline link with TEXT pointing to URL.
4744 Optionally, the user can provide a TITLE."
4745 (let ((cur (point)))
4746 (setq title (and title (concat " \"" title "\"")))
4747 (insert (concat "[" text "](" url title ")"))
4748 (cond ((not text) (goto-char (+ 1 cur)))
4749 ((not url) (goto-char (+ 3 (length text) cur))))))
4751 (defun markdown-insert-inline-image (text url &optional title)
4752 "Insert an inline link with alt TEXT pointing to URL.
4753 Optionally, also provide a TITLE."
4754 (let ((cur (point)))
4755 (setq title (and title (concat " \"" title "\"")))
4756 (insert (concat "![" text "](" url title ")"))
4757 (cond ((not text) (goto-char (+ 2 cur)))
4758 ((not url) (goto-char (+ 4 (length text) cur))))))
4760 (defun markdown-insert-reference-link (text label &optional url title)
4761 "Insert a reference link and, optionally, a reference definition.
4762 The link TEXT will be inserted followed by the optional LABEL.
4763 If a URL is given, also insert a definition for the reference
4764 LABEL according to `markdown-reference-location'. If a TITLE is
4765 given, it will be added to the end of the reference definition
4766 and will be used to populate the title attribute when converted
4767 to XHTML. If URL is nil, insert only the link portion (for
4768 example, when a reference label is already defined)."
4769 (insert (concat "[" text "][" label "]"))
4770 (when url
4771 (markdown-insert-reference-definition
4772 (if (string-equal label "") text label)
4773 url title)))
4775 (defun markdown-insert-reference-image (text label &optional url title)
4776 "Insert a reference image and, optionally, a reference definition.
4777 The alt TEXT will be inserted followed by the optional LABEL.
4778 If a URL is given, also insert a definition for the reference
4779 LABEL according to `markdown-reference-location'. If a TITLE is
4780 given, it will be added to the end of the reference definition
4781 and will be used to populate the title attribute when converted
4782 to XHTML. If URL is nil, insert only the link portion (for
4783 example, when a reference label is already defined)."
4784 (insert (concat "![" text "][" label "]"))
4785 (when url
4786 (markdown-insert-reference-definition
4787 (if (string-equal label "") text label)
4788 url title)))
4790 (defun markdown-insert-reference-definition (label &optional url title)
4791 "Add definition for reference LABEL with URL and TITLE.
4792 LABEL is a Markdown reference label without square brackets.
4793 URL and TITLE are optional. When given, the TITLE will
4794 be used to populate the title attribute when converted to XHTML."
4795 ;; END specifies where to leave the point upon return
4796 (let ((end (point)))
4797 (cl-case markdown-reference-location
4798 (end (goto-char (point-max)))
4799 (immediately (markdown-end-of-text-block))
4800 (subtree (markdown-end-of-subtree))
4801 (header (markdown-end-of-defun)))
4802 ;; Skip backwards over local variables. This logic is similar to the one
4803 ;; used in ‘hack-local-variables’.
4804 (when (and enable-local-variables (eobp))
4805 (search-backward "\n\f" (max (- (point) 3000) (point-min)) :move)
4806 (when (let ((case-fold-search t))
4807 (search-forward "Local Variables:" nil :move))
4808 (beginning-of-line 0)
4809 (when (eq (char-before) ?\n) (backward-char))))
4810 (unless (or (markdown-cur-line-blank-p)
4811 (thing-at-point-looking-at markdown-regex-reference-definition))
4812 (insert "\n"))
4813 (insert "\n[" label "]: ")
4814 (if url
4815 (insert url)
4816 ;; When no URL is given, leave point at END following the colon
4817 (setq end (point)))
4818 (when (> (length title) 0)
4819 (insert " \"" title "\""))
4820 (unless (looking-at-p "\n")
4821 (insert "\n"))
4822 (goto-char end)
4823 (when url
4824 (message
4825 (markdown--substitute-command-keys
4826 "Reference [%s] was defined, press \\[markdown-do] to jump there")
4827 label))))
4829 (define-obsolete-function-alias
4830 'markdown-insert-inline-link-dwim 'markdown-insert-link "v2.3")
4831 (define-obsolete-function-alias
4832 'markdown-insert-reference-link-dwim 'markdown-insert-link "v2.3")
4834 (defun markdown--insert-link-or-image (image)
4835 "Interactively insert new or update an existing link or image.
4836 When IMAGE is non-nil, insert an image. Otherwise, insert a link.
4837 This is an internal function called by
4838 `markdown-insert-link' and `markdown-insert-image'."
4839 (cl-multiple-value-bind (begin end text uri ref title)
4840 (if (markdown-use-region-p)
4841 ;; Use region as either link text or URL as appropriate.
4842 (let ((region (buffer-substring-no-properties
4843 (region-beginning) (region-end))))
4844 (if (string-match markdown-regex-uri region)
4845 ;; Region contains a URL; use it as such.
4846 (list (region-beginning) (region-end)
4847 nil (match-string 0 region) nil nil)
4848 ;; Region doesn't contain a URL, so use it as text.
4849 (list (region-beginning) (region-end)
4850 region nil nil nil)))
4851 ;; Extract and use properties of existing link, if any.
4852 (markdown-link-at-pos (point)))
4853 (let* ((ref (when ref (concat "[" ref "]")))
4854 (defined-refs (append
4855 (mapcar (lambda (ref) (concat "[" ref "]"))
4856 (markdown-get-defined-references))))
4857 (used-uris (markdown-get-used-uris))
4858 (uri-or-ref (completing-read
4859 "URL or [reference]: "
4860 (append defined-refs used-uris)
4861 nil nil (or uri ref)))
4862 (ref (cond ((string-match "\\`\\[\\(.*\\)\\]\\'" uri-or-ref)
4863 (match-string 1 uri-or-ref))
4864 ((string-equal "" uri-or-ref)
4865 "")))
4866 (uri (unless ref uri-or-ref))
4867 (text-prompt (if image
4868 "Alt text: "
4869 (if ref
4870 "Link text: "
4871 "Link text (blank for plain URL): ")))
4872 (text (read-string text-prompt text))
4873 (text (if (= (length text) 0) nil text))
4874 (plainp (and uri (not text)))
4875 (implicitp (string-equal ref ""))
4876 (ref (if implicitp text ref))
4877 (definedp (and ref (markdown-reference-definition ref)))
4878 (ref-url (unless (or uri definedp)
4879 (completing-read "Reference URL: " used-uris)))
4880 (title (unless (or plainp definedp)
4881 (read-string "Title (tooltip text, optional): " title)))
4882 (title (if (= (length title) 0) nil title)))
4883 (when (and image implicitp)
4884 (user-error "Reference required: implicit image references are invalid"))
4885 (when (and begin end)
4886 (delete-region begin end))
4887 (cond
4888 ((and (not image) uri text)
4889 (markdown-insert-inline-link text uri title))
4890 ((and image uri text)
4891 (markdown-insert-inline-image text uri title))
4892 ((and ref text)
4893 (if image
4894 (markdown-insert-reference-image text (unless implicitp ref) nil title)
4895 (markdown-insert-reference-link text (unless implicitp ref) nil title))
4896 (unless definedp
4897 (markdown-insert-reference-definition ref ref-url title)))
4898 ((and (not image) uri)
4899 (markdown-insert-uri uri))))))
4901 (defun markdown-insert-link ()
4902 "Insert new or update an existing link, with interactive prompts.
4903 If the point is at an existing link or URL, update the link text,
4904 URL, reference label, and/or title. Otherwise, insert a new link.
4905 The type of link inserted (inline, reference, or plain URL)
4906 depends on which values are provided:
4908 * If a URL and TEXT are given, insert an inline link: [TEXT](URL).
4909 * If [REF] and TEXT are given, insert a reference link: [TEXT][REF].
4910 * If only TEXT is given, insert an implicit reference link: [TEXT][].
4911 * If only a URL is given, insert a plain link: <URL>.
4913 In other words, to create an implicit reference link, leave the
4914 URL prompt empty and to create a plain URL link, leave the link
4915 text empty.
4917 If there is an active region, use the text as the default URL, if
4918 it seems to be a URL, or link text value otherwise.
4920 If a given reference is not defined, this function will
4921 additionally prompt for the URL and optional title. In this case,
4922 the reference definition is placed at the location determined by
4923 `markdown-reference-location'.
4925 Through updating the link, this function can be used to convert a
4926 link of one type (inline, reference, or plain) to another type by
4927 selectively adding or removing information via the prompts."
4928 (interactive)
4929 (markdown--insert-link-or-image nil))
4931 (defun markdown-insert-image ()
4932 "Insert new or update an existing image, with interactive prompts.
4933 If the point is at an existing image, update the alt text, URL,
4934 reference label, and/or title. Otherwise, insert a new image.
4935 The type of image inserted (inline or reference) depends on which
4936 values are provided:
4938 * If a URL and ALT-TEXT are given, insert an inline image:
4939 ![ALT-TEXT](URL).
4940 * If [REF] and ALT-TEXT are given, insert a reference image:
4941 ![ALT-TEXT][REF].
4943 If there is an active region, use the text as the default URL, if
4944 it seems to be a URL, or alt text value otherwise.
4946 If a given reference is not defined, this function will
4947 additionally prompt for the URL and optional title. In this case,
4948 the reference definition is placed at the location determined by
4949 `markdown-reference-location'.
4951 Through updating the image, this function can be used to convert an
4952 image of one type (inline or reference) to another type by
4953 selectively adding or removing information via the prompts."
4954 (interactive)
4955 (markdown--insert-link-or-image t))
4957 (defun markdown-insert-uri (&optional uri)
4958 "Insert markup for an inline URI.
4959 If there is an active region, use it as the URI. If the point is
4960 at a URI, wrap it with angle brackets. If the point is at an
4961 inline URI, remove the angle brackets. Otherwise, simply insert
4962 angle brackets place the point between them."
4963 (interactive)
4964 (if (markdown-use-region-p)
4965 ;; Active region
4966 (let ((bounds (markdown-unwrap-things-in-region
4967 (region-beginning) (region-end)
4968 markdown-regex-angle-uri 0 2)))
4969 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
4970 ;; Markup removal, URI at point, new URI, or empty markup insertion
4971 (if (thing-at-point-looking-at markdown-regex-angle-uri)
4972 (markdown-unwrap-thing-at-point nil 0 2)
4973 (if uri
4974 (insert "<" uri ">")
4975 (markdown-wrap-or-insert "<" ">" 'url nil nil)))))
4977 (defun markdown-insert-wiki-link ()
4978 "Insert a wiki link of the form [[WikiLink]].
4979 If there is an active region, use the region as the link text.
4980 If the point is at a word, use the word as the link text. If
4981 there is no active region and the point is not at word, simply
4982 insert link markup."
4983 (interactive)
4984 (if (markdown-use-region-p)
4985 ;; Active region
4986 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
4987 ;; Markup removal, wiki link at at point, or empty markup insertion
4988 (if (thing-at-point-looking-at markdown-regex-wiki-link)
4989 (if (or markdown-wiki-link-alias-first
4990 (null (match-string 5)))
4991 (markdown-unwrap-thing-at-point nil 1 3)
4992 (markdown-unwrap-thing-at-point nil 1 5))
4993 (markdown-wrap-or-insert "[[" "]]"))))
4995 (defun markdown-remove-header ()
4996 "Remove header markup if point is at a header.
4997 Return bounds of remaining header text if a header was removed
4998 and nil otherwise."
4999 (interactive "*")
5000 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
5001 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
5003 (defun markdown-insert-header (&optional level text setext)
5004 "Insert or replace header markup.
5005 The level of the header is specified by LEVEL and header text is
5006 given by TEXT. LEVEL must be an integer from 1 and 6, and the
5007 default value is 1.
5008 When TEXT is nil, the header text is obtained as follows.
5009 If there is an active region, it is used as the header text.
5010 Otherwise, the current line will be used as the header text.
5011 If there is not an active region and the point is at a header,
5012 remove the header markup and replace with level N header.
5013 Otherwise, insert empty header markup and place the point in
5014 between.
5015 The style of the header will be atx (hash marks) unless
5016 SETEXT is non-nil, in which case a setext-style (underlined)
5017 header will be inserted."
5018 (interactive "p\nsHeader text: ")
5019 (setq level (min (max (or level 1) 1) (if setext 2 6)))
5020 ;; Determine header text if not given
5021 (when (null text)
5022 (if (markdown-use-region-p)
5023 ;; Active region
5024 (setq text (delete-and-extract-region (region-beginning) (region-end)))
5025 ;; No active region
5026 (markdown-remove-header)
5027 (setq text (delete-and-extract-region
5028 (line-beginning-position) (line-end-position)))
5029 (when (and setext (string-match-p "^[ \t]*$" text))
5030 (setq text (read-string "Header text: "))))
5031 (setq text (markdown-compress-whitespace-string text)))
5032 ;; Insertion with given text
5033 (markdown-ensure-blank-line-before)
5034 (let (hdr)
5035 (cond (setext
5036 (setq hdr (make-string (string-width text) (if (= level 2) ?- ?=)))
5037 (insert text "\n" hdr))
5039 (setq hdr (make-string level ?#))
5040 (insert hdr " " text)
5041 (when (null markdown-asymmetric-header) (insert " " hdr)))))
5042 (markdown-ensure-blank-line-after)
5043 ;; Leave point at end of text
5044 (cond (setext
5045 (backward-char (1+ (string-width text))))
5046 ((null markdown-asymmetric-header)
5047 (backward-char (1+ level)))))
5049 (defun markdown-insert-header-dwim (&optional arg setext)
5050 "Insert or replace header markup.
5051 The level and type of the header are determined automatically by
5052 the type and level of the previous header, unless a prefix
5053 argument is given via ARG.
5054 With a numeric prefix valued 1 to 6, insert a header of the given
5055 level, with the type being determined automatically (note that
5056 only level 1 or 2 setext headers are possible).
5058 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
5059 promote the heading by one level.
5060 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
5061 demote the heading by one level.
5062 When SETEXT is non-nil, prefer setext-style headers when
5063 possible (levels one and two).
5065 When there is an active region, use it for the header text. When
5066 the point is at an existing header, change the type and level
5067 according to the rules above.
5068 Otherwise, if the line is not empty, create a header using the
5069 text on the current line as the header text.
5070 Finally, if the point is on a blank line, insert empty header
5071 markup (atx) or prompt for text (setext).
5072 See `markdown-insert-header' for more details about how the
5073 header text is determined."
5074 (interactive "*P")
5075 (let (level)
5076 (save-excursion
5077 (when (or (thing-at-point-looking-at markdown-regex-header)
5078 (re-search-backward markdown-regex-header nil t))
5079 ;; level of current or previous header
5080 (setq level (markdown-outline-level))
5081 ;; match group 1 indicates a setext header
5082 (setq setext (match-end 1))))
5083 ;; check prefix argument
5084 (cond
5085 ((and (equal arg '(4)) level (> level 1)) ;; C-u
5086 (cl-decf level))
5087 ((and (equal arg '(16)) level (< level 6)) ;; C-u C-u
5088 (cl-incf level))
5089 (arg ;; numeric prefix
5090 (setq level (prefix-numeric-value arg))))
5091 ;; setext headers must be level one or two
5092 (and level (setq setext (and setext (<= level 2))))
5093 ;; insert the heading
5094 (markdown-insert-header level nil setext)))
5096 (defun markdown-insert-header-setext-dwim (&optional arg)
5097 "Insert or replace header markup, with preference for setext.
5098 See `markdown-insert-header-dwim' for details, including how ARG is handled."
5099 (interactive "*P")
5100 (markdown-insert-header-dwim arg t))
5102 (defun markdown-insert-header-atx-1 ()
5103 "Insert a first level atx-style (hash mark) header.
5104 See `markdown-insert-header'."
5105 (interactive "*")
5106 (markdown-insert-header 1 nil nil))
5108 (defun markdown-insert-header-atx-2 ()
5109 "Insert a level two atx-style (hash mark) header.
5110 See `markdown-insert-header'."
5111 (interactive "*")
5112 (markdown-insert-header 2 nil nil))
5114 (defun markdown-insert-header-atx-3 ()
5115 "Insert a level three atx-style (hash mark) header.
5116 See `markdown-insert-header'."
5117 (interactive "*")
5118 (markdown-insert-header 3 nil nil))
5120 (defun markdown-insert-header-atx-4 ()
5121 "Insert a level four atx-style (hash mark) header.
5122 See `markdown-insert-header'."
5123 (interactive "*")
5124 (markdown-insert-header 4 nil nil))
5126 (defun markdown-insert-header-atx-5 ()
5127 "Insert a level five atx-style (hash mark) header.
5128 See `markdown-insert-header'."
5129 (interactive "*")
5130 (markdown-insert-header 5 nil nil))
5132 (defun markdown-insert-header-atx-6 ()
5133 "Insert a sixth level atx-style (hash mark) header.
5134 See `markdown-insert-header'."
5135 (interactive "*")
5136 (markdown-insert-header 6 nil nil))
5138 (defun markdown-insert-header-setext-1 ()
5139 "Insert a setext-style (underlined) first-level header.
5140 See `markdown-insert-header'."
5141 (interactive "*")
5142 (markdown-insert-header 1 nil t))
5144 (defun markdown-insert-header-setext-2 ()
5145 "Insert a setext-style (underlined) second-level header.
5146 See `markdown-insert-header'."
5147 (interactive "*")
5148 (markdown-insert-header 2 nil t))
5150 (defun markdown-blockquote-indentation (loc)
5151 "Return string containing necessary indentation for a blockquote at LOC.
5152 Also see `markdown-pre-indentation'."
5153 (save-excursion
5154 (goto-char loc)
5155 (let* ((list-level (length (markdown-calculate-list-levels)))
5156 (indent ""))
5157 (dotimes (_ list-level indent)
5158 (setq indent (concat indent " "))))))
5160 (defun markdown-insert-blockquote ()
5161 "Start a blockquote section (or blockquote the region).
5162 If Transient Mark mode is on and a region is active, it is used as
5163 the blockquote text."
5164 (interactive)
5165 (if (markdown-use-region-p)
5166 (markdown-blockquote-region (region-beginning) (region-end))
5167 (markdown-ensure-blank-line-before)
5168 (insert (markdown-blockquote-indentation (point)) "> ")
5169 (markdown-ensure-blank-line-after)))
5171 (defun markdown-block-region (beg end prefix)
5172 "Format the region using a block prefix.
5173 Arguments BEG and END specify the beginning and end of the
5174 region. The characters PREFIX will appear at the beginning
5175 of each line."
5176 (save-excursion
5177 (let* ((end-marker (make-marker))
5178 (beg-marker (make-marker))
5179 (prefix-without-trailing-whitespace
5180 (replace-regexp-in-string (rx (+ blank) eos) "" prefix)))
5181 ;; Ensure blank line after and remove extra whitespace
5182 (goto-char end)
5183 (skip-syntax-backward "-")
5184 (set-marker end-marker (point))
5185 (delete-horizontal-space)
5186 (markdown-ensure-blank-line-after)
5187 ;; Ensure blank line before and remove extra whitespace
5188 (goto-char beg)
5189 (skip-syntax-forward "-")
5190 (delete-horizontal-space)
5191 (markdown-ensure-blank-line-before)
5192 (set-marker beg-marker (point))
5193 ;; Insert PREFIX before each line
5194 (goto-char beg-marker)
5195 (while (and (< (line-beginning-position) end-marker)
5196 (not (eobp)))
5197 ;; Don’t insert trailing whitespace.
5198 (insert (if (eolp) prefix-without-trailing-whitespace prefix))
5199 (forward-line)))))
5201 (defun markdown-blockquote-region (beg end)
5202 "Blockquote the region.
5203 Arguments BEG and END specify the beginning and end of the region."
5204 (interactive "*r")
5205 (markdown-block-region
5206 beg end (concat (markdown-blockquote-indentation
5207 (max (point-min) (1- beg))) "> ")))
5209 (defun markdown-pre-indentation (loc)
5210 "Return string containing necessary whitespace for a pre block at LOC.
5211 Also see `markdown-blockquote-indentation'."
5212 (save-excursion
5213 (goto-char loc)
5214 (let* ((list-level (length (markdown-calculate-list-levels)))
5215 indent)
5216 (dotimes (_ (1+ list-level) indent)
5217 (setq indent (concat indent " "))))))
5219 (defun markdown-insert-pre ()
5220 "Start a preformatted section (or apply to the region).
5221 If Transient Mark mode is on and a region is active, it is marked
5222 as preformatted text."
5223 (interactive)
5224 (if (markdown-use-region-p)
5225 (markdown-pre-region (region-beginning) (region-end))
5226 (markdown-ensure-blank-line-before)
5227 (insert (markdown-pre-indentation (point)))
5228 (markdown-ensure-blank-line-after)))
5230 (defun markdown-pre-region (beg end)
5231 "Format the region as preformatted text.
5232 Arguments BEG and END specify the beginning and end of the region."
5233 (interactive "*r")
5234 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
5235 (markdown-block-region beg end indent)))
5237 (defun markdown-electric-backquote (arg)
5238 "Insert a backquote.
5239 The numeric prefix argument ARG says how many times to repeat the insertion.
5240 Call `markdown-insert-gfm-code-block' interactively
5241 if three backquotes inserted at the beginning of line."
5242 (interactive "*P")
5243 (self-insert-command (prefix-numeric-value arg))
5244 (when (and markdown-gfm-use-electric-backquote (looking-back "^```" nil))
5245 (replace-match "")
5246 (call-interactively #'markdown-insert-gfm-code-block)))
5248 (defconst markdown-gfm-recognized-languages
5249 ;; To reproduce/update, evaluate the let-form in
5250 ;; scripts/get-recognized-gfm-languages.el. that produces a single long sexp,
5251 ;; but with appropriate use of a keyboard macro, indenting and filling it
5252 ;; properly is pretty fast.
5253 '("1C-Enterprise" "ABAP" "ABNF" "AGS-Script" "AMPL" "ANTLR"
5254 "API-Blueprint" "APL" "ASN.1" "ASP" "ATS" "ActionScript" "Ada" "Agda"
5255 "Alloy" "Alpine-Abuild" "Ant-Build-System" "ApacheConf" "Apex"
5256 "Apollo-Guidance-Computer" "AppleScript" "Arc" "Arduino" "AsciiDoc"
5257 "AspectJ" "Assembly" "Augeas" "AutoHotkey" "AutoIt" "Awk" "Batchfile"
5258 "Befunge" "Bison" "BitBake" "Blade" "BlitzBasic" "BlitzMax" "Bluespec"
5259 "Boo" "Brainfuck" "Brightscript" "Bro" "C#" "C++" "C-ObjDump"
5260 "C2hs-Haskell" "CLIPS" "CMake" "COBOL" "COLLADA" "CSON" "CSS" "CSV"
5261 "CWeb" "Cap'n-Proto" "CartoCSS" "Ceylon" "Chapel" "Charity" "ChucK"
5262 "Cirru" "Clarion" "Clean" "Click" "Clojure" "Closure-Templates"
5263 "CoffeeScript" "ColdFusion" "ColdFusion-CFC" "Common-Lisp"
5264 "Component-Pascal" "Cool" "Coq" "Cpp-ObjDump" "Creole" "Crystal"
5265 "Csound" "Csound-Document" "Csound-Score" "Cuda" "Cycript" "Cython"
5266 "D-ObjDump" "DIGITAL-Command-Language" "DM" "DNS-Zone" "DTrace"
5267 "Darcs-Patch" "Dart" "Diff" "Dockerfile" "Dogescript" "Dylan" "EBNF"
5268 "ECL" "ECLiPSe" "EJS" "EQ" "Eagle" "Ecere-Projects" "Eiffel" "Elixir"
5269 "Elm" "Emacs-Lisp" "EmberScript" "Erlang" "F#" "FLUX" "Factor" "Fancy"
5270 "Fantom" "Filebench-WML" "Filterscript" "Formatted" "Forth" "Fortran"
5271 "FreeMarker" "Frege" "G-code" "GAMS" "GAP" "GCC-Machine-Description"
5272 "GDB" "GDScript" "GLSL" "GN" "Game-Maker-Language" "Genie" "Genshi"
5273 "Gentoo-Ebuild" "Gentoo-Eclass" "Gettext-Catalog" "Gherkin" "Glyph"
5274 "Gnuplot" "Go" "Golo" "Gosu" "Grace" "Gradle" "Grammatical-Framework"
5275 "Graph-Modeling-Language" "GraphQL" "Graphviz-(DOT)" "Groovy"
5276 "Groovy-Server-Pages" "HCL" "HLSL" "HTML" "HTML+Django" "HTML+ECR"
5277 "HTML+EEX" "HTML+ERB" "HTML+PHP" "HTTP" "Hack" "Haml" "Handlebars"
5278 "Harbour" "Haskell" "Haxe" "Hy" "HyPhy" "IDL" "IGOR-Pro" "INI"
5279 "IRC-log" "Idris" "Inform-7" "Inno-Setup" "Io" "Ioke" "Isabelle"
5280 "Isabelle-ROOT" "JFlex" "JSON" "JSON5" "JSONLD" "JSONiq" "JSX"
5281 "Jasmin" "Java" "Java-Server-Pages" "JavaScript" "Jison" "Jison-Lex"
5282 "Jolie" "Julia" "Jupyter-Notebook" "KRL" "KiCad" "Kit" "Kotlin" "LFE"
5283 "LLVM" "LOLCODE" "LSL" "LabVIEW" "Lasso" "Latte" "Lean" "Less" "Lex"
5284 "LilyPond" "Limbo" "Linker-Script" "Linux-Kernel-Module" "Liquid"
5285 "Literate-Agda" "Literate-CoffeeScript" "Literate-Haskell"
5286 "LiveScript" "Logos" "Logtalk" "LookML" "LoomScript" "Lua" "M4"
5287 "M4Sugar" "MAXScript" "MQL4" "MQL5" "MTML" "MUF" "Makefile" "Mako"
5288 "Markdown" "Marko" "Mask" "Mathematica" "Matlab" "Maven-POM" "Max"
5289 "MediaWiki" "Mercury" "Meson" "Metal" "MiniD" "Mirah" "Modelica"
5290 "Modula-2" "Module-Management-System" "Monkey" "Moocode" "MoonScript"
5291 "Myghty" "NCL" "NL" "NSIS" "Nemerle" "NetLinx" "NetLinx+ERB" "NetLogo"
5292 "NewLisp" "Nginx" "Nim" "Ninja" "Nit" "Nix" "Nu" "NumPy" "OCaml"
5293 "ObjDump" "Objective-C" "Objective-C++" "Objective-J" "Omgrofl" "Opa"
5294 "Opal" "OpenCL" "OpenEdge-ABL" "OpenRC-runscript" "OpenSCAD"
5295 "OpenType-Feature-File" "Org" "Ox" "Oxygene" "Oz" "P4" "PAWN" "PHP"
5296 "PLSQL" "PLpgSQL" "POV-Ray-SDL" "Pan" "Papyrus" "Parrot"
5297 "Parrot-Assembly" "Parrot-Internal-Representation" "Pascal" "Pep8"
5298 "Perl" "Perl6" "Pic" "Pickle" "PicoLisp" "PigLatin" "Pike" "Pod"
5299 "PogoScript" "Pony" "PostScript" "PowerBuilder" "PowerShell"
5300 "Processing" "Prolog" "Propeller-Spin" "Protocol-Buffer" "Public-Key"
5301 "Pug" "Puppet" "Pure-Data" "PureBasic" "PureScript" "Python"
5302 "Python-console" "Python-traceback" "QML" "QMake" "RAML" "RDoc"
5303 "REALbasic" "REXX" "RHTML" "RMarkdown" "RPM-Spec" "RUNOFF" "Racket"
5304 "Ragel" "Rascal" "Raw-token-data" "Reason" "Rebol" "Red" "Redcode"
5305 "Regular-Expression" "Ren'Py" "RenderScript" "RobotFramework" "Roff"
5306 "Rouge" "Ruby" "Rust" "SAS" "SCSS" "SMT" "SPARQL" "SQF" "SQL" "SQLPL"
5307 "SRecode-Template" "STON" "SVG" "Sage" "SaltStack" "Sass" "Scala"
5308 "Scaml" "Scheme" "Scilab" "Self" "ShaderLab" "Shell" "ShellSession"
5309 "Shen" "Slash" "Slim" "Smali" "Smalltalk" "Smarty" "SourcePawn"
5310 "Spline-Font-Database" "Squirrel" "Stan" "Standard-ML" "Stata"
5311 "Stylus" "SubRip-Text" "Sublime-Text-Config" "SuperCollider" "Swift"
5312 "SystemVerilog" "TI-Program" "TLA" "TOML" "TXL" "Tcl" "Tcsh" "TeX"
5313 "Tea" "Terra" "Text" "Textile" "Thrift" "Turing" "Turtle" "Twig"
5314 "Type-Language" "TypeScript" "Unified-Parallel-C" "Unity3D-Asset"
5315 "Unix-Assembly" "Uno" "UnrealScript" "UrWeb" "VCL" "VHDL" "Vala"
5316 "Verilog" "Vim-script" "Visual-Basic" "Volt" "Vue"
5317 "Wavefront-Material" "Wavefront-Object" "Web-Ontology-Language"
5318 "WebAssembly" "WebIDL" "World-of-Warcraft-Addon-Data" "X10" "XC"
5319 "XCompose" "XML" "XPages" "XProc" "XQuery" "XS" "XSLT" "Xojo" "Xtend"
5320 "YAML" "YANG" "Yacc" "Zephir" "Zimpl" "desktop" "eC" "edn" "fish"
5321 "mupad" "nesC" "ooc" "reStructuredText" "wisp" "xBase")
5322 "Language specifiers recognized by GitHub's syntax highlighting features.")
5324 (defvar markdown-gfm-used-languages nil
5325 "Language names used in GFM code blocks.")
5326 (make-variable-buffer-local 'markdown-gfm-used-languages)
5328 (defun markdown-trim-whitespace (str)
5329 (markdown-replace-regexp-in-string
5330 "\\(?:[[:space:]\r\n]+\\'\\|\\`[[:space:]\r\n]+\\)" "" str))
5332 (defun markdown-clean-language-string (str)
5333 (markdown-replace-regexp-in-string
5334 "{\\.?\\|}" "" (markdown-trim-whitespace str)))
5336 (defun markdown-validate-language-string (widget)
5337 (let ((str (widget-value widget)))
5338 (unless (string= str (markdown-clean-language-string str))
5339 (widget-put widget :error (format "Invalid language spec: '%s'" str))
5340 widget)))
5342 (defun markdown-gfm-get-corpus ()
5343 "Create corpus of recognized GFM code block languages for the given buffer."
5344 (let ((given-corpus (append markdown-gfm-additional-languages
5345 markdown-gfm-recognized-languages)))
5346 (append
5347 markdown-gfm-used-languages
5348 (if markdown-gfm-downcase-languages (cl-mapcar #'downcase given-corpus)
5349 given-corpus))))
5351 (defun markdown-gfm-add-used-language (lang)
5352 "Clean LANG and add to list of used languages."
5353 (setq markdown-gfm-used-languages
5354 (cons lang (remove lang markdown-gfm-used-languages))))
5356 (defcustom markdown-spaces-after-code-fence 1
5357 "Number of space characters to insert after a code fence.
5358 \\<gfm-mode-map>\\[markdown-insert-gfm-code-block] inserts this many spaces between an
5359 opening code fence and an info string."
5360 :group 'markdown
5361 :type 'integer
5362 :safe #'natnump
5363 :package-version '(markdown-mode . "2.3"))
5365 (defun markdown-insert-gfm-code-block (&optional lang edit)
5366 "Insert GFM code block for language LANG.
5367 If LANG is nil, the language will be queried from user. If a
5368 region is active, wrap this region with the markup instead. If
5369 the region boundaries are not on empty lines, these are added
5370 automatically in order to have the correct markup. When EDIT is
5371 non-nil (e.g., when \\[universal-argument] is given), edit the
5372 code block in an indirect buffer after insertion."
5373 (interactive
5374 (list (let ((completion-ignore-case nil))
5375 (condition-case nil
5376 (markdown-clean-language-string
5377 (completing-read
5378 "Programming language: "
5379 (markdown-gfm-get-corpus)
5380 nil 'confirm (car markdown-gfm-used-languages)
5381 'markdown-gfm-language-history))
5382 (quit "")))
5383 current-prefix-arg))
5384 (unless (string= lang "") (markdown-gfm-add-used-language lang))
5385 (when (> (length lang) 0)
5386 (setq lang (concat (make-string markdown-spaces-after-code-fence ?\s)
5387 lang)))
5388 (if (markdown-use-region-p)
5389 (let* ((b (region-beginning)) (e (region-end)) end
5390 (indent (progn (goto-char b) (current-indentation))))
5391 (goto-char e)
5392 ;; if we're on a blank line, don't newline, otherwise the ```
5393 ;; should go on its own line
5394 (unless (looking-back "\n" nil)
5395 (newline))
5396 (indent-to indent)
5397 (insert "```")
5398 (markdown-ensure-blank-line-after)
5399 (setq end (point))
5400 (goto-char b)
5401 ;; if we're on a blank line, insert the quotes here, otherwise
5402 ;; add a new line first
5403 (unless (looking-at-p "\n")
5404 (newline)
5405 (forward-line -1))
5406 (markdown-ensure-blank-line-before)
5407 (indent-to indent)
5408 (insert "```" lang)
5409 (markdown-syntax-propertize-fenced-block-constructs (point-at-bol) end))
5410 (let ((indent (current-indentation)) start)
5411 (delete-horizontal-space :backward-only)
5412 (markdown-ensure-blank-line-before)
5413 (indent-to indent)
5414 (setq start (point))
5415 (insert "```" lang "\n")
5416 (indent-to indent)
5417 (unless edit (insert ?\n))
5418 (indent-to indent)
5419 (insert "```")
5420 (markdown-ensure-blank-line-after)
5421 (markdown-syntax-propertize-fenced-block-constructs start (point)))
5422 (end-of-line 0)
5423 (when edit (markdown-edit-code-block))))
5425 (defun markdown-code-block-lang (&optional pos-prop)
5426 "Return the language name for a GFM or tilde fenced code block.
5427 The beginning of the block may be described by POS-PROP,
5428 a cons of (pos . prop) giving the position and property
5429 at the beginning of the block."
5430 (or pos-prop
5431 (setq pos-prop
5432 (markdown-max-of-seq
5433 #'car
5434 (cl-remove-if
5435 #'null
5436 (cl-mapcar
5437 #'markdown-find-previous-prop
5438 (markdown-get-fenced-block-begin-properties))))))
5439 (when pos-prop
5440 (goto-char (car pos-prop))
5441 (set-match-data (get-text-property (point) (cdr pos-prop)))
5442 ;; Note: Hard-coded group number assumes tilde
5443 ;; and GFM fenced code regexp groups agree.
5444 (let ((begin (match-beginning 3))
5445 (end (match-end 3)))
5446 (when (and begin end)
5447 ;; Fix language strings beginning with periods, like ".ruby".
5448 (when (eq (char-after begin) ?.)
5449 (setq begin (1+ begin)))
5450 (buffer-substring-no-properties begin end)))))
5452 (defun markdown-gfm-parse-buffer-for-languages (&optional buffer)
5453 (with-current-buffer (or buffer (current-buffer))
5454 (save-excursion
5455 (goto-char (point-min))
5456 (cl-loop
5457 with prop = 'markdown-gfm-block-begin
5458 for pos-prop = (markdown-find-next-prop prop)
5459 while pos-prop
5460 for lang = (markdown-code-block-lang pos-prop)
5461 do (progn (when lang (markdown-gfm-add-used-language lang))
5462 (goto-char (next-single-property-change (point) prop)))))))
5465 ;;; Footnotes ==================================================================
5467 (defun markdown-footnote-counter-inc ()
5468 "Increment `markdown-footnote-counter' and return the new value."
5469 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
5470 (save-excursion
5471 (goto-char (point-min))
5472 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
5473 (point-max) t)
5474 (let ((fn (string-to-number (match-string 1))))
5475 (when (> fn markdown-footnote-counter)
5476 (setq markdown-footnote-counter fn))))))
5477 (cl-incf markdown-footnote-counter))
5479 (defun markdown-insert-footnote ()
5480 "Insert footnote with a new number and move point to footnote definition."
5481 (interactive)
5482 (let ((fn (markdown-footnote-counter-inc)))
5483 (insert (format "[^%d]" fn))
5484 (markdown-footnote-text-find-new-location)
5485 (markdown-ensure-blank-line-before)
5486 (unless (markdown-cur-line-blank-p)
5487 (insert "\n"))
5488 (insert (format "[^%d]: " fn))
5489 (markdown-ensure-blank-line-after)))
5491 (defun markdown-footnote-text-find-new-location ()
5492 "Position the point at the proper location for a new footnote text."
5493 (cond
5494 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
5495 ((eq markdown-footnote-location 'immediately) (markdown-end-of-text-block))
5496 ((eq markdown-footnote-location 'subtree) (markdown-end-of-subtree))
5497 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
5499 (defun markdown-footnote-kill ()
5500 "Kill the footnote at point.
5501 The footnote text is killed (and added to the kill ring), the
5502 footnote marker is deleted. Point has to be either at the
5503 footnote marker or in the footnote text."
5504 (interactive)
5505 (let ((marker-pos nil)
5506 (skip-deleting-marker nil)
5507 (starting-footnote-text-positions
5508 (markdown-footnote-text-positions)))
5509 (when starting-footnote-text-positions
5510 ;; We're starting in footnote text, so mark our return position and jump
5511 ;; to the marker if possible.
5512 (let ((marker-pos (markdown-footnote-find-marker
5513 (cl-first starting-footnote-text-positions))))
5514 (if marker-pos
5515 (goto-char (1- marker-pos))
5516 ;; If there isn't a marker, we still want to kill the text.
5517 (setq skip-deleting-marker t))))
5518 ;; Either we didn't start in the text, or we started in the text and jumped
5519 ;; to the marker. We want to assume we're at the marker now and error if
5520 ;; we're not.
5521 (unless skip-deleting-marker
5522 (let ((marker (markdown-footnote-delete-marker)))
5523 (unless marker
5524 (error "Not at a footnote"))
5525 ;; Even if we knew the text position before, it changed when we deleted
5526 ;; the label.
5527 (setq marker-pos (cl-second marker))
5528 (let ((new-text-pos (markdown-footnote-find-text (cl-first marker))))
5529 (unless new-text-pos
5530 (error "No text for footnote `%s'" (cl-first marker)))
5531 (goto-char new-text-pos))))
5532 (let ((pos (markdown-footnote-kill-text)))
5533 (goto-char (if starting-footnote-text-positions
5535 marker-pos)))))
5537 (defun markdown-footnote-delete-marker ()
5538 "Delete a footnote marker at point.
5539 Returns a list (ID START) containing the footnote ID and the
5540 start position of the marker before deletion. If no footnote
5541 marker was deleted, this function returns NIL."
5542 (let ((marker (markdown-footnote-marker-positions)))
5543 (when marker
5544 (delete-region (cl-second marker) (cl-third marker))
5545 (butlast marker))))
5547 (defun markdown-footnote-kill-text ()
5548 "Kill footnote text at point.
5549 Returns the start position of the footnote text before deletion,
5550 or NIL if point was not inside a footnote text.
5552 The killed text is placed in the kill ring (without the footnote
5553 number)."
5554 (let ((fn (markdown-footnote-text-positions)))
5555 (when fn
5556 (let ((text (delete-and-extract-region (cl-second fn) (cl-third fn))))
5557 (string-match (concat "\\[\\" (cl-first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
5558 (kill-new (match-string 1 text))
5559 (when (and (markdown-cur-line-blank-p)
5560 (markdown-prev-line-blank-p)
5561 (not (bobp)))
5562 (delete-region (1- (point)) (point)))
5563 (cl-second fn)))))
5565 (defun markdown-footnote-goto-text ()
5566 "Jump to the text of the footnote at point."
5567 (interactive)
5568 (let ((fn (car (markdown-footnote-marker-positions))))
5569 (unless fn
5570 (user-error "Not at a footnote marker"))
5571 (let ((new-pos (markdown-footnote-find-text fn)))
5572 (unless new-pos
5573 (error "No definition found for footnote `%s'" fn))
5574 (goto-char new-pos))))
5576 (defun markdown-footnote-return ()
5577 "Return from a footnote to its footnote number in the main text."
5578 (interactive)
5579 (let ((fn (save-excursion
5580 (car (markdown-footnote-text-positions)))))
5581 (unless fn
5582 (user-error "Not in a footnote"))
5583 (let ((new-pos (markdown-footnote-find-marker fn)))
5584 (unless new-pos
5585 (error "Footnote marker `%s' not found" fn))
5586 (goto-char new-pos))))
5588 (defun markdown-footnote-find-marker (id)
5589 "Find the location of the footnote marker with ID.
5590 The actual buffer position returned is the position directly
5591 following the marker's closing bracket. If no marker is found,
5592 NIL is returned."
5593 (save-excursion
5594 (goto-char (point-min))
5595 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
5596 (skip-chars-backward "^]")
5597 (point))))
5599 (defun markdown-footnote-find-text (id)
5600 "Find the location of the text of footnote ID.
5601 The actual buffer position returned is the position of the first
5602 character of the text, after the footnote's identifier. If no
5603 footnote text is found, NIL is returned."
5604 (save-excursion
5605 (goto-char (point-min))
5606 (when (re-search-forward (concat "^ \\{0,3\\}\\[" id "\\]:") nil t)
5607 (skip-chars-forward "[ \t]")
5608 (point))))
5610 (defun markdown-footnote-marker-positions ()
5611 "Return the position and ID of the footnote marker point is on.
5612 The return value is a list (ID START END). If point is not on a
5613 footnote, NIL is returned."
5614 ;; first make sure we're at a footnote marker
5615 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
5616 (looking-at-p (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
5617 (save-excursion
5618 ;; move point between [ and ^:
5619 (if (looking-at-p "\\[")
5620 (forward-char 1)
5621 (skip-chars-backward "^["))
5622 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
5623 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
5625 (defun markdown-footnote-text-positions ()
5626 "Return the start and end positions of the footnote text point is in.
5627 The exact return value is a list of three elements: (ID START END).
5628 The start position is the position of the opening bracket
5629 of the footnote id. The end position is directly after the
5630 newline that ends the footnote. If point is not in a footnote,
5631 NIL is returned instead."
5632 (save-excursion
5633 (let (result)
5634 (move-beginning-of-line 1)
5635 ;; Try to find the label. If we haven't found the label and we're at a blank
5636 ;; or indented line, back up if possible.
5637 (while (and
5638 (not (and (looking-at markdown-regex-footnote-definition)
5639 (setq result (list (match-string 1) (point)))))
5640 (and (not (bobp))
5641 (or (markdown-cur-line-blank-p)
5642 (>= (current-indentation) 4))))
5643 (forward-line -1))
5644 (when result
5645 ;; Advance if there is a next line that is either blank or indented.
5646 ;; (Need to check if we're on the last line, because
5647 ;; markdown-next-line-blank-p returns true for last line in buffer.)
5648 (while (and (/= (line-end-position) (point-max))
5649 (or (markdown-next-line-blank-p)
5650 (>= (markdown-next-line-indent) 4)))
5651 (forward-line))
5652 ;; Move back while the current line is blank.
5653 (while (markdown-cur-line-blank-p)
5654 (forward-line -1))
5655 ;; Advance to capture this line and a single trailing newline (if there
5656 ;; is one).
5657 (forward-line)
5658 (append result (list (point)))))))
5661 ;;; Element Removal ===========================================================
5663 (defun markdown-kill-thing-at-point ()
5664 "Kill thing at point and add important text, without markup, to kill ring.
5665 Possible things to kill include (roughly in order of precedence):
5666 inline code, headers, horizonal rules, links (add link text to
5667 kill ring), images (add alt text to kill ring), angle uri, email
5668 addresses, bold, italics, reference definition (add URI to kill
5669 ring), footnote markers and text (kill both marker and text, add
5670 text to kill ring), and list items."
5671 (interactive "*")
5672 (let (val)
5673 (cond
5674 ;; Inline code
5675 ((markdown-inline-code-at-point)
5676 (kill-new (match-string 2))
5677 (delete-region (match-beginning 0) (match-end 0)))
5678 ;; ATX header
5679 ((thing-at-point-looking-at markdown-regex-header-atx)
5680 (kill-new (match-string 2))
5681 (delete-region (match-beginning 0) (match-end 0)))
5682 ;; Setext header
5683 ((thing-at-point-looking-at markdown-regex-header-setext)
5684 (kill-new (match-string 1))
5685 (delete-region (match-beginning 0) (match-end 0)))
5686 ;; Horizonal rule
5687 ((thing-at-point-looking-at markdown-regex-hr)
5688 (kill-new (match-string 0))
5689 (delete-region (match-beginning 0) (match-end 0)))
5690 ;; Inline link or image (add link or alt text to kill ring)
5691 ((thing-at-point-looking-at markdown-regex-link-inline)
5692 (kill-new (match-string 3))
5693 (delete-region (match-beginning 0) (match-end 0)))
5694 ;; Reference link or image (add link or alt text to kill ring)
5695 ((thing-at-point-looking-at markdown-regex-link-reference)
5696 (kill-new (match-string 3))
5697 (delete-region (match-beginning 0) (match-end 0)))
5698 ;; Angle URI (add URL to kill ring)
5699 ((thing-at-point-looking-at markdown-regex-angle-uri)
5700 (kill-new (match-string 2))
5701 (delete-region (match-beginning 0) (match-end 0)))
5702 ;; Email address in angle brackets (add email address to kill ring)
5703 ((thing-at-point-looking-at markdown-regex-email)
5704 (kill-new (match-string 1))
5705 (delete-region (match-beginning 0) (match-end 0)))
5706 ;; Wiki link (add alias text to kill ring)
5707 ((and markdown-enable-wiki-links
5708 (thing-at-point-looking-at markdown-regex-wiki-link))
5709 (kill-new (markdown-wiki-link-alias))
5710 (delete-region (match-beginning 1) (match-end 1)))
5711 ;; Bold
5712 ((thing-at-point-looking-at markdown-regex-bold)
5713 (kill-new (match-string 4))
5714 (delete-region (match-beginning 2) (match-end 2)))
5715 ;; Italics
5716 ((thing-at-point-looking-at markdown-regex-italic)
5717 (kill-new (match-string 3))
5718 (delete-region (match-beginning 1) (match-end 1)))
5719 ;; Strikethrough
5720 ((thing-at-point-looking-at markdown-regex-strike-through)
5721 (kill-new (match-string 4))
5722 (delete-region (match-beginning 2) (match-end 2)))
5723 ;; Footnote marker (add footnote text to kill ring)
5724 ((thing-at-point-looking-at markdown-regex-footnote)
5725 (markdown-footnote-kill))
5726 ;; Footnote text (add footnote text to kill ring)
5727 ((setq val (markdown-footnote-text-positions))
5728 (markdown-footnote-kill))
5729 ;; Reference definition (add URL to kill ring)
5730 ((thing-at-point-looking-at markdown-regex-reference-definition)
5731 (kill-new (match-string 5))
5732 (delete-region (match-beginning 0) (match-end 0)))
5733 ;; List item
5734 ((setq val (markdown-cur-list-item-bounds))
5735 (kill-new (delete-and-extract-region (cl-first val) (cl-second val))))
5737 (user-error "Nothing found at point to kill")))))
5740 ;;; Indentation ====================================================================
5742 (defun markdown-indent-find-next-position (cur-pos positions)
5743 "Return the position after the index of CUR-POS in POSITIONS.
5744 Positions are calculated by `markdown-calc-indents'."
5745 (while (and positions
5746 (not (equal cur-pos (car positions))))
5747 (setq positions (cdr positions)))
5748 (or (cadr positions) 0))
5750 (define-obsolete-function-alias 'markdown-exdent-find-next-position
5751 'markdown-outdent-find-next-position "v2.3")
5753 (defun markdown-outdent-find-next-position (cur-pos positions)
5754 "Return the maximal element that precedes CUR-POS from POSITIONS.
5755 Positions are calculated by `markdown-calc-indents'."
5756 (let ((result 0))
5757 (dolist (i positions)
5758 (when (< i cur-pos)
5759 (setq result (max result i))))
5760 result))
5762 (defun markdown-indent-line ()
5763 "Indent the current line using some heuristics.
5764 If the _previous_ command was either `markdown-enter-key' or
5765 `markdown-cycle', then we should cycle to the next
5766 reasonable indentation position. Otherwise, we could have been
5767 called directly by `markdown-enter-key', by an initial call of
5768 `markdown-cycle', or indirectly by `auto-fill-mode'. In
5769 these cases, indent to the default position.
5770 Positions are calculated by `markdown-calc-indents'."
5771 (interactive)
5772 (let ((positions (markdown-calc-indents))
5773 (point-pos (current-column))
5774 (_ (back-to-indentation))
5775 (cur-pos (current-column)))
5776 (if (not (equal this-command 'markdown-cycle))
5777 (indent-line-to (car positions))
5778 (setq positions (sort (delete-dups positions) '<))
5779 (let* ((next-pos (markdown-indent-find-next-position cur-pos positions))
5780 (new-point-pos (max (+ point-pos (- next-pos cur-pos)) 0)))
5781 (indent-line-to next-pos)
5782 (move-to-column new-point-pos)))))
5784 (defun markdown-calc-indents ()
5785 "Return a list of indentation columns to cycle through.
5786 The first element in the returned list should be considered the
5787 default indentation level. This function does not worry about
5788 duplicate positions, which are handled up by calling functions."
5789 (let (pos prev-line-pos positions)
5791 ;; Indentation of previous line
5792 (setq prev-line-pos (markdown-prev-line-indent))
5793 (setq positions (cons prev-line-pos positions))
5795 ;; Indentation of previous non-list-marker text
5796 (when (setq pos (markdown-prev-non-list-indent))
5797 (setq positions (cons pos positions)))
5799 ;; Indentation required for a pre block in current context
5800 (setq pos (length (markdown-pre-indentation (point))))
5801 (setq positions (cons pos positions))
5803 ;; Indentation of the previous line + tab-width
5804 (if prev-line-pos
5805 (setq positions (cons (+ prev-line-pos tab-width) positions))
5806 (setq positions (cons tab-width positions)))
5808 ;; Indentation of the previous line - tab-width
5809 (if (and prev-line-pos (> prev-line-pos tab-width))
5810 (setq positions (cons (- prev-line-pos tab-width) positions)))
5812 ;; Indentation of all preceeding list markers (when in a list)
5813 (when (setq pos (markdown-calculate-list-levels))
5814 (setq positions (append pos positions)))
5816 ;; First column
5817 (setq positions (cons 0 positions))
5819 ;; Return reversed list
5820 (reverse positions)))
5822 (defun markdown-enter-key ()
5823 "Handle RET depending on the context.
5824 If the point is at a table, move to the next row. Otherwise,
5825 indent according to value of `markdown-indent-on-enter'.
5826 When it is nil, simply call `newline'. Otherwise, indent the next line
5827 following RET using `markdown-indent-line'. Furthermore, when it
5828 is set to 'indent-and-new-item and the point is in a list item,
5829 start a new item with the same indentation. If the point is in an
5830 empty list item, remove it (so that pressing RET twice when in a
5831 list simply adds a blank line)."
5832 (interactive)
5833 (cond
5834 ;; Table
5835 ((markdown-table-at-point-p)
5836 (call-interactively #'markdown-table-next-row))
5837 ;; Indent non-table text
5838 (markdown-indent-on-enter
5839 (let (bounds)
5840 (if (and (memq markdown-indent-on-enter '(indent-and-new-item))
5841 (setq bounds (markdown-cur-list-item-bounds)))
5842 (let ((beg (cl-first bounds))
5843 (end (cl-second bounds))
5844 (length (cl-fourth bounds)))
5845 ;; Point is in a list item
5846 (if (= (- end beg) length)
5847 ;; Delete blank list
5848 (progn
5849 (delete-region beg end)
5850 (newline)
5851 (markdown-indent-line))
5852 (call-interactively #'markdown-insert-list-item)))
5853 ;; Point is not in a list
5854 (newline)
5855 (markdown-indent-line))))
5856 ;; Insert a raw newline
5857 (t (newline))))
5859 (define-obsolete-function-alias 'markdown-exdent-or-delete
5860 'markdown-outdent-or-delete "v2.3")
5862 (defun markdown-outdent-or-delete (arg)
5863 "Handle BACKSPACE by cycling through indentation points.
5864 When BACKSPACE is pressed, if there is only whitespace
5865 before the current point, then outdent the line one level.
5866 Otherwise, do normal delete by repeating
5867 `backward-delete-char-untabify' ARG times."
5868 (interactive "*p")
5869 (if (use-region-p)
5870 (backward-delete-char-untabify arg)
5871 (let ((cur-pos (current-column))
5872 (start-of-indention (save-excursion
5873 (back-to-indentation)
5874 (current-column)))
5875 (positions (markdown-calc-indents)))
5876 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
5877 (indent-line-to (markdown-outdent-find-next-position cur-pos positions))
5878 (backward-delete-char-untabify arg)))))
5880 (defun markdown-find-leftmost-column (beg end)
5881 "Find the leftmost column in the region from BEG to END."
5882 (let ((mincol 1000))
5883 (save-excursion
5884 (goto-char beg)
5885 (while (< (point) end)
5886 (back-to-indentation)
5887 (unless (looking-at-p "[ \t]*$")
5888 (setq mincol (min mincol (current-column))))
5889 (forward-line 1)
5891 mincol))
5893 (defun markdown-indent-region (beg end arg)
5894 "Indent the region from BEG to END using some heuristics.
5895 When ARG is non-nil, outdent the region instead.
5896 See `markdown-indent-line' and `markdown-indent-line'."
5897 (interactive "*r\nP")
5898 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
5899 (leftmostcol (markdown-find-leftmost-column beg end))
5900 (next-pos (if arg
5901 (markdown-outdent-find-next-position leftmostcol positions)
5902 (markdown-indent-find-next-position leftmostcol positions))))
5903 (indent-rigidly beg end (- next-pos leftmostcol))
5904 (setq deactivate-mark nil)))
5906 (define-obsolete-function-alias 'markdown-exdent-region
5907 'markdown-outdent-region "v2.3")
5909 (defun markdown-outdent-region (beg end)
5910 "Call `markdown-indent-region' on region from BEG to END with prefix."
5911 (interactive "*r")
5912 (markdown-indent-region beg end t))
5915 ;;; Markup Completion =========================================================
5917 (defconst markdown-complete-alist
5918 '((markdown-regex-header-atx . markdown-complete-atx)
5919 (markdown-regex-header-setext . markdown-complete-setext)
5920 (markdown-regex-hr . markdown-complete-hr))
5921 "Association list of form (regexp . function) for markup completion.")
5923 (defun markdown-incomplete-atx-p ()
5924 "Return t if ATX header markup is incomplete and nil otherwise.
5925 Assumes match data is available for `markdown-regex-header-atx'.
5926 Checks that the number of trailing hash marks equals the number of leading
5927 hash marks, that there is only a single space before and after the text,
5928 and that there is no extraneous whitespace in the text."
5930 ;; Number of starting and ending hash marks differs
5931 (not (= (length (match-string 1)) (length (match-string 3))))
5932 ;; When the header text is not empty...
5933 (and (> (length (match-string 2)) 0)
5934 ;; ...if there are extra leading, trailing, or interior spaces
5935 (or (not (= (match-beginning 2) (1+ (match-end 1))))
5936 (not (= (match-beginning 3) (1+ (match-end 2))))
5937 (string-match-p "[ \t\n]\\{2\\}" (match-string 2))))
5938 ;; When the header text is empty...
5939 (and (= (length (match-string 2)) 0)
5940 ;; ...if there are too many or too few spaces
5941 (not (= (match-beginning 3) (+ (match-end 1) 2))))))
5943 (defun markdown-complete-atx ()
5944 "Complete and normalize ATX headers.
5945 Add or remove hash marks to the end of the header to match the
5946 beginning. Ensure that there is only a single space between hash
5947 marks and header text. Removes extraneous whitespace from header text.
5948 Assumes match data is available for `markdown-regex-header-atx'.
5949 Return nil if markup was complete and non-nil if markup was completed."
5950 (when (markdown-incomplete-atx-p)
5951 (let* ((new-marker (make-marker))
5952 (new-marker (set-marker new-marker (match-end 2))))
5953 ;; Hash marks and spacing at end
5954 (goto-char (match-end 2))
5955 (delete-region (match-end 2) (match-end 3))
5956 (insert " " (match-string 1))
5957 ;; Remove extraneous whitespace from title
5958 (replace-match (markdown-compress-whitespace-string (match-string 2))
5959 t t nil 2)
5960 ;; Spacing at beginning
5961 (goto-char (match-end 1))
5962 (delete-region (match-end 1) (match-beginning 2))
5963 (insert " ")
5964 ;; Leave point at end of text
5965 (goto-char new-marker))))
5967 (defun markdown-incomplete-setext-p ()
5968 "Return t if setext header markup is incomplete and nil otherwise.
5969 Assumes match data is available for `markdown-regex-header-setext'.
5970 Checks that length of underline matches text and that there is no
5971 extraneous whitespace in the text."
5972 (or (not (= (length (match-string 1)) (length (match-string 2))))
5973 (string-match-p "[ \t\n]\\{2\\}" (match-string 1))))
5975 (defun markdown-complete-setext ()
5976 "Complete and normalize setext headers.
5977 Add or remove underline characters to match length of header
5978 text. Removes extraneous whitespace from header text. Assumes
5979 match data is available for `markdown-regex-header-setext'.
5980 Return nil if markup was complete and non-nil if markup was completed."
5981 (when (markdown-incomplete-setext-p)
5982 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
5983 (char (char-after (match-beginning 2)))
5984 (level (if (char-equal char ?-) 2 1)))
5985 (goto-char (match-beginning 0))
5986 (delete-region (match-beginning 0) (match-end 0))
5987 (markdown-insert-header level text t)
5988 t)))
5990 (defun markdown-incomplete-hr-p ()
5991 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
5992 Assumes match data is available for `markdown-regex-hr'."
5993 (not (member (match-string 0) markdown-hr-strings)))
5995 (defun markdown-complete-hr ()
5996 "Complete horizontal rules.
5997 If horizontal rule string is a member of `markdown-hr-strings',
5998 do nothing. Otherwise, replace with the car of
5999 `markdown-hr-strings'.
6000 Assumes match data is available for `markdown-regex-hr'.
6001 Return nil if markup was complete and non-nil if markup was completed."
6002 (when (markdown-incomplete-hr-p)
6003 (replace-match (car markdown-hr-strings))
6006 (defun markdown-complete ()
6007 "Complete markup of object near point or in region when active.
6008 Handle all objects in `markdown-complete-alist', in order.
6009 See `markdown-complete-at-point' and `markdown-complete-region'."
6010 (interactive "*")
6011 (if (markdown-use-region-p)
6012 (markdown-complete-region (region-beginning) (region-end))
6013 (markdown-complete-at-point)))
6015 (defun markdown-complete-at-point ()
6016 "Complete markup of object near point.
6017 Handle all elements of `markdown-complete-alist' in order."
6018 (interactive "*")
6019 (let ((list markdown-complete-alist) found changed)
6020 (while list
6021 (let ((regexp (eval (caar list)))
6022 (function (cdar list)))
6023 (setq list (cdr list))
6024 (when (thing-at-point-looking-at regexp)
6025 (setq found t)
6026 (setq changed (funcall function))
6027 (setq list nil))))
6028 (if found
6029 (or changed (user-error "Markup at point is complete"))
6030 (user-error "Nothing to complete at point"))))
6032 (defun markdown-complete-region (beg end)
6033 "Complete markup of objects in region from BEG to END.
6034 Handle all objects in `markdown-complete-alist', in order. Each
6035 match is checked to ensure that a previous regexp does not also
6036 match."
6037 (interactive "*r")
6038 (let ((end-marker (set-marker (make-marker) end))
6039 previous)
6040 (dolist (element markdown-complete-alist)
6041 (let ((regexp (eval (car element)))
6042 (function (cdr element)))
6043 (goto-char beg)
6044 (while (re-search-forward regexp end-marker 'limit)
6045 (when (match-string 0)
6046 ;; Make sure this is not a match for any of the preceding regexps.
6047 ;; This prevents mistaking an HR for a Setext subheading.
6048 (let (match)
6049 (save-match-data
6050 (dolist (prev-regexp previous)
6051 (or match (setq match (looking-back prev-regexp nil)))))
6052 (unless match
6053 (save-excursion (funcall function))))))
6054 (cl-pushnew regexp previous :test #'equal)))
6055 previous))
6057 (defun markdown-complete-buffer ()
6058 "Complete markup for all objects in the current buffer."
6059 (interactive "*")
6060 (markdown-complete-region (point-min) (point-max)))
6063 ;;; Markup Cycling ============================================================
6065 (defun markdown-cycle-atx (arg &optional remove)
6066 "Cycle ATX header markup.
6067 Promote header (decrease level) when ARG is 1 and demote
6068 header (increase level) if arg is -1. When REMOVE is non-nil,
6069 remove the header when the level reaches zero and stop cycling
6070 when it reaches six. Otherwise, perform a proper cycling through
6071 levels one through six. Assumes match data is available for
6072 `markdown-regex-header-atx'."
6073 (let* ((old-level (length (match-string 1)))
6074 (new-level (+ old-level arg))
6075 (text (match-string 2)))
6076 (when (not remove)
6077 (setq new-level (% new-level 6))
6078 (setq new-level (cond ((= new-level 0) 6)
6079 ((< new-level 0) (+ new-level 6))
6080 (t new-level))))
6081 (cond
6082 ((= new-level 0)
6083 (markdown-unwrap-thing-at-point nil 0 2))
6084 ((<= new-level 6)
6085 (goto-char (match-beginning 0))
6086 (delete-region (match-beginning 0) (match-end 0))
6087 (markdown-insert-header new-level text nil)))))
6089 (defun markdown-cycle-setext (arg &optional remove)
6090 "Cycle setext header markup.
6091 Promote header (increase level) when ARG is 1 and demote
6092 header (decrease level or remove) if arg is -1. When demoting a
6093 level-two setext header, replace with a level-three atx header.
6094 When REMOVE is non-nil, remove the header when the level reaches
6095 zero. Otherwise, cycle back to a level six atx header. Assumes
6096 match data is available for `markdown-regex-header-setext'."
6097 (let* ((char (char-after (match-beginning 2)))
6098 (old-level (if (char-equal char ?=) 1 2))
6099 (new-level (+ old-level arg)))
6100 (when (and (not remove) (= new-level 0))
6101 (setq new-level 6))
6102 (cond
6103 ((= new-level 0)
6104 (markdown-unwrap-thing-at-point nil 0 1))
6105 ((<= new-level 2)
6106 (markdown-insert-header new-level nil t))
6107 ((<= new-level 6)
6108 (markdown-insert-header new-level nil nil)))))
6110 (defun markdown-cycle-hr (arg &optional remove)
6111 "Cycle string used for horizontal rule from `markdown-hr-strings'.
6112 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
6113 backwards (promote). When REMOVE is non-nil, remove the hr instead
6114 of cycling when the end of the list is reached.
6115 Assumes match data is available for `markdown-regex-hr'."
6116 (let* ((strings (if (= arg -1)
6117 (reverse markdown-hr-strings)
6118 markdown-hr-strings))
6119 (tail (member (match-string 0) strings))
6120 (new (or (cadr tail)
6121 (if remove
6122 (if (= arg 1)
6124 (car tail))
6125 (car strings)))))
6126 (replace-match new)))
6128 (defun markdown-cycle-bold ()
6129 "Cycle bold markup between underscores and asterisks.
6130 Assumes match data is available for `markdown-regex-bold'."
6131 (save-excursion
6132 (let* ((old-delim (match-string 3))
6133 (new-delim (if (string-equal old-delim "**") "__" "**")))
6134 (replace-match new-delim t t nil 3)
6135 (replace-match new-delim t t nil 5))))
6137 (defun markdown-cycle-italic ()
6138 "Cycle italic markup between underscores and asterisks.
6139 Assumes match data is available for `markdown-regex-italic'."
6140 (save-excursion
6141 (let* ((old-delim (match-string 2))
6142 (new-delim (if (string-equal old-delim "*") "_" "*")))
6143 (replace-match new-delim t t nil 2)
6144 (replace-match new-delim t t nil 4))))
6147 ;;; Keymap ====================================================================
6149 (defun markdown--style-map-prompt ()
6150 "Return a formatted prompt for Markdown markup insertion."
6151 (when markdown-enable-prefix-prompts
6152 (concat
6153 "Markdown: "
6154 (propertize "bold" 'face 'markdown-bold-face) ", "
6155 (propertize "italic" 'face 'markdown-italic-face) ", "
6156 (propertize "code" 'face 'markdown-inline-code-face) ", "
6157 (propertize "C = GFM code" 'face 'markdown-code-face) ", "
6158 (propertize "pre" 'face 'markdown-pre-face) ", "
6159 (propertize "footnote" 'face 'markdown-footnote-text-face) ", "
6160 (propertize "q = blockquote" 'face 'markdown-blockquote-face) ", "
6161 (propertize "h & 1-6 = heading" 'face 'markdown-header-face) ", "
6162 (propertize "- = hr" 'face 'markdown-hr-face) ", "
6163 "C-h = more")))
6165 (defun markdown--command-map-prompt ()
6166 "Return prompt for Markdown buffer-wide commands."
6167 (when markdown-enable-prefix-prompts
6168 (concat
6169 "Command: "
6170 (propertize "m" 'face 'markdown-bold-face) "arkdown, "
6171 (propertize "p" 'face 'markdown-bold-face) "review, "
6172 (propertize "o" 'face 'markdown-bold-face) "pen, "
6173 (propertize "e" 'face 'markdown-bold-face) "xport, "
6174 "export & pre" (propertize "v" 'face 'markdown-bold-face) "iew, "
6175 (propertize "c" 'face 'markdown-bold-face) "heck refs, "
6176 "C-h = more")))
6178 (defvar markdown-mode-style-map
6179 (let ((map (make-keymap (markdown--style-map-prompt))))
6180 (define-key map (kbd "1") 'markdown-insert-header-atx-1)
6181 (define-key map (kbd "2") 'markdown-insert-header-atx-2)
6182 (define-key map (kbd "3") 'markdown-insert-header-atx-3)
6183 (define-key map (kbd "4") 'markdown-insert-header-atx-4)
6184 (define-key map (kbd "5") 'markdown-insert-header-atx-5)
6185 (define-key map (kbd "6") 'markdown-insert-header-atx-6)
6186 (define-key map (kbd "!") 'markdown-insert-header-setext-1)
6187 (define-key map (kbd "@") 'markdown-insert-header-setext-2)
6188 (define-key map (kbd "b") 'markdown-insert-bold)
6189 (define-key map (kbd "c") 'markdown-insert-code)
6190 (define-key map (kbd "C") 'markdown-insert-gfm-code-block)
6191 (define-key map (kbd "f") 'markdown-insert-footnote)
6192 (define-key map (kbd "h") 'markdown-insert-header-dwim)
6193 (define-key map (kbd "H") 'markdown-insert-header-setext-dwim)
6194 (define-key map (kbd "i") 'markdown-insert-italic)
6195 (define-key map (kbd "k") 'markdown-insert-kbd)
6196 (define-key map (kbd "l") 'markdown-insert-link)
6197 (define-key map (kbd "p") 'markdown-insert-pre)
6198 (define-key map (kbd "P") 'markdown-pre-region)
6199 (define-key map (kbd "q") 'markdown-insert-blockquote)
6200 (define-key map (kbd "s") 'markdown-insert-strike-through)
6201 (define-key map (kbd "Q") 'markdown-blockquote-region)
6202 (define-key map (kbd "w") 'markdown-insert-wiki-link)
6203 (define-key map (kbd "-") 'markdown-insert-hr)
6204 (define-key map (kbd "[") 'markdown-insert-gfm-checkbox)
6205 ;; Deprecated keys that may be removed in a future version
6206 (define-key map (kbd "e") 'markdown-insert-italic)
6207 map)
6208 "Keymap for Markdown text styling commands.")
6210 (defvar markdown-mode-command-map
6211 (let ((map (make-keymap (markdown--command-map-prompt))))
6212 (define-key map (kbd "m") 'markdown-other-window)
6213 (define-key map (kbd "p") 'markdown-preview)
6214 (define-key map (kbd "e") 'markdown-export)
6215 (define-key map (kbd "v") 'markdown-export-and-preview)
6216 (define-key map (kbd "o") 'markdown-open)
6217 (define-key map (kbd "l") 'markdown-live-preview-mode)
6218 (define-key map (kbd "w") 'markdown-kill-ring-save)
6219 (define-key map (kbd "c") 'markdown-check-refs)
6220 (define-key map (kbd "n") 'markdown-cleanup-list-numbers)
6221 (define-key map (kbd "]") 'markdown-complete-buffer)
6222 (define-key map (kbd "^") 'markdown-table-sort-lines)
6223 (define-key map (kbd "|") 'markdown-table-convert-region)
6224 (define-key map (kbd "t") 'markdown-table-transpose)
6225 map)
6226 "Keymap for Markdown buffer-wide commands.")
6228 (defvar markdown-mode-map
6229 (let ((map (make-keymap)))
6230 ;; Markup insertion & removal
6231 (define-key map (kbd "C-c C-s") markdown-mode-style-map)
6232 (define-key map (kbd "C-c C-l") 'markdown-insert-link)
6233 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
6234 ;; Promotion, demotion, and cycling
6235 (define-key map (kbd "C-c C--") 'markdown-promote)
6236 (define-key map (kbd "C-c C-=") 'markdown-demote)
6237 (define-key map (kbd "C-c C-]") 'markdown-complete)
6238 ;; Following and doing things
6239 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
6240 (define-key map (kbd "C-c C-d") 'markdown-do)
6241 (define-key map (kbd "C-c '") 'markdown-edit-code-block)
6242 ;; Indentation
6243 (define-key map (kbd "C-m") 'markdown-enter-key)
6244 (define-key map (kbd "DEL") 'markdown-outdent-or-delete)
6245 (define-key map (kbd "C-c >") 'markdown-indent-region)
6246 (define-key map (kbd "C-c <") 'markdown-outdent-region)
6247 ;; Visibility cycling
6248 (define-key map (kbd "TAB") 'markdown-cycle)
6249 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
6250 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
6251 (define-key map (kbd "<backtab>") 'markdown-shifttab)
6252 ;; Heading and list navigation
6253 (define-key map (kbd "C-c C-n") 'markdown-outline-next)
6254 (define-key map (kbd "C-c C-p") 'markdown-outline-previous)
6255 (define-key map (kbd "C-c C-f") 'markdown-outline-next-same-level)
6256 (define-key map (kbd "C-c C-b") 'markdown-outline-previous-same-level)
6257 (define-key map (kbd "C-c C-u") 'markdown-outline-up)
6258 ;; Buffer-wide commands
6259 (define-key map (kbd "C-c C-c") markdown-mode-command-map)
6260 ;; Subtree, list, and table editing
6261 (define-key map (kbd "C-c <up>") 'markdown-move-up)
6262 (define-key map (kbd "C-c <down>") 'markdown-move-down)
6263 (define-key map (kbd "C-c <left>") 'markdown-promote)
6264 (define-key map (kbd "C-c <right>") 'markdown-demote)
6265 (define-key map (kbd "C-c S-<up>") 'markdown-table-delete-row)
6266 (define-key map (kbd "C-c S-<down>") 'markdown-table-insert-row)
6267 (define-key map (kbd "C-c S-<left>") 'markdown-table-delete-column)
6268 (define-key map (kbd "C-c S-<right>") 'markdown-table-insert-column)
6269 (define-key map (kbd "C-c C-M-h") 'markdown-mark-subtree)
6270 (define-key map (kbd "C-x n s") 'markdown-narrow-to-subtree)
6271 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
6272 (define-key map (kbd "C-c C-j") 'markdown-insert-list-item)
6273 ;; Paragraphs (Markdown context aware)
6274 (define-key map [remap backward-paragraph] 'markdown-backward-paragraph)
6275 (define-key map [remap forward-paragraph] 'markdown-forward-paragraph)
6276 (define-key map [remap mark-paragraph] 'markdown-mark-paragraph)
6277 ;; Blocks (one or more paragraphs)
6278 (define-key map (kbd "C-M-{") 'markdown-backward-block)
6279 (define-key map (kbd "C-M-}") 'markdown-forward-block)
6280 (define-key map (kbd "C-c M-h") 'markdown-mark-block)
6281 (define-key map (kbd "C-x n b") 'markdown-narrow-to-block)
6282 ;; Pages (top-level sections)
6283 (define-key map [remap backward-page] 'markdown-backward-page)
6284 (define-key map [remap forward-page] 'markdown-forward-page)
6285 (define-key map [remap mark-page] 'markdown-mark-page)
6286 (define-key map [remap narrow-to-page] 'markdown-narrow-to-page)
6287 ;; Link Movement
6288 (define-key map (kbd "M-n") 'markdown-next-link)
6289 (define-key map (kbd "M-p") 'markdown-previous-link)
6290 ;; Toggling functionality
6291 (define-key map (kbd "C-c C-x C-e") 'markdown-toggle-math)
6292 (define-key map (kbd "C-c C-x C-f") 'markdown-toggle-fontify-code-blocks-natively)
6293 (define-key map (kbd "C-c C-x C-i") 'markdown-toggle-inline-images)
6294 (define-key map (kbd "C-c C-x C-l") 'markdown-toggle-url-hiding)
6295 (define-key map (kbd "C-c C-x C-m") 'markdown-toggle-markup-hiding)
6296 ;; Alternative keys (in case of problems with the arrow keys)
6297 (define-key map (kbd "C-c C-x u") 'markdown-move-up)
6298 (define-key map (kbd "C-c C-x d") 'markdown-move-down)
6299 (define-key map (kbd "C-c C-x l") 'markdown-promote)
6300 (define-key map (kbd "C-c C-x r") 'markdown-demote)
6301 ;; Deprecated keys that may be removed in a future version
6302 (define-key map (kbd "C-c C-a L") 'markdown-insert-link) ;; C-c C-l
6303 (define-key map (kbd "C-c C-a l") 'markdown-insert-link) ;; C-c C-l
6304 (define-key map (kbd "C-c C-a r") 'markdown-insert-link) ;; C-c C-l
6305 (define-key map (kbd "C-c C-a u") 'markdown-insert-uri) ;; C-c C-l
6306 (define-key map (kbd "C-c C-a f") 'markdown-insert-footnote)
6307 (define-key map (kbd "C-c C-a w") 'markdown-insert-wiki-link)
6308 (define-key map (kbd "C-c C-t 1") 'markdown-insert-header-atx-1)
6309 (define-key map (kbd "C-c C-t 2") 'markdown-insert-header-atx-2)
6310 (define-key map (kbd "C-c C-t 3") 'markdown-insert-header-atx-3)
6311 (define-key map (kbd "C-c C-t 4") 'markdown-insert-header-atx-4)
6312 (define-key map (kbd "C-c C-t 5") 'markdown-insert-header-atx-5)
6313 (define-key map (kbd "C-c C-t 6") 'markdown-insert-header-atx-6)
6314 (define-key map (kbd "C-c C-t !") 'markdown-insert-header-setext-1)
6315 (define-key map (kbd "C-c C-t @") 'markdown-insert-header-setext-2)
6316 (define-key map (kbd "C-c C-t h") 'markdown-insert-header-dwim)
6317 (define-key map (kbd "C-c C-t H") 'markdown-insert-header-setext-dwim)
6318 (define-key map (kbd "C-c C-t s") 'markdown-insert-header-setext-2)
6319 (define-key map (kbd "C-c C-t t") 'markdown-insert-header-setext-1)
6320 (define-key map (kbd "C-c C-i") 'markdown-insert-image)
6321 (define-key map (kbd "C-c C-x m") 'markdown-insert-list-item) ;; C-c C-j
6322 (define-key map (kbd "C-c C-x C-x") 'markdown-toggle-gfm-checkbox) ;; C-c C-d
6323 (define-key map (kbd "C-c -") 'markdown-insert-hr)
6324 map)
6325 "Keymap for Markdown major mode.")
6327 (defvar markdown-mode-mouse-map
6328 (let ((map (make-sparse-keymap)))
6329 (define-key map [follow-link] 'mouse-face)
6330 (define-key map [mouse-2] 'markdown-follow-link-at-point)
6331 map)
6332 "Keymap for following links with mouse.")
6334 (defvar gfm-mode-map
6335 (let ((map (make-sparse-keymap)))
6336 (set-keymap-parent map markdown-mode-map)
6337 (define-key map (kbd "C-c C-s d") 'markdown-insert-strike-through)
6338 (define-key map "`" 'markdown-electric-backquote)
6339 map)
6340 "Keymap for `gfm-mode'.
6341 See also `markdown-mode-map'.")
6344 ;;; Menu ==================================================================
6346 (easy-menu-define markdown-mode-menu markdown-mode-map
6347 "Menu for Markdown mode"
6348 '("Markdown"
6349 "---"
6350 ("Movement"
6351 ["Jump" markdown-do]
6352 ["Follow Link" markdown-follow-thing-at-point]
6353 ["Next Link" markdown-next-link]
6354 ["Previous Link" markdown-previous-link]
6355 "---"
6356 ["Next Heading or List Item" markdown-outline-next]
6357 ["Previous Heading or List Item" markdown-outline-previous]
6358 ["Next at Same Level" markdown-outline-next-same-level]
6359 ["Previous at Same Level" markdown-outline-previous-same-level]
6360 ["Up to Parent" markdown-outline-up]
6361 "---"
6362 ["Forward Paragraph" markdown-forward-paragraph]
6363 ["Backward Paragraph" markdown-backward-paragraph]
6364 ["Forward Block" markdown-forward-block]
6365 ["Backward Block" markdown-backward-block])
6366 ("Show & Hide"
6367 ["Cycle Heading Visibility" markdown-cycle (markdown-on-heading-p)]
6368 ["Cycle Heading Visibility (Global)" markdown-shifttab]
6369 "---"
6370 ["Narrow to Region" narrow-to-region]
6371 ["Narrow to Block" markdown-narrow-to-block]
6372 ["Narrow to Section" narrow-to-defun]
6373 ["Narrow to Subtree" markdown-narrow-to-subtree]
6374 ["Widen" widen (buffer-narrowed-p)]
6375 "---"
6376 ["Toggle Markup Hiding" markdown-toggle-markup-hiding
6377 :keys "C-c C-x C-m"
6378 :style radio
6379 :selected markdown-hide-markup])
6380 "---"
6381 ("Headings & Structure"
6382 ["Automatic Heading" markdown-insert-header-dwim :keys "C-c C-s h"]
6383 ["Automatic Heading (Setext)" markdown-insert-header-setext-dwim :keys "C-c C-s H"]
6384 ("Specific Heading (atx)"
6385 ["First Level atx" markdown-insert-header-atx-1 :keys "C-c C-s 1"]
6386 ["Second Level atx" markdown-insert-header-atx-2 :keys "C-c C-s 2"]
6387 ["Third Level atx" markdown-insert-header-atx-3 :keys "C-c C-s 3"]
6388 ["Fourth Level atx" markdown-insert-header-atx-4 :keys "C-c C-s 4"]
6389 ["Fifth Level atx" markdown-insert-header-atx-5 :keys "C-c C-s 5"]
6390 ["Sixth Level atx" markdown-insert-header-atx-6 :keys "C-c C-s 6"])
6391 ("Specific Heading (Setext)"
6392 ["First Level Setext" markdown-insert-header-setext-1 :keys "C-c C-s !"]
6393 ["Second Level Setext" markdown-insert-header-setext-2 :keys "C-c C-s @"])
6394 ["Horizontal Rule" markdown-insert-hr :keys "C-c C-s -"]
6395 "---"
6396 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6397 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6398 ["Promote Subtree" markdown-promote :keys "C-c <left>"]
6399 ["Demote Subtree" markdown-demote :keys "C-c <right>"])
6400 ("Region & Mark"
6401 ["Indent Region" markdown-indent-region]
6402 ["Outdent Region" markdown-outdent-region]
6403 "--"
6404 ["Mark Paragraph" mark-paragraph]
6405 ["Mark Block" markdown-mark-block]
6406 ["Mark Section" mark-defun]
6407 ["Mark Subtree" markdown-mark-subtree])
6408 ("Lists"
6409 ["Insert List Item" markdown-insert-list-item]
6410 ["Move Subtree Up" markdown-move-up :keys "C-c <up>"]
6411 ["Move Subtree Down" markdown-move-down :keys "C-c <down>"]
6412 ["Indent Subtree" markdown-demote :keys "C-c <right>"]
6413 ["Outdent Subtree" markdown-promote :keys "C-c <left>"]
6414 ["Renumber List" markdown-cleanup-list-numbers]
6415 ["Insert Task List Item" markdown-insert-gfm-checkbox :keys "C-c C-x ["]
6416 ["Toggle Task List Item" markdown-toggle-gfm-checkbox (markdown-gfm-task-list-item-at-point) :keys "C-c C-d"])
6417 ("Links & Images"
6418 ["Insert Link" markdown-insert-link]
6419 ["Insert Image" markdown-insert-image]
6420 ["Insert Footnote" markdown-insert-footnote :keys "C-c C-s f"]
6421 ["Insert Wiki Link" markdown-insert-wiki-link :keys "C-c C-s w"]
6422 "---"
6423 ["Check References" markdown-check-refs]
6424 ["Toggle URL Hiding" markdown-toggle-url-hiding
6425 :style radio
6426 :selected markdown-hide-urls]
6427 ["Toggle Inline Images" markdown-toggle-inline-images
6428 :keys "C-c C-x C-i"
6429 :style radio
6430 :selected markdown-inline-image-overlays]
6431 ["Toggle Wiki Links" markdown-toggle-wiki-links
6432 :style radio
6433 :selected markdown-enable-wiki-links])
6434 ("Styles"
6435 ["Bold" markdown-insert-bold]
6436 ["Italic" markdown-insert-italic]
6437 ["Code" markdown-insert-code]
6438 ["Strikethrough" markdown-insert-strike-through]
6439 ["Keyboard" markdown-insert-kbd]
6440 "---"
6441 ["Blockquote" markdown-insert-blockquote]
6442 ["Preformatted" markdown-insert-pre]
6443 ["GFM Code Block" markdown-insert-gfm-code-block]
6444 ["Edit Code Block" markdown-edit-code-block (markdown-code-block-at-point-p)]
6445 "---"
6446 ["Blockquote Region" markdown-blockquote-region]
6447 ["Preformatted Region" markdown-pre-region]
6448 "---"
6449 ["Fontify Code Blocks Natively" markdown-toggle-fontify-code-blocks-natively
6450 :style radio
6451 :selected markdown-fontify-code-blocks-natively]
6452 ["LaTeX Math Support" markdown-toggle-math
6453 :style radio
6454 :selected markdown-enable-math])
6455 "---"
6456 ("Preview & Export"
6457 ["Compile" markdown-other-window]
6458 ["Preview" markdown-preview]
6459 ["Export" markdown-export]
6460 ["Export & View" markdown-export-and-preview]
6461 ["Open" markdown-open]
6462 ["Live Export" markdown-live-preview-mode
6463 :style radio
6464 :selected markdown-live-preview-mode]
6465 ["Kill ring save" markdown-kill-ring-save])
6466 ("Markup Completion and Cycling"
6467 ["Complete Markup" markdown-complete]
6468 ["Promote Element" markdown-promote :keys "C-c C--"]
6469 ["Demote Element" markdown-demote :keys "C-c C-="])
6470 "---"
6471 ["Kill Element" markdown-kill-thing-at-point]
6472 "---"
6473 ("Documentation"
6474 ["Version" markdown-show-version]
6475 ["Homepage" markdown-mode-info]
6476 ["Describe Mode" (describe-function 'markdown-mode)]
6477 ["Guide" (browse-url "https://leanpub.com/markdown-mode")])))
6480 ;;; imenu =====================================================================
6482 (defun markdown-imenu-create-nested-index ()
6483 "Create and return a nested imenu index alist for the current buffer.
6484 See `imenu-create-index-function' and `imenu--index-alist' for details."
6485 (let* ((root '(nil . nil))
6486 cur-alist
6487 (cur-level 0)
6488 (empty-heading "-")
6489 (self-heading ".")
6490 hashes pos level heading)
6491 (save-excursion
6492 (goto-char (point-min))
6493 (while (re-search-forward markdown-regex-header (point-max) t)
6494 (unless (markdown-code-block-at-point-p)
6495 (cond
6496 ((match-string-no-properties 2) ;; level 1 setext
6497 (setq heading (match-string-no-properties 1))
6498 (setq pos (match-beginning 1)
6499 level 1))
6500 ((match-string-no-properties 3) ;; level 2 setext
6501 (setq heading (match-string-no-properties 1))
6502 (setq pos (match-beginning 1)
6503 level 2))
6504 ((setq hashes (markdown-trim-whitespace
6505 (match-string-no-properties 4)))
6506 (setq heading (match-string-no-properties 5)
6507 pos (match-beginning 4)
6508 level (length hashes))))
6509 (let ((alist (list (cons heading pos))))
6510 (cond
6511 ((= cur-level level) ; new sibling
6512 (setcdr cur-alist alist)
6513 (setq cur-alist alist))
6514 ((< cur-level level) ; first child
6515 (dotimes (_ (- level cur-level 1))
6516 (setq alist (list (cons empty-heading alist))))
6517 (if cur-alist
6518 (let* ((parent (car cur-alist))
6519 (self-pos (cdr parent)))
6520 (setcdr parent (cons (cons self-heading self-pos) alist)))
6521 (setcdr root alist)) ; primogenitor
6522 (setq cur-alist alist)
6523 (setq cur-level level))
6524 (t ; new sibling of an ancestor
6525 (let ((sibling-alist (last (cdr root))))
6526 (dotimes (_ (1- level))
6527 (setq sibling-alist (last (cdar sibling-alist))))
6528 (setcdr sibling-alist alist)
6529 (setq cur-alist alist))
6530 (setq cur-level level))))))
6531 (cdr root))))
6533 (defun markdown-imenu-create-flat-index ()
6534 "Create and return a flat imenu index alist for the current buffer.
6535 See `imenu-create-index-function' and `imenu--index-alist' for details."
6536 (let* ((empty-heading "-") index heading pos)
6537 (save-excursion
6538 (goto-char (point-min))
6539 (while (re-search-forward markdown-regex-header (point-max) t)
6540 (when (and (not (markdown-code-block-at-point-p))
6541 (not (markdown-text-property-at-point 'markdown-yaml-metadata-begin)))
6542 (cond
6543 ((setq heading (match-string-no-properties 1))
6544 (setq pos (match-beginning 1)))
6545 ((setq heading (match-string-no-properties 5))
6546 (setq pos (match-beginning 4))))
6547 (or (> (length heading) 0)
6548 (setq heading empty-heading))
6549 (setq index (append index (list (cons heading pos))))))
6550 index)))
6553 ;;; References ================================================================
6555 (defun markdown-reference-goto-definition ()
6556 "Jump to the definition of the reference at point or create it."
6557 (interactive)
6558 (when (thing-at-point-looking-at markdown-regex-link-reference)
6559 (let* ((text (match-string-no-properties 3))
6560 (reference (match-string-no-properties 6))
6561 (target (downcase (if (string= reference "") text reference)))
6562 (loc (cadr (save-match-data (markdown-reference-definition target)))))
6563 (if loc
6564 (goto-char loc)
6565 (goto-char (match-beginning 0))
6566 (markdown-insert-reference-definition target)))))
6568 (defun markdown-reference-find-links (reference)
6569 "Return a list of all links for REFERENCE.
6570 REFERENCE should not include the surrounding square brackets.
6571 Elements of the list have the form (text start line), where
6572 text is the link text, start is the location at the beginning of
6573 the link, and line is the line number on which the link appears."
6574 (let* ((ref-quote (regexp-quote reference))
6575 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
6576 ref-quote ref-quote))
6577 links)
6578 (save-excursion
6579 (goto-char (point-min))
6580 (while (re-search-forward regexp nil t)
6581 (let* ((text (or (match-string-no-properties 1)
6582 (match-string-no-properties 2)))
6583 (start (match-beginning 0))
6584 (line (markdown-line-number-at-pos)))
6585 (cl-pushnew (list text start line) links :test #'equal))))
6586 links))
6588 (defun markdown-get-undefined-refs ()
6589 "Return a list of undefined Markdown references.
6590 Result is an alist of pairs (reference . occurrences), where
6591 occurrences is itself another alist of pairs (label . line-number).
6592 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
6593 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
6594 \((\"emacs\" (\"Nice editor\" . 12) (\"GNU Emacs\" . 45)) (\"elisp\" (\"manual\" . 127)))."
6595 (let ((missing))
6596 (save-excursion
6597 (goto-char (point-min))
6598 (while
6599 (re-search-forward markdown-regex-link-reference nil t)
6600 (let* ((text (match-string-no-properties 3))
6601 (reference (match-string-no-properties 6))
6602 (target (downcase (if (string= reference "") text reference))))
6603 (unless (markdown-reference-definition target)
6604 (let ((entry (assoc target missing)))
6605 (if (not entry)
6606 (cl-pushnew
6607 (cons target (list (cons text (markdown-line-number-at-pos))))
6608 missing :test #'equal)
6609 (setcdr entry
6610 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
6611 (reverse missing))))
6613 (defconst markdown-reference-check-buffer
6614 "*Undefined references for %buffer%*"
6615 "Pattern for name of buffer for listing undefined references.
6616 The string %buffer% will be replaced by the corresponding
6617 `markdown-mode' buffer name.")
6619 (defun markdown-reference-check-buffer (&optional buffer-name)
6620 "Name and return buffer for reference checking.
6621 BUFFER-NAME is the name of the main buffer being visited."
6622 (or buffer-name (setq buffer-name (buffer-name)))
6623 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
6624 "%buffer%" buffer-name
6625 markdown-reference-check-buffer))))
6626 (with-current-buffer refbuf
6627 (when view-mode
6628 (View-exit-and-edit))
6629 (use-local-map button-buffer-map)
6630 (erase-buffer))
6631 refbuf))
6633 (defconst markdown-reference-links-buffer
6634 "*Reference links for %buffer%*"
6635 "Pattern for name of buffer for listing references.
6636 The string %buffer% will be replaced by the corresponding buffer name.")
6638 (defun markdown-reference-links-buffer (&optional buffer-name)
6639 "Name, setup, and return a buffer for listing links.
6640 BUFFER-NAME is the name of the main buffer being visited."
6641 (or buffer-name (setq buffer-name (buffer-name)))
6642 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
6643 "%buffer%" buffer-name
6644 markdown-reference-links-buffer))))
6645 (with-current-buffer linkbuf
6646 (when view-mode
6647 (View-exit-and-edit))
6648 (use-local-map button-buffer-map)
6649 (erase-buffer))
6650 linkbuf))
6652 ;; Add an empty Markdown reference definition to buffer
6653 ;; specified in the 'target-buffer property. The reference name is
6654 ;; the button's label.
6655 (define-button-type 'markdown-undefined-reference-button
6656 'help-echo "mouse-1, RET: create definition for undefined reference"
6657 'follow-link t
6658 'face 'bold
6659 'action (lambda (b)
6660 (let ((buffer (button-get b 'target-buffer))
6661 (line (button-get b 'target-line))
6662 (label (button-label b)))
6663 (switch-to-buffer-other-window buffer)
6664 (goto-char (point-min))
6665 (forward-line line)
6666 (markdown-insert-reference-definition label)
6667 (markdown-check-refs t))))
6669 ;; Jump to line in buffer specified by 'target-buffer property.
6670 ;; Line number is button's 'line property.
6671 (define-button-type 'markdown-goto-line-button
6672 'help-echo "mouse-1, RET: go to line"
6673 'follow-link t
6674 'face 'italic
6675 'action (lambda (b)
6676 (message (button-get b 'buffer))
6677 (switch-to-buffer-other-window (button-get b 'target-buffer))
6678 ;; use call-interactively to silence compiler
6679 (let ((current-prefix-arg (button-get b 'target-line)))
6680 (call-interactively 'goto-line))))
6682 ;; Jumps to a particular link at location given by 'target-char
6683 ;; property in buffer given by 'target-buffer property.
6684 (define-button-type 'markdown-location-button
6685 'help-echo "mouse-1, RET: jump to location of link"
6686 'follow-link t
6687 'face 'bold
6688 'action (lambda (b)
6689 (let ((target (button-get b 'target-buffer))
6690 (loc (button-get b 'target-char)))
6691 (kill-buffer-and-window)
6692 (switch-to-buffer target)
6693 (goto-char loc))))
6695 (defun markdown-insert-undefined-reference-button (reference oldbuf)
6696 "Insert a button for creating REFERENCE in buffer OLDBUF.
6697 REFERENCE should be a list of the form (reference . occurrences),
6698 as by `markdown-get-undefined-refs'."
6699 (let ((label (car reference)))
6700 ;; Create a reference button
6701 (insert-button label
6702 :type 'markdown-undefined-reference-button
6703 'target-buffer oldbuf
6704 'target-line (cdr (car (cdr reference))))
6705 (insert " (")
6706 (dolist (occurrence (cdr reference))
6707 (let ((line (cdr occurrence)))
6708 ;; Create a line number button
6709 (insert-button (number-to-string line)
6710 :type 'markdown-goto-line-button
6711 'target-buffer oldbuf
6712 'target-line line)
6713 (insert " ")))
6714 (delete-char -1)
6715 (insert ")")
6716 (newline)))
6718 (defun markdown-insert-link-button (link oldbuf)
6719 "Insert a button for jumping to LINK in buffer OLDBUF.
6720 LINK should be a list of the form (text char line) containing
6721 the link text, location, and line number."
6722 (let ((label (cl-first link))
6723 (char (cl-second link))
6724 (line (cl-third link)))
6725 ;; Create a reference button
6726 (insert-button label
6727 :type 'markdown-location-button
6728 'target-buffer oldbuf
6729 'target-char char)
6730 (insert (format " (line %d)\n" line))))
6732 (defun markdown-reference-goto-link (&optional reference)
6733 "Jump to the location of the first use of REFERENCE."
6734 (interactive)
6735 (unless reference
6736 (if (thing-at-point-looking-at markdown-regex-reference-definition)
6737 (setq reference (match-string-no-properties 2))
6738 (user-error "No reference definition at point")))
6739 (let ((links (markdown-reference-find-links reference)))
6740 (cond ((= (length links) 1)
6741 (goto-char (cadr (car links))))
6742 ((> (length links) 1)
6743 (let ((oldbuf (current-buffer))
6744 (linkbuf (markdown-reference-links-buffer)))
6745 (with-current-buffer linkbuf
6746 (insert "Links using reference " reference ":\n\n")
6747 (dolist (link (reverse links))
6748 (markdown-insert-link-button link oldbuf)))
6749 (view-buffer-other-window linkbuf)
6750 (goto-char (point-min))
6751 (forward-line 2)))
6753 (error "No links for reference %s" reference)))))
6755 (defun markdown-check-refs (&optional silent)
6756 "Show all undefined Markdown references in current `markdown-mode' buffer.
6757 If SILENT is non-nil, do not message anything when no undefined
6758 references found.
6759 Links which have empty reference definitions are considered to be
6760 defined."
6761 (interactive "P")
6762 (when (not (eq major-mode 'markdown-mode))
6763 (user-error "Not available in current mode"))
6764 (let ((oldbuf (current-buffer))
6765 (refs (markdown-get-undefined-refs))
6766 (refbuf (markdown-reference-check-buffer)))
6767 (if (null refs)
6768 (progn
6769 (when (not silent)
6770 (message "No undefined references found"))
6771 (kill-buffer refbuf))
6772 (with-current-buffer refbuf
6773 (insert "The following references are undefined:\n\n")
6774 (dolist (ref refs)
6775 (markdown-insert-undefined-reference-button ref oldbuf))
6776 (view-buffer-other-window refbuf)
6777 (goto-char (point-min))
6778 (forward-line 2)))))
6781 ;;; Lists =====================================================================
6783 (defun markdown-insert-list-item (&optional arg)
6784 "Insert a new list item.
6785 If the point is inside unordered list, insert a bullet mark. If
6786 the point is inside ordered list, insert the next number followed
6787 by a period. Use the previous list item to determine the amount
6788 of whitespace to place before and after list markers.
6790 With a \\[universal-argument] prefix (i.e., when ARG is (4)),
6791 decrease the indentation by one level.
6793 With two \\[universal-argument] prefixes (i.e., when ARG is (16)),
6794 increase the indentation by one level."
6795 (interactive "p")
6796 (let (bounds cur-indent marker indent new-indent new-loc)
6797 (save-match-data
6798 ;; Look for a list item on current or previous non-blank line
6799 (save-excursion
6800 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
6801 (not (bobp))
6802 (markdown-cur-line-blank-p))
6803 (forward-line -1)))
6804 (when bounds
6805 (cond ((save-excursion
6806 (skip-chars-backward " \t")
6807 (looking-at-p markdown-regex-list))
6808 (beginning-of-line)
6809 (insert "\n")
6810 (forward-line -1))
6811 ((not (markdown-cur-line-blank-p))
6812 (newline)))
6813 (setq new-loc (point)))
6814 ;; Look ahead for a list item on next non-blank line
6815 (unless bounds
6816 (save-excursion
6817 (while (and (null bounds)
6818 (not (eobp))
6819 (markdown-cur-line-blank-p))
6820 (forward-line)
6821 (setq bounds (markdown-cur-list-item-bounds))))
6822 (when bounds
6823 (setq new-loc (point))
6824 (unless (markdown-cur-line-blank-p)
6825 (newline))))
6826 (if (not bounds)
6827 ;; When not in a list, start a new unordered one
6828 (progn
6829 (unless (markdown-cur-line-blank-p)
6830 (insert "\n"))
6831 (insert markdown-unordered-list-item-prefix))
6832 ;; Compute indentation and marker for new list item
6833 (setq cur-indent (nth 2 bounds))
6834 (setq marker (nth 4 bounds))
6835 ;; If current item is a GFM checkbox, insert new unchecked checkbox.
6836 (when (nth 5 bounds)
6837 (setq marker
6838 (concat marker
6839 (replace-regexp-in-string "[Xx]" " " (nth 5 bounds)))))
6840 (cond
6841 ;; Dedent: decrement indentation, find previous marker.
6842 ((= arg 4)
6843 (setq indent (max (- cur-indent 4) 0))
6844 (let ((prev-bounds
6845 (save-excursion
6846 (goto-char (nth 0 bounds))
6847 (when (markdown-up-list)
6848 (markdown-cur-list-item-bounds)))))
6849 (when prev-bounds
6850 (setq marker (nth 4 prev-bounds)))))
6851 ;; Indent: increment indentation by 4, use same marker.
6852 ((= arg 16) (setq indent (+ cur-indent 4)))
6853 ;; Same level: keep current indentation and marker.
6854 (t (setq indent cur-indent)))
6855 (setq new-indent (make-string indent 32))
6856 (goto-char new-loc)
6857 (cond
6858 ;; Ordered list
6859 ((string-match-p "[0-9]" marker)
6860 (if (= arg 16) ;; starting a new column indented one more level
6861 (insert (concat new-indent "1. "))
6862 ;; Don't use previous match-data
6863 (set-match-data nil)
6864 ;; travel up to the last item and pick the correct number. If
6865 ;; the argument was nil, "new-indent = cur-indent" is the same,
6866 ;; so we don't need special treatment. Neat.
6867 (save-excursion
6868 (while (and (not (looking-at (concat new-indent "\\([0-9]+\\)\\(\\.[ \t]*\\)")))
6869 (>= (forward-line -1) 0))))
6870 (let* ((old-prefix (match-string 1))
6871 (old-spacing (match-string 2))
6872 (new-prefix (if old-prefix
6873 (int-to-string (1+ (string-to-number old-prefix)))
6874 "1"))
6875 (space-adjust (- (length old-prefix) (length new-prefix)))
6876 (new-spacing (if (and (match-string 2)
6877 (not (string-match-p "\t" old-spacing))
6878 (< space-adjust 0)
6879 (> space-adjust (- 1 (length (match-string 2)))))
6880 (substring (match-string 2) 0 space-adjust)
6881 (or old-spacing ". "))))
6882 (insert (concat new-indent new-prefix new-spacing)))))
6883 ;; Unordered list, GFM task list, or ordered list with hash mark
6884 ((string-match-p "[\\*\\+-]\\|#\\." marker)
6885 (insert new-indent marker))))
6886 ;; Propertize the newly inserted list item now
6887 (markdown-syntax-propertize-list-items (point-at-bol) (point-at-eol)))))
6889 (defun markdown-move-list-item-up ()
6890 "Move the current list item up in the list when possible.
6891 In nested lists, move child items with the parent item."
6892 (interactive)
6893 (let (cur prev old)
6894 (when (setq cur (markdown-cur-list-item-bounds))
6895 (setq old (point))
6896 (goto-char (nth 0 cur))
6897 (if (markdown-prev-list-item (nth 3 cur))
6898 (progn
6899 (setq prev (markdown-cur-list-item-bounds))
6900 (condition-case nil
6901 (progn
6902 (transpose-regions (nth 0 prev) (nth 1 prev)
6903 (nth 0 cur) (nth 1 cur) t)
6904 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
6905 ;; Catch error in case regions overlap.
6906 (error (goto-char old))))
6907 (goto-char old)))))
6909 (defun markdown-move-list-item-down ()
6910 "Move the current list item down in the list when possible.
6911 In nested lists, move child items with the parent item."
6912 (interactive)
6913 (let (cur next old)
6914 (when (setq cur (markdown-cur-list-item-bounds))
6915 (setq old (point))
6916 (if (markdown-next-list-item (nth 3 cur))
6917 (progn
6918 (setq next (markdown-cur-list-item-bounds))
6919 (condition-case nil
6920 (progn
6921 (transpose-regions (nth 0 cur) (nth 1 cur)
6922 (nth 0 next) (nth 1 next) nil)
6923 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
6924 ;; Catch error in case regions overlap.
6925 (error (goto-char old))))
6926 (goto-char old)))))
6928 (defun markdown-demote-list-item (&optional bounds)
6929 "Indent (or demote) the current list item.
6930 Optionally, BOUNDS of the current list item may be provided if available.
6931 In nested lists, demote child items as well."
6932 (interactive)
6933 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6934 (save-excursion
6935 (let* ((item-start (set-marker (make-marker) (nth 0 bounds)))
6936 (item-end (set-marker (make-marker) (nth 1 bounds)))
6937 (list-start (progn (markdown-beginning-of-list)
6938 (set-marker (make-marker) (point))))
6939 (list-end (progn (markdown-end-of-list)
6940 (set-marker (make-marker) (point)))))
6941 (goto-char item-start)
6942 (while (< (point) item-end)
6943 (unless (markdown-cur-line-blank-p)
6944 (insert (make-string markdown-list-indent-width ? )))
6945 (forward-line))
6946 (markdown-syntax-propertize-list-items list-start list-end)))))
6948 (defun markdown-promote-list-item (&optional bounds)
6949 "Unindent (or promote) the current list item.
6950 Optionally, BOUNDS of the current list item may be provided if available.
6951 In nested lists, demote child items as well."
6952 (interactive)
6953 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
6954 (save-excursion
6955 (save-match-data
6956 (let ((item-start (set-marker (make-marker) (nth 0 bounds)))
6957 (item-end (set-marker (make-marker) (nth 1 bounds)))
6958 (list-start (progn (markdown-beginning-of-list)
6959 (set-marker (make-marker) (point))))
6960 (list-end (progn (markdown-end-of-list)
6961 (set-marker (make-marker) (point))))
6962 num regexp)
6963 (goto-char item-start)
6964 (when (looking-at (format "^[ ]\\{1,%d\\}"
6965 markdown-list-indent-width))
6966 (setq num (- (match-end 0) (match-beginning 0)))
6967 (setq regexp (format "^[ ]\\{1,%d\\}" num))
6968 (while (and (< (point) item-end)
6969 (re-search-forward regexp item-end t))
6970 (replace-match "" nil nil)
6971 (forward-line))
6972 (markdown-syntax-propertize-list-items list-start list-end)))))))
6974 (defun markdown-cleanup-list-numbers-level (&optional pfx)
6975 "Update the numbering for level PFX (as a string of spaces).
6977 Assume that the previously found match was for a numbered item in
6978 a list."
6979 (let ((cpfx pfx)
6980 (idx 0)
6981 (continue t)
6982 (step t)
6983 (sep nil))
6984 (while (and continue (not (eobp)))
6985 (setq step t)
6986 (cond
6987 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
6988 (setq cpfx (match-string-no-properties 1))
6989 (cond
6990 ((string= cpfx pfx)
6991 (save-excursion
6992 (replace-match
6993 (concat pfx (number-to-string (setq idx (1+ idx))) ". ")))
6994 (setq sep nil))
6995 ;; indented a level
6996 ((string< pfx cpfx)
6997 (setq sep (markdown-cleanup-list-numbers-level cpfx))
6998 (setq step nil))
6999 ;; exit the loop
7001 (setq step nil)
7002 (setq continue nil))))
7004 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
7005 (setq cpfx (match-string-no-properties 1))
7006 (cond
7007 ;; reset if separated before
7008 ((string= cpfx pfx) (when sep (setq idx 0)))
7009 ((string< cpfx pfx)
7010 (setq step nil)
7011 (setq continue nil))))
7012 (t (setq sep t)))
7014 (when step
7015 (beginning-of-line)
7016 (setq continue (= (forward-line) 0))))
7017 sep))
7019 (defun markdown-cleanup-list-numbers ()
7020 "Update the numbering of ordered lists."
7021 (interactive)
7022 (save-excursion
7023 (goto-char (point-min))
7024 (markdown-cleanup-list-numbers-level "")))
7027 ;;; Movement ==================================================================
7029 (defun markdown-beginning-of-defun (&optional arg)
7030 "`beginning-of-defun-function' for Markdown.
7031 This is used to find the beginning of the defun and should behave
7032 like ‘beginning-of-defun’, returning non-nil if it found the
7033 beginning of a defun. It moves the point backward, right before a
7034 heading which defines a defun. When ARG is non-nil, repeat that
7035 many times. When ARG is negative, move forward to the ARG-th
7036 following section."
7037 (or arg (setq arg 1))
7038 (when (< arg 0) (end-of-line))
7039 ;; Adjust position for setext headings.
7040 (when (and (thing-at-point-looking-at markdown-regex-header-setext)
7041 (not (= (point) (match-beginning 0)))
7042 (not (markdown-code-block-at-point-p)))
7043 (goto-char (match-end 0)))
7044 (let (found)
7045 ;; Move backward with positive argument.
7046 (while (and (not (bobp)) (> arg 0))
7047 (setq found nil)
7048 (while (and (not found)
7049 (not (bobp))
7050 (re-search-backward markdown-regex-header nil 'move))
7051 (when (not (markdown-code-block-at-pos (match-beginning 0))))
7052 (setq found (match-beginning 0)))
7053 (setq arg (1- arg)))
7054 ;; Move forward with negative argument.
7055 (while (and (not (eobp)) (< arg 0))
7056 (setq found nil)
7057 (while (and (not found)
7058 (not (eobp))
7059 (re-search-forward markdown-regex-header nil 'move))
7060 (when (not (markdown-code-block-at-pos (match-beginning 0))))
7061 (setq found (match-beginning 0)))
7062 (setq arg (1+ arg)))
7063 (when found
7064 (beginning-of-line)
7065 t)))
7067 (defun markdown-end-of-defun ()
7068 "`end-of-defun-function’ for Markdown.
7069 This is used to find the end of the defun at point.
7070 It is called with no argument, right after calling ‘beginning-of-defun-raw’,
7071 so it can assume that point is at the beginning of the defun body.
7072 It should move point to the first position after the defun."
7073 (or (eobp) (forward-char 1))
7074 (let (found)
7075 (while (and (not found)
7076 (not (eobp))
7077 (re-search-forward markdown-regex-header nil 'move))
7078 (when (not (markdown-code-block-at-pos (match-beginning 0)))
7079 (setq found (match-beginning 0))))
7080 (when found
7081 (goto-char found)
7082 (skip-syntax-backward "-"))))
7084 (make-obsolete 'markdown-beginning-of-block 'markdown-beginning-of-text-block "v2.2")
7086 (defun markdown-beginning-of-text-block ()
7087 "Move backward to previous beginning of a plain text block.
7088 This function simply looks for blank lines without considering
7089 the surrounding context in light of Markdown syntax. For that, see
7090 `markdown-backward-block'."
7091 (interactive)
7092 (let ((start (point)))
7093 (if (re-search-backward markdown-regex-block-separator nil t)
7094 (goto-char (match-end 0))
7095 (goto-char (point-min)))
7096 (when (and (= start (point)) (not (bobp)))
7097 (forward-line -1)
7098 (if (re-search-backward markdown-regex-block-separator nil t)
7099 (goto-char (match-end 0))
7100 (goto-char (point-min))))))
7102 (make-obsolete 'markdown-end-of-block 'markdown-end-of-text-block "v2.2")
7104 (defun markdown-end-of-text-block ()
7105 "Move forward to next beginning of a plain text block.
7106 This function simply looks for blank lines without considering
7107 the surrounding context in light of Markdown syntax. For that, see
7108 `markdown-forward-block'."
7109 (interactive)
7110 (beginning-of-line)
7111 (skip-syntax-forward "-")
7112 (when (= (point) (point-min))
7113 (forward-char))
7114 (if (re-search-forward markdown-regex-block-separator nil t)
7115 (goto-char (match-end 0))
7116 (goto-char (point-max)))
7117 (skip-syntax-backward "-")
7118 (forward-line))
7120 (defun markdown-backward-paragraph (&optional arg)
7121 "Move the point to the start of the current paragraph.
7122 With argument ARG, do it ARG times; a negative argument ARG = -N
7123 means move forward N blocks."
7124 (interactive "^p")
7125 (or arg (setq arg 1))
7126 (if (< arg 0)
7127 (markdown-forward-paragraph (- arg))
7128 (dotimes (_ arg)
7129 ;; Skip over whitespace in between paragraphs when moving backward.
7130 (skip-syntax-backward "-")
7131 (beginning-of-line)
7132 ;; Skip over code block endings.
7133 (when (markdown-range-properties-exist
7134 (point-at-bol) (point-at-eol)
7135 '(markdown-gfm-block-end
7136 markdown-tilde-fence-end))
7137 (forward-line -1))
7138 ;; Skip over blank lines inside blockquotes.
7139 (while (and (not (eobp))
7140 (looking-at markdown-regex-blockquote)
7141 (= (length (match-string 3)) 0))
7142 (forward-line -1))
7143 ;; Proceed forward based on the type of block of paragraph.
7144 (let (bounds skip)
7145 (cond
7146 ;; Blockquotes
7147 ((looking-at markdown-regex-blockquote)
7148 (while (and (not (bobp))
7149 (looking-at markdown-regex-blockquote)
7150 (> (length (match-string 3)) 0)) ;; not blank
7151 (forward-line -1))
7152 (forward-line))
7153 ;; List items
7154 ((setq bounds (markdown-cur-list-item-bounds))
7155 (goto-char (nth 0 bounds)))
7156 ;; Other
7158 (while (and (not (bobp))
7159 (not skip)
7160 (not (markdown-cur-line-blank-p))
7161 (not (looking-at markdown-regex-blockquote))
7162 (not (markdown-range-properties-exist
7163 (point-at-bol) (point-at-eol)
7164 '(markdown-gfm-block-end
7165 markdown-tilde-fence-end))))
7166 (setq skip (markdown-range-properties-exist
7167 (point-at-bol) (point-at-eol)
7168 '(markdown-gfm-block-begin
7169 markdown-tilde-fence-begin)))
7170 (forward-line -1))
7171 (unless (bobp)
7172 (forward-line 1))))))))
7174 (defun markdown-forward-paragraph (&optional arg)
7175 "Move forward to the next end of a paragraph.
7176 With argument ARG, do it ARG times; a negative argument ARG = -N
7177 means move backward N blocks."
7178 (interactive "^p")
7179 (or arg (setq arg 1))
7180 (if (< arg 0)
7181 (markdown-backward-paragraph (- arg))
7182 (dotimes (_ arg)
7183 ;; Skip whitespace in between paragraphs.
7184 (when (markdown-cur-line-blank-p)
7185 (skip-syntax-forward "-")
7186 (beginning-of-line))
7187 ;; Proceed forward based on the type of block.
7188 (let (bounds skip)
7189 (cond
7190 ;; Blockquotes
7191 ((looking-at markdown-regex-blockquote)
7192 ;; Skip over blank lines inside blockquotes.
7193 (while (and (not (eobp))
7194 (looking-at markdown-regex-blockquote)
7195 (= (length (match-string 3)) 0))
7196 (forward-line))
7197 ;; Move to end of quoted text block
7198 (while (and (not (eobp))
7199 (looking-at markdown-regex-blockquote)
7200 (> (length (match-string 3)) 0)) ;; not blank
7201 (forward-line)))
7202 ;; List items
7203 ((and (markdown-cur-list-item-bounds)
7204 (setq bounds (markdown-next-list-item-bounds)))
7205 (goto-char (nth 0 bounds)))
7206 ;; Other
7208 (forward-line)
7209 (while (and (not (eobp))
7210 (not skip)
7211 (not (markdown-cur-line-blank-p))
7212 (not (looking-at markdown-regex-blockquote))
7213 (not (markdown-range-properties-exist
7214 (point-at-bol) (point-at-eol)
7215 '(markdown-gfm-block-begin
7216 markdown-tilde-fence-begin))))
7217 (setq skip (markdown-range-properties-exist
7218 (point-at-bol) (point-at-eol)
7219 '(markdown-gfm-block-end
7220 markdown-tilde-fence-end)))
7221 (forward-line))))))))
7223 (defun markdown-backward-block (&optional arg)
7224 "Move the point to the start of the current Markdown block.
7225 Moves across complete code blocks, list items, and blockquotes,
7226 but otherwise stops at blank lines, headers, and horizontal
7227 rules. With argument ARG, do it ARG times; a negative argument
7228 ARG = -N means move forward N blocks."
7229 (interactive "^p")
7230 (or arg (setq arg 1))
7231 (if (< arg 0)
7232 (markdown-forward-block (- arg))
7233 (dotimes (_ arg)
7234 ;; Skip over whitespace in between blocks when moving backward,
7235 ;; unless at a block boundary with no whitespace.
7236 (skip-syntax-backward "-")
7237 (beginning-of-line)
7238 ;; Proceed forward based on the type of block.
7239 (cond
7240 ;; Code blocks
7241 ((and (markdown-code-block-at-pos (point)) ;; this line
7242 (markdown-code-block-at-pos (point-at-bol 0))) ;; previous line
7243 (forward-line -1)
7244 (while (and (markdown-code-block-at-point-p) (not (bobp)))
7245 (forward-line -1))
7246 (forward-line))
7247 ;; Headings
7248 ((markdown-heading-at-point)
7249 (goto-char (match-beginning 0)))
7250 ;; Horizontal rules
7251 ((looking-at markdown-regex-hr))
7252 ;; Blockquotes
7253 ((looking-at markdown-regex-blockquote)
7254 (forward-line -1)
7255 (while (and (looking-at markdown-regex-blockquote)
7256 (not (bobp)))
7257 (forward-line -1))
7258 (forward-line))
7259 ;; List items
7260 ((markdown-cur-list-item-bounds)
7261 (markdown-beginning-of-list))
7262 ;; Other
7264 ;; Move forward in case it is a one line regular paragraph.
7265 (unless (markdown-next-line-blank-p)
7266 (forward-line))
7267 (unless (markdown-prev-line-blank-p)
7268 (markdown-backward-paragraph)))))))
7270 (defun markdown-forward-block (&optional arg)
7271 "Move forward to the next end of a Markdown block.
7272 Moves across complete code blocks, list items, and blockquotes,
7273 but otherwise stops at blank lines, headers, and horizontal
7274 rules. With argument ARG, do it ARG times; a negative argument
7275 ARG = -N means move backward N blocks."
7276 (interactive "^p")
7277 (or arg (setq arg 1))
7278 (if (< arg 0)
7279 (markdown-backward-block (- arg))
7280 (dotimes (_ arg)
7281 ;; Skip over whitespace in between blocks when moving forward.
7282 (if (markdown-cur-line-blank-p)
7283 (skip-syntax-forward "-")
7284 (beginning-of-line))
7285 ;; Proceed forward based on the type of block.
7286 (cond
7287 ;; Code blocks
7288 ((markdown-code-block-at-point-p)
7289 (forward-line)
7290 (while (and (markdown-code-block-at-point-p) (not (eobp)))
7291 (forward-line)))
7292 ;; Headings
7293 ((looking-at markdown-regex-header)
7294 (goto-char (or (match-end 4) (match-end 2) (match-end 3)))
7295 (forward-line))
7296 ;; Horizontal rules
7297 ((looking-at markdown-regex-hr)
7298 (forward-line))
7299 ;; Blockquotes
7300 ((looking-at markdown-regex-blockquote)
7301 (forward-line)
7302 (while (and (looking-at markdown-regex-blockquote) (not (eobp)))
7303 (forward-line)))
7304 ;; List items
7305 ((markdown-cur-list-item-bounds)
7306 (markdown-end-of-list)
7307 (forward-line))
7308 ;; Other
7309 (t (markdown-forward-paragraph))))
7310 (skip-syntax-backward "-")
7311 (unless (eobp)
7312 (forward-char 1))))
7314 (defun markdown-backward-page (&optional count)
7315 "Move backward to boundary of the current toplevel section.
7316 With COUNT, repeat, or go forward if negative."
7317 (interactive "p")
7318 (or count (setq count 1))
7319 (if (< count 0)
7320 (markdown-forward-page (- count))
7321 (skip-syntax-backward "-")
7322 (or (markdown-back-to-heading-over-code-block t t)
7323 (goto-char (point-min)))
7324 (when (looking-at markdown-regex-header)
7325 (let ((level (markdown-outline-level)))
7326 (when (> level 1) (markdown-up-heading level))
7327 (when (> count 1)
7328 (condition-case nil
7329 (markdown-backward-same-level (1- count))
7330 (error (goto-char (point-min)))))))))
7332 (defun markdown-forward-page (&optional count)
7333 "Move forward to boundary of the current toplevel section.
7334 With COUNT, repeat, or go backward if negative."
7335 (interactive "p")
7336 (or count (setq count 1))
7337 (if (< count 0)
7338 (markdown-backward-page (- count))
7339 (if (markdown-back-to-heading-over-code-block t t)
7340 (let ((level (markdown-outline-level)))
7341 (when (> level 1) (markdown-up-heading level))
7342 (condition-case nil
7343 (markdown-forward-same-level count)
7344 (error (goto-char (point-max)))))
7345 (markdown-next-visible-heading 1))))
7347 (defun markdown-next-link ()
7348 "Jump to next inline, reference, or wiki link.
7349 If successful, return point. Otherwise, return nil.
7350 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
7351 (interactive)
7352 (let ((opoint (point)))
7353 (when (or (markdown-link-p) (markdown-wiki-link-p))
7354 ;; At a link already, move past it.
7355 (goto-char (+ (match-end 0) 1)))
7356 ;; Search for the next wiki link and move to the beginning.
7357 (while (and (re-search-forward (markdown-make-regex-link-generic) nil t)
7358 (markdown-code-block-at-point-p)
7359 (< (point) (point-max))))
7360 (if (and (not (eq (point) opoint))
7361 (or (markdown-link-p) (markdown-wiki-link-p)))
7362 ;; Group 1 will move past non-escape character in wiki link regexp.
7363 ;; Go to beginning of group zero for all other link types.
7364 (goto-char (or (match-beginning 1) (match-beginning 0)))
7365 (goto-char opoint)
7366 nil)))
7368 (defun markdown-previous-link ()
7369 "Jump to previous wiki link.
7370 If successful, return point. Otherwise, return nil.
7371 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
7372 (interactive)
7373 (let ((opoint (point)))
7374 (while (and (re-search-backward (markdown-make-regex-link-generic) nil t)
7375 (markdown-code-block-at-point-p)
7376 (> (point) (point-min))))
7377 (if (and (not (eq (point) opoint))
7378 (or (markdown-link-p) (markdown-wiki-link-p)))
7379 (goto-char (or (match-beginning 1) (match-beginning 0)))
7380 (goto-char opoint)
7381 nil)))
7384 ;;; Outline ===================================================================
7386 (defun markdown-move-heading-common (move-fn &optional arg adjust)
7387 "Wrapper for `outline-mode' functions to skip false positives.
7388 MOVE-FN is a function and ARG is its argument. For example,
7389 headings inside preformatted code blocks may match
7390 `outline-regexp' but should not be considered as headings.
7391 When ADJUST is non-nil, adjust the point for interactive calls
7392 to avoid leaving the point at invisible markup. This adjustment
7393 generally should only be done for interactive calls, since other
7394 functions may expect the point to be at the beginning of the
7395 regular expression."
7396 (let ((prev -1) (start (point)))
7397 (if arg (funcall move-fn arg) (funcall move-fn))
7398 (while (and (/= prev (point)) (markdown-code-block-at-point-p))
7399 (setq prev (point))
7400 (if arg (funcall move-fn arg) (funcall move-fn)))
7401 ;; Adjust point for setext headings and invisible text.
7402 (save-match-data
7403 (when (and adjust (thing-at-point-looking-at markdown-regex-header))
7404 (if markdown-hide-markup
7405 ;; Move to beginning of heading text if markup is hidden.
7406 (goto-char (or (match-beginning 1) (match-beginning 5)))
7407 ;; Move to beginning of markup otherwise.
7408 (goto-char (or (match-beginning 1) (match-beginning 4))))))
7409 (if (= (point) start) nil (point))))
7411 (defun markdown-next-visible-heading (arg)
7412 "Move to the next visible heading line of any level.
7413 With argument, repeats or can move backward if negative. ARG is
7414 passed to `outline-next-visible-heading'."
7415 (interactive "p")
7416 (markdown-move-heading-common #'outline-next-visible-heading arg 'adjust))
7418 (defun markdown-previous-visible-heading (arg)
7419 "Move to the previous visible heading line of any level.
7420 With argument, repeats or can move backward if negative. ARG is
7421 passed to `outline-previous-visible-heading'."
7422 (interactive "p")
7423 (markdown-move-heading-common #'outline-previous-visible-heading arg 'adjust))
7425 (defun markdown-next-heading ()
7426 "Move to the next heading line of any level."
7427 (markdown-move-heading-common #'outline-next-heading))
7429 (defun markdown-previous-heading ()
7430 "Move to the previous heading line of any level."
7431 (markdown-move-heading-common #'outline-previous-heading))
7433 (defun markdown-back-to-heading-over-code-block (&optional invisible-ok no-error)
7434 "Move back to the beginning of the previous heading.
7435 Returns t if the point is at a heading, the location if a heading
7436 was found, and nil otherwise.
7437 Only visible heading lines are considered, unless INVISIBLE-OK is
7438 non-nil. Throw an error if there is no previous heading unless
7439 NO-ERROR is non-nil.
7440 Leaves match data intact for `markdown-regex-header'."
7441 (beginning-of-line)
7442 (or (and (markdown-heading-at-point)
7443 (not (markdown-code-block-at-point-p)))
7444 (let (found)
7445 (save-excursion
7446 (while (and (not found)
7447 (re-search-backward markdown-regex-header nil t))
7448 (when (and (or invisible-ok (not (outline-invisible-p)))
7449 (not (markdown-code-block-at-point-p)))
7450 (setq found (point))))
7451 (if (not found)
7452 (unless no-error (user-error "Before first heading"))
7453 (setq found (point))))
7454 (when found (goto-char found)))))
7456 (defun markdown-forward-same-level (arg)
7457 "Move forward to the ARG'th heading at same level as this one.
7458 Stop at the first and last headings of a superior heading."
7459 (interactive "p")
7460 (markdown-back-to-heading-over-code-block)
7461 (markdown-move-heading-common #'outline-forward-same-level arg 'adjust))
7463 (defun markdown-backward-same-level (arg)
7464 "Move backward to the ARG'th heading at same level as this one.
7465 Stop at the first and last headings of a superior heading."
7466 (interactive "p")
7467 (markdown-back-to-heading-over-code-block)
7468 (while (> arg 0)
7469 (let ((point-to-move-to
7470 (save-excursion
7471 (markdown-move-heading-common #'outline-get-last-sibling nil 'adjust))))
7472 (if point-to-move-to
7473 (progn
7474 (goto-char point-to-move-to)
7475 (setq arg (1- arg)))
7476 (user-error "No previous same-level heading")))))
7478 (defun markdown-up-heading (arg)
7479 "Move to the visible heading line of which the present line is a subheading.
7480 With argument, move up ARG levels."
7481 (interactive "p")
7482 (and (called-interactively-p 'any)
7483 (not (eq last-command 'markdown-up-heading)) (push-mark))
7484 (markdown-move-heading-common #'outline-up-heading arg 'adjust))
7486 (defun markdown-back-to-heading (&optional invisible-ok)
7487 "Move to previous heading line, or beg of this line if it's a heading.
7488 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
7489 (markdown-move-heading-common #'outline-back-to-heading invisible-ok))
7491 (defalias 'markdown-end-of-heading 'outline-end-of-heading)
7493 (defun markdown-on-heading-p ()
7494 "Return non-nil if point is on a heading line."
7495 (get-text-property (point-at-bol) 'markdown-heading))
7497 (defun markdown-end-of-subtree (&optional invisible-OK)
7498 "Move to the end of the current subtree.
7499 Only visible heading lines are considered, unless INVISIBLE-OK is
7500 non-nil.
7501 Derived from `org-end-of-subtree'."
7502 (markdown-back-to-heading invisible-OK)
7503 (let ((first t)
7504 (level (markdown-outline-level)))
7505 (while (and (not (eobp))
7506 (or first (> (markdown-outline-level) level)))
7507 (setq first nil)
7508 (markdown-next-heading))
7509 (if (memq (preceding-char) '(?\n ?\^M))
7510 (progn
7511 ;; Go to end of line before heading
7512 (forward-char -1)
7513 (if (memq (preceding-char) '(?\n ?\^M))
7514 ;; leave blank line before heading
7515 (forward-char -1)))))
7516 (point))
7518 (defun markdown-outline-fix-visibility ()
7519 "Hide any false positive headings that should not be shown.
7520 For example, headings inside preformatted code blocks may match
7521 `outline-regexp' but should not be shown as headings when cycling.
7522 Also, the ending --- line in metadata blocks appears to be a
7523 setext header, but should not be folded."
7524 (save-excursion
7525 (goto-char (point-min))
7526 ;; Unhide any false positives in metadata blocks
7527 (when (markdown-text-property-at-point 'markdown-yaml-metadata-begin)
7528 (let ((body (progn (forward-line)
7529 (markdown-text-property-at-point
7530 'markdown-yaml-metadata-section))))
7531 (when body
7532 (let ((end (progn (goto-char (cl-second body))
7533 (markdown-text-property-at-point
7534 'markdown-yaml-metadata-end))))
7535 (outline-flag-region (point-min) (1+ (cl-second end)) nil)))))
7536 ;; Hide any false positives in code blocks
7537 (unless (outline-on-heading-p)
7538 (outline-next-visible-heading 1))
7539 (while (< (point) (point-max))
7540 (when (markdown-code-block-at-point-p)
7541 (outline-flag-region (1- (point-at-bol)) (point-at-eol) t))
7542 (outline-next-visible-heading 1))))
7544 (defvar markdown-cycle-global-status 1)
7545 (defvar markdown-cycle-subtree-status nil)
7547 (defun markdown-next-preface ()
7548 (let (finish)
7549 (while (and (not finish) (re-search-forward (concat "\n\\(?:" outline-regexp "\\)")
7550 nil 'move))
7551 (unless (markdown-code-block-at-point-p)
7552 (goto-char (match-beginning 0))
7553 (setq finish t))))
7554 (when (and (bolp) (or outline-blank-line (eobp)) (not (bobp)))
7555 (forward-char -1)))
7557 (defun markdown-show-entry ()
7558 (save-excursion
7559 (outline-back-to-heading t)
7560 (outline-flag-region (1- (point))
7561 (progn
7562 (markdown-next-preface)
7563 (if (= 1 (- (point-max) (point)))
7564 (point-max)
7565 (point)))
7566 nil)))
7568 ;; This function was originally derived from `org-cycle' from org.el.
7569 (defun markdown-cycle (&optional arg)
7570 "Visibility cycling for Markdown mode.
7571 If ARG is t, perform global visibility cycling. If the point is
7572 at an atx-style header, cycle visibility of the corresponding
7573 subtree. Otherwise, indent the current line or insert a tab,
7574 as appropriate, by calling `indent-for-tab-command'."
7575 (interactive "P")
7576 (cond
7578 ;; Global cycling
7579 ((eq arg t)
7580 (cond
7581 ;; Move from overview to contents
7582 ((and (eq last-command this-command)
7583 (eq markdown-cycle-global-status 2))
7584 (markdown-hide-sublevels 1)
7585 (message "CONTENTS")
7586 (setq markdown-cycle-global-status 3)
7587 (markdown-outline-fix-visibility))
7588 ;; Move from contents to all
7589 ((and (eq last-command this-command)
7590 (eq markdown-cycle-global-status 3))
7591 (markdown-show-all)
7592 (message "SHOW ALL")
7593 (setq markdown-cycle-global-status 1))
7594 ;; Defaults to overview
7596 (markdown-hide-body)
7597 (message "OVERVIEW")
7598 (setq markdown-cycle-global-status 2)
7599 (markdown-outline-fix-visibility))))
7601 ;; At a heading: rotate between three different views
7602 ((save-excursion (beginning-of-line 1) (markdown-on-heading-p))
7603 (markdown-back-to-heading)
7604 (let ((goal-column 0) eoh eol eos)
7605 ;; Determine boundaries
7606 (save-excursion
7607 (markdown-back-to-heading)
7608 (save-excursion
7609 (beginning-of-line 2)
7610 (while (and (not (eobp)) ;; this is like `next-line'
7611 (get-char-property (1- (point)) 'invisible))
7612 (beginning-of-line 2)) (setq eol (point)))
7613 (markdown-end-of-heading) (setq eoh (point))
7614 (markdown-end-of-subtree t)
7615 (skip-chars-forward " \t\n")
7616 (beginning-of-line 1) ; in case this is an item
7617 (setq eos (1- (point))))
7618 ;; Find out what to do next and set `this-command'
7619 (cond
7620 ;; Nothing is hidden behind this heading
7621 ((= eos eoh)
7622 (message "EMPTY ENTRY")
7623 (setq markdown-cycle-subtree-status nil))
7624 ;; Entire subtree is hidden in one line: open it
7625 ((>= eol eos)
7626 (markdown-show-entry)
7627 (markdown-show-children)
7628 (message "CHILDREN")
7629 (setq markdown-cycle-subtree-status 'children))
7630 ;; We just showed the children, now show everything.
7631 ((and (eq last-command this-command)
7632 (eq markdown-cycle-subtree-status 'children))
7633 (markdown-show-subtree)
7634 (message "SUBTREE")
7635 (setq markdown-cycle-subtree-status 'subtree))
7636 ;; Default action: hide the subtree.
7638 (markdown-hide-subtree)
7639 (message "FOLDED")
7640 (setq markdown-cycle-subtree-status 'folded)))))
7642 ;; In a table, move forward by one cell
7643 ((markdown-table-at-point-p)
7644 (call-interactively #'markdown-table-forward-cell))
7646 ;; Otherwise, indent as appropriate
7648 (indent-for-tab-command))))
7650 (defun markdown-shifttab ()
7651 "Handle S-TAB keybinding based on context.
7652 When in a table, move backward one cell.
7653 Otherwise, cycle global heading visibility by calling
7654 `markdown-cycle' with argument t."
7655 (interactive)
7656 (cond ((markdown-table-at-point-p)
7657 (call-interactively #'markdown-table-backward-cell))
7658 (t (markdown-cycle t))))
7660 (defun markdown-outline-level ()
7661 "Return the depth to which a statement is nested in the outline."
7662 (cond
7663 ((and (match-beginning 0)
7664 (markdown-code-block-at-pos (match-beginning 0)))
7665 7) ;; Only 6 header levels are defined.
7666 ((match-end 2) 1)
7667 ((match-end 3) 2)
7668 ((match-end 4)
7669 (length (markdown-trim-whitespace (match-string-no-properties 4))))))
7671 (defun markdown-promote-subtree (&optional arg)
7672 "Promote the current subtree of ATX headings.
7673 Note that Markdown does not support heading levels higher than
7674 six and therefore level-six headings will not be promoted
7675 further. If ARG is non-nil promote the heading, otherwise
7676 demote."
7677 (interactive "*P")
7678 (save-excursion
7679 (when (and (or (thing-at-point-looking-at markdown-regex-header-atx)
7680 (re-search-backward markdown-regex-header-atx nil t))
7681 (not (markdown-code-block-at-point-p)))
7682 (let ((level (length (match-string 1)))
7683 (promote-or-demote (if arg 1 -1))
7684 (remove 't))
7685 (markdown-cycle-atx promote-or-demote remove)
7686 (catch 'end-of-subtree
7687 (while (and (markdown-next-heading)
7688 (looking-at markdown-regex-header-atx))
7689 ;; Exit if this not a higher level heading; promote otherwise.
7690 (if (and (looking-at markdown-regex-header-atx)
7691 (<= (length (match-string-no-properties 1)) level))
7692 (throw 'end-of-subtree nil)
7693 (markdown-cycle-atx promote-or-demote remove))))))))
7695 (defun markdown-demote-subtree ()
7696 "Demote the current subtree of ATX headings."
7697 (interactive)
7698 (markdown-promote-subtree t))
7700 (defun markdown-move-subtree-up ()
7701 "Move the current subtree of ATX headings up."
7702 (interactive)
7703 (outline-move-subtree-up 1))
7705 (defun markdown-move-subtree-down ()
7706 "Move the current subtree of ATX headings down."
7707 (interactive)
7708 (outline-move-subtree-down 1))
7710 (defun markdown-outline-next ()
7711 "Move to next list item, when in a list, or next visible heading."
7712 (interactive)
7713 (let ((bounds (markdown-next-list-item-bounds)))
7714 (if bounds
7715 (goto-char (nth 0 bounds))
7716 (markdown-next-visible-heading 1))))
7718 (defun markdown-outline-previous ()
7719 "Move to previous list item, when in a list, or previous visible heading."
7720 (interactive)
7721 (let ((bounds (markdown-prev-list-item-bounds)))
7722 (if bounds
7723 (goto-char (nth 0 bounds))
7724 (markdown-previous-visible-heading 1))))
7726 (defun markdown-outline-next-same-level ()
7727 "Move to next list item or heading of same level."
7728 (interactive)
7729 (let ((bounds (markdown-cur-list-item-bounds)))
7730 (if bounds
7731 (markdown-next-list-item (nth 3 bounds))
7732 (markdown-forward-same-level 1))))
7734 (defun markdown-outline-previous-same-level ()
7735 "Move to previous list item or heading of same level."
7736 (interactive)
7737 (let ((bounds (markdown-cur-list-item-bounds)))
7738 (if bounds
7739 (markdown-prev-list-item (nth 3 bounds))
7740 (markdown-backward-same-level 1))))
7742 (defun markdown-outline-up ()
7743 "Move to previous list item, when in a list, or next heading."
7744 (interactive)
7745 (unless (markdown-up-list)
7746 (markdown-up-heading 1)))
7749 ;;; Marking and Narrowing =====================================================
7751 (defun markdown-mark-paragraph ()
7752 "Put mark at end of this block, point at beginning.
7753 The block marked is the one that contains point or follows point.
7755 Interactively, if this command is repeated or (in Transient Mark
7756 mode) if the mark is active, it marks the next block after the
7757 ones already marked."
7758 (interactive)
7759 (if (or (and (eq last-command this-command) (mark t))
7760 (and transient-mark-mode mark-active))
7761 (set-mark
7762 (save-excursion
7763 (goto-char (mark))
7764 (markdown-forward-paragraph)
7765 (point)))
7766 (let ((beginning-of-defun-function 'markdown-backward-paragraph)
7767 (end-of-defun-function 'markdown-forward-paragraph))
7768 (mark-defun))))
7770 (defun markdown-mark-block ()
7771 "Put mark at end of this block, point at beginning.
7772 The block marked is the one that contains point or follows point.
7774 Interactively, if this command is repeated or (in Transient Mark
7775 mode) if the mark is active, it marks the next block after the
7776 ones already marked."
7777 (interactive)
7778 (if (or (and (eq last-command this-command) (mark t))
7779 (and transient-mark-mode mark-active))
7780 (set-mark
7781 (save-excursion
7782 (goto-char (mark))
7783 (markdown-forward-block)
7784 (point)))
7785 (let ((beginning-of-defun-function 'markdown-backward-block)
7786 (end-of-defun-function 'markdown-forward-block))
7787 (mark-defun))))
7789 (defun markdown-narrow-to-block ()
7790 "Make text outside current block invisible.
7791 The current block is the one that contains point or follows point."
7792 (interactive)
7793 (let ((beginning-of-defun-function 'markdown-backward-block)
7794 (end-of-defun-function 'markdown-forward-block))
7795 (narrow-to-defun)))
7797 (defun markdown-mark-text-block ()
7798 "Put mark at end of this plain text block, point at beginning.
7799 The block marked is the one that contains point or follows point.
7801 Interactively, if this command is repeated or (in Transient Mark
7802 mode) if the mark is active, it marks the next block after the
7803 ones already marked."
7804 (interactive)
7805 (if (or (and (eq last-command this-command) (mark t))
7806 (and transient-mark-mode mark-active))
7807 (set-mark
7808 (save-excursion
7809 (goto-char (mark))
7810 (markdown-end-of-text-block)
7811 (point)))
7812 (let ((beginning-of-defun-function 'markdown-beginning-of-text-block)
7813 (end-of-defun-function 'markdown-end-of-text-block))
7814 (mark-defun))))
7816 (defun markdown-mark-page ()
7817 "Put mark at end of this top level section, point at beginning.
7818 The top level section marked is the one that contains point or
7819 follows point.
7821 Interactively, if this command is repeated or (in Transient Mark
7822 mode) if the mark is active, it marks the next page after the
7823 ones already marked."
7824 (interactive)
7825 (if (or (and (eq last-command this-command) (mark t))
7826 (and transient-mark-mode mark-active))
7827 (set-mark
7828 (save-excursion
7829 (goto-char (mark))
7830 (markdown-forward-page)
7831 (point)))
7832 (let ((beginning-of-defun-function 'markdown-backward-page)
7833 (end-of-defun-function 'markdown-forward-page))
7834 (mark-defun))))
7836 (defun markdown-narrow-to-page ()
7837 "Make text outside current top level section invisible.
7838 The current section is the one that contains point or follows point."
7839 (interactive)
7840 (let ((beginning-of-defun-function 'markdown-backward-page)
7841 (end-of-defun-function 'markdown-forward-page))
7842 (narrow-to-defun)))
7844 (defun markdown-mark-subtree ()
7845 "Mark the current subtree.
7846 This puts point at the start of the current subtree, and mark at the end."
7847 (interactive)
7848 (let ((beg))
7849 (if (markdown-heading-at-point)
7850 (beginning-of-line)
7851 (markdown-previous-visible-heading 1))
7852 (setq beg (point))
7853 (markdown-end-of-subtree)
7854 (push-mark (point) nil t)
7855 (goto-char beg)))
7857 (defun markdown-narrow-to-subtree ()
7858 "Narrow buffer to the current subtree."
7859 (interactive)
7860 (save-excursion
7861 (save-match-data
7862 (narrow-to-region
7863 (progn (markdown-back-to-heading-over-code-block t) (point))
7864 (progn (markdown-end-of-subtree)
7865 (if (and (markdown-heading-at-point) (not (eobp)))
7866 (backward-char 1))
7867 (point))))))
7870 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
7872 (defun markdown-move-up ()
7873 "Move thing at point up.
7874 When in a list item, call `markdown-move-list-item-up'.
7875 When in a table, call `markdown-table-move-row-up'.
7876 Otherwise, move the current heading subtree up with
7877 `markdown-move-subtree-up'."
7878 (interactive)
7879 (cond
7880 ((markdown-list-item-at-point-p)
7881 (call-interactively #'markdown-move-list-item-up))
7882 ((markdown-table-at-point-p)
7883 (call-interactively #'markdown-table-move-row-up))
7885 (call-interactively #'markdown-move-subtree-up))))
7887 (defun markdown-move-down ()
7888 "Move thing at point down.
7889 When in a list item, call `markdown-move-list-item-down'.
7890 Otherwise, move the current heading subtree up with
7891 `markdown-move-subtree-down'."
7892 (interactive)
7893 (cond
7894 ((markdown-list-item-at-point-p)
7895 (call-interactively #'markdown-move-list-item-down))
7896 ((markdown-table-at-point-p)
7897 (call-interactively #'markdown-table-move-row-down))
7899 (call-interactively #'markdown-move-subtree-down))))
7901 (defun markdown-promote ()
7902 "Promote or move element at point to the left.
7903 Depending on the context, this function will promote a heading or
7904 list item at the point, move a table column to the left, or cycle
7905 markup."
7906 (interactive)
7907 (let (bounds)
7908 (cond
7909 ;; Promote atx heading subtree
7910 ((thing-at-point-looking-at markdown-regex-header-atx)
7911 (markdown-promote-subtree))
7912 ;; Promote setext heading
7913 ((thing-at-point-looking-at markdown-regex-header-setext)
7914 (markdown-cycle-setext -1))
7915 ;; Promote horizonal rule
7916 ((thing-at-point-looking-at markdown-regex-hr)
7917 (markdown-cycle-hr -1))
7918 ;; Promote list item
7919 ((setq bounds (markdown-cur-list-item-bounds))
7920 (markdown-promote-list-item bounds))
7921 ;; Move table column to the left
7922 ((markdown-table-at-point-p)
7923 (call-interactively #'markdown-table-move-column-left))
7924 ;; Promote bold
7925 ((thing-at-point-looking-at markdown-regex-bold)
7926 (markdown-cycle-bold))
7927 ;; Promote italic
7928 ((thing-at-point-looking-at markdown-regex-italic)
7929 (markdown-cycle-italic))
7931 (user-error "Nothing to promote at point")))))
7933 (defun markdown-demote ()
7934 "Demote or move element at point to the right.
7935 Depending on the context, this function will demote a heading or
7936 list item at the point, move a table column to the right, or cycle
7937 or remove markup."
7938 (interactive)
7939 (let (bounds)
7940 (cond
7941 ;; Demote atx heading subtree
7942 ((thing-at-point-looking-at markdown-regex-header-atx)
7943 (markdown-demote-subtree))
7944 ;; Demote setext heading
7945 ((thing-at-point-looking-at markdown-regex-header-setext)
7946 (markdown-cycle-setext 1))
7947 ;; Demote horizonal rule
7948 ((thing-at-point-looking-at markdown-regex-hr)
7949 (markdown-cycle-hr 1))
7950 ;; Demote list item
7951 ((setq bounds (markdown-cur-list-item-bounds))
7952 (markdown-demote-list-item bounds))
7953 ;; Move table column to the right
7954 ((markdown-table-at-point-p)
7955 (call-interactively #'markdown-table-move-column-right))
7956 ;; Demote bold
7957 ((thing-at-point-looking-at markdown-regex-bold)
7958 (markdown-cycle-bold))
7959 ;; Demote italic
7960 ((thing-at-point-looking-at markdown-regex-italic)
7961 (markdown-cycle-italic))
7963 (user-error "Nothing to demote at point")))))
7966 ;;; Commands ==================================================================
7968 (defun markdown (&optional output-buffer-name)
7969 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
7970 The output buffer name defaults to `markdown-output-buffer-name'.
7971 Return the name of the output buffer used."
7972 (interactive)
7973 (save-window-excursion
7974 (let ((begin-region)
7975 (end-region))
7976 (if (markdown-use-region-p)
7977 (setq begin-region (region-beginning)
7978 end-region (region-end))
7979 (setq begin-region (point-min)
7980 end-region (point-max)))
7982 (unless output-buffer-name
7983 (setq output-buffer-name markdown-output-buffer-name))
7984 (cond
7985 ;; Handle case when `markdown-command' does not read from stdin
7986 ((and (stringp markdown-command) markdown-command-needs-filename)
7987 (if (not buffer-file-name)
7988 (user-error "Must be visiting a file")
7989 (shell-command (concat markdown-command " "
7990 (shell-quote-argument buffer-file-name))
7991 output-buffer-name)))
7992 ;; Pass region to `markdown-command' via stdin
7994 (let ((buf (get-buffer-create output-buffer-name)))
7995 (with-current-buffer buf
7996 (setq buffer-read-only nil)
7997 (erase-buffer))
7998 (if (stringp markdown-command)
7999 (call-process-region begin-region end-region
8000 shell-file-name nil buf nil
8001 shell-command-switch markdown-command)
8002 (funcall markdown-command begin-region end-region buf))))))
8003 output-buffer-name))
8005 (defun markdown-standalone (&optional output-buffer-name)
8006 "Special function to provide standalone HTML output.
8007 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
8008 (interactive)
8009 (setq output-buffer-name (markdown output-buffer-name))
8010 (with-current-buffer output-buffer-name
8011 (set-buffer output-buffer-name)
8012 (unless (markdown-output-standalone-p)
8013 (markdown-add-xhtml-header-and-footer output-buffer-name))
8014 (goto-char (point-min))
8015 (html-mode))
8016 output-buffer-name)
8018 (defun markdown-other-window (&optional output-buffer-name)
8019 "Run `markdown-command' on current buffer and display in other window.
8020 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
8021 that name."
8022 (interactive)
8023 (markdown-display-buffer-other-window
8024 (markdown-standalone output-buffer-name)))
8026 (defun markdown-output-standalone-p ()
8027 "Determine whether `markdown-command' output is standalone XHTML.
8028 Standalone XHTML output is identified by an occurrence of
8029 `markdown-xhtml-standalone-regexp' in the first five lines of output."
8030 (save-excursion
8031 (goto-char (point-min))
8032 (save-match-data
8033 (re-search-forward
8034 markdown-xhtml-standalone-regexp
8035 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
8036 t))))
8038 (defun markdown-stylesheet-link-string (stylesheet-path)
8039 (concat "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
8040 stylesheet-path
8041 "\" />"))
8043 (defun markdown-add-xhtml-header-and-footer (title)
8044 "Wrap XHTML header and footer with given TITLE around current buffer."
8045 (goto-char (point-min))
8046 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
8047 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
8048 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
8049 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
8050 "<head>\n<title>")
8051 (insert title)
8052 (insert "</title>\n")
8053 (when (> (length markdown-content-type) 0)
8054 (insert
8055 (format
8056 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
8057 markdown-content-type
8058 (or (and markdown-coding-system
8059 (fboundp 'coding-system-get)
8060 (coding-system-get markdown-coding-system
8061 'mime-charset))
8062 (and (fboundp 'coding-system-get)
8063 (coding-system-get buffer-file-coding-system
8064 'mime-charset))
8065 "iso-8859-1"))))
8066 (if (> (length markdown-css-paths) 0)
8067 (insert (mapconcat #'markdown-stylesheet-link-string
8068 markdown-css-paths "\n")))
8069 (when (> (length markdown-xhtml-header-content) 0)
8070 (insert markdown-xhtml-header-content))
8071 (insert "\n</head>\n\n"
8072 "<body>\n\n")
8073 (goto-char (point-max))
8074 (insert "\n"
8075 "</body>\n"
8076 "</html>\n"))
8078 (defun markdown-preview (&optional output-buffer-name)
8079 "Run `markdown-command' on the current buffer and view output in browser.
8080 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
8081 that name."
8082 (interactive)
8083 (browse-url-of-buffer
8084 (markdown-standalone (or output-buffer-name markdown-output-buffer-name))))
8086 (defun markdown-export-file-name (&optional extension)
8087 "Attempt to generate a filename for Markdown output.
8088 The file extension will be EXTENSION if given, or .html by default.
8089 If the current buffer is visiting a file, we construct a new
8090 output filename based on that filename. Otherwise, return nil."
8091 (when (buffer-file-name)
8092 (unless extension
8093 (setq extension ".html"))
8094 (let ((candidate
8095 (concat
8096 (cond
8097 ((buffer-file-name)
8098 (file-name-sans-extension (buffer-file-name)))
8099 (t (buffer-name)))
8100 extension)))
8101 (cond
8102 ((equal candidate (buffer-file-name))
8103 (concat candidate extension))
8105 candidate)))))
8107 (defun markdown-export (&optional output-file)
8108 "Run Markdown on the current buffer, save to file, and return the filename.
8109 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
8110 generated by `markdown-export-file-name', which will be constructed using the
8111 current filename, but with the extension removed and replaced with .html."
8112 (interactive)
8113 (unless output-file
8114 (setq output-file (markdown-export-file-name ".html")))
8115 (when output-file
8116 (let* ((init-buf (current-buffer))
8117 (init-point (point))
8118 (init-buf-string (buffer-string))
8119 (output-buffer (find-file-noselect output-file))
8120 (output-buffer-name (buffer-name output-buffer)))
8121 (run-hooks 'markdown-before-export-hook)
8122 (markdown-standalone output-buffer-name)
8123 (with-current-buffer output-buffer
8124 (run-hooks 'markdown-after-export-hook)
8125 (save-buffer)
8126 (when markdown-export-kill-buffer (kill-buffer)))
8127 ;; if modified, restore initial buffer
8128 (when (buffer-modified-p init-buf)
8129 (erase-buffer)
8130 (insert init-buf-string)
8131 (save-buffer)
8132 (goto-char init-point))
8133 output-file)))
8135 (defun markdown-export-and-preview ()
8136 "Export to XHTML using `markdown-export' and browse the resulting file."
8137 (interactive)
8138 (browse-url-of-file (markdown-export)))
8140 (defvar markdown-live-preview-buffer nil
8141 "Buffer used to preview markdown output in `markdown-live-preview-export'.")
8142 (make-variable-buffer-local 'markdown-live-preview-buffer)
8144 (defvar markdown-live-preview-source-buffer nil
8145 "Source buffer from which current buffer was generated.
8146 This is the inverse of `markdown-live-preview-buffer'.")
8147 (make-variable-buffer-local 'markdown-live-preview-source-buffer)
8149 (defvar markdown-live-preview-currently-exporting nil)
8151 (defun markdown-live-preview-get-filename ()
8152 "Standardize the filename exported by `markdown-live-preview-export'."
8153 (markdown-export-file-name ".html"))
8155 (defun markdown-live-preview-window-eww (file)
8156 "Preview FILE with eww.
8157 To be used with `markdown-live-preview-window-function'."
8158 (if (require 'eww nil t)
8159 (progn
8160 (eww-open-file file)
8161 (get-buffer "*eww*"))
8162 (error "EWW is not present or not loaded on this version of Emacs")))
8164 (defun markdown-visual-lines-between-points (beg end)
8165 (save-excursion
8166 (goto-char beg)
8167 (cl-loop with count = 0
8168 while (progn (end-of-visual-line)
8169 (and (< (point) end) (line-move-visual 1 t)))
8170 do (cl-incf count)
8171 finally return count)))
8173 (defun markdown-live-preview-window-serialize (buf)
8174 "Get window point and scroll data for all windows displaying BUF."
8175 (when (buffer-live-p buf)
8176 (with-current-buffer buf
8177 (mapcar
8178 (lambda (win)
8179 (with-selected-window win
8180 (let* ((start (window-start))
8181 (pt (window-point))
8182 (pt-or-sym (cond ((= pt (point-min)) 'min)
8183 ((= pt (point-max)) 'max)
8184 (t pt)))
8185 (diff (markdown-visual-lines-between-points
8186 start pt)))
8187 (list win pt-or-sym diff))))
8188 (get-buffer-window-list buf)))))
8190 (defun markdown-get-point-back-lines (pt num-lines)
8191 (save-excursion
8192 (goto-char pt)
8193 (line-move-visual (- num-lines) t)
8194 ;; in testing, can occasionally overshoot the number of lines to traverse
8195 (let ((actual-num-lines (markdown-visual-lines-between-points (point) pt)))
8196 (when (> actual-num-lines num-lines)
8197 (line-move-visual (- actual-num-lines num-lines) t)))
8198 (point)))
8200 (defun markdown-live-preview-window-deserialize (window-posns)
8201 "Apply window point and scroll data from WINDOW-POSNS.
8202 WINDOW-POSNS is provided by `markdown-live-preview-window-serialize'."
8203 (cl-destructuring-bind (win pt-or-sym diff) window-posns
8204 (when (window-live-p win)
8205 (with-current-buffer markdown-live-preview-buffer
8206 (set-window-buffer win (current-buffer))
8207 (cl-destructuring-bind (actual-pt actual-diff)
8208 (cl-case pt-or-sym
8209 (min (list (point-min) 0))
8210 (max (list (point-max) diff))
8211 (t (list pt-or-sym diff)))
8212 (set-window-start
8213 win (markdown-get-point-back-lines actual-pt actual-diff))
8214 (set-window-point win actual-pt))))))
8216 (defun markdown-live-preview-export ()
8217 "Export to XHTML using `markdown-export'.
8218 Browse the resulting file within Emacs using
8219 `markdown-live-preview-window-function' Return the buffer
8220 displaying the rendered output."
8221 (interactive)
8222 (let ((filename (markdown-live-preview-get-filename)))
8223 (when filename
8224 (let* ((markdown-live-preview-currently-exporting t)
8225 (cur-buf (current-buffer))
8226 (export-file (markdown-export filename))
8227 ;; get positions in all windows currently displaying output buffer
8228 (window-data
8229 (markdown-live-preview-window-serialize
8230 markdown-live-preview-buffer)))
8231 (save-window-excursion
8232 (let ((output-buffer
8233 (funcall markdown-live-preview-window-function export-file)))
8234 (with-current-buffer output-buffer
8235 (setq markdown-live-preview-source-buffer cur-buf)
8236 (add-hook 'kill-buffer-hook
8237 #'markdown-live-preview-remove-on-kill t t))
8238 (with-current-buffer cur-buf
8239 (setq markdown-live-preview-buffer output-buffer))))
8240 (with-current-buffer cur-buf
8241 ;; reset all windows displaying output buffer to where they were,
8242 ;; now with the new output
8243 (mapc #'markdown-live-preview-window-deserialize window-data)
8244 ;; delete html editing buffer
8245 (let ((buf (get-file-buffer export-file))) (when buf (kill-buffer buf)))
8246 (when (and export-file (file-exists-p export-file)
8247 (eq markdown-live-preview-delete-export
8248 'delete-on-export))
8249 (delete-file export-file))
8250 markdown-live-preview-buffer)))))
8252 (defun markdown-live-preview-remove ()
8253 (when (buffer-live-p markdown-live-preview-buffer)
8254 (kill-buffer markdown-live-preview-buffer))
8255 (setq markdown-live-preview-buffer nil)
8256 ;; if set to 'delete-on-export, the output has already been deleted
8257 (when (eq markdown-live-preview-delete-export 'delete-on-destroy)
8258 (let ((outfile-name (markdown-live-preview-get-filename)))
8259 (when (and outfile-name (file-exists-p outfile-name))
8260 (delete-file outfile-name)))))
8262 (defun markdown-get-other-window ()
8263 "Find another window to display preview or output content."
8264 (cond
8265 ((memq markdown-split-window-direction '(vertical below))
8266 (or (window-in-direction 'below) (split-window-vertically)))
8267 ((memq markdown-split-window-direction '(horizontal right))
8268 (or (window-in-direction 'right) (split-window-horizontally)))
8269 (t (split-window-sensibly (get-buffer-window)))))
8271 (defun markdown-display-buffer-other-window (buf)
8272 "Display preview or output buffer BUF in another window."
8273 (let ((cur-buf (current-buffer))
8274 (window (markdown-get-other-window)))
8275 (set-window-buffer window buf)
8276 (set-buffer cur-buf)))
8278 (defun markdown-live-preview-if-markdown ()
8279 (when (and (derived-mode-p 'markdown-mode)
8280 markdown-live-preview-mode)
8281 (unless markdown-live-preview-currently-exporting
8282 (if (buffer-live-p markdown-live-preview-buffer)
8283 (markdown-live-preview-export)
8284 (markdown-display-buffer-other-window
8285 (markdown-live-preview-export))))))
8287 (defun markdown-live-preview-remove-on-kill ()
8288 (cond ((and (derived-mode-p 'markdown-mode)
8289 markdown-live-preview-mode)
8290 (markdown-live-preview-remove))
8291 (markdown-live-preview-source-buffer
8292 (with-current-buffer markdown-live-preview-source-buffer
8293 (setq markdown-live-preview-buffer nil))
8294 (setq markdown-live-preview-source-buffer nil))))
8296 (defun markdown-live-preview-switch-to-output ()
8297 "Switch to output buffer."
8298 (interactive)
8299 "Turn on `markdown-live-preview-mode' if not already on, and switch to its
8300 output buffer in another window."
8301 (if markdown-live-preview-mode
8302 (markdown-display-buffer-other-window (markdown-live-preview-export)))
8303 (markdown-live-preview-mode))
8305 (defun markdown-live-preview-re-export ()
8306 "Re export source buffer."
8307 (interactive)
8308 "If the current buffer is a buffer displaying the exported version of a
8309 `markdown-live-preview-mode' buffer, call `markdown-live-preview-export' and
8310 update this buffer's contents."
8311 (when markdown-live-preview-source-buffer
8312 (with-current-buffer markdown-live-preview-source-buffer
8313 (markdown-live-preview-export))))
8315 (defun markdown-open ()
8316 "Open file for the current buffer with `markdown-open-command'."
8317 (interactive)
8318 (unless markdown-open-command
8319 (user-error "Variable `markdown-open-command' must be set"))
8320 (if (stringp markdown-open-command)
8321 (if (not buffer-file-name)
8322 (user-error "Must be visiting a file")
8323 (save-buffer)
8324 (call-process markdown-open-command nil 0 nil buffer-file-name))
8325 (funcall markdown-open-command))
8326 nil)
8328 (defun markdown-kill-ring-save ()
8329 "Run Markdown on file and store output in the kill ring."
8330 (interactive)
8331 (save-window-excursion
8332 (markdown)
8333 (with-current-buffer markdown-output-buffer-name
8334 (kill-ring-save (point-min) (point-max)))))
8337 ;;; Links =====================================================================
8339 (defun markdown-link-p ()
8340 "Return non-nil when `point' is at a non-wiki link.
8341 See `markdown-wiki-link-p' for more information."
8342 (let ((case-fold-search nil))
8343 (and (not (markdown-wiki-link-p))
8344 (not (markdown-code-block-at-point-p))
8345 (or (thing-at-point-looking-at markdown-regex-link-inline)
8346 (thing-at-point-looking-at markdown-regex-link-reference)
8347 (thing-at-point-looking-at markdown-regex-uri)
8348 (thing-at-point-looking-at markdown-regex-angle-uri)))))
8350 (make-obsolete 'markdown-link-link 'markdown-link-url "v2.3")
8352 (defun markdown-link-at-pos (pos)
8353 "Return properties of link or image at position POS.
8354 Value is a list of elements describing the link:
8355 0. beginning position
8356 1. end position
8357 2. link text
8358 3. URL
8359 4. reference label
8360 5. title text
8361 6. bang (nil or \"!\")"
8362 (save-excursion
8363 (goto-char pos)
8364 (let (begin end text url reference title bang)
8365 (cond
8366 ;; Inline or reference image or link at point.
8367 ((or (thing-at-point-looking-at markdown-regex-link-inline)
8368 (thing-at-point-looking-at markdown-regex-link-reference))
8369 (setq bang (match-string-no-properties 1)
8370 begin (match-beginning 0)
8371 end (match-end 0)
8372 text (match-string-no-properties 3))
8373 (if (char-equal (char-after (match-beginning 5)) ?\[)
8374 ;; Reference link
8375 (setq reference (match-string-no-properties 6))
8376 ;; Inline link
8377 (setq url (match-string-no-properties 6))
8378 (when (match-end 7)
8379 (setq title (substring (match-string-no-properties 7) 1 -1)))))
8380 ;; Angle bracket URI at point.
8381 ((thing-at-point-looking-at markdown-regex-angle-uri)
8382 (setq begin (match-beginning 0)
8383 end (match-end 0)
8384 url (match-string-no-properties 2)))
8385 ;; Plain URI at point.
8386 ((thing-at-point-looking-at markdown-regex-uri)
8387 (setq begin (match-beginning 0)
8388 end (match-end 0)
8389 url (match-string-no-properties 1))))
8390 (list begin end text url reference title bang))))
8392 (defun markdown-link-url ()
8393 "Return the URL part of the regular (non-wiki) link at point.
8394 Works with both inline and reference style links, and with images.
8395 If point is not at a link or the link reference is not defined
8396 returns nil."
8397 (let* ((values (markdown-link-at-pos (point)))
8398 (text (nth 2 values))
8399 (url (nth 3 values))
8400 (ref (nth 4 values)))
8401 (or url (and ref (car (markdown-reference-definition
8402 (downcase (if (string= ref "") text ref))))))))
8404 (defun markdown-follow-link-at-point ()
8405 "Open the current non-wiki link.
8406 If the link is a complete URL, open in browser with `browse-url'.
8407 Otherwise, open with `find-file' after stripping anchor and/or query string.
8408 Translate filenames using `markdown-filename-translate-function'."
8409 (interactive)
8410 (if (markdown-link-p)
8411 (let* ((url (markdown-link-url))
8412 (struct (url-generic-parse-url url))
8413 (full (url-fullness struct))
8414 (file url))
8415 ;; Parse URL, determine fullness, strip query string
8416 (if (fboundp 'url-path-and-query)
8417 (setq file (car (url-path-and-query struct)))
8418 (when (and (setq file (url-filename struct))
8419 (string-match "\\?" file))
8420 (setq file (substring file 0 (match-beginning 0)))))
8421 ;; Open full URLs in browser, files in Emacs
8422 (if full
8423 (browse-url url)
8424 (when (and file (> (length file) 0))
8425 (find-file (funcall markdown-translate-filename-function file)))))
8426 (user-error "Point is not at a Markdown link or URL")))
8428 (defun markdown-fontify-inline-links (last)
8429 "Add text properties to next inline link from point to LAST."
8430 (when (markdown-match-generic-links last nil)
8431 (let* ((link-start (match-beginning 3))
8432 (link-end (match-end 3))
8433 (url-start (match-beginning 6))
8434 (url-end (match-end 6))
8435 (url (match-string-no-properties 6))
8436 (title-start (match-beginning 7))
8437 (title-end (match-end 7))
8438 (title (match-string-no-properties 7))
8439 ;; Markup part
8440 (mp (list 'face 'markdown-markup-face
8441 'invisible 'markdown-markup
8442 'rear-nonsticky t
8443 'font-lock-multiline t))
8444 ;; Link part
8445 (lp (list 'keymap markdown-mode-mouse-map
8446 'face markdown-link-face
8447 'mouse-face 'markdown-highlight-face
8448 'font-lock-multiline t
8449 'help-echo (if title (concat title "\n" url) url)))
8450 ;; URL part
8451 (up (list 'keymap markdown-mode-mouse-map
8452 'face 'markdown-url-face
8453 'invisible 'markdown-markup
8454 'mouse-face 'markdown-highlight-face
8455 'font-lock-multiline t))
8456 ;; URL composition character
8457 (url-char (markdown--first-displayable markdown-url-compose-char))
8458 ;; Title part
8459 (tp (list 'face 'markdown-link-title-face
8460 'invisible 'markdown-markup
8461 'font-lock-multiline t)))
8462 (dolist (g '(1 2 4 5 8))
8463 (when (match-end g)
8464 (add-text-properties (match-beginning g) (match-end g) mp)))
8465 (when link-start (add-text-properties link-start link-end lp))
8466 (when url-start (add-text-properties url-start url-end up))
8467 (when title-start (add-text-properties url-end title-end tp))
8468 (when (and markdown-hide-urls url-start)
8469 (compose-region url-start (or title-end url-end) url-char))
8470 t)))
8472 (defun markdown-fontify-reference-links (last)
8473 "Add text properties to next reference link from point to LAST."
8474 (when (markdown-match-generic-links last t)
8475 (let* ((link-start (match-beginning 3))
8476 (link-end (match-end 3))
8477 (ref-start (match-beginning 6))
8478 (ref-end (match-end 6))
8479 ;; Markup part
8480 (mp (list 'face 'markdown-markup-face
8481 'invisible 'markdown-markup
8482 'rear-nonsticky t
8483 'font-lock-multiline t))
8484 ;; Link part
8485 (lp (list 'keymap markdown-mode-mouse-map
8486 'face markdown-link-face
8487 'mouse-face 'markdown-highlight-face
8488 'font-lock-multiline t
8489 'help-echo (lambda (_ __ pos)
8490 (save-match-data
8491 (save-excursion
8492 (goto-char pos)
8493 (or (markdown-link-url)
8494 "Undefined reference"))))))
8495 ;; URL composition character
8496 (url-char (markdown--first-displayable markdown-url-compose-char))
8497 ;; Reference part
8498 (rp (list 'face 'markdown-reference-face
8499 'invisible 'markdown-markup
8500 'font-lock-multiline t)))
8501 (dolist (g '(1 2 4 5 8))
8502 (when (match-end g)
8503 (add-text-properties (match-beginning g) (match-end g) mp)))
8504 (when link-start (add-text-properties link-start link-end lp))
8505 (when ref-start (add-text-properties ref-start ref-end rp)
8506 (when (and markdown-hide-urls (> (- ref-end ref-start) 2))
8507 (compose-region ref-start ref-end url-char)))
8508 t)))
8510 (defun markdown-fontify-angle-uris (last)
8511 "Add text properties to angle URIs from point to LAST."
8512 (when (markdown-match-angle-uris last)
8513 (let* ((url-start (match-beginning 2))
8514 (url-end (match-end 2))
8515 ;; Markup part
8516 (mp (list 'face 'markdown-markup-face
8517 'invisible 'markdown-markup
8518 'rear-nonsticky t
8519 'font-lock-multiline t))
8520 ;; URI part
8521 (up (list 'keymap markdown-mode-mouse-map
8522 'face 'markdown-plain-url-face
8523 'mouse-face 'markdown-highlight-face
8524 'font-lock-multiline t)))
8525 (dolist (g '(1 3))
8526 (add-text-properties (match-beginning g) (match-end g) mp))
8527 (add-text-properties url-start url-end up)
8528 t)))
8530 (defun markdown-fontify-plain-uris (last)
8531 "Add text properties to plain URLs from point to LAST."
8532 (when (markdown-match-plain-uris last)
8533 (let* ((start (match-beginning 0))
8534 (end (match-end 0))
8535 (props (list 'keymap markdown-mode-mouse-map
8536 'face 'markdown-plain-url-face
8537 'mouse-face 'markdown-highlight-face
8538 'rear-nonsticky t
8539 'font-lock-multiline t)))
8540 (add-text-properties start end props)
8541 t)))
8543 (defun markdown-toggle-url-hiding (&optional arg)
8544 "Toggle the display or hiding of URLs.
8545 With a prefix argument ARG, enable URL hiding if ARG is positive,
8546 and disable it otherwise."
8547 (interactive (list (or current-prefix-arg 'toggle)))
8548 (setq markdown-hide-urls
8549 (if (eq arg 'toggle)
8550 (not markdown-hide-urls)
8551 (> (prefix-numeric-value arg) 0)))
8552 (if markdown-hide-urls
8553 (message "markdown-mode URL hiding enabled")
8554 (message "markdown-mode URL hiding disabled"))
8555 (markdown-reload-extensions))
8558 ;;; WikiLink Following/Markup =================================================
8560 (defun markdown-wiki-link-p ()
8561 "Return non-nil if wiki links are enabled and `point' is at a true wiki link.
8562 A true wiki link name matches `markdown-regex-wiki-link' but does
8563 not match the current file name after conversion. This modifies
8564 the data returned by `match-data'. Note that the potential wiki
8565 link name must be available via `match-string'."
8566 (when markdown-enable-wiki-links
8567 (let ((case-fold-search nil))
8568 (and (thing-at-point-looking-at markdown-regex-wiki-link)
8569 (not (markdown-code-block-at-point-p))
8570 (or (not buffer-file-name)
8571 (not (string-equal (buffer-file-name)
8572 (markdown-convert-wiki-link-to-filename
8573 (markdown-wiki-link-link)))))))))
8575 (defun markdown-wiki-link-link ()
8576 "Return the link part of the wiki link using current match data.
8577 The location of the link component depends on the value of
8578 `markdown-wiki-link-alias-first'."
8579 (if markdown-wiki-link-alias-first
8580 (or (match-string-no-properties 5) (match-string-no-properties 3))
8581 (match-string-no-properties 3)))
8583 (defun markdown-wiki-link-alias ()
8584 "Return the alias or text part of the wiki link using current match data.
8585 The location of the alias component depends on the value of
8586 `markdown-wiki-link-alias-first'."
8587 (if markdown-wiki-link-alias-first
8588 (match-string-no-properties 3)
8589 (or (match-string-no-properties 5) (match-string-no-properties 3))))
8591 (defun markdown-convert-wiki-link-to-filename (name)
8592 "Generate a filename from the wiki link NAME.
8593 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
8594 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
8595 and [[test test]] both map to Test-test.ext. Look in the current
8596 directory first, then in subdirectories if
8597 `markdown-wiki-link-search-subdirectories' is non-nil, and then
8598 in parent directories if
8599 `markdown-wiki-link-search-parent-directories' is non-nil."
8600 (let* ((basename (markdown-replace-regexp-in-string
8601 "[[:space:]\n]" markdown-link-space-sub-char name))
8602 (basename (if (eq major-mode 'gfm-mode)
8603 (concat (upcase (substring basename 0 1))
8604 (downcase (substring basename 1 nil)))
8605 basename))
8606 directory extension default candidates dir)
8607 (when buffer-file-name
8608 (setq directory (file-name-directory buffer-file-name)
8609 extension (file-name-extension buffer-file-name)))
8610 (setq default (concat basename
8611 (when extension (concat "." extension))))
8612 (cond
8613 ;; Look in current directory first.
8614 ((or (null buffer-file-name)
8615 (file-exists-p default))
8616 default)
8617 ;; Possibly search in subdirectories, next.
8618 ((and markdown-wiki-link-search-subdirectories
8619 (setq candidates
8620 (markdown-directory-files-recursively
8621 directory (concat "^" default "$"))))
8622 (car candidates))
8623 ;; Possibly search in parent directories as a last resort.
8624 ((and markdown-wiki-link-search-parent-directories
8625 (setq dir (locate-dominating-file directory default)))
8626 (concat dir default))
8627 ;; If nothing is found, return default in current directory.
8628 (t default))))
8630 (defun markdown-follow-wiki-link (name &optional other)
8631 "Follow the wiki link NAME.
8632 Convert the name to a file name and call `find-file'. Ensure that
8633 the new buffer remains in `markdown-mode'. Open the link in another
8634 window when OTHER is non-nil."
8635 (let ((filename (markdown-convert-wiki-link-to-filename name))
8636 (wp (when buffer-file-name
8637 (file-name-directory buffer-file-name))))
8638 (if (not wp)
8639 (user-error "Must be visiting a file")
8640 (when other (other-window 1))
8641 (let ((default-directory wp))
8642 (find-file filename)))
8643 (when (not (eq major-mode 'markdown-mode))
8644 (markdown-mode))))
8646 (defun markdown-follow-wiki-link-at-point (&optional arg)
8647 "Find Wiki Link at point.
8648 With prefix argument ARG, open the file in other window.
8649 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
8650 (interactive "P")
8651 (if (markdown-wiki-link-p)
8652 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
8653 (user-error "Point is not at a Wiki Link")))
8655 (defun markdown-highlight-wiki-link (from to face)
8656 "Highlight the wiki link in the region between FROM and TO using FACE."
8657 (put-text-property from to 'font-lock-face face))
8659 (defun markdown-unfontify-region-wiki-links (from to)
8660 "Remove wiki link faces from the region specified by FROM and TO."
8661 (interactive "*r")
8662 (let ((modified (buffer-modified-p)))
8663 (remove-text-properties from to '(font-lock-face markdown-link-face))
8664 (remove-text-properties from to '(font-lock-face markdown-missing-link-face))
8665 ;; remove-text-properties marks the buffer modified in emacs 24.3,
8666 ;; undo that if it wasn't originally marked modified
8667 (set-buffer-modified-p modified)))
8669 (defun markdown-fontify-region-wiki-links (from to)
8670 "Search region given by FROM and TO for wiki links and fontify them.
8671 If a wiki link is found check to see if the backing file exists
8672 and highlight accordingly."
8673 (goto-char from)
8674 (save-match-data
8675 (while (re-search-forward markdown-regex-wiki-link to t)
8676 (when (not (markdown-code-block-at-point-p))
8677 (let ((highlight-beginning (match-beginning 1))
8678 (highlight-end (match-end 1))
8679 (file-name
8680 (markdown-convert-wiki-link-to-filename
8681 (markdown-wiki-link-link))))
8682 (if (condition-case nil (file-exists-p file-name) (error nil))
8683 (markdown-highlight-wiki-link
8684 highlight-beginning highlight-end markdown-link-face)
8685 (markdown-highlight-wiki-link
8686 highlight-beginning highlight-end markdown-missing-link-face)))))))
8688 (defun markdown-extend-changed-region (from to)
8689 "Extend region given by FROM and TO so that we can fontify all links.
8690 The region is extended to the first newline before and the first
8691 newline after."
8692 ;; start looking for the first new line before 'from
8693 (goto-char from)
8694 (re-search-backward "\n" nil t)
8695 (let ((new-from (point-min))
8696 (new-to (point-max)))
8697 (if (not (= (point) from))
8698 (setq new-from (point)))
8699 ;; do the same thing for the first new line after 'to
8700 (goto-char to)
8701 (re-search-forward "\n" nil t)
8702 (if (not (= (point) to))
8703 (setq new-to (point)))
8704 (cl-values new-from new-to)))
8706 (defun markdown-check-change-for-wiki-link (from to)
8707 "Check region between FROM and TO for wiki links and re-fontify as needed."
8708 (interactive "*r")
8709 (let* ((modified (buffer-modified-p))
8710 (buffer-undo-list t)
8711 (inhibit-read-only t)
8712 (inhibit-point-motion-hooks t)
8713 deactivate-mark
8714 buffer-file-truename)
8715 (unwind-protect
8716 (save-excursion
8717 (save-match-data
8718 (save-restriction
8719 ;; Extend the region to fontify so that it starts
8720 ;; and ends at safe places.
8721 (cl-multiple-value-bind (new-from new-to)
8722 (markdown-extend-changed-region from to)
8723 (goto-char new-from)
8724 ;; Only refontify when the range contains text with a
8725 ;; wiki link face or if the wiki link regexp matches.
8726 (when (or (markdown-range-property-any
8727 new-from new-to 'font-lock-face
8728 (list markdown-link-face
8729 markdown-missing-link-face))
8730 (re-search-forward
8731 markdown-regex-wiki-link new-to t))
8732 ;; Unfontify existing fontification (start from scratch)
8733 (markdown-unfontify-region-wiki-links new-from new-to)
8734 ;; Now do the fontification.
8735 (markdown-fontify-region-wiki-links new-from new-to))))))
8736 (and (not modified)
8737 (buffer-modified-p)
8738 (set-buffer-modified-p nil)))))
8740 (defun markdown-check-change-for-wiki-link-after-change (from to _)
8741 "Check region between FROM and TO for wiki links and re-fontify as needed.
8742 Designed to be used with the `after-change-functions' hook."
8743 (markdown-check-change-for-wiki-link from to))
8745 (defun markdown-fontify-buffer-wiki-links ()
8746 "Refontify all wiki links in the buffer."
8747 (interactive)
8748 (markdown-check-change-for-wiki-link (point-min) (point-max)))
8751 ;;; Following & Doing =========================================================
8753 (defun markdown-follow-thing-at-point (arg)
8754 "Follow thing at point if possible, such as a reference link or wiki link.
8755 Opens inline and reference links in a browser. Opens wiki links
8756 to other files in the current window, or the another window if
8757 ARG is non-nil.
8758 See `markdown-follow-link-at-point' and
8759 `markdown-follow-wiki-link-at-point'."
8760 (interactive "P")
8761 (cond ((markdown-link-p)
8762 (markdown-follow-link-at-point))
8763 ((markdown-wiki-link-p)
8764 (markdown-follow-wiki-link-at-point arg))
8766 (user-error "Nothing to follow at point"))))
8768 (make-obsolete 'markdown-jump 'markdown-do "v2.3")
8770 (defun markdown-do ()
8771 "Do something sensible based on context at point.
8772 Jumps between reference links and definitions; between footnote
8773 markers and footnote text."
8774 (interactive)
8775 (cond
8776 ;; Footnote definition
8777 ((markdown-footnote-text-positions)
8778 (markdown-footnote-return))
8779 ;; Footnote marker
8780 ((markdown-footnote-marker-positions)
8781 (markdown-footnote-goto-text))
8782 ;; Reference link
8783 ((thing-at-point-looking-at markdown-regex-link-reference)
8784 (markdown-reference-goto-definition))
8785 ;; Reference definition
8786 ((thing-at-point-looking-at markdown-regex-reference-definition)
8787 (markdown-reference-goto-link (match-string-no-properties 2)))
8788 ;; GFM task list item
8789 ((markdown-gfm-task-list-item-at-point)
8790 (markdown-toggle-gfm-checkbox))
8791 ;; Align table
8792 ((markdown-table-at-point-p)
8793 (call-interactively #'markdown-table-align))
8794 ;; Otherwise
8796 (markdown-insert-gfm-checkbox))))
8799 ;;; Miscellaneous =============================================================
8801 (defun markdown-compress-whitespace-string (str)
8802 "Compress whitespace in STR and return result.
8803 Leading and trailing whitespace is removed. Sequences of multiple
8804 spaces, tabs, and newlines are replaced with single spaces."
8805 (markdown-replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
8806 (markdown-replace-regexp-in-string "[ \t\n]+" " " str)))
8808 (defun markdown--substitute-command-keys (string)
8809 "Like `substitute-command-keys' but, but prefers control characters.
8810 First pass STRING to `substitute-command-keys' and then
8811 substitute `C-i` for `TAB` and `C-m` for `RET`."
8812 (replace-regexp-in-string
8813 "\\<TAB\\>" "C-i"
8814 (replace-regexp-in-string
8815 "\\<RET\\>" "C-m" (substitute-command-keys string) t) t))
8817 (defun markdown-line-number-at-pos (&optional pos)
8818 "Return (narrowed) buffer line number at position POS.
8819 If POS is nil, use current buffer location.
8820 This is an exact copy of `line-number-at-pos' for use in emacs21."
8821 (let ((opoint (or pos (point))) start)
8822 (save-excursion
8823 (goto-char (point-min))
8824 (setq start (point))
8825 (goto-char opoint)
8826 (forward-line 0)
8827 (1+ (count-lines start (point))))))
8829 (defun markdown-inside-link-p ()
8830 "Return t if point is within a link."
8831 (save-match-data
8832 (thing-at-point-looking-at (markdown-make-regex-link-generic))))
8834 (defun markdown-line-is-reference-definition-p ()
8835 "Return whether the current line is a (non-footnote) reference defition."
8836 (save-excursion
8837 (move-beginning-of-line 1)
8838 (and (looking-at-p markdown-regex-reference-definition)
8839 (not (looking-at-p "[ \t]*\\[^")))))
8841 (defun markdown-adaptive-fill-function ()
8842 "Return prefix for filling paragraph or nil if not determined."
8843 (cond
8844 ;; List item inside blockquote
8845 ((looking-at "^[ \t]*>[ \t]*\\(\\(?:[0-9]+\\|#\\)\\.\\|[*+:-]\\)[ \t]+")
8846 (markdown-replace-regexp-in-string
8847 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
8848 ;; Blockquote
8849 ((looking-at markdown-regex-blockquote)
8850 (buffer-substring-no-properties (match-beginning 0) (match-end 2)))
8851 ;; List items
8852 ((looking-at markdown-regex-list)
8853 (match-string-no-properties 0))
8854 ;; Footnote definition
8855 ((looking-at-p markdown-regex-footnote-definition)
8856 " ") ; four spaces
8857 ;; No match
8858 (t nil)))
8860 (defun markdown-fill-paragraph (&optional justify)
8861 "Fill paragraph at or after point.
8862 This function is like \\[fill-paragraph], but it skips Markdown
8863 code blocks. If the point is in a code block, or just before one,
8864 do not fill. Otherwise, call `fill-paragraph' as usual. If
8865 JUSTIFY is non-nil, justify text as well. Since this function
8866 handles filling itself, it always returns t so that
8867 `fill-paragraph' doesn't run."
8868 (interactive "P")
8869 (unless (or (markdown-code-block-at-point-p)
8870 (save-excursion
8871 (back-to-indentation)
8872 (skip-syntax-forward "-")
8873 (markdown-code-block-at-point-p)))
8874 (fill-paragraph justify))
8877 (make-obsolete 'markdown-fill-forward-paragraph-function
8878 'markdown-fill-forward-paragraph "v2.3")
8880 (defun markdown-fill-forward-paragraph (&optional arg)
8881 "Function used by `fill-paragraph' to move over ARG paragraphs.
8882 This is a `fill-forward-paragraph-function' for `markdown-mode'.
8883 It is called with a single argument specifying the number of
8884 paragraphs to move. Just like `forward-paragraph', it should
8885 return the number of paragraphs left to move."
8886 (or arg (setq arg 1))
8887 (if (> arg 0)
8888 ;; With positive ARG, move across ARG non-code-block paragraphs,
8889 ;; one at a time. When passing a code block, don't decrement ARG.
8890 (while (and (not (eobp))
8891 (> arg 0)
8892 (= (forward-paragraph 1) 0)
8893 (or (markdown-code-block-at-pos (point-at-bol 0))
8894 (setq arg (1- arg)))))
8895 ;; Move backward by one paragraph with negative ARG (always -1).
8896 (let ((start (point)))
8897 (setq arg (forward-paragraph arg))
8898 (while (and (not (eobp))
8899 (progn (move-to-left-margin) (not (eobp)))
8900 (looking-at-p paragraph-separate))
8901 (forward-line 1))
8902 (cond
8903 ;; Move point past whitespace following list marker.
8904 ((looking-at markdown-regex-list)
8905 (goto-char (match-end 0)))
8906 ;; Move point past whitespace following pipe at beginning of line
8907 ;; to handle Pandoc line blocks.
8908 ((looking-at "^|\\s-*")
8909 (goto-char (match-end 0)))
8910 ;; Return point if the paragraph passed was a code block.
8911 ((markdown-code-block-at-pos (point-at-bol 2))
8912 (goto-char start)))))
8913 arg)
8915 (defun markdown--inhibit-electric-quote ()
8916 "Function added to `electric-quote-inhibit-functions'.
8917 Return non-nil if the quote has been inserted inside a code block
8918 or span."
8919 (let ((pos (1- (point))))
8920 (or (markdown-inline-code-at-pos pos)
8921 (markdown-code-block-at-pos pos))))
8924 ;;; Extension Framework =======================================================
8926 (defun markdown-reload-extensions ()
8927 "Check settings, update font-lock keywords and hooks, and re-fontify buffer."
8928 (interactive)
8929 (when (member major-mode '(markdown-mode gfm-mode))
8930 ;; Refontify buffer
8931 (if (eval-when-compile (fboundp 'font-lock-flush))
8932 ;; Use font-lock-flush in Emacs >= 25.1
8933 (font-lock-flush)
8934 ;; Backwards compatibility for Emacs 24.3-24.5
8935 (when (and font-lock-mode (fboundp 'font-lock-refresh-defaults))
8936 (font-lock-refresh-defaults)))
8937 ;; Add or remove hooks related to extensions
8938 (markdown-setup-wiki-link-hooks)))
8940 (defun markdown-handle-local-variables ()
8941 "Run in `hack-local-variables-hook' to update font lock rules.
8942 Checks to see if there is actually a ‘markdown-mode’ file local variable
8943 before regenerating font-lock rules for extensions."
8944 (when (and (boundp 'file-local-variables-alist)
8945 (or (assoc 'markdown-enable-wiki-links file-local-variables-alist)
8946 (assoc 'markdown-enable-math file-local-variables-alist)))
8947 (when (assoc 'markdown-enable-math file-local-variables-alist)
8948 (markdown-toggle-math markdown-enable-math))
8949 (markdown-reload-extensions)))
8952 ;;; Wiki Links ================================================================
8954 (defun markdown-toggle-wiki-links (&optional arg)
8955 "Toggle support for wiki links.
8956 With a prefix argument ARG, enable wiki link support if ARG is positive,
8957 and disable it otherwise."
8958 (interactive (list (or current-prefix-arg 'toggle)))
8959 (setq markdown-enable-wiki-links
8960 (if (eq arg 'toggle)
8961 (not markdown-enable-wiki-links)
8962 (> (prefix-numeric-value arg) 0)))
8963 (if markdown-enable-wiki-links
8964 (message "markdown-mode wiki link support enabled")
8965 (message "markdown-mode wiki link support disabled"))
8966 (markdown-reload-extensions))
8968 (defun markdown-setup-wiki-link-hooks ()
8969 "Add or remove hooks for fontifying wiki links.
8970 These are only enabled when `markdown-wiki-link-fontify-missing' is non-nil."
8971 ;; Anytime text changes make sure it gets fontified correctly
8972 (if (and markdown-enable-wiki-links
8973 markdown-wiki-link-fontify-missing)
8974 (add-hook 'after-change-functions
8975 'markdown-check-change-for-wiki-link-after-change t t)
8976 (remove-hook 'after-change-functions
8977 'markdown-check-change-for-wiki-link-after-change t))
8978 ;; If we left the buffer there is a really good chance we were
8979 ;; creating one of the wiki link documents. Make sure we get
8980 ;; refontified when we come back.
8981 (if (and markdown-enable-wiki-links
8982 markdown-wiki-link-fontify-missing)
8983 (progn
8984 (add-hook 'window-configuration-change-hook
8985 'markdown-fontify-buffer-wiki-links t t)
8986 (markdown-fontify-buffer-wiki-links))
8987 (remove-hook 'window-configuration-change-hook
8988 'markdown-fontify-buffer-wiki-links t)
8989 (markdown-unfontify-region-wiki-links (point-min) (point-max))))
8992 ;;; Math Support ==============================================================
8994 (make-obsolete 'markdown-enable-math 'markdown-toggle-math "v2.1")
8996 (defconst markdown-mode-font-lock-keywords-math
8997 (list
8998 ;; Equation reference (eq:foo)
8999 '("\\((eq:\\)\\([[:alnum:]:_]+\\)\\()\\)" . ((1 markdown-markup-face)
9000 (2 markdown-reference-face)
9001 (3 markdown-markup-face)))
9002 ;; Equation reference \eqref{foo}
9003 '("\\(\\\\eqref{\\)\\([[:alnum:]:_]+\\)\\(}\\)" . ((1 markdown-markup-face)
9004 (2 markdown-reference-face)
9005 (3 markdown-markup-face))))
9006 "Font lock keywords to add and remove when toggling math support.")
9008 (defun markdown-toggle-math (&optional arg)
9009 "Toggle support for inline and display LaTeX math expressions.
9010 With a prefix argument ARG, enable math mode if ARG is positive,
9011 and disable it otherwise. If called from Lisp, enable the mode
9012 if ARG is omitted or nil."
9013 (interactive (list (or current-prefix-arg 'toggle)))
9014 (setq markdown-enable-math
9015 (if (eq arg 'toggle)
9016 (not markdown-enable-math)
9017 (> (prefix-numeric-value arg) 0)))
9018 (if markdown-enable-math
9019 (progn
9020 (font-lock-add-keywords
9021 'markdown-mode markdown-mode-font-lock-keywords-math)
9022 (message "markdown-mode math support enabled"))
9023 (font-lock-remove-keywords
9024 'markdown-mode markdown-mode-font-lock-keywords-math)
9025 (message "markdown-mode math support disabled"))
9026 (markdown-reload-extensions))
9029 ;;; GFM Checkboxes ============================================================
9031 (define-button-type 'markdown-gfm-checkbox-button
9032 'follow-link t
9033 'face 'markdown-gfm-checkbox-face
9034 'mouse-face 'markdown-highlight-face
9035 'action #'markdown-toggle-gfm-checkbox-button)
9037 (defun markdown-gfm-task-list-item-at-point (&optional bounds)
9038 "Return non-nil if there is a GFM task list item at the point.
9039 Optionally, the list item BOUNDS may be given if available, as
9040 returned by `markdown-cur-list-item-bounds'. When a task list item
9041 is found, the return value is the same value returned by
9042 `markdown-cur-list-item-bounds'."
9043 (unless bounds
9044 (setq bounds (markdown-cur-list-item-bounds)))
9045 (> (length (nth 5 bounds)) 0))
9047 (defun markdown-insert-gfm-checkbox ()
9048 "Add GFM checkbox at point.
9049 Returns t if added.
9050 Returns nil if non-applicable."
9051 (interactive)
9052 (let ((bounds (markdown-cur-list-item-bounds)))
9053 (if bounds
9054 (unless (cl-sixth bounds)
9055 (let ((pos (+ (cl-first bounds) (cl-fourth bounds)))
9056 (markup "[ ] "))
9057 (if (< pos (point))
9058 (save-excursion
9059 (goto-char pos)
9060 (insert markup))
9061 (goto-char pos)
9062 (insert markup))
9064 (unless (save-excursion
9065 (back-to-indentation)
9066 (or (markdown-list-item-at-point-p)
9067 (markdown-heading-at-point)
9068 (markdown-in-comment-p)
9069 (markdown-code-block-at-point-p)))
9070 (let ((pos (save-excursion
9071 (back-to-indentation)
9072 (point)))
9073 (markup (concat (or (save-excursion
9074 (beginning-of-line 0)
9075 (cl-fifth (markdown-cur-list-item-bounds)))
9076 markdown-unordered-list-item-prefix)
9077 "[ ] ")))
9078 (if (< pos (point))
9079 (save-excursion
9080 (goto-char pos)
9081 (insert markup))
9082 (goto-char pos)
9083 (insert markup))
9084 t)))))
9086 (defun markdown-toggle-gfm-checkbox ()
9087 "Toggle GFM checkbox at point.
9088 Returns the resulting status as a string, either \"[x]\" or \"[ ]\".
9089 Returns nil if there is no task list item at the point."
9090 (interactive)
9091 (save-match-data
9092 (save-excursion
9093 (let ((bounds (markdown-cur-list-item-bounds)))
9094 (when bounds
9095 ;; Move to beginning of task list item
9096 (goto-char (cl-first bounds))
9097 ;; Advance to column of first non-whitespace after marker
9098 (forward-char (cl-fourth bounds))
9099 (cond ((looking-at "\\[ \\]")
9100 (replace-match
9101 (if markdown-gfm-uppercase-checkbox "[X]" "[x]")
9102 nil t)
9103 (match-string-no-properties 0))
9104 ((looking-at "\\[[xX]\\]")
9105 (replace-match "[ ]" nil t)
9106 (match-string-no-properties 0))))))))
9108 (defun markdown-toggle-gfm-checkbox-button (button)
9109 "Toggle GFM checkbox BUTTON on click."
9110 (save-match-data
9111 (save-excursion
9112 (goto-char (button-start button))
9113 (markdown-toggle-gfm-checkbox))))
9115 (defun markdown-make-gfm-checkboxes-buttons (start end)
9116 "Make GFM checkboxes buttons in region between START and END."
9117 (save-excursion
9118 (goto-char start)
9119 (let ((case-fold-search t))
9120 (save-excursion
9121 (while (re-search-forward markdown-regex-gfm-checkbox end t)
9122 (make-button (match-beginning 1) (match-end 1)
9123 :type 'markdown-gfm-checkbox-button))))))
9125 ;; Called when any modification is made to buffer text.
9126 (defun markdown-gfm-checkbox-after-change-function (beg end _)
9127 "Add to `after-change-functions' to setup GFM checkboxes as buttons.
9128 BEG and END are the limits of scanned region."
9129 (save-excursion
9130 (save-match-data
9131 ;; Rescan between start of line from `beg' and start of line after `end'.
9132 (markdown-make-gfm-checkboxes-buttons
9133 (progn (goto-char beg) (beginning-of-line) (point))
9134 (progn (goto-char end) (forward-line 1) (point))))))
9136 (defun markdown-remove-gfm-checkbox-overlays ()
9137 "Remove all GFM checkbox overlays in buffer."
9138 (save-excursion
9139 (save-restriction
9140 (widen)
9141 (remove-overlays nil nil 'face 'markdown-gfm-checkbox-face))))
9144 ;;; Display inline image =================================================
9146 (defvar markdown-inline-image-overlays nil)
9147 (make-variable-buffer-local 'markdown-inline-image-overlays)
9149 (defun markdown-remove-inline-images ()
9150 "Remove inline image overlays from image links in the buffer.
9151 This can be toggled with `markdown-toggle-inline-images'
9152 or \\[markdown-toggle-inline-images]."
9153 (interactive)
9154 (mapc #'delete-overlay markdown-inline-image-overlays)
9155 (setq markdown-inline-image-overlays nil))
9157 (defun markdown-display-inline-images ()
9158 "Add inline image overlays to image links in the buffer.
9159 This can be toggled with `markdown-toggle-inline-images'
9160 or \\[markdown-toggle-inline-images]."
9161 (interactive)
9162 (unless (display-images-p)
9163 (error "Cannot show images"))
9164 (save-excursion
9165 (save-restriction
9166 (widen)
9167 (goto-char (point-min))
9168 (while (re-search-forward markdown-regex-link-inline nil t)
9169 (let ((start (match-beginning 0))
9170 (end (match-end 0))
9171 (file (match-string-no-properties 6)))
9172 (when (file-exists-p file)
9173 (let* ((abspath (if (file-name-absolute-p file)
9174 file
9175 (concat default-directory file)))
9176 (image
9177 (if (and markdown-max-image-size
9178 (image-type-available-p 'imagemagick))
9179 (create-image
9180 abspath 'imagemagick nil
9181 :max-width (car markdown-max-image-size)
9182 :max-height (cdr markdown-max-image-size))
9183 (create-image abspath))))
9184 (when image
9185 (let ((ov (make-overlay start end)))
9186 (overlay-put ov 'display image)
9187 (overlay-put ov 'face 'default)
9188 (push ov markdown-inline-image-overlays))))))))))
9190 (defun markdown-toggle-inline-images ()
9191 "Toggle inline image overlays in the buffer."
9192 (interactive)
9193 (if markdown-inline-image-overlays
9194 (markdown-remove-inline-images)
9195 (markdown-display-inline-images)))
9198 ;;; GFM Code Block Fontification ==============================================
9200 (defcustom markdown-fontify-code-blocks-natively nil
9201 "When non-nil, fontify code in code blocks using the native major mode.
9202 This only works for fenced code blocks where the language is
9203 specified where we can automatically determine the appropriate
9204 mode to use. The language to mode mapping may be customized by
9205 setting the variable `markdown-code-lang-modes'."
9206 :group 'markdown
9207 :type 'boolean
9208 :safe 'booleanp
9209 :package-version '(markdown-mode . "2.3"))
9211 (defun markdown-toggle-fontify-code-blocks-natively (&optional arg)
9212 "Toggle the native fontification of code blocks.
9213 With a prefix argument ARG, enable if ARG is positive,
9214 and disable otherwise."
9215 (interactive (list (or current-prefix-arg 'toggle)))
9216 (setq markdown-fontify-code-blocks-natively
9217 (if (eq arg 'toggle)
9218 (not markdown-fontify-code-blocks-natively)
9219 (> (prefix-numeric-value arg) 0)))
9220 (if markdown-fontify-code-blocks-natively
9221 (message "markdown-mode native code block fontification enabled")
9222 (message "markdown-mode native code block fontification disabled"))
9223 (markdown-reload-extensions))
9225 ;; This is based on `org-src-lang-modes' from org-src.el
9226 (defcustom markdown-code-lang-modes
9227 '(("ocaml" . tuareg-mode) ("elisp" . emacs-lisp-mode) ("ditaa" . artist-mode)
9228 ("asymptote" . asy-mode) ("dot" . fundamental-mode) ("sqlite" . sql-mode)
9229 ("calc" . fundamental-mode) ("C" . c-mode) ("cpp" . c++-mode)
9230 ("C++" . c++-mode) ("screen" . shell-script-mode) ("shell" . sh-mode)
9231 ("bash" . sh-mode))
9232 "Alist mapping languages to their major mode.
9233 The key is the language name, the value is the major mode. For
9234 many languages this is simple, but for language where this is not
9235 the case, this variable provides a way to simplify things on the
9236 user side. For example, there is no ocaml-mode in Emacs, but the
9237 mode to use is `tuareg-mode'."
9238 :group 'markdown
9239 :type '(repeat
9240 (cons
9241 (string "Language name")
9242 (symbol "Major mode")))
9243 :package-version '(markdown-mode . "2.3"))
9245 (defun markdown-get-lang-mode (lang)
9246 "Return major mode that should be used for LANG.
9247 LANG is a string, and the returned major mode is a symbol."
9248 (cl-find-if
9249 'fboundp
9250 (list (cdr (assoc lang markdown-code-lang-modes))
9251 (cdr (assoc (downcase lang) markdown-code-lang-modes))
9252 (intern (concat lang "-mode"))
9253 (intern (concat (downcase lang) "-mode")))))
9255 (defun markdown-fontify-code-blocks-generic (matcher last)
9256 "Add text properties to next code block from point to LAST.
9257 Use matching function MATCHER."
9258 (when (funcall matcher last)
9259 (save-excursion
9260 (save-match-data
9261 (let* ((start (match-beginning 0))
9262 (end (match-end 0))
9263 ;; Find positions outside opening and closing backquotes.
9264 (bol-prev (progn (goto-char start)
9265 (if (bolp) (point-at-bol 0) (point-at-bol))))
9266 (eol-next (progn (goto-char end)
9267 (if (bolp) (point-at-bol 2) (point-at-bol 3))))
9268 lang)
9269 (if (and markdown-fontify-code-blocks-natively
9270 (setq lang (markdown-code-block-lang)))
9271 (markdown-fontify-code-block-natively lang start end)
9272 (add-text-properties start end '(face markdown-pre-face)))
9273 ;; Set background for block as well as opening and closing lines.
9274 (font-lock-append-text-property
9275 bol-prev eol-next 'face 'markdown-code-face)
9276 ;; Set invisible property for lines before and after, including newline.
9277 (add-text-properties bol-prev start '(invisible markdown-markup))
9278 (add-text-properties end eol-next '(invisible markdown-markup)))))
9281 (defun markdown-fontify-gfm-code-blocks (last)
9282 "Add text properties to next GFM code block from point to LAST."
9283 (markdown-fontify-code-blocks-generic 'markdown-match-gfm-code-blocks last))
9285 (defun markdown-fontify-fenced-code-blocks (last)
9286 "Add text properties to next tilde fenced code block from point to LAST."
9287 (markdown-fontify-code-blocks-generic 'markdown-match-fenced-code-blocks last))
9289 ;; Based on `org-src-font-lock-fontify-block' from org-src.el.
9290 (defun markdown-fontify-code-block-natively (lang start end)
9291 "Fontify given GFM or fenced code block.
9292 This function is called by Emacs for automatic fontification when
9293 `markdown-fontify-code-blocks-natively' is non-nil. LANG is the
9294 language used in the block. START and END specify the block
9295 position."
9296 (let ((lang-mode (markdown-get-lang-mode lang)))
9297 (when (fboundp lang-mode)
9298 (let ((string (buffer-substring-no-properties start end))
9299 (modified (buffer-modified-p))
9300 (markdown-buffer (current-buffer)) pos next)
9301 (remove-text-properties start end '(face nil))
9302 (with-current-buffer
9303 (get-buffer-create
9304 (concat " markdown-code-fontification:" (symbol-name lang-mode)))
9305 ;; Make sure that modification hooks are not inhibited in
9306 ;; the org-src-fontification buffer in case we're called
9307 ;; from `jit-lock-function' (Bug#25132).
9308 (let ((inhibit-modification-hooks nil))
9309 (delete-region (point-min) (point-max))
9310 (insert string " ")) ;; so there's a final property change
9311 (unless (eq major-mode lang-mode) (funcall lang-mode))
9312 (markdown-font-lock-ensure)
9313 (setq pos (point-min))
9314 (while (setq next (next-single-property-change pos 'face))
9315 (let ((val (get-text-property pos 'face)))
9316 (when val
9317 (put-text-property
9318 (+ start (1- pos)) (1- (+ start next)) 'face
9319 val markdown-buffer)))
9320 (setq pos next)))
9321 (add-text-properties
9322 start end
9323 '(font-lock-fontified t fontified t font-lock-multiline t))
9324 (set-buffer-modified-p modified)))))
9326 (require 'edit-indirect nil t)
9327 (defvar edit-indirect-guess-mode-function)
9328 (defvar edit-indirect-after-commit-functions)
9330 (defun markdown--edit-indirect-after-commit-function (_beg end)
9331 "Ensure trailing newlines at the END of code blocks."
9332 (goto-char end)
9333 (unless (eq (char-before) ?\n)
9334 (insert "\n")))
9336 (defun markdown-edit-code-block ()
9337 "Edit Markdown code block in an indirect buffer."
9338 (interactive)
9339 (save-excursion
9340 (if (fboundp 'edit-indirect-region)
9341 (let* ((bounds (markdown-get-enclosing-fenced-block-construct))
9342 (begin (and bounds (goto-char (nth 0 bounds)) (point-at-bol 2)))
9343 (end (and bounds (goto-char (nth 1 bounds)) (point-at-bol 1))))
9344 (if (and begin end)
9345 (let* ((lang (markdown-code-block-lang))
9346 (mode (or (and lang (markdown-get-lang-mode lang))
9347 markdown-edit-code-block-default-mode))
9348 (edit-indirect-guess-mode-function
9349 (lambda (_parent-buffer _beg _end)
9350 (funcall mode))))
9351 (edit-indirect-region begin end 'display-buffer))
9352 (user-error "Not inside a GFM or tilde fenced code block")))
9353 (when (y-or-n-p "Package edit-indirect needed to edit code blocks. Install it now? ")
9354 (progn (package-refresh-contents)
9355 (package-install 'edit-indirect)
9356 (markdown-edit-code-block))))))
9359 ;;; Table Editing
9361 ;; These functions were originally adapted from `org-table.el'.
9363 ;; General helper functions
9365 (defmacro markdown--with-gensyms (symbols &rest body)
9366 (declare (debug (sexp body)) (indent 1))
9367 `(let ,(mapcar (lambda (s)
9368 `(,s (make-symbol (concat "--" (symbol-name ',s)))))
9369 symbols)
9370 ,@body))
9372 (defun markdown--split-string (string &optional separators)
9373 "Splits STRING into substrings at SEPARATORS.
9374 SEPARATORS is a regular expression. If nil it defaults to
9375 `split-string-default-separators'. This version returns no empty
9376 strings if there are matches at the beginning and end of string."
9377 (let ((start 0) notfirst list)
9378 (while (and (string-match
9379 (or separators split-string-default-separators)
9380 string
9381 (if (and notfirst
9382 (= start (match-beginning 0))
9383 (< start (length string)))
9384 (1+ start) start))
9385 (< (match-beginning 0) (length string)))
9386 (setq notfirst t)
9387 (or (eq (match-beginning 0) 0)
9388 (and (eq (match-beginning 0) (match-end 0))
9389 (eq (match-beginning 0) start))
9390 (push (substring string start (match-beginning 0)) list))
9391 (setq start (match-end 0)))
9392 (or (eq start (length string))
9393 (push (substring string start) list))
9394 (nreverse list)))
9396 (defun markdown--string-width (s)
9397 "Return width of string S.
9398 This version ignores characters with invisibility property
9399 `markdown-markup'."
9400 (let (b)
9401 (when (or (eq t buffer-invisibility-spec)
9402 (member 'markdown-markup buffer-invisibility-spec))
9403 (while (setq b (text-property-any
9404 0 (length s)
9405 'invisible 'markdown-markup s))
9406 (setq s (concat
9407 (substring s 0 b)
9408 (substring s (or (next-single-property-change
9409 b 'invisible s)
9410 (length s))))))))
9411 (string-width s))
9413 (defun markdown--remove-invisible-markup (s)
9414 "Remove Markdown markup from string S.
9415 This version removes characters with invisibility property
9416 `markdown-markup'."
9417 (let (b)
9418 (while (setq b (text-property-any
9419 0 (length s)
9420 'invisible 'markdown-markup s))
9421 (setq s (concat
9422 (substring s 0 b)
9423 (substring s (or (next-single-property-change
9424 b 'invisible s)
9425 (length s)))))))
9428 ;; Functions for maintaining tables
9430 (defvar markdown-table-at-point-p-function nil
9431 "Function to decide if point is inside a table.
9433 The indirection serves to differentiate between standard markdown
9434 tables and gfm tables which are less strict about the markup.")
9436 (defconst markdown-table-line-regexp "^[ \t]*|"
9437 "Regexp matching any line inside a table.")
9439 (defconst markdown-table-hline-regexp "^[ \t]*|[-:]"
9440 "Regexp matching hline inside a table.")
9442 (defconst markdown-table-dline-regexp "^[ \t]*|[^-:]"
9443 "Regexp matching dline inside a table.")
9445 (defun markdown-table-at-point-p ()
9446 "Return non-nil when point is inside a table."
9447 (if (functionp markdown-table-at-point-p-function)
9448 (funcall markdown-table-at-point-p-function)
9449 (markdown--table-at-point-p)))
9451 (defun markdown--table-at-point-p ()
9452 "Return non-nil when point is inside a table."
9453 (save-excursion
9454 (beginning-of-line)
9455 (and (looking-at-p markdown-table-line-regexp)
9456 (not (markdown-code-block-at-point-p)))))
9458 (defconst gfm-table-line-regexp "^.?*|"
9459 "Regexp matching any line inside a table.")
9461 (defconst gfm-table-hline-regexp "^-+\\(|-\\)+"
9462 "Regexp matching hline inside a table.")
9464 ;; GFM simplified tables syntax is as follows:
9465 ;; - A header line for the column names, this is any text
9466 ;; separated by `|'.
9467 ;; - Followed by a string -|-|- ..., the number of dashes is optional
9468 ;; but must be higher than 1. The number of separators should match
9469 ;; the number of columns.
9470 ;; - Followed by the rows of data, which has the same format as the
9471 ;; header line.
9472 ;; Example:
9474 ;; foo | bar
9475 ;; ------|---------
9476 ;; bar | baz
9477 ;; bar | baz
9478 (defun gfm--table-at-point-p ()
9479 "Return non-nil when point is inside a gfm-compatible table."
9480 (or (markdown--table-at-point-p)
9481 (save-excursion
9482 (beginning-of-line)
9483 (when (looking-at-p gfm-table-line-regexp)
9484 ;; we might be at the first line of the table, check if the
9485 ;; line below is the hline
9486 (or (save-excursion
9487 (forward-line 1)
9488 (looking-at-p gfm-table-hline-regexp))
9489 ;; go up to find the header
9490 (catch 'done
9491 (while (looking-at-p gfm-table-line-regexp)
9492 (when (looking-at-p gfm-table-hline-regexp)
9493 (throw 'done t))
9494 (forward-line -1))
9495 nil))))))
9497 (defun markdown-table-hline-at-point-p ()
9498 "Return non-nil when point is on a hline in a table.
9499 This function assumes point is on a table."
9500 (save-excursion
9501 (beginning-of-line)
9502 (looking-at-p markdown-table-hline-regexp)))
9504 (defun markdown-table-begin ()
9505 "Find the beginning of the table and return its position.
9506 This function assumes point is on a table."
9507 (save-excursion
9508 (while (and (not (bobp))
9509 (markdown-table-at-point-p))
9510 (forward-line -1))
9511 (unless (eobp)
9512 (forward-line 1))
9513 (point)))
9515 (defun markdown-table-end ()
9516 "Find the end of the table and return its position.
9517 This function assumes point is on a table."
9518 (save-excursion
9519 (while (and (not (eobp))
9520 (markdown-table-at-point-p))
9521 (forward-line 1))
9522 (point)))
9524 (defun markdown-table-get-dline ()
9525 "Return index of the table data line at point.
9526 This function assumes point is on a table."
9527 (let ((pos (point)) (end (markdown-table-end)) (cnt 0))
9528 (save-excursion
9529 (goto-char (markdown-table-begin))
9530 (while (and (re-search-forward
9531 markdown-table-dline-regexp end t)
9532 (setq cnt (1+ cnt))
9533 (< (point-at-eol) pos))))
9534 cnt))
9536 (defun markdown-table-get-column ()
9537 "Return table column at point.
9538 This function assumes point is on a table."
9539 (let ((pos (point)) (cnt 0))
9540 (save-excursion
9541 (beginning-of-line)
9542 (while (search-forward "|" pos t) (setq cnt (1+ cnt))))
9543 cnt))
9545 (defun markdown-table-get-cell (&optional n)
9546 "Return the content of the cell in column N of current row.
9547 N defaults to column at point. This function assumes point is on
9548 a table."
9549 (and n (markdown-table-goto-column n))
9550 (skip-chars-backward "^|\n") (backward-char 1)
9551 (if (looking-at "|[^|\r\n]*")
9552 (let* ((pos (match-beginning 0))
9553 (val (buffer-substring (1+ pos) (match-end 0))))
9554 (goto-char (min (point-at-eol) (+ 2 pos)))
9555 ;; Trim whitespaces
9556 (setq val (replace-regexp-in-string "\\`[ \t]+" "" val)
9557 val (replace-regexp-in-string "[ \t]+\\'" "" val)))
9558 (forward-char 1) ""))
9560 (defun markdown-table-goto-dline (n)
9561 "Go to the Nth data line in the table at point.
9562 Return t when the line exists, nil otherwise. This function
9563 assumes point is on a table."
9564 (goto-char (markdown-table-begin))
9565 (let ((end (markdown-table-end)) (cnt 0))
9566 (while (and (re-search-forward
9567 markdown-table-dline-regexp end t)
9568 (< (setq cnt (1+ cnt)) n)))
9569 (= cnt n)))
9571 (defun markdown-table-goto-column (n &optional on-delim)
9572 "Go to the Nth column in the table line at point.
9573 With optional argument ON-DELIM, stop with point before the left
9574 delimiter of the cell. If there are less than N cells, just go
9575 beyond the last delimiter. This function assumes point is on a
9576 table."
9577 (beginning-of-line 1)
9578 (when (> n 0)
9579 (while (and (> (setq n (1- n)) -1)
9580 (search-forward "|" (point-at-eol) t)))
9581 (if on-delim
9582 (backward-char 1)
9583 (when (looking-at " ") (forward-char 1)))))
9585 (defmacro markdown-table-save-cell (&rest body)
9586 "Save cell at point, execute BODY and restore cell.
9587 This function assumes point is on a table."
9588 (declare (debug (body)))
9589 (markdown--with-gensyms (line column)
9590 `(let ((,line (copy-marker (line-beginning-position)))
9591 (,column (markdown-table-get-column)))
9592 (unwind-protect
9593 (progn ,@body)
9594 (goto-char ,line)
9595 (markdown-table-goto-column ,column)
9596 (set-marker ,line nil)))))
9598 (defun markdown-table-blank-line (s)
9599 "Convert a table line S into a line with blank cells."
9600 (if (string-match "^[ \t]*|-" s)
9601 (setq s (mapconcat
9602 (lambda (x) (if (member x '(?| ?+)) "|" " "))
9603 s ""))
9604 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9605 (setq s (replace-match
9606 (concat "|" (make-string (length (match-string 1 s)) ?\ ) "|")
9607 t t s)))
9610 (defun markdown-table-colfmt (fmtspec)
9611 "Process column alignment specifier FMTSPEC for tables."
9612 (when (stringp fmtspec)
9613 (mapcar (lambda (x)
9614 (cond ((string-match-p "^:.*:$" x) 'c)
9615 ((string-match-p "^:" x) 'l)
9616 ((string-match-p ":$" x) 'r)
9617 (t 'd)))
9618 (markdown--split-string fmtspec "\\s-*|\\s-*"))))
9620 (defun markdown-table-align ()
9621 "Align table at point.
9622 This function assumes point is on a table."
9623 (interactive)
9624 (let ((begin (markdown-table-begin))
9625 (end (copy-marker (markdown-table-end))))
9626 (markdown-table-save-cell
9627 (goto-char begin)
9628 (let* (fmtspec
9629 ;; Store table indent
9630 (indent (progn (looking-at "[ \t]*") (match-string 0)))
9631 ;; Split table in lines and save column format specifier
9632 (lines (mapcar (lambda (l)
9633 (if (string-match-p "\\`[ \t]*|[-:]" l)
9634 (progn (setq fmtspec (or fmtspec l)) nil) l))
9635 (markdown--split-string (buffer-substring begin end) "\n")))
9636 ;; Split lines in cells
9637 (cells (mapcar (lambda (l) (markdown--split-string l "\\s-*|\\s-*"))
9638 (remq nil lines)))
9639 ;; Calculate maximum number of cells in a line
9640 (maxcells (if cells
9641 (apply #'max (mapcar #'length cells))
9642 (user-error "Empty table")))
9643 ;; Empty cells to fill short lines
9644 (emptycells (make-list maxcells "")) maxwidths)
9645 ;; Calculate maximum width for each column
9646 (dotimes (i maxcells)
9647 (let ((column (mapcar (lambda (x) (or (nth i x) "")) cells)))
9648 (push (apply #'max 1 (mapcar #'markdown--string-width column))
9649 maxwidths)))
9650 (setq maxwidths (nreverse maxwidths))
9651 ;; Process column format specifier
9652 (setq fmtspec (markdown-table-colfmt fmtspec))
9653 ;; Compute formats needed for output of table lines
9654 (let ((hfmt (concat indent "|"))
9655 (rfmt (concat indent "|"))
9656 hfmt1 rfmt1 fmt)
9657 (dolist (width maxwidths (setq hfmt (concat (substring hfmt 0 -1) "|")))
9658 (setq fmt (pop fmtspec))
9659 (cond ((equal fmt 'l) (setq hfmt1 ":%s-|" rfmt1 " %%-%ds |"))
9660 ((equal fmt 'r) (setq hfmt1 "-%s:|" rfmt1 " %%%ds |"))
9661 ((equal fmt 'c) (setq hfmt1 ":%s:|" rfmt1 " %%-%ds |"))
9662 (t (setq hfmt1 "-%s-|" rfmt1 " %%-%ds |")))
9663 (setq rfmt (concat rfmt (format rfmt1 width)))
9664 (setq hfmt (concat hfmt (format hfmt1 (make-string width ?-)))))
9665 ;; Replace modified lines only
9666 (dolist (line lines)
9667 (let ((line (if line
9668 (apply #'format rfmt (append (pop cells) emptycells))
9669 hfmt))
9670 (previous (buffer-substring (point) (line-end-position))))
9671 (if (equal previous line)
9672 (forward-line)
9673 (insert line "\n")
9674 (delete-region (point) (line-beginning-position 2))))))
9675 (set-marker end nil)))))
9677 (defun markdown-table-insert-row (&optional arg)
9678 "Insert a new row above the row at point into the table.
9679 With optional argument ARG, insert below the current row."
9680 (interactive "P")
9681 (unless (markdown-table-at-point-p)
9682 (user-error "Not at a table"))
9683 (let* ((line (buffer-substring
9684 (line-beginning-position) (line-end-position)))
9685 (new (markdown-table-blank-line line)))
9686 (beginning-of-line (if arg 2 1))
9687 (unless (bolp) (insert "\n"))
9688 (insert-before-markers new "\n")
9689 (beginning-of-line 0)
9690 (re-search-forward "| ?" (line-end-position) t)))
9692 (defun markdown-table-delete-row ()
9693 "Delete row or horizontal line at point from the table."
9694 (interactive)
9695 (unless (markdown-table-at-point-p)
9696 (user-error "Not at a table"))
9697 (let ((col (current-column)))
9698 (kill-region (point-at-bol)
9699 (min (1+ (point-at-eol)) (point-max)))
9700 (unless (markdown-table-at-point-p) (beginning-of-line 0))
9701 (move-to-column col)))
9703 (defun markdown-table-move-row (&optional up)
9704 "Move table line at point down.
9705 With optional argument UP, move it up."
9706 (interactive "P")
9707 (unless (markdown-table-at-point-p)
9708 (user-error "Not at a table"))
9709 (let* ((col (current-column)) (pos (point))
9710 (tonew (if up 0 2)) txt)
9711 (beginning-of-line tonew)
9712 (unless (markdown-table-at-point-p)
9713 (goto-char pos) (user-error "Cannot move row further"))
9714 (goto-char pos) (beginning-of-line 1) (setq pos (point))
9715 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9716 (delete-region (point) (1+ (point-at-eol)))
9717 (beginning-of-line tonew)
9718 (insert txt) (beginning-of-line 0)
9719 (move-to-column col)))
9721 (defun markdown-table-move-row-up ()
9722 "Move table row at point up."
9723 (interactive)
9724 (markdown-table-move-row 'up))
9726 (defun markdown-table-move-row-down ()
9727 "Move table row at point down."
9728 (interactive)
9729 (markdown-table-move-row nil))
9731 (defun markdown-table-insert-column ()
9732 "Insert a new table column."
9733 (interactive)
9734 (unless (markdown-table-at-point-p)
9735 (user-error "Not at a table"))
9736 (let* ((col (max 1 (markdown-table-get-column)))
9737 (begin (markdown-table-begin))
9738 (end (copy-marker (markdown-table-end))))
9739 (markdown-table-save-cell
9740 (goto-char begin)
9741 (while (< (point) end)
9742 (markdown-table-goto-column col t)
9743 (if (markdown-table-hline-at-point-p)
9744 (insert "|---")
9745 (insert "| "))
9746 (forward-line)))
9747 (set-marker end nil)
9748 (markdown-table-align)))
9750 (defun markdown-table-delete-column ()
9751 "Delete column at point from table."
9752 (interactive)
9753 (unless (markdown-table-at-point-p)
9754 (user-error "Not at a table"))
9755 (let ((col (markdown-table-get-column))
9756 (begin (markdown-table-begin))
9757 (end (copy-marker (markdown-table-end))))
9758 (markdown-table-save-cell
9759 (goto-char begin)
9760 (while (< (point) end)
9761 (markdown-table-goto-column col t)
9762 (and (looking-at "|[^|\n]+|")
9763 (replace-match "|"))
9764 (forward-line)))
9765 (set-marker end nil)
9766 (markdown-table-goto-column (max 1 (1- col)))
9767 (markdown-table-align)))
9769 (defun markdown-table-move-column (&optional left)
9770 "Move table column at point to the right.
9771 With optional argument LEFT, move it to the left."
9772 (interactive "P")
9773 (unless (markdown-table-at-point-p)
9774 (user-error "Not at a table"))
9775 (let* ((col (markdown-table-get-column))
9776 (col1 (if left (1- col) col))
9777 (colpos (if left (1- col) (1+ col)))
9778 (begin (markdown-table-begin))
9779 (end (copy-marker (markdown-table-end))))
9780 (when (and left (= col 1))
9781 (user-error "Cannot move column further left"))
9782 (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9783 (user-error "Cannot move column further right"))
9784 (markdown-table-save-cell
9785 (goto-char begin)
9786 (while (< (point) end)
9787 (markdown-table-goto-column col1 t)
9788 (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9789 (replace-match "|\\2|\\1|"))
9790 (forward-line)))
9791 (set-marker end nil)
9792 (markdown-table-goto-column colpos)
9793 (markdown-table-align)))
9795 (defun markdown-table-move-column-left ()
9796 "Move table column at point to the left."
9797 (interactive)
9798 (markdown-table-move-column 'left))
9800 (defun markdown-table-move-column-right ()
9801 "Move table column at point to the right."
9802 (interactive)
9803 (markdown-table-move-column nil))
9805 (defun markdown-table-next-row ()
9806 "Go to the next row (same column) in the table.
9807 Create new table lines if required."
9808 (interactive)
9809 (unless (markdown-table-at-point-p)
9810 (user-error "Not at a table"))
9811 (if (or (looking-at "[ \t]*$")
9812 (save-excursion (skip-chars-backward " \t") (bolp)))
9813 (newline)
9814 (markdown-table-align)
9815 (let ((col (markdown-table-get-column)))
9816 (beginning-of-line 2)
9817 (if (or (not (markdown-table-at-point-p))
9818 (markdown-table-hline-at-point-p))
9819 (progn
9820 (beginning-of-line 0)
9821 (markdown-table-insert-row 'below)))
9822 (markdown-table-goto-column col)
9823 (skip-chars-backward "^|\n\r")
9824 (when (looking-at " ") (forward-char 1)))))
9826 (defun markdown-table-forward-cell ()
9827 "Go to the next cell in the table.
9828 Create new table lines if required."
9829 (interactive)
9830 (unless (markdown-table-at-point-p)
9831 (user-error "Not at a table"))
9832 (markdown-table-align)
9833 (let ((end (markdown-table-end)))
9834 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9835 (condition-case nil
9836 (progn
9837 (re-search-forward "|" end)
9838 (if (looking-at "[ \t]*$")
9839 (re-search-forward "|" end))
9840 (if (and (looking-at "[-:]")
9841 (re-search-forward "^[ \t]*|\\([^-:]\\)" end t))
9842 (goto-char (match-beginning 1)))
9843 (if (looking-at "[-:]")
9844 (progn
9845 (beginning-of-line 0)
9846 (markdown-table-insert-row 'below))
9847 (when (looking-at " ") (forward-char 1))))
9848 (error (markdown-table-insert-row 'below)))))
9850 (defun markdown-table-backward-cell ()
9851 "Go to the previous cell in the table."
9852 (interactive)
9853 (unless (markdown-table-at-point-p)
9854 (user-error "Not at a table"))
9855 (markdown-table-align)
9856 (when (markdown-table-hline-at-point-p) (end-of-line 1))
9857 (condition-case nil
9858 (progn
9859 (re-search-backward "|" (markdown-table-begin))
9860 (re-search-backward "|" (markdown-table-begin)))
9861 (error (user-error "Cannot move to previous table cell")))
9862 (while (looking-at "|\\([-:]\\|[ \t]*$\\)")
9863 (re-search-backward "|" (markdown-table-begin)))
9864 (when (looking-at "| ?") (goto-char (match-end 0))))
9866 (defun markdown-table-transpose ()
9867 "Transpose table at point.
9868 Horizontal separator lines will be eliminated."
9869 (interactive)
9870 (unless (markdown-table-at-point-p)
9871 (user-error "Not at a table"))
9872 (let* ((table (buffer-substring-no-properties
9873 (markdown-table-begin) (markdown-table-end)))
9874 ;; Convert table to a Lisp structure
9875 (table (delq nil
9876 (mapcar
9877 (lambda (x)
9878 (unless (string-match-p
9879 markdown-table-hline-regexp x)
9880 (markdown--split-string x "\\s-*|\\s-*")))
9881 (markdown--split-string table "[ \t]*\n[ \t]*"))))
9882 (dline_old (markdown-table-get-dline))
9883 (col_old (markdown-table-get-column))
9884 (contents (mapcar (lambda (_)
9885 (let ((tp table))
9886 (mapcar
9887 (lambda (_)
9888 (prog1
9889 (pop (car tp))
9890 (setq tp (cdr tp))))
9891 table)))
9892 (car table))))
9893 (goto-char (markdown-table-begin))
9894 (re-search-forward "|") (backward-char)
9895 (delete-region (point) (markdown-table-end))
9896 (insert (mapconcat
9897 (lambda(x)
9898 (concat "| " (mapconcat 'identity x " | " ) " |\n"))
9899 contents ""))
9900 (markdown-table-goto-dline col_old)
9901 (markdown-table-goto-column dline_old))
9902 (markdown-table-align))
9904 (defun markdown-table-sort-lines (&optional sorting-type)
9905 "Sort table lines according to the column at point.
9907 The position of point indicates the column to be used for
9908 sorting, and the range of lines is the range between the nearest
9909 horizontal separator lines, or the entire table of no such lines
9910 exist. If point is before the first column, user will be prompted
9911 for the sorting column. If there is an active region, the mark
9912 specifies the first line and the sorting column, while point
9913 should be in the last line to be included into the sorting.
9915 The command then prompts for the sorting type which can be
9916 alphabetically or numerically. Sorting in reverse order is also
9917 possible.
9919 If SORTING-TYPE is specified when this function is called from a
9920 Lisp program, no prompting will take place. SORTING-TYPE must be
9921 a character, any of (?a ?A ?n ?N) where the capital letters
9922 indicate that sorting should be done in reverse order."
9923 (interactive)
9924 (unless (markdown-table-at-point-p)
9925 (user-error "Not at a table"))
9926 ;; Set sorting type and column used for sorting
9927 (let ((column (let ((c (markdown-table-get-column)))
9928 (cond ((> c 0) c)
9929 ((called-interactively-p 'any)
9930 (read-number "Use column N for sorting: "))
9931 (t 1))))
9932 (sorting-type
9933 (or sorting-type
9934 (read-char-exclusive
9935 "Sort type: [a]lpha [n]umeric (A/N means reversed): "))))
9936 (save-restriction
9937 ;; Narrow buffer to appropriate sorting area
9938 (if (region-active-p)
9939 (narrow-to-region
9940 (save-excursion
9941 (progn
9942 (goto-char (region-beginning)) (line-beginning-position)))
9943 (save-excursion
9944 (progn
9945 (goto-char (region-end)) (line-end-position))))
9946 (let ((start (markdown-table-begin))
9947 (end (markdown-table-end)))
9948 (narrow-to-region
9949 (save-excursion
9950 (if (re-search-backward
9951 markdown-table-hline-regexp start t)
9952 (line-beginning-position 2)
9953 start))
9954 (if (save-excursion (re-search-forward
9955 markdown-table-hline-regexp end t))
9956 (match-beginning 0)
9957 end))))
9958 ;; Determine arguments for `sort-subr'
9959 (let* ((extract-key-from-cell
9960 (cl-case sorting-type
9961 ((?a ?A) #'markdown--remove-invisible-markup) ;; #'identity)
9962 ((?n ?N) #'string-to-number)
9963 (t (user-error "Invalid sorting type: %c" sorting-type))))
9964 (predicate
9965 (cl-case sorting-type
9966 ((?n ?N) #'<)
9967 ((?a ?A) #'string<))))
9968 ;; Sort selected area
9969 (goto-char (point-min))
9970 (sort-subr (memq sorting-type '(?A ?N))
9971 (lambda ()
9972 (forward-line)
9973 (while (and (not (eobp))
9974 (not (looking-at
9975 markdown-table-dline-regexp)))
9976 (forward-line)))
9977 #'end-of-line
9978 (lambda ()
9979 (funcall extract-key-from-cell
9980 (markdown-table-get-cell column)))
9982 predicate)
9983 (goto-char (point-min))))))
9985 (defun markdown-table-convert-region (begin end &optional separator)
9986 "Convert region from BEGIN to END to table with SEPARATOR.
9988 If every line contains at least one TAB character, the function
9989 assumes that the material is tab separated (TSV). If every line
9990 contains a comma, comma-separated values (CSV) are assumed. If
9991 not, lines are split at whitespace into cells.
9993 You can use a prefix argument to force a specific separator:
9994 \\[universal-argument] once forces CSV, \\[universal-argument]
9995 twice forces TAB, and \\[universal-argument] three times will
9996 prompt for a regular expression to match the separator, and a
9997 numeric argument N indicates that at least N consecutive
9998 spaces, or alternatively a TAB should be used as the separator."
10000 (interactive "r\nP")
10001 (let* ((begin (min begin end)) (end (max begin end)) re)
10002 (goto-char begin) (beginning-of-line 1)
10003 (setq begin (point-marker))
10004 (goto-char end)
10005 (if (bolp) (backward-char 1) (end-of-line 1))
10006 (setq end (point-marker))
10007 (when (equal separator '(64))
10008 (setq separator (read-regexp "Regexp for cell separator: ")))
10009 (unless separator
10010 ;; Get the right cell separator
10011 (goto-char begin)
10012 (setq separator
10013 (cond
10014 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
10015 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
10016 (t 1))))
10017 (goto-char begin)
10018 (if (equal separator '(4))
10019 ;; Parse CSV
10020 (while (< (point) end)
10021 (cond
10022 ((looking-at "^") (insert "| "))
10023 ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
10024 ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
10025 (replace-match "\\1") (if (looking-at "\"") (insert "\"")))
10026 ((looking-at "[^,\n]+") (goto-char (match-end 0)))
10027 ((looking-at "[ \t]*,") (replace-match " | "))
10028 (t (beginning-of-line 2))))
10029 (setq re
10030 (cond
10031 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
10032 ((equal separator '(16)) "^\\|\t")
10033 ((integerp separator)
10034 (if (< separator 1)
10035 (user-error "Cell separator must contain one or more spaces")
10036 (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
10037 ((stringp separator) (format "^ *\\|%s" separator))
10038 (t (error "Invalid cell separator"))))
10039 (while (re-search-forward re end t) (replace-match "| " t t)))
10040 (goto-char begin)
10041 (markdown-table-align)))
10044 ;;; ElDoc Support
10046 (defun markdown-eldoc-function ()
10047 "Return a helpful string when appropriate based on context.
10048 * Report URL when point is at a hidden URL.
10049 * Report language name when point is a code block with hidden markup."
10050 (cond
10051 ;; Hidden URL or reference for inline link
10052 ((and (or (thing-at-point-looking-at markdown-regex-link-inline)
10053 (thing-at-point-looking-at markdown-regex-link-reference))
10054 (or markdown-hide-urls markdown-hide-markup))
10055 (let* ((imagep (string-equal (match-string 1) "!"))
10056 (edit-keys (markdown--substitute-command-keys
10057 (if imagep
10058 "\\[markdown-insert-image]"
10059 "\\[markdown-insert-link]")))
10060 (edit-str (propertize edit-keys 'face 'font-lock-constant-face))
10061 (referencep (string-equal (match-string 5) "["))
10062 (object (if referencep "reference" "URL")))
10063 (format "Hidden %s (%s to edit): %s" object edit-str
10064 (if referencep
10065 (concat
10066 (propertize "[" 'face 'markdown-markup-face)
10067 (propertize (match-string-no-properties 6)
10068 'face 'markdown-reference-face)
10069 (propertize "]" 'face 'markdown-markup-face))
10070 (propertize (match-string-no-properties 6)
10071 'face 'markdown-url-face)))))
10072 ;; Hidden language name for fenced code blocks
10073 ((and (markdown-code-block-at-point-p)
10074 (not (get-text-property (point) 'markdown-pre))
10075 markdown-hide-markup)
10076 (let ((lang (save-excursion (markdown-code-block-lang))))
10077 (unless lang (setq lang "[unspecified]"))
10078 (format "Hidden code block language: %s (%s to toggle markup)"
10079 (propertize lang 'face 'markdown-language-keyword-face)
10080 (markdown--substitute-command-keys
10081 "\\[markdown-toggle-markup-hiding]"))))))
10084 ;;; Mode Definition ==========================================================
10086 (defun markdown-show-version ()
10087 "Show the version number in the minibuffer."
10088 (interactive)
10089 (message "markdown-mode, version %s" markdown-mode-version))
10091 (defun markdown-mode-info ()
10092 "Open the `markdown-mode' homepage."
10093 (interactive)
10094 (browse-url "https://jblevins.org/projects/markdown-mode/"))
10096 ;;;###autoload
10097 (define-derived-mode markdown-mode text-mode "Markdown"
10098 "Major mode for editing Markdown files."
10099 ;; Natural Markdown tab width
10100 (setq tab-width 4)
10101 ;; Comments
10102 (setq-local comment-start "<!-- ")
10103 (setq-local comment-end " -->")
10104 (setq-local comment-start-skip "<!--[ \t]*")
10105 (setq-local comment-column 0)
10106 (setq-local comment-auto-fill-only-comments nil)
10107 (setq-local comment-use-syntax t)
10108 ;; Syntax
10109 (add-hook 'syntax-propertize-extend-region-functions
10110 #'markdown-syntax-propertize-extend-region)
10111 (add-hook 'jit-lock-after-change-extend-region-functions
10112 #'markdown-font-lock-extend-region-function t t)
10113 (setq-local syntax-propertize-function #'markdown-syntax-propertize)
10114 (syntax-propertize (point-max)) ;; Propertize before hooks run, etc.
10115 ;; Font lock.
10116 (setq-local font-lock-defaults nil)
10117 (setq-local font-lock-multiline t)
10118 (setq-local font-lock-extra-managed-props
10119 (append font-lock-extra-managed-props
10120 '(composition display invisible)))
10121 (if markdown-hide-markup
10122 (add-to-invisibility-spec 'markdown-markup)
10123 (remove-from-invisibility-spec 'markdown-markup))
10124 (setq font-lock-defaults
10125 '(markdown-mode-font-lock-keywords-basic
10126 nil nil nil nil
10127 (font-lock-syntactic-face-function . markdown-syntactic-face)))
10128 ;; Wiki links
10129 (markdown-setup-wiki-link-hooks)
10130 ;; Math mode
10131 (when markdown-enable-math (markdown-toggle-math t))
10132 ;; Add a buffer-local hook to reload after file-local variables are read
10133 (add-hook 'hack-local-variables-hook #'markdown-handle-local-variables nil t)
10134 ;; For imenu support
10135 (setq imenu-create-index-function
10136 (if markdown-nested-imenu-heading-index
10137 #'markdown-imenu-create-nested-index
10138 #'markdown-imenu-create-flat-index))
10139 ;; For menu support in XEmacs
10140 (easy-menu-add markdown-mode-menu markdown-mode-map)
10141 ;; Defun movement
10142 (setq-local beginning-of-defun-function #'markdown-beginning-of-defun)
10143 (setq-local end-of-defun-function #'markdown-end-of-defun)
10144 ;; Paragraph filling
10145 (setq-local fill-paragraph-function #'markdown-fill-paragraph)
10146 (setq-local paragraph-start
10147 ;; Should match start of lines that start or separate paragraphs
10148 (mapconcat #'identity
10150 "\f" ; starts with a literal line-feed
10151 "[ \t\f]*$" ; space-only line
10152 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10153 "[ \t]*[*+-][ \t]+" ; unordered list item
10154 "[ \t]*\\(?:[0-9]+\\|#\\)\\.[ \t]+" ; ordered list item
10155 "[ \t]*\\[\\S-*\\]:[ \t]+" ; link ref def
10156 "[ \t]*:[ \t]+" ; definition
10157 "^|" ; table or Pandoc line block
10159 "\\|"))
10160 (setq-local paragraph-separate
10161 ;; Should match lines that separate paragraphs without being
10162 ;; part of any paragraph:
10163 (mapconcat #'identity
10164 '("[ \t\f]*$" ; space-only line
10165 "\\(?:[ \t]*>\\)+[ \t\f]*$"; empty line in blockquote
10166 ;; The following is not ideal, but the Fill customization
10167 ;; options really only handle paragraph-starting prefixes,
10168 ;; not paragraph-ending suffixes:
10169 ".* $" ; line ending in two spaces
10170 "^#+"
10171 "[ \t]*\\[\\^\\S-*\\]:[ \t]*$") ; just the start of a footnote def
10172 "\\|"))
10173 (setq-local adaptive-fill-first-line-regexp "\\`[ \t]*[A-Z]?>[ \t]*?\\'")
10174 (setq-local adaptive-fill-regexp "\\s-*")
10175 (setq-local adaptive-fill-function #'markdown-adaptive-fill-function)
10176 (setq-local fill-forward-paragraph-function #'markdown-fill-forward-paragraph)
10177 ;; Outline mode
10178 (setq-local outline-regexp markdown-regex-header)
10179 (setq-local outline-level #'markdown-outline-level)
10180 ;; Cause use of ellipses for invisible text.
10181 (add-to-invisibility-spec '(outline . t))
10182 ;; ElDoc support
10183 (if (eval-when-compile (fboundp 'add-function))
10184 (add-function :before-until (local 'eldoc-documentation-function)
10185 #'markdown-eldoc-function)
10186 (setq-local eldoc-documentation-function #'markdown-eldoc-function))
10187 ;; Inhibiting line-breaking:
10188 ;; Separating out each condition into a separate function so that users can
10189 ;; override if desired (with remove-hook)
10190 (add-hook 'fill-nobreak-predicate
10191 #'markdown-line-is-reference-definition-p nil t)
10192 (add-hook 'fill-nobreak-predicate
10193 #'markdown-pipe-at-bol-p nil t)
10195 ;; Indentation
10196 (setq-local indent-line-function markdown-indent-function)
10198 ;; Flyspell
10199 (setq-local flyspell-generic-check-word-predicate
10200 #'markdown-flyspell-check-word-p)
10202 ;; Electric quoting
10203 (add-hook 'electric-quote-inhibit-functions
10204 #'markdown--inhibit-electric-quote nil :local)
10206 ;; Backwards compatibility with markdown-css-path
10207 (when (boundp 'markdown-css-path)
10208 (warn "markdown-css-path is deprecated, see markdown-css-paths.")
10209 (add-to-list 'markdown-css-paths markdown-css-path))
10211 ;; Prepare hooks for XEmacs compatibility
10212 (when (featurep 'xemacs)
10213 (make-local-hook 'after-change-functions)
10214 (make-local-hook 'font-lock-extend-region-functions)
10215 (make-local-hook 'window-configuration-change-hook))
10217 ;; Make checkboxes buttons
10218 (when markdown-make-gfm-checkboxes-buttons
10219 (markdown-make-gfm-checkboxes-buttons (point-min) (point-max))
10220 (add-hook 'after-change-functions #'markdown-gfm-checkbox-after-change-function t t)
10221 (add-hook 'change-major-mode-hook #'markdown-remove-gfm-checkbox-overlays t t))
10223 ;; edit-indirect
10224 (add-hook 'edit-indirect-after-commit-functions
10225 #'markdown--edit-indirect-after-commit-function
10226 nil 'local)
10228 ;; Marginalized headings
10229 (when markdown-marginalize-headers
10230 (add-hook 'window-configuration-change-hook
10231 #'markdown-marginalize-update-current nil t))
10233 ;; add live preview export hook
10234 (add-hook 'after-save-hook #'markdown-live-preview-if-markdown t t)
10235 (add-hook 'kill-buffer-hook #'markdown-live-preview-remove-on-kill t t))
10237 ;;;###autoload
10238 (add-to-list 'auto-mode-alist '("\\.markdown\\'" . markdown-mode) t)
10239 ;;;###autoload
10240 (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode) t)
10243 ;;; GitHub Flavored Markdown Mode ============================================
10245 (defvar gfm-mode-hook nil
10246 "Hook run when entering GFM mode.")
10248 (defvar gfm-font-lock-keywords
10249 ;; Basic Markdown features (excluding possibly overridden ones)
10250 markdown-mode-font-lock-keywords-basic
10251 "Default highlighting expressions for GitHub Flavored Markdown mode.")
10253 ;;;###autoload
10254 (define-derived-mode gfm-mode markdown-mode "GFM"
10255 "Major mode for editing GitHub Flavored Markdown files."
10256 (setq markdown-link-space-sub-char "-")
10257 (setq markdown-wiki-link-search-subdirectories t)
10258 (setq-local font-lock-defaults '(gfm-font-lock-keywords))
10259 (setq-local markdown-table-at-point-p-function 'gfm--table-at-point-p)
10260 ;; do the initial link fontification
10261 (markdown-gfm-parse-buffer-for-languages))
10264 ;;; Live Preview Mode ============================================
10265 (define-minor-mode markdown-live-preview-mode
10266 "Toggle native previewing on save for a specific markdown file."
10267 :lighter " MD-Preview"
10268 (if markdown-live-preview-mode
10269 (if (markdown-live-preview-get-filename)
10270 (markdown-display-buffer-other-window (markdown-live-preview-export))
10271 (markdown-live-preview-mode -1)
10272 (user-error "Buffer %s does not visit a file" (current-buffer)))
10273 (markdown-live-preview-remove)))
10276 (provide 'markdown-mode)
10278 ;; Local Variables:
10279 ;; indent-tabs-mode: nil
10280 ;; coding: utf-8
10281 ;; End:
10282 ;;; markdown-mode.el ends here