1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2013 Jason R. Blevins <jrblevin@sdf.org>
4 ;; Copyright (C) 2007, 2009 Edward O'Connor <ted@oconnor.cx>
5 ;; Copyright (C) 2007 Conal Elliott <conal@conal.net>
6 ;; Copyright (C) 2008 Greg Bognar <greg_bognar@hms.harvard.edu>
7 ;; Copyright (C) 2008 Dmitry Dzhus <mail@sphinx.net.ru>
8 ;; Copyright (C) 2008 Bryan Kyle <bryan.kyle@gmail.com>
9 ;; Copyright (C) 2008 Ben Voui <intrigeri@boum.org>
10 ;; Copyright (C) 2009 Ankit Solanki <ankit.solanki@gmail.com>
11 ;; Copyright (C) 2009 Hilko Bengen <bengen@debian.org>
12 ;; Copyright (C) 2009 Peter Williams <pezra@barelyenough.org>
13 ;; Copyright (C) 2010 George Ogata <george.ogata@gmail.com>
14 ;; Copyright (C) 2011 Eric Merritt <ericbmerritt@gmail.com>
15 ;; Copyright (C) 2011 Philippe Ivaldi <pivaldi@sfr.fr>
16 ;; Copyright (C) 2011 Jeremiah Dodds <jeremiah.dodds@gmail.com>
17 ;; Copyright (C) 2011 Christopher J. Madsen <cjm@cjmweb.net>
18 ;; Copyright (C) 2011 Shigeru Fukaya <shigeru.fukaya@gmail.com>
19 ;; Copyright (C) 2011 Joost Kremers <joostkremers@fastmail.fm>
20 ;; Copyright (C) 2011-2012 Donald Ephraim Curtis <dcurtis@milkbox.net>
21 ;; Copyright (C) 2012 Akinori Musha <knu@idaemons.org>
22 ;; Copyright (C) 2012 Zhenlei Jia <zhenlei.jia@gmail.com>
23 ;; Copyright (C) 2012 Peter Jones <pjones@pmade.com>
24 ;; Copyright (C) 2013 Matus Goljer <dota.keys@gmail.com>
26 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
27 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
28 ;; Created: May 24, 2007
30 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
31 ;; URL: http://jblevins.org/projects/markdown-mode/
33 ;; This file is not part of GNU Emacs.
35 ;; This program is free software; you can redistribute it and/or modify
36 ;; it under the terms of the GNU General Public License as published by
37 ;; the Free Software Foundation; either version 2, or (at your option)
40 ;; This program is distributed in the hope that it will be useful,
41 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
42 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
43 ;; GNU General Public License for more details.
45 ;; You should have received a copy of the GNU General Public License
46 ;; along with this program; if not, write to the Free Software
47 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
48 ;; Boston, MA 02110-1301, USA.
52 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
53 ;; text files in GNU Emacs. markdown-mode is free software, licensed
56 ;; [Markdown]: http://daringfireball.net/projects/markdown/
58 ;; The latest stable version is markdown-mode 1.9, released on January 25, 2013:
60 ;; * [markdown-mode.el][]
61 ;; * [Screenshot][][^theme]
62 ;; * [Release notes][]
64 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
65 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
66 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-9
68 ;; [^theme]: The theme used in the screenshot is
69 ;; [color-theme-twilight](https://github.com/crafterm/twilight-emacs).
71 ;; markdown-mode is also available in several package managers, including:
73 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
74 ;; * RedHat and Fedora Linux: [emacs-goodies][]
75 ;; * OpenBSD: [textproc/markdown-mode][]
76 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
77 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
78 ;; * FreeBSD: [textproc/markdown-mode.el][freebsd-port]
80 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
81 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
82 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
83 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
84 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
85 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
86 ;; [freebsd-port]: http://svnweb.freebsd.org/ports/head/textproc/markdown-mode.el
88 ;; The latest development version can be downloaded directly
89 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
90 ;; (browsable and clonable) Git repository at
91 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
92 ;; including the full project history, can be cloned via the Git protocol
95 ;; git clone git://jblevins.org/git/markdown-mode.git
97 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
101 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
102 ;; 19 and XEmacs 19, which provides a uniform interface for creating
103 ;; menus in GNU Emacs and XEmacs.
107 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
108 ;; the following lines to your `.emacs` file to associate markdown-mode
109 ;; with `.text` files:
111 ;; (autoload 'markdown-mode "markdown-mode"
112 ;; "Major mode for editing Markdown files" t)
113 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
115 ;; There is no consensus on an official file extension so change `.text` to
116 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
120 ;; Although no configuration is *necessary* there are a few things
121 ;; that can be customized. The `M-x customize-mode` command
122 ;; provides an interface to all of the possible customizations:
124 ;; * `markdown-command' - the command used to run Markdown (default:
125 ;; `markdown`). This variable may be customized to pass
126 ;; command-line options to your Markdown processor of choice.
128 ;; * `markdown-command-needs-filename' - by default, `markdown-mode'
129 ;; will pass the Markdown content to `markdown-command' using
130 ;; standard input (`stdin`). If `markdown-command' does not
131 ;; accept standard input, then `markdown-command-needs-filename'
132 ;; should be set to non-nil, which instructs `markdown-mode' to
133 ;; pass the name of the file as the final command-line argument.
134 ;; Note that with this option, you will only be able to run
135 ;; `markdown-command' from buffers which are visiting a file.
137 ;; * `markdown-open-command' - the command used for calling a standalone
138 ;; Markdown previewer which is capable of opening Markdown source files
139 ;; directly (default: `nil'). This command will be called
140 ;; with a single argument, the filename of the current buffer.
141 ;; A representative program is the Mac app [Marked][], a
142 ;; live-updating MultiMarkdown previewer which has a command line
143 ;; utility at `/usr/local/bin/mark`.
145 ;; * `markdown-hr-strings' - list of strings to use when inserting
146 ;; horizontal rules. Different strings will not be distinguished
147 ;; when converted to HTML--they will all be converted to
148 ;; `<hr/>`--but they may add visual distinction and style to plain
149 ;; text documents. To maintain some notion of promotion and
150 ;; demotion, keep these sorted from largest to smallest.
152 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
153 ;; underscores for bold instead of two asterisks (default: `nil').
155 ;; * `markdown-italic-underscore' - set to a non-nil value to use
156 ;; underscores for italic instead of asterisks (default: `nil').
158 ;; * `markdown-indent-function' - the function to use for automatic
159 ;; indentation (default: `markdown-indent-line').
161 ;; * `markdown-indent-on-enter' - set to a non-nil value to
162 ;; automatically indent new lines when the enter key is pressed
165 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
166 ;; to automatically open a linked document in a new buffer if the
167 ;; cursor is an wiki link
170 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
171 ;; treat aliased wiki links like `[[link text|PageName]]`.
172 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
174 ;; * `markdown-uri-types' - a list of protocols for URIs that
175 ;; `markdown-mode' should highlight.
177 ;; * `markdown-enable-math' - syntax highlighting for
178 ;; LaTeX fragments (default: `nil').
180 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
182 ;; * `markdown-content-type' - when set to a nonempty string, an
183 ;; `http-equiv` attribute will be included in the XHTML `<head>`
184 ;; block. If needed, the suggested values are
185 ;; `application/xhtml+xml` or `text/html`.
187 ;; * `markdown-coding-system' - used for specifying the character
188 ;; set identifier in the `http-equiv` attribute (see
189 ;; `markdown-content-type'). When set to `nil',
190 ;; `buffer-file-coding-system' will be used (and falling back to
191 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
192 ;; and `iso-latin-1'.
194 ;; * `markdown-xhtml-header-content' - additional content to include
195 ;; in the XHTML `<head>` block.
197 ;; * `markdown-command-needs-filename' - set to non-nil if
198 ;; `markdown-command' does not accept input from stdin (default: nil).
199 ;; Instead, it will be passed a filename as the final command-line
200 ;; argument. As a result, you will only be able to run Markdown
201 ;; from buffers which are visiting a file.
203 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
204 ;; `markdown-mode' uses to determine whether the output of
205 ;; `markdown-command' is a standalone XHTML document or an XHTML
206 ;; fragment (default: `"^\\(\<\\?xml\\|\<!DOCTYPE\\|\<html\\)"`). If
207 ;; this regular expression not matched in the first five lines of
208 ;; output, `markdown-mode' assumes the output is a fragment and
209 ;; adds a header and footer.
211 ;; * `markdown-link-space-sub-char' - a character to replace spaces
212 ;; when mapping wiki links to filenames (default: `_`).
213 ;; For example, use an underscore for compatibility with the
214 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
215 ;; with GitHub wiki links.
217 ;; Additionally, the faces used for syntax highlighting can be modified to
218 ;; your liking by issuing `M-x customize-group RET markdown-faces`
219 ;; or by using the "Markdown Faces" link at the bottom of the mode
220 ;; customization screen.
222 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
226 ;; Keybindings are grouped by prefixes based on their function. For
227 ;; example, commands dealing with headers begin with `C-c C-t`. The
228 ;; primary commands in each group will are described below. You can
229 ;; obtain a list of all keybindings by pressing `C-c C-h`.
231 ;; * Anchors: `C-c C-a`
233 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
234 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
235 ;; The label definition will be placed at the end of the current
236 ;; block. `C-c C-a w` acts similarly for wiki links of the form
237 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
238 ;; text in the region is used as the link text.
240 ;; * Commands: `C-c C-c`
242 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
243 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
244 ;; runs Markdown on the current buffer and previews, stores the
245 ;; output in a temporary file, and displays the file in a browser.
246 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
247 ;; and save the result in the file `basename.html`, where
248 ;; `basename` is the name of the Markdown file with the extension
249 ;; removed. *Export and View:* press `C-c C-c v` to export the
250 ;; file and view it in a browser. **For both export commands, the
251 ;; output file will be overwritten without notice.**
252 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
253 ;; using `markdown-open-command'.
257 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
258 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
259 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
260 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
261 ;; - `C-c C-c w`: `markdown-command' > kill ring.
262 ;; - `C-c C-c o`: `markdown-open-command'.
264 ;; `C-c C-c c` will check for undefined references. If there are
265 ;; any, a small buffer will open with a list of undefined
266 ;; references and the line numbers on which they appear. In Emacs
267 ;; 22 and greater, selecting a reference from this list and
268 ;; pressing `RET` will insert an empty reference definition at the
269 ;; end of the buffer. Similarly, selecting the line number will
270 ;; jump to the corresponding line.
272 ;; `C-c C-c n` will clean up the numbering of ordered lists.
274 ;; * Images: `C-c C-i`
276 ;; `C-c C-i i` inserts markup for an inline image, using the
277 ;; active region (if any) or the word at point as the alt text.
278 ;; To insert reference-style image markup, provide a `C-u` prefix.
280 ;; * Physical styles: `C-c C-p`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
284 ;; the selected text bold, `C-c C-p f` formats the region as
285 ;; fixed-width text, and `C-c C-p i` is used for italic text.
287 ;; * Logical styles: `C-c C-s`
289 ;; These commands all act on text in the active region, if any,
290 ;; and insert empty markup fragments otherwise. Logical styles
291 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
292 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
295 ;; * Headers: `C-c C-t`
297 ;; All header commands use text in the active region, if any, as
298 ;; the header text. Otherwise, if the current line is not blank,
299 ;; use the text on the current line. Finally, prompt for header
300 ;; text if there is no active region and the current line is
301 ;; blank. To insert an atx or hash style level-n
302 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
303 ;; top-level setext or underline style header press `C-c C-t t`
304 ;; (mnemonic: title) and for a second-level underline-style header
305 ;; press `C-c C-t s` (mnemonic: section).
307 ;; If the point is at a header, these commands will replace the
308 ;; existing markup in order to update the level and/or type of the
309 ;; header. To remove the markup of the header at the point, press
312 ;; * Footnotes: `C-c C-f`
314 ;; To create a new footnote at the point, press `C-c C-f n`.
315 ;; Press `C-c C-f g` with the point at a footnote to jump to the
316 ;; location where the footnote text is defined. Then, press
317 ;; `C-c C-f b` to return to the footnote marker in the main text.
318 ;; When the point is at a footnote marker or in the body of a
319 ;; footnote, press `C-c C-f k` to kill the footnote and add the
320 ;; text to the kill ring.
324 ;; `C-c -` inserts a horizontal rule. By default, insert the
325 ;; first string in the list `markdown-hr-strings' (the most
326 ;; prominent rule). With a `C-u` prefix, insert the last string.
327 ;; With a numeric prefix `N`, insert the string in position `N`
328 ;; (counting from 1).
330 ;; * Following Links:
332 ;; Press `C-c C-o` when the point is on an inline or reference
333 ;; link to open the URL in a browser. When the point is at a
334 ;; wiki link, open it in another buffer (in the current window,
335 ;; or in the other window with the `C-u` prefix).
336 ;; To move between links, use `M-p` and `M-n` to quickly jump
337 ;; to the previous or next link of any type.
341 ;; Use `C-c C-j` to jump from the object at point to its counterpart
342 ;; elsewhere in the text, when possible. Jumps between reference
343 ;; links and definitions; between footnote markers and footnote
344 ;; text. If more than one link uses the same reference name, a
345 ;; new buffer will be created containing clickable buttons for jumping
346 ;; to each link. You may press `TAB` or `S-TAB` to jump between
347 ;; buttons in this window.
349 ;; * Killing Elements:
351 ;; Press `C-c C-k` to kill the thing at point and add important
352 ;; text, without markup, to the kill ring. Possible things to
353 ;; kill include (roughly in order of precedece): inline code,
354 ;; headers, horizonal rules, links (add link text to kill ring),
355 ;; images (add alt text to kill ring), angle URIs, email
356 ;; addresses, bold, italics, reference definitions (add URI to
357 ;; kill ring), footnote markers and text (kill both marker and
358 ;; text, add text to kill ring), and list items.
360 ;; * Outline Navigation:
362 ;; Navigation between headings is possible using `outline-mode'.
363 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
364 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
365 ;; next and previous visible headings at the same level as the one
366 ;; at the point. Finally, `C-M-u` will move up to a lower-level
367 ;; (more inclusive) visible heading.
369 ;; * Movement by Block:
371 ;; markdown-mode supports the usual Emacs paragraph movement with
372 ;; `M-{` and `M-}`. These commands treat list items as
373 ;; paragraphs, so they will stop at each line within a block of
374 ;; list items. Additionally, markdown-mode includes movement
375 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
376 ;; of an entire block of text (with blocks being separated by at
377 ;; least one blank line).
379 ;; * Movement by Defun:
381 ;; The usual Emacs commands can be used to move by defuns
382 ;; (top-level major definitions). In markdown-mode, a defun
383 ;; is a section. As usual, `C-M-a` will move the point to
384 ;; the beginning of the current or preceding defun, `C-M-e`
385 ;; will move to the end of the current or following defun,
386 ;; and `C-M-h` will put the region around the entire defun.
388 ;; Many of the commands described above behave differently depending on
389 ;; whether Transient Mark mode is enabled or not. When it makes sense,
390 ;; if Transient Mark mode is on and a region is active, the command
391 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
392 ;; bold). For users who prefer to work outside of Transient Mark mode,
393 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
395 ;; When applicable, commands that specifically act on the region even
396 ;; outside of Transient Mark mode have the same keybinding as the with
397 ;; the exception of an additional `C-` prefix. For example,
398 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
399 ;; the region in Transient Mark mode while `markdown-blockquote-region'
400 ;; is bound to `C-c C-s C-b` and always applies to the region (when
403 ;; Note that these region-specific functions are useful in many
404 ;; cases where it may not be obvious. For example, yanking text from
405 ;; the kill ring sets the mark at the beginning of the yanked text
406 ;; and moves the point to the end. Therefore, the (inactive) region
407 ;; contains the yanked text. So, `C-y` then `C-c C-s C-b` will yank
408 ;; text and make it a blockquote.
410 ;; markdown-mode attempts to be flexible in how it handles
411 ;; indentation. When you press `TAB` repeatedly, the point will cycle
412 ;; through several possible indentation levels corresponding to things
413 ;; you might have in mind when you press `RET` at the end of a line or
414 ;; `TAB`. For example, you may want to start a new list item,
415 ;; continue a list item with hanging indentation, indent for a nested
416 ;; pre block, and so on.
418 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
419 ;; visibility cycling for atx- or hash-style headers. There are two
420 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
421 ;; the table of contents view (headers only), outline view (top-level
422 ;; headers only), and the full document view. Pressing `TAB` while the
423 ;; point is at a header will cycle through levels of visibility for the
424 ;; subtree: completely folded, visible children, and fully visible.
425 ;; Note that mixing hash and underline style headers will give undesired
430 ;; Besides supporting the basic Markdown syntax, markdown-mode also
431 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
432 ;; links may be followed automatically by pressing the enter key when
433 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
434 ;; auto-following on enter key may be controlled with the
435 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
436 ;; `M-n` to quickly jump to the previous and next wiki links,
437 ;; respectively. Aliased or piped wiki links of the form
438 ;; `[[link text|PageName]]` are also supported. Since some wikis
439 ;; reverse these components, set `markdown-wiki-link-alias-first'
440 ;; to nil to treat them as `[[PageName|link text]]`.
442 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
443 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
444 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
445 ;; You can do this either by using `M-x customize-group markdown`
446 ;; or by placing the following in your `.emacs` file:
448 ;; (defun markdown-custom ()
449 ;; "markdown-mode-hook"
450 ;; (setq markdown-command "markdown | smartypants"))
451 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
453 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
455 ;; Syntax highlighting for mathematical expressions written
456 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
457 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
458 ;; either via customize or by placing `(setq markdown-enable-math t)`
459 ;; in `.emacs`, and then restarting Emacs or calling
460 ;; `markdown-reload-extensions'.
462 ;;; GitHub Flavored Markdown:
464 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
465 ;; available. The GitHub implementation of differs slightly from
466 ;; standard Markdown. The most important differences are that
467 ;; newlines are significant, triggering hard line breaks, and that
468 ;; underscores inside of words (e.g., variable names) need not be
469 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
470 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
471 ;; not available). Underscores inside of words (such as
472 ;; test_variable) will not trigger emphasis.
474 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
475 ;; replacing spaces in filenames and where the first letter of the
476 ;; filename capitalized. For example, `[[wiki link]]' will map to a
477 ;; file named `Wiki-link` with the same extension as the current file.
479 ;; GFM code blocks, with optional programming language keywords, will
480 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
481 ;; is an active region, the text in the region will be placed inside
482 ;; the code block. You will be prompted for the name of the language,
483 ;; but may press enter to continue without naming a language.
485 ;; For a more complete GitHub-flavored markdown experience, consider
486 ;; adding README.md to your `auto-mode-alist':
488 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
490 ;; For GFM preview can be powered by setting `markdown-command' to
491 ;; use [Docter][]. This may also be configured to work with [Marked][]
492 ;; for `markdown-open-command'.
494 ;; [GFM]: http://github.github.com/github-flavored-markdown/
495 ;; [Docter]: https://github.com/alampros/Docter
499 ;; markdown-mode has benefited greatly from the efforts of the
502 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
503 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
504 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
505 ;; GitHub Flavored Markdown mode (`gfm-mode').
506 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
507 ;; `markdown' with an active region.
508 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
509 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
510 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
511 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
512 ;; visibility cycling functionality was derived, and for a bug fix
513 ;; related to `orgtbl-mode'.
514 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
515 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
516 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
517 ;; compatibility and custom CSS.
518 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
519 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
520 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
521 ;; comment matching functions were derived.
522 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
523 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
524 ;; functions, bug reports regarding indentation, and
525 ;; fixes for byte-compilation warnings.
526 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
528 ;; * George Ogata <george.ogata@gmail.com> for fixing several
529 ;; byte-compilation warnings.
530 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
531 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
532 ;; customizations and XHTML export.
533 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
534 ;; Markdown processors which do not accept input from stdin.
535 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
536 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
537 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
538 ;; substitution character for mapping wiki links to filenames.
539 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
540 ;; escape shell commands.
541 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
542 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
543 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
544 ;; Emacs Lisp coding conventions.
545 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
546 ;; regexp, refactoring the compilation and preview functions,
547 ;; heading font-lock generalizations, list renumbering,
548 ;; and kill ring save.
549 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
550 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
551 ;; for an autoload token for `gfm-mode'.
552 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
553 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
554 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
555 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
556 ;; declaration in XHTML output.
557 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
558 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
559 ;; and GFM code block insertion.
560 ;; * Peter Jones <pjones@pmade.com> for link following functions.
561 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
562 ;; externally modified files.
563 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
564 ;; related to `orgtbl-mode'.
565 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
566 ;; export hooks and unit test improvements.
567 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
568 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
573 ;; Although markdown-mode is developed and tested primarily using
574 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
577 ;; If you find any bugs in markdown-mode, please construct a test case
578 ;; or a patch and email me at <jrblevin@sdf.org>.
582 ;; markdown-mode was written and is maintained by Jason Blevins. The
583 ;; first version was released on May 24, 2007.
585 ;; * 2007-05-24: Version 1.1
586 ;; * 2007-05-25: Version 1.2
587 ;; * 2007-06-05: [Version 1.3][]
588 ;; * 2007-06-29: Version 1.4
589 ;; * 2007-10-11: [Version 1.5][]
590 ;; * 2008-06-04: [Version 1.6][]
591 ;; * 2009-10-01: [Version 1.7][]
592 ;; * 2011-08-12: [Version 1.8][]
593 ;; * 2011-08-15: [Version 1.8.1][]
594 ;; * 2013-01-25: [Version 1.9][]
596 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
597 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
598 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
599 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
600 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
601 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
602 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
609 (eval-when-compile (require 'cl
))
612 ;;; Constants =================================================================
614 (defconst markdown-mode-version
"2.0-pre"
615 "Markdown mode version number.")
617 (defconst markdown-output-buffer-name
"*markdown-output*"
618 "Name of temporary buffer for markdown command output.")
621 ;;; Global Variables ==========================================================
623 (defvar markdown-reference-label-history nil
624 "History of used reference labels.")
627 ;;; Customizable Variables ====================================================
629 (defvar markdown-mode-hook nil
630 "Hook run when entering Markdown mode.")
632 (defvar markdown-before-export-hooks nil
633 "Hook run before output XHTML.
634 This hook is abnormal and registered functions are given an argument that is output filename.")
636 (defvar markdown-after-export-hooks nil
637 "Hook run after output XHTML.
638 This hook is abnormal and registered functions are given an argument that is output filename.")
640 (defgroup markdown nil
641 "Major mode for editing text files in Markdown format."
644 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
646 (defcustom markdown-command
"markdown"
647 "Command to run markdown."
651 (defcustom markdown-command-needs-filename nil
652 "Set to non-nil if `markdown-command' does not accept input from stdin.
653 Instead, it will be passed a filename as the final command line
654 option. As a result, you will only be able to run Markdown from
655 buffers which are visiting a file."
659 (defcustom markdown-open-command nil
660 "Command used for opening Markdown files directly.
661 For example, a standalone Markdown previewer. This command will
662 be called with a single argument: the filename of the current
667 (defcustom markdown-hr-strings
668 '("-------------------------------------------------------------------------------"
669 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
670 "---------------------------------------"
671 "* * * * * * * * * * * * * * * * * * * *"
674 "Strings to use when inserting horizontal rules.
675 The first string in the list will be the default when inserting a
676 horizontal rule. Strings should be listed in decreasing order of
677 prominence (as in headers from level one to six) for use with
678 promotion and demotion functions."
682 (defcustom markdown-bold-underscore nil
683 "Use two underscores for bold instead of two asterisks."
687 (defcustom markdown-italic-underscore nil
688 "Use underscores for italic instead of asterisks."
692 (defcustom markdown-indent-function
'markdown-indent-line
693 "Function to use to indent."
697 (defcustom markdown-indent-on-enter t
698 "Automatically indent new lines when enter key is pressed."
702 (defcustom markdown-follow-wiki-link-on-enter t
703 "Follow wiki link at point (if any) when the enter key is pressed."
707 (defcustom markdown-wiki-link-alias-first t
708 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
709 Otherwise, they will be treated as [[PageName|alias text]]."
713 (defcustom markdown-uri-types
714 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
715 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
716 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
717 "Link types for syntax highlighting of URIs."
721 (defcustom markdown-enable-math nil
722 "Syntax highlighting for inline LaTeX and itex expressions.
723 Set this to a non-nil value to turn on math support by default.
724 Math support can be toggled later using `markdown-enable-math'
725 or \\[markdown-enable-math]."
730 (defcustom markdown-css-path
""
731 "URL of CSS file to link to in the output XHTML."
735 (defcustom markdown-content-type
""
736 "Content type string for the http-equiv header in XHTML output.
737 When set to a non-empty string, insert the http-equiv attribute.
738 Otherwise, this attribute is omitted."
742 (defcustom markdown-coding-system nil
743 "Character set string for the http-equiv header in XHTML output.
744 Defaults to `buffer-file-coding-system' (and falling back to
745 `iso-8859-1' when not available). Common settings are `utf-8'
746 and `iso-latin-1'. Use `list-coding-systems' for more choices."
748 :type
'coding-system
)
750 (defcustom markdown-xhtml-header-content
""
751 "Additional content to include in the XHTML <head> block."
755 (defcustom markdown-xhtml-standalone-regexp
756 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
757 "Regexp indicating whether `markdown-command' output is standalone XHTML."
761 (defcustom markdown-link-space-sub-char
763 "Character to use instead of spaces when mapping wiki links to filenames."
767 (defcustom markdown-reference-location
'header
768 "Position where new reference definitions are inserted in the document."
770 :type
'(choice (const :tag
"At the end of the document" end
)
771 (const :tag
"Immediately after the current block" immediately
)
772 (const :tag
"Before next header" header
)))
774 (defcustom markdown-footnote-location
'end
775 "Position where new footnotes are inserted in the document."
777 :type
'(choice (const :tag
"At the end of the document" end
)
778 (const :tag
"Immediately after the current block" immediately
)
779 (const :tag
"Before next header" header
)))
782 ;;; Font Lock =================================================================
786 (defvar markdown-italic-face
'markdown-italic-face
787 "Face name to use for italic text.")
789 (defvar markdown-bold-face
'markdown-bold-face
790 "Face name to use for bold text.")
792 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
793 "Face name to use as a base for header delimiters.")
795 (defvar markdown-header-rule-face
'markdown-header-rule-face
796 "Face name to use as a base for header rules.")
798 (defvar markdown-header-face
'markdown-header-face
799 "Face name to use as a base for headers.")
801 (defvar markdown-header-face-1
'markdown-header-face-1
802 "Face name to use for level-1 headers.")
804 (defvar markdown-header-face-2
'markdown-header-face-2
805 "Face name to use for level-2 headers.")
807 (defvar markdown-header-face-3
'markdown-header-face-3
808 "Face name to use for level-3 headers.")
810 (defvar markdown-header-face-4
'markdown-header-face-4
811 "Face name to use for level-4 headers.")
813 (defvar markdown-header-face-5
'markdown-header-face-5
814 "Face name to use for level-5 headers.")
816 (defvar markdown-header-face-6
'markdown-header-face-6
817 "Face name to use for level-6 headers.")
819 (defvar markdown-inline-code-face
'markdown-inline-code-face
820 "Face name to use for inline code.")
822 (defvar markdown-list-face
'markdown-list-face
823 "Face name to use for list markers.")
825 (defvar markdown-blockquote-face
'markdown-blockquote-face
826 "Face name to use for blockquote.")
828 (defvar markdown-pre-face
'markdown-pre-face
829 "Face name to use for preformatted text.")
831 (defvar markdown-language-keyword-face
'markdown-language-keyword-face
832 "Face name to use for programming language identifiers.")
834 (defvar markdown-link-face
'markdown-link-face
835 "Face name to use for links.")
837 (defvar markdown-missing-link-face
'markdown-missing-link-face
838 "Face name to use for links where the linked file does not exist.")
840 (defvar markdown-reference-face
'markdown-reference-face
841 "Face name to use for reference.")
843 (defvar markdown-footnote-face
'markdown-footnote-face
844 "Face name to use for footnote identifiers.")
846 (defvar markdown-url-face
'markdown-url-face
847 "Face name to use for URLs.")
849 (defvar markdown-link-title-face
'markdown-link-title-face
850 "Face name to use for reference link titles.")
852 (defvar markdown-line-break-face
'markdown-line-break-face
853 "Face name to use for hard line breaks.")
855 (defvar markdown-comment-face
'markdown-comment-face
856 "Face name to use for HTML comments.")
858 (defvar markdown-math-face
'markdown-math-face
859 "Face name to use for LaTeX expressions.")
861 (defvar markdown-metadata-key-face
'markdown-metadata-key-face
862 "Face name to use for metadata keys.")
864 (defvar markdown-metadata-value-face
'markdown-metadata-value-face
865 "Face name to use for metadata values.")
867 (defgroup markdown-faces nil
868 "Faces used in Markdown Mode"
872 (defface markdown-italic-face
873 '((t (:inherit font-lock-variable-name-face
:slant italic
)))
874 "Face for italic text."
875 :group
'markdown-faces
)
877 (defface markdown-bold-face
878 '((t (:inherit font-lock-variable-name-face
:weight bold
)))
879 "Face for bold text."
880 :group
'markdown-faces
)
882 (defface markdown-header-rule-face
883 '((t (:inherit font-lock-function-name-face
:weight bold
)))
884 "Base face for headers rules."
885 :group
'markdown-faces
)
887 (defface markdown-header-delimiter-face
888 '((t (:inherit font-lock-function-name-face
:weight bold
)))
889 "Base face for headers hash delimiter."
890 :group
'markdown-faces
)
892 (defface markdown-header-face
893 '((t (:inherit font-lock-function-name-face
:weight bold
)))
894 "Base face for headers."
895 :group
'markdown-faces
)
897 (defface markdown-header-face-1
898 '((t (:inherit markdown-header-face
)))
899 "Face for level-1 headers."
900 :group
'markdown-faces
)
902 (defface markdown-header-face-2
903 '((t (:inherit markdown-header-face
)))
904 "Face for level-2 headers."
905 :group
'markdown-faces
)
907 (defface markdown-header-face-3
908 '((t (:inherit markdown-header-face
)))
909 "Face for level-3 headers."
910 :group
'markdown-faces
)
912 (defface markdown-header-face-4
913 '((t (:inherit markdown-header-face
)))
914 "Face for level-4 headers."
915 :group
'markdown-faces
)
917 (defface markdown-header-face-5
918 '((t (:inherit markdown-header-face
)))
919 "Face for level-5 headers."
920 :group
'markdown-faces
)
922 (defface markdown-header-face-6
923 '((t (:inherit markdown-header-face
)))
924 "Face for level-6 headers."
925 :group
'markdown-faces
)
927 (defface markdown-inline-code-face
928 '((t (:inherit font-lock-constant-face
)))
929 "Face for inline code."
930 :group
'markdown-faces
)
932 (defface markdown-list-face
933 '((t (:inherit font-lock-builtin-face
)))
934 "Face for list item markers."
935 :group
'markdown-faces
)
937 (defface markdown-blockquote-face
938 '((t (:inherit font-lock-doc-face
)))
939 "Face for blockquote sections."
940 :group
'markdown-faces
)
942 (defface markdown-pre-face
943 '((t (:inherit font-lock-constant-face
)))
944 "Face for preformatted text."
945 :group
'markdown-faces
)
947 (defface markdown-language-keyword-face
948 '((t (:inherit font-lock-type-face
)))
949 "Face for programming language identifiers."
950 :group
'markdown-faces
)
952 (defface markdown-link-face
953 '((t (:inherit font-lock-keyword-face
)))
955 :group
'markdown-faces
)
957 (defface markdown-missing-link-face
958 '((t (:inherit font-lock-warning-face
)))
959 "Face for missing links."
960 :group
'markdown-faces
)
962 (defface markdown-reference-face
963 '((t (:inherit font-lock-type-face
)))
964 "Face for link references."
965 :group
'markdown-faces
)
967 (defface markdown-footnote-face
968 '((t (:inherit font-lock-keyword-face
)))
969 "Face for footnote markers."
970 :group
'markdown-faces
)
972 (defface markdown-url-face
973 '((t (:inherit font-lock-string-face
)))
975 :group
'markdown-faces
)
977 (defface markdown-link-title-face
978 '((t (:inherit font-lock-comment-face
)))
979 "Face for reference link titles."
980 :group
'markdown-faces
)
982 (defface markdown-line-break-face
983 '((t (:inherit font-lock-constant-face
:underline t
)))
984 "Face for hard line breaks."
985 :group
'markdown-faces
)
987 (defface markdown-comment-face
988 '((t (:inherit font-lock-comment-face
)))
989 "Face for HTML comments."
990 :group
'markdown-faces
)
992 (defface markdown-math-face
993 '((t (:inherit font-lock-string-face
)))
994 "Face for LaTeX expressions."
995 :group
'markdown-faces
)
997 (defface markdown-metadata-key-face
998 '((t (:inherit font-lock-variable-name-face
)))
999 "Face for metadata keys."
1000 :group
'markdown-faces
)
1002 (defface markdown-metadata-value-face
1003 '((t (:inherit font-lock-string-face
)))
1004 "Face for metadata values."
1005 :group
'markdown-faces
)
1007 (defconst markdown-regex-link-inline
1008 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
1009 "Regular expression for a [text](file) or an image link ![text](file).
1010 Group 1 matches the leading exclamation point, if any.
1011 Group 2 matchs the entire square bracket term, including the text.
1012 Group 3 matches the text inside the square brackets.
1013 Group 4 matches the entire parenthesis term, including the URL and title.
1014 Group 5 matches the URL.
1015 Group 6 matches (optional) title.")
1017 (defconst markdown-regex-link-reference
1018 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
1019 "Regular expression for a reference link [text][id].
1020 Group 1 matches the leading exclamation point, if any.
1021 Group 2 matchs the entire first square bracket term, including the text.
1022 Group 3 matches the text inside the square brackets.
1023 Group 4 matches the entire second square bracket term.
1024 Group 5 matches the reference label.")
1026 (defconst markdown-regex-reference-definition
1027 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1028 "Regular expression for a link definition [id]: ...")
1030 (defconst markdown-regex-footnote
1031 "\\(\\[\\^.+?\\]\\)"
1032 "Regular expression for a footnote marker [^fn].")
1034 (defconst markdown-regex-header
1035 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1036 "Regexp identifying Markdown headers.")
1038 (defconst markdown-regex-header-1-atx
1039 "^\\(#\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1040 "Regular expression for level 1 atx-style (hash mark) headers.")
1042 (defconst markdown-regex-header-2-atx
1043 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1044 "Regular expression for level 2 atx-style (hash mark) headers.")
1046 (defconst markdown-regex-header-3-atx
1047 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1048 "Regular expression for level 3 atx-style (hash mark) headers.")
1050 (defconst markdown-regex-header-4-atx
1051 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1052 "Regular expression for level 4 atx-style (hash mark) headers.")
1054 (defconst markdown-regex-header-5-atx
1055 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1056 "Regular expression for level 5 atx-style (hash mark) headers.")
1058 (defconst markdown-regex-header-6-atx
1059 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1060 "Regular expression for level 6 atx-style (hash mark) headers.")
1062 (defconst markdown-regex-header-1-setext
1063 "^\\(.*\\)\n\\(=+\\)$"
1064 "Regular expression for level 1 setext-style (underline) headers.")
1066 (defconst markdown-regex-header-2-setext
1067 "^\\(.*\\)\n\\(-+\\)$"
1068 "Regular expression for level 2 setext-style (underline) headers.")
1070 (defconst markdown-regex-header-setext
1071 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1072 "Regular expression for generic setext-style (underline) headers.")
1074 (defconst markdown-regex-header-atx
1075 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1076 "Regular expression for generic atx-style (hash mark) headers.")
1078 (defconst markdown-regex-hr
1079 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1080 "Regular expression for matching Markdown horizontal rules.")
1082 (defconst markdown-regex-code
1083 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1084 "Regular expression for matching inline code fragments.
1086 The first group ensures that the leading backquote character
1087 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1088 character, including newlines, but not two newlines in a row.
1089 The final group requires that the character following the code
1090 fragment is not a backquote.")
1092 (defconst markdown-regex-pre
1094 "Regular expression for matching preformatted text sections.")
1096 (defconst markdown-regex-list
1097 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1098 "Regular expression for matching list items.")
1100 (defconst markdown-regex-bold
1101 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1102 "Regular expression for matching bold text.
1103 Group 1 matches the character before the opening asterisk or
1104 underscore, if any, ensuring that it is not a backslash escape.
1105 Group 2 matches the entire expression, including delimiters.
1106 Groups 3 and 5 matches the opening and closing delimiters.
1107 Group 4 matches the text inside the delimiters.")
1109 (defconst markdown-regex-italic
1110 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1111 "Regular expression for matching italic text.
1112 Group 1 matches the character before the opening asterisk or
1113 underscore, if any, ensuring that it is not a backslash escape.
1114 Group 2 matches the entire expression, including delimiters.
1115 Groups 3 and 5 matches the opening and closing delimiters.
1116 Group 4 matches the text inside the delimiters.")
1118 (defconst markdown-regex-gfm-italic
1119 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1120 "Regular expression for matching italic text in GitHub-flavored Markdown.
1121 Underscores in words are not treated as special.")
1123 (defconst markdown-regex-blockquote
1125 "Regular expression for matching blockquote lines.")
1127 (defconst markdown-regex-line-break
1128 "[^ \n\t][ \t]*\\( \\)$"
1129 "Regular expression for matching line breaks.")
1131 (defconst markdown-regex-wiki-link
1132 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1133 "Regular expression for matching wiki links.
1134 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1135 wiki links of the form [[PageName|link text]]. In this regular
1136 expression, #1 matches the page name and #3 matches the link
1139 (defconst markdown-regex-uri
1140 (concat (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;() ]+")
1141 "Regular expression for matching inline URIs.")
1143 (defconst markdown-regex-angle-uri
1144 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1145 "Regular expression for matching inline URIs in angle brackets.")
1147 (defconst markdown-regex-email
1148 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1149 "Regular expression for matching inline email addresses.")
1151 (defconst markdown-regex-link-generic
1152 (concat "\\(?:" markdown-regex-wiki-link
1153 "\\|" markdown-regex-link-inline
1154 "\\|" markdown-regex-link-reference
1155 "\\|" markdown-regex-angle-uri
"\\)")
1156 "Regular expression for matching any recognized link.")
1158 (defconst markdown-regex-block-separator
1159 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1160 "Regular expression for matching block boundaries.")
1162 (defconst markdown-regex-math-inline
1163 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1164 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1166 (defconst markdown-regex-math-display
1167 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1168 "Regular expression for itex \[..\] display mode expressions.")
1170 (defconst markdown-regex-multimarkdown-metadata
1171 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1172 "Regular expression for matching MultiMarkdown metadata.")
1174 (defconst markdown-regex-pandoc-metadata
1175 "^\\(%\\)[ \t]*\\(.*\\)$"
1176 "Regular expression for matching Pandoc metadata.")
1178 (defvar markdown-mode-font-lock-keywords-basic
1180 (cons 'markdown-match-pre-blocks
'((0 markdown-pre-face
)))
1181 (cons 'markdown-match-fenced-code-blocks
'((0 markdown-pre-face
)))
1182 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
1183 (cons markdown-regex-header-1-setext
'((1 markdown-header-face-1
)
1184 (2 markdown-header-rule-face
)))
1185 (cons markdown-regex-header-2-setext
'((1 markdown-header-face-2
)
1186 (2 markdown-header-rule-face
)))
1187 (cons markdown-regex-header-6-atx
'((1 markdown-header-delimiter-face
)
1188 (2 markdown-header-face-6
)
1189 (3 markdown-header-delimiter-face
)))
1190 (cons markdown-regex-header-5-atx
'((1 markdown-header-delimiter-face
)
1191 (2 markdown-header-face-5
)
1192 (3 markdown-header-delimiter-face
)))
1193 (cons markdown-regex-header-4-atx
'((1 markdown-header-delimiter-face
)
1194 (2 markdown-header-face-4
)
1195 (3 markdown-header-delimiter-face
)))
1196 (cons markdown-regex-header-3-atx
'((1 markdown-header-delimiter-face
)
1197 (2 markdown-header-face-3
)
1198 (3 markdown-header-delimiter-face
)))
1199 (cons markdown-regex-header-2-atx
'((1 markdown-header-delimiter-face
)
1200 (2 markdown-header-face-2
)
1201 (3 markdown-header-delimiter-face
)))
1202 (cons markdown-regex-header-1-atx
'((1 markdown-header-delimiter-face
)
1203 (2 markdown-header-face-1
)
1204 (3 markdown-header-delimiter-face
)))
1205 (cons 'markdown-match-multimarkdown-metadata
'((1 markdown-metadata-key-face
)
1206 (2 markdown-metadata-value-face
)))
1207 (cons 'markdown-match-pandoc-metadata
'((1 markdown-comment-face
)
1208 (2 markdown-metadata-value-face
)))
1209 (cons markdown-regex-hr
'markdown-header-face
)
1210 (cons 'markdown-match-comments
'((0 markdown-comment-face
)))
1211 (cons 'markdown-match-code
'((0 markdown-inline-code-face
)))
1212 (cons markdown-regex-angle-uri
'markdown-link-face
)
1213 (cons markdown-regex-uri
'markdown-link-face
)
1214 (cons markdown-regex-email
'markdown-link-face
)
1215 (cons markdown-regex-list
'(2 markdown-list-face
))
1216 (cons markdown-regex-footnote
'markdown-footnote-face
)
1217 (cons markdown-regex-link-inline
'((1 markdown-link-face t t
)
1218 (2 markdown-link-face t
)
1219 (4 markdown-url-face t
)
1220 (6 markdown-link-title-face t t
)))
1221 (cons markdown-regex-link-reference
'((1 markdown-link-face t t
)
1222 (2 markdown-link-face t
)
1223 (4 markdown-reference-face t
)))
1224 (cons markdown-regex-reference-definition
'((1 markdown-reference-face t
)
1225 (2 markdown-url-face t
)
1226 (3 markdown-link-title-face t
)))
1227 (cons markdown-regex-bold
'(2 markdown-bold-face
))
1228 (cons markdown-regex-line-break
'(1 markdown-line-break-face prepend
))
1230 "Syntax highlighting for Markdown files.")
1232 (defvar markdown-mode-font-lock-keywords-core
1234 (cons markdown-regex-italic
'(2 markdown-italic-face
))
1236 "Additional syntax highlighting for Markdown files.
1237 Includes features which are overridden by some variants.")
1239 (defconst markdown-mode-font-lock-keywords-math
1241 ;; Math mode $..$ or $$..$$
1242 (cons markdown-regex-math-inline
'(2 markdown-math-face
))
1243 ;; Display mode equations with brackets: \[ \]
1244 (cons markdown-regex-math-display
'markdown-math-face
)
1245 ;; Equation reference (eq:foo)
1246 (cons "(eq:[[:alnum:]:_]+)" 'markdown-reference-face
)
1247 ;; Equation reference \eqref{foo}
1248 (cons "\\\\eqref{[[:alnum:]:_]+}" 'markdown-reference-face
))
1249 "Syntax highlighting for LaTeX and itex fragments.")
1251 (defvar markdown-mode-font-lock-keywords nil
1252 "Default highlighting expressions for Markdown mode.
1253 This variable is defined as a buffer-local variable for dynamic
1254 extension support.")
1257 (defvar markdown-footnote-counter
0
1258 "Counter for footnote numbers.")
1259 (make-variable-buffer-local 'markdown-footnote-counter
)
1261 (defconst markdown-footnote-chars
1263 "Regular expression maching any character that is allowed in a footnote identifier.")
1266 ;;; Compatibility =============================================================
1268 (defun markdown-replace-regexp-in-string (regexp rep string
)
1269 "Replace ocurrences of REGEXP with REP in STRING.
1270 This is a compatibility wrapper to provide `replace-regexp-in-string'
1272 (if (featurep 'xemacs
)
1273 (replace-in-string string regexp rep
)
1274 (replace-regexp-in-string regexp rep string
)))
1276 ;; `markdown-use-region-p' is a compatibility function which checks
1277 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1280 ;; Emacs 23 and newer
1281 ((fboundp 'use-region-p
)
1282 (defalias 'markdown-use-region-p
'use-region-p
))
1284 ((and (boundp 'transient-mark-mode
) (boundp 'mark-active
))
1285 (defun markdown-use-region-p ()
1286 "Compatibility wrapper to provide `use-region-p'."
1287 (and transient-mark-mode mark-active
)))
1289 ((fboundp 'region-active-p
)
1290 (defalias 'markdown-use-region-p
'region-active-p
))))
1292 (defun markdown-use-buttons-p ()
1293 "Determine whether this Emacs supports buttons."
1294 (or (featurep 'button
) (locate-library "button")))
1297 ;;; Markdown Parsing Functions ================================================
1299 (defun markdown-cur-line-blank-p ()
1300 "Return t if the current line is blank and nil otherwise."
1303 (re-search-forward "^\\s *$" (line-end-position) t
)))
1305 (defun markdown-prev-line-blank-p ()
1306 "Return t if the previous line is blank and nil otherwise.
1307 If we are at the first line, then consider the previous line to be blank."
1308 (or (= (line-beginning-position) (point-min))
1311 (markdown-cur-line-blank-p))))
1313 (defun markdown-next-line-blank-p ()
1314 "Return t if the next line is blank and nil otherwise.
1315 If we are at the last line, then consider the next line to be blank."
1316 (or (= (line-end-position) (point-max))
1319 (markdown-cur-line-blank-p))))
1321 (defun markdown-prev-line-indent-p ()
1322 "Return t if the previous line is indented and nil otherwise."
1325 (goto-char (line-beginning-position))
1326 (if (re-search-forward "^\\s " (line-end-position) t
) t
)))
1328 (defun markdown-cur-line-indent ()
1329 "Return the number of leading whitespace characters in the current line."
1332 (goto-char (line-beginning-position))
1333 (re-search-forward "^[ \t]+" (line-end-position) t
)
1336 (defun markdown-prev-line-indent ()
1337 "Return the number of leading whitespace characters in the previous line."
1340 (markdown-cur-line-indent)))
1342 (defun markdown-next-line-indent ()
1343 "Return the number of leading whitespace characters in the next line."
1346 (markdown-cur-line-indent)))
1348 (defun markdown-cur-non-list-indent ()
1349 "Return beginning position of list item text (not including the list marker).
1350 Return nil if the current line is not the beginning of a list item."
1354 (when (re-search-forward markdown-regex-list
(line-end-position) t
)
1355 (current-column)))))
1357 (defun markdown-prev-non-list-indent ()
1358 "Return position of the first non-list-marker on the previous line."
1361 (markdown-cur-non-list-indent)))
1363 (defun markdown-new-baseline-p ()
1364 "Determine if the current line begins a new baseline level."
1368 (or (looking-at markdown-regex-header
)
1369 (looking-at markdown-regex-hr
)
1370 (and (null (markdown-cur-non-list-indent))
1371 (= (markdown-cur-line-indent) 0)
1372 (markdown-prev-line-blank-p))))))
1374 (defun markdown-search-backward-baseline ()
1375 "Search backward baseline point with no indentation and not a list item."
1378 (while (not (or stop
(bobp)))
1379 (re-search-backward markdown-regex-block-separator nil t
)
1381 (goto-char (match-end 2))
1383 ((markdown-new-baseline-p)
1385 ((looking-at markdown-regex-list
)
1387 (t (setq stop t
)))))))
1389 (defun markdown-update-list-levels (marker indent levels
)
1390 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1391 Here, MARKER is a string representing the type of list, INDENT is an integer
1392 giving the indentation, in spaces, of the current block, and LEVELS is a
1393 list of the indentation levels of parent list items. When LEVELS is nil,
1394 it means we are at baseline (not inside of a nested list)."
1396 ;; New list item at baseline.
1397 ((and marker
(null levels
))
1398 (setq levels
(list indent
)))
1399 ;; List item with greater indentation (four or more spaces).
1400 ;; Increase list level.
1401 ((and marker
(>= indent
(+ (car levels
) 4)))
1402 (setq levels
(cons indent levels
)))
1403 ;; List item with greater or equal indentation (less than four spaces).
1404 ;; Do not increase list level.
1405 ((and marker
(>= indent
(car levels
)))
1407 ;; Lesser indentation level.
1408 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1409 ;; indentation could move back more than one list level). Note
1410 ;; that this block need not be the beginning of list item.
1411 ((< indent
(car levels
))
1412 (while (and (> (length levels
) 1)
1413 (< indent
(+ (cadr levels
) 4)))
1414 (setq levels
(cdr levels
)))
1416 ;; Otherwise, do nothing.
1419 (defun markdown-calculate-list-levels ()
1420 "Calculate list levels at point.
1421 Return a list of the form (n1 n2 n3 ...) where n1 is the
1422 indentation of the deepest nested list item in the branch of
1423 the list at the point, n2 is the indentation of the parent
1424 list item, and so on. The depth of the list item is therefore
1425 the length of the returned list. If the point is not at or
1426 immediately after a list item, return nil."
1428 (let ((first (point)) levels indent pre-regexp
)
1429 ;; Find a baseline point with zero list indentation
1430 (markdown-search-backward-baseline)
1431 ;; Search for all list items between baseline and LOC
1432 (while (and (< (point) first
)
1433 (re-search-forward markdown-regex-list first t
))
1434 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
1437 ;; Make sure this is not a header or hr
1438 ((markdown-new-baseline-p) (setq levels nil
))
1439 ;; Make sure this is not a line from a pre block
1440 ((looking-at pre-regexp
))
1441 ;; If not, then update levels
1443 (setq indent
(markdown-cur-line-indent))
1444 (setq levels
(markdown-update-list-levels (match-string 2)
1449 (defun markdown-prev-list-item (level)
1450 "Search backward from point for a list item with indentation LEVEL.
1451 Set point to the beginning of the item, and return point, or nil
1453 (let (bounds indent prev
)
1456 (setq indent
(markdown-cur-line-indent))
1459 ;; Stop at beginning of buffer
1460 ((bobp) (setq prev nil
))
1461 ;; Continue if current line is blank
1462 ((markdown-cur-line-blank-p) t
)
1464 ((and (looking-at markdown-regex-list
)
1465 (setq bounds
(markdown-cur-list-item-bounds)))
1467 ;; Continue at item with greater indentation
1468 ((> (nth 3 bounds
) level
) t
)
1469 ;; Stop and return point at item of equal indentation
1470 ((= (nth 3 bounds
) level
)
1473 ;; Stop and return nil at item with lesser indentation
1474 ((< (nth 3 bounds
) level
)
1477 ;; Continue while indentation is the same or greater
1478 ((>= indent level
) t
)
1479 ;; Stop if current indentation is less than list item
1480 ;; and the next is blank
1481 ((and (< indent level
)
1482 (markdown-next-line-blank-p))
1485 ((looking-at markdown-regex-header
) (setq prev nil
))
1486 ;; Stop at a horizontal rule
1487 ((looking-at markdown-regex-hr
) (setq prev nil
))
1488 ;; Otherwise, continue.
1491 (setq indent
(markdown-cur-line-indent)))
1494 (defun markdown-next-list-item (level)
1495 "Search forward from point for the next list item with indentation LEVEL.
1496 Set point to the beginning of the item, and return point, or nil
1498 (let (bounds indent prev next
)
1501 (setq indent
(markdown-cur-line-indent))
1504 ;; Stop at end of the buffer.
1505 ((eobp) (setq prev nil
))
1506 ;; Continue if the current line is blank
1507 ((markdown-cur-line-blank-p) t
)
1509 ((and (looking-at markdown-regex-list
)
1510 (setq bounds
(markdown-cur-list-item-bounds)))
1512 ;; Continue at item with greater indentation
1513 ((> (nth 3 bounds
) level
) t
)
1514 ;; Stop and return point at item of equal indentation
1515 ((= (nth 3 bounds
) level
)
1518 ;; Stop and return nil at item with lesser indentation
1519 ((< (nth 3 bounds
) level
)
1522 ;; Continue while indentation is the same or greater
1523 ((>= indent level
) t
)
1524 ;; Stop if current indentation is less than list item
1525 ;; and the previous line was blank.
1526 ((and (< indent level
)
1527 (markdown-prev-line-blank-p))
1530 ((looking-at markdown-regex-header
) (setq next nil
))
1531 ;; Stop at a horizontal rule
1532 ((looking-at markdown-regex-hr
) (setq next nil
))
1533 ;; Otherwise, continue.
1536 (setq indent
(markdown-cur-line-indent)))
1539 (defun markdown-cur-list-item-end (level)
1540 "Move to the end of the current list item with nonlist indentation LEVEL.
1541 If the point is not in a list item, do nothing."
1544 (setq indent
(markdown-cur-line-indent))
1547 ;; Stop at end of the buffer.
1549 ;; Continue if the current line is blank
1550 ((markdown-cur-line-blank-p) t
)
1551 ;; Continue while indentation is the same or greater
1552 ((>= indent level
) t
)
1553 ;; Stop if current indentation is less than list item
1554 ;; and the previous line was blank.
1555 ((and (< indent level
)
1556 (markdown-prev-line-blank-p))
1558 ;; Stop at a new list item of the same or lesser indentation
1559 ((looking-at markdown-regex-list
) nil
)
1561 ((looking-at markdown-regex-header
) nil
)
1562 ;; Stop at a horizontal rule
1563 ((looking-at markdown-regex-hr
) nil
)
1564 ;; Otherwise, continue.
1567 (setq indent
(markdown-cur-line-indent)))
1568 ;; Don't skip over whitespace for empty list items (marker and
1569 ;; whitespace only), just move to end of whitespace.
1570 (if (looking-back (concat markdown-regex-list
"\\s-*"))
1571 (goto-char (match-end 3))
1572 (skip-syntax-backward "-"))))
1574 (defun markdown-cur-list-item-bounds ()
1575 "Return bounds and indentation of the current list item.
1576 Return a list of the form (begin end indent nonlist-indent marker).
1577 If the point is not inside a list item, return nil.
1578 Leave match data intact for `markdown-regex-list'."
1579 (let (cur prev-begin prev-end indent nonlist-indent marker
)
1580 ;; Store current location
1582 ;; Verify that cur is between beginning and end of item
1585 (when (re-search-backward markdown-regex-list nil t
)
1586 (setq prev-begin
(match-beginning 0))
1587 (setq indent
(length (match-string 1)))
1588 (setq nonlist-indent
(length (match-string 0)))
1589 (setq marker
(concat (match-string 2) (match-string 3)))
1591 (markdown-cur-list-item-end nonlist-indent
)
1592 (setq prev-end
(point)))
1593 (when (and (>= cur prev-begin
)
1596 (list prev-begin prev-end indent nonlist-indent marker
))))))
1598 (defun markdown-bounds-of-thing-at-point (thing)
1599 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1600 Does not include trailing newlines when THING is 'line. Handles the
1601 end of buffer case by setting both endpoints equal to the value of
1602 `point-max', since an empty region will trigger empty markup insertion.
1603 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1604 (let* ((bounds (bounds-of-thing-at-point thing
))
1608 (when (eq thing
'line
)
1609 (cond ((and (eobp) (markdown-cur-line-blank-p))
1611 ((char-equal (char-before b
) ?\^J
)
1615 (defun markdown-reference-definition (reference)
1616 "Find out whether Markdown REFERENCE is defined.
1617 REFERENCE should include the square brackets, like [this].
1618 When REFERENCE is defined, return a list of the form (text start end)
1619 containing the definition text itself followed by the start and end
1620 locations of the text. Otherwise, return nil.
1621 Leave match data for `markdown-regex-reference-definition'
1622 intact additional processing."
1623 (let ((reference (downcase reference
)))
1625 (goto-char (point-min))
1627 (while (re-search-forward markdown-regex-reference-definition nil t
)
1628 (when (string= reference
(downcase (match-string-no-properties 1)))
1630 (list (match-string-no-properties 2)
1631 (match-beginning 2) (match-end 2)))))))))
1633 (defun markdown-get-defined-references ()
1634 "Return a list of all defined reference labels (including square brackets)."
1636 (goto-char (point-min))
1638 (while (re-search-forward markdown-regex-reference-definition nil t
)
1639 (let ((target (match-string-no-properties 1)))
1640 (add-to-list 'refs target t
)))
1644 ;;; Markdown Font Lock Matching Functions =====================================
1646 (defun markdown-match-comments (last)
1647 "Match HTML comments from the point to LAST."
1648 (cond ((search-forward "<!--" last t
)
1650 (let ((beg (point)))
1651 (cond ((search-forward-regexp "--[ \t]*>" last t
)
1652 (set-match-data (list beg
(point)))
1657 (defun markdown-match-code (last)
1658 "Match inline code from the point to LAST."
1661 (cond ((re-search-forward markdown-regex-code last t
)
1662 (set-match-data (list (match-beginning 2) (match-end 2)))
1663 (goto-char (match-end 0))
1665 (t (forward-char 2) nil
)))
1667 (defun markdown-match-pre-blocks (last)
1668 "Match Markdown pre blocks from point to LAST."
1669 (let ((levels (markdown-calculate-list-levels))
1670 indent pre-regexp end-regexp begin end stop
)
1671 (while (and (< (point) last
) (not end
))
1672 ;; Search for a region with sufficient indentation
1675 (setq indent
(1+ (length levels
))))
1676 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1677 (setq end-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1680 ;; If not at the beginning of a line, move forward
1681 ((not (bolp)) (forward-line))
1682 ;; Move past blank lines
1683 ((markdown-cur-line-blank-p) (forward-line))
1684 ;; At headers and horizontal rules, reset levels
1685 ((markdown-new-baseline-p) (forward-line) (setq levels nil
))
1686 ;; If the current line has sufficient indentation, mark out pre block
1687 ((looking-at pre-regexp
)
1688 (setq begin
(match-beginning 0))
1689 (while (and (or (looking-at pre-regexp
) (markdown-cur-line-blank-p))
1693 ;; If current line has a list marker, update levels, move to end of block
1694 ((looking-at markdown-regex-list
)
1695 (setq levels
(markdown-update-list-levels
1696 (match-string 2) (markdown-cur-line-indent) levels
))
1697 (markdown-end-of-block-element))
1698 ;; If this is the end of the indentation level, adjust levels accordingly.
1699 ;; Only match end of indentation level if levels is not the empty list.
1700 ((and (car levels
) (looking-at end-regexp
))
1701 (setq levels
(markdown-update-list-levels
1702 nil
(markdown-cur-line-indent) levels
))
1703 (markdown-end-of-block-element))
1704 (t (markdown-end-of-block-element))))
1706 (if (not (and begin end
))
1707 ;; Return nil if no pre block was found
1709 ;; Set match data and return t upon success
1710 (set-match-data (list begin end
))
1713 (defun markdown-match-fenced-code-blocks (last)
1714 "Match fenced code blocks from the point to LAST."
1715 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t
)
1717 (let ((beg (point)))
1719 (cond ((search-forward-regexp
1720 (concat "^" (match-string 1) "~*") last t
)
1721 (set-match-data (list beg
(point)))
1726 (defun markdown-match-gfm-code-blocks (last)
1727 "Match GFM quoted code blocks from point to LAST."
1728 (let (open lang body close all
)
1729 (cond ((and (eq major-mode
'gfm-mode
)
1730 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t
))
1732 (setq open
(list (match-beginning 1) (match-end 1))
1733 lang
(list (match-beginning 2) (match-end 2)))
1735 (setq body
(list (point)))
1736 (cond ((search-forward-regexp "^```$" last t
)
1737 (setq body
(reverse (cons (1- (match-beginning 0)) body
))
1738 close
(list (match-beginning 0) (match-end 0))
1739 all
(list (car open
) (match-end 0)))
1740 (set-match-data (append all open lang body close
))
1745 (defun markdown-match-generic-metadata (regexp last
)
1746 "Match generic metadata specified by REGEXP from the point to LAST."
1747 (let ((header-end (save-excursion
1748 (goto-char (point-min))
1749 (if (re-search-forward "\n\n" (point-max) t
)
1752 (cond ((>= (point) header-end
)
1753 ;; Don't match anything outside of the header.
1755 ((re-search-forward regexp
(min last header-end
) t
)
1756 ;; If a metadata item is found, it may span several lines.
1757 (let ((key-beginning (match-beginning 1))
1758 (key-end (match-end 1))
1759 (value-beginning (match-beginning 2)))
1760 (while (and (not (looking-at regexp
))
1761 (not (> (point) (min last header-end
)))
1767 (set-match-data (list key-beginning
(point) ; complete metadata
1768 key-beginning key-end
; key
1769 value-beginning
(point))) ; value
1773 (defun markdown-match-multimarkdown-metadata (last)
1774 "Match MultiMarkdown metadata from the point to LAST."
1775 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last
))
1777 (defun markdown-match-pandoc-metadata (last)
1778 "Match Pandoc metadata from the point to LAST."
1779 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
1781 (defun markdown-font-lock-extend-region ()
1782 "Extend the search region to include an entire block of text.
1783 This helps improve font locking for block constructs such as pre blocks."
1784 ;; Avoid compiler warnings about these global variables from font-lock.el.
1785 ;; See the documentation for variable `font-lock-extend-region-functions'.
1786 (eval-when-compile (defvar font-lock-beg
) (defvar font-lock-end
))
1788 (goto-char font-lock-beg
)
1789 (let ((found (or (re-search-backward "\n\n" nil t
) (point-min))))
1790 (goto-char font-lock-end
)
1791 (when (re-search-forward "\n\n" nil t
)
1793 (setq font-lock-end
(point)))
1794 (setq font-lock-beg found
))))
1797 ;;; Syntax Table ==============================================================
1799 (defvar markdown-mode-syntax-table
1800 (let ((tab (make-syntax-table text-mode-syntax-table
)))
1801 (modify-syntax-entry ?
\" "." tab
)
1803 "Syntax table for `markdown-mode'.")
1806 ;;; Element Insertion =========================================================
1808 (defun markdown-ensure-blank-line-before ()
1809 "If previous line is not already blank, insert a blank line before point."
1810 (unless (bolp) (insert "\n"))
1811 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1813 (defun markdown-ensure-blank-line-after ()
1814 "If following line is not already blank, insert a blank line after point.
1815 Return the point where it was originally."
1817 (unless (eolp) (insert "\n"))
1818 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1820 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
1821 "Insert the strings S1 and S2, wrapping around region or THING.
1822 If a region is specified by the optional BEG and END arguments,
1823 wrap the strings S1 and S2 around that region.
1824 If there is an active region, wrap the strings S1 and S2 around
1825 the region. If there is not an active region but the point is at
1826 THING, wrap that thing (which defaults to word). Otherwise, just
1827 insert S1 and S2 and place the cursor in between. Return the
1828 bounds of the entire wrapped string, or nil if nothing was wrapped
1829 and S1 and S2 were only inserted."
1830 (let (a b bounds new-point
)
1836 new-point
(+ (point) (length s1
))))
1838 ((markdown-use-region-p)
1839 (setq a
(region-beginning)
1841 new-point
(+ (point) (length s1
))))
1842 ;; Thing (word) at point
1843 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
1844 (setq a
(car bounds
)
1846 new-point
(+ (point) (length s1
))))
1847 ;; No active region and no word
1855 (when new-point
(goto-char new-point
))
1858 (setq b
(+ b
(length s1
) (length s2
)))
1861 (defun markdown-point-after-unwrap (cur prefix suffix
)
1862 "Return desired position of point after an unwrapping operation.
1863 CUR gives the position of the point before the operation.
1864 Additionally, two cons cells must be provided. PREFIX gives the
1865 bounds of the prefix string and SUFFIX gives the bounds of the
1867 (cond ((< cur
(cdr prefix
)) (car prefix
))
1868 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
1869 ((<= cur
(cdr suffix
))
1870 (- cur
(+ (- (cdr prefix
) (car prefix
))
1871 (- cur
(car suffix
)))))
1874 (defun markdown-unwrap-thing-at-point (regexp all text
)
1875 "Remove prefix and suffix of thing at point and reposition the point.
1876 When the thing at point matches REGEXP, replace the subexpression
1877 ALL with the string in subexpression TEXT. Reposition the point
1878 in an appropriate location accounting for the removal of prefix
1879 and suffix strings. Return new bounds of string from group TEXT.
1880 When REGEXP is nil, assumes match data is already set."
1881 (when (or (null regexp
)
1882 (thing-at-point-looking-at regexp
))
1884 (prefix (cons (match-beginning all
) (match-beginning text
)))
1885 (suffix (cons (match-end text
) (match-end all
)))
1886 (bounds (cons (match-beginning text
) (match-end text
))))
1887 ;; Replace the thing at point
1888 (replace-match (match-string text
) t t nil all
)
1889 ;; Reposition the point
1890 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
1892 (setq bounds
(cons (car prefix
)
1893 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
1895 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
1896 "Remove prefix and suffix of all things in region from BEG to END.
1897 When a thing in the region matches REGEXP, replace the
1898 subexpression ALL with the string in subexpression TEXT.
1899 Return a cons cell containing updated bounds for the region."
1902 (let ((removed 0) len-all len-text
)
1903 (while (re-search-forward regexp
(- end removed
) t
)
1904 (setq len-all
(length (match-string-no-properties all
)))
1905 (setq len-text
(length (match-string-no-properties text
)))
1906 (setq removed
(+ removed
(- len-all len-text
)))
1907 (replace-match (match-string text
) t t nil all
))
1908 (cons beg
(- end removed
)))))
1910 (defun markdown-insert-hr (arg)
1911 "Insert or replace a horizonal rule.
1912 By default, use the first element of `markdown-hr-strings'. When
1913 ARG is non-nil, as when given a prefix, select a different
1914 element as follows. When prefixed with \\[universal-argument],
1915 use the last element of `markdown-hr-strings' instead. When
1916 prefixed with an integer from 1 to the length of
1917 `markdown-hr-strings', use the element in that position instead."
1919 (when (thing-at-point-looking-at markdown-regex-hr
)
1920 (delete-region (match-beginning 0) (match-end 0)))
1921 (markdown-ensure-blank-line-before)
1922 (cond ((equal arg
'(4))
1923 (insert (car (reverse markdown-hr-strings
))))
1924 ((and (integerp arg
) (> arg
0)
1925 (<= arg
(length markdown-hr-strings
)))
1926 (insert (nth (1- arg
) markdown-hr-strings
)))
1928 (insert (car markdown-hr-strings
))))
1929 (markdown-ensure-blank-line-after))
1931 (defun markdown-insert-bold ()
1932 "Insert markup to make a region or word bold.
1933 If there is an active region, make the region bold. If the point
1934 is at a non-bold word, make the word bold. If the point is at a
1935 bold word or phrase, remove the bold markup. Otherwise, simply
1936 insert bold delimiters and place the cursor in between them."
1938 (let ((delim (if markdown-bold-underscore
"__" "**")))
1939 (if (markdown-use-region-p)
1941 (let ((bounds (markdown-unwrap-things-in-region
1942 (region-beginning) (region-end)
1943 markdown-regex-bold
2 4)))
1944 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1945 ;; Bold markup removal, bold word at point, or empty markup insertion
1946 (if (thing-at-point-looking-at markdown-regex-bold
)
1947 (markdown-unwrap-thing-at-point nil
2 4)
1948 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1950 (defun markdown-insert-italic ()
1951 "Insert markup to make a region or word italic.
1952 If there is an active region, make the region italic. If the point
1953 is at a non-italic word, make the word italic. If the point is at an
1954 italic word or phrase, remove the italic markup. Otherwise, simply
1955 insert italic delimiters and place the cursor in between them."
1957 (let ((delim (if markdown-italic-underscore
"_" "*")))
1958 (if (markdown-use-region-p)
1960 (let ((bounds (markdown-unwrap-things-in-region
1961 (region-beginning) (region-end)
1962 markdown-regex-italic
2 4)))
1963 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1964 ;; Italic markup removal, italic word at point, or empty markup insertion
1965 (if (thing-at-point-looking-at markdown-regex-italic
)
1966 (markdown-unwrap-thing-at-point nil
2 4)
1967 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1969 (defun markdown-insert-code ()
1970 "Insert markup to make a region or word an inline code fragment.
1971 If there is an active region, make the region an inline code
1972 fragment. If the point is at a word, make the word an inline
1973 code fragment. Otherwise, simply insert code delimiters and
1974 place the cursor in between them."
1976 (if (markdown-use-region-p)
1978 (let ((bounds (markdown-unwrap-things-in-region
1979 (region-beginning) (region-end)
1980 markdown-regex-code
2 4)))
1981 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
1982 ;; Code markup removal, code markup for word, or empty markup insertion
1983 (if (thing-at-point-looking-at markdown-regex-code
)
1984 (markdown-unwrap-thing-at-point nil
2 4)
1985 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
1987 (defun markdown-insert-link ()
1988 "Insert an inline link, using region or word as link text if possible.
1989 If there is an active region, use the region as the link text. If the
1990 point is at a word, use the word as the link text. In these cases, the
1991 point will be left at the position for inserting a URL. If there is no
1992 active region and the point is not at word, simply insert link markup and
1993 place the point in the position to enter link text."
1995 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1997 (goto-char (- (cdr bounds
) 1)))))
1999 (defun markdown-insert-reference-link (text label
&optional url title
)
2000 "Insert a reference link and, optionally, a reference definition.
2001 The link TEXT will be inserted followed by the optional LABEL.
2002 If a URL is given, also insert a definition for the reference
2003 LABEL after the end of the paragraph. If a TITLE is given, it
2004 will be added to the end of the reference definition and will be
2005 used to populate the title attribute when converted to XHTML. If
2006 URL is nil, insert only the link portion (for example, when a
2007 reference label is already defined)."
2008 (insert (concat "[" text
"][" label
"]"))
2011 (label (if (> (length label
) 0) label text
)))
2013 ((eq markdown-reference-location
'end
) (goto-char (point-max)))
2014 ((eq markdown-reference-location
'immediately
) (markdown-end-of-block))
2015 ((eq markdown-reference-location
'header
) (markdown-end-of-defun)))
2016 (unless (markdown-cur-line-blank-p) (insert "\n"))
2017 (insert "\n[" label
"]: " url
)
2018 (unless (> (length url
) 0)
2020 (when (> (length title
) 0)
2021 (insert " \"" title
"\""))
2023 (unless (or (eobp) (looking-at "\n"))
2026 (when (> (length url
) 0)
2028 (substitute-command-keys
2029 "Defined reference [%s], press \\[markdown-jump] to jump there")
2030 (or label text
))))))
2032 (defun markdown-insert-reference-link-dwim ()
2033 "Insert a reference link of the form [text][label] at point.
2034 If there is an active region, the text in the region will be used
2035 as the link text. If the point is at a word, it will be used as
2036 the link text. Otherwise, the link text will be read from the
2037 minibuffer. The link label will be read from the minibuffer in
2038 both cases, with completion from the set of currently defined
2039 references. To create an implicit reference link, press RET to
2040 accept the default, an empty label. If the entered referenced
2041 label is not defined, additionally prompt for the URL
2042 and (optional) title. The reference definition is placed at the
2043 end of the current paragraph."
2045 (let* ((defined-labels (mapcar (lambda (x) (substring x
1 -
1))
2046 (markdown-get-defined-references)))
2047 (bounds (or (and (markdown-use-region-p)
2048 (cons (region-beginning) (region-end)))
2049 (markdown-bounds-of-thing-at-point 'word
)))
2051 (buffer-substring (car bounds
) (cdr bounds
))
2052 (read-string "Link Text: ")))
2053 (label (completing-read
2054 "Link Label (default: none): " defined-labels
2055 nil nil nil
'markdown-reference-label-history nil
))
2056 (ref (markdown-reference-definition
2057 (concat "[" (if (> (length label
) 0) label text
) "]")))
2058 (url (unless ref
(read-string "Link URL: ")))
2059 (title (when (> (length url
) 0)
2060 (read-string "Link Title (optional): "))))
2061 (when bounds
(delete-region (car bounds
) (cdr bounds
)))
2062 (markdown-insert-reference-link text label url title
)))
2064 (defun markdown-insert-uri ()
2065 "Insert markup for an inline URI.
2066 If there is an active region, use it as the URI. If the point is
2067 at a URI, wrap it with angle brackets. If the point is at an
2068 inline URI, remove the angle brackets. Otherwise, simply insert
2069 angle brackets place the point between them."
2071 (if (markdown-use-region-p)
2073 (let ((bounds (markdown-unwrap-things-in-region
2074 (region-beginning) (region-end)
2075 markdown-regex-angle-uri
0 2)))
2076 (markdown-wrap-or-insert "<" ">" nil
(car bounds
) (cdr bounds
)))
2077 ;; Markup removal, URI at point, or empty markup insertion
2078 (if (thing-at-point-looking-at markdown-regex-angle-uri
)
2079 (markdown-unwrap-thing-at-point nil
0 2)
2080 (markdown-wrap-or-insert "<" ">" 'url nil nil
))))
2082 (defun markdown-insert-wiki-link ()
2083 "Insert a wiki link of the form [[WikiLink]].
2084 If Transient Mark mode is on and a region is active, it is used
2087 (markdown-wrap-or-insert "[[" "]]")
2090 (defun markdown-insert-image (&optional arg
)
2091 "Insert image markup using region or word as alt text if possible.
2092 If there is an active region, use the region as the alt text. If the
2093 point is at a word, use the word as the alt text. In these cases, the
2094 point will be left at the position for inserting a URL. If there is no
2095 active region and the point is not at word, simply insert image markup and
2096 place the point in the position to enter alt text. If ARG is nil, insert
2097 inline image markup. Otherwise, insert reference image markup."
2099 (let ((bounds (if arg
2100 (markdown-wrap-or-insert "![" "][]")
2101 (markdown-wrap-or-insert "![" "]()"))))
2103 (goto-char (- (cdr bounds
) 1)))))
2105 (defun markdown-insert-reference-image ()
2106 "Insert reference-style image markup using region or word as alt text.
2107 Calls `markdown-insert-image' with prefix argument."
2109 (markdown-insert-image t
))
2111 (defun markdown-remove-header ()
2112 "Remove header markup if point is at a header.
2113 Return bounds of remaining header text if a header was removed
2116 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
2117 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
2119 (defun markdown-insert-header (&optional level text setext
)
2120 "Insert or replace header markup.
2121 The level of the header is specified by LEVEL and header text is
2122 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2124 When TEXT is nil, the header text is obtained as follows.
2125 If there is an active region, it is used as the header text.
2126 Otherwise, the current line will be used as the header text.
2127 If there is not an active region and the point is at a header,
2128 remove the header markup and replace with level N header.
2129 Otherwise, insert empty header markup and place the cursor in
2131 The style of the header will be atx (hash marks) unless
2132 SETEXT is non-nil, in which case a setext-style (underlined)
2133 header will be inserted."
2134 (interactive "p\nsHeader text: ")
2135 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
2136 ;; Determine header text if not given
2138 (if (markdown-use-region-p)
2140 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
2142 (markdown-remove-header)
2143 (setq text
(delete-and-extract-region
2144 (line-beginning-position) (line-end-position)))
2145 (when (and setext
(string-match "^[ \t]*$" text
))
2146 (setq text
(read-string "Header text: "))))
2147 (setq text
(markdown-compress-whitespace-string text
)))
2148 ;; Insertion with given text
2149 (markdown-ensure-blank-line-before)
2152 (setq hdr
(make-string (length text
) (if (= level
2) ?- ?
=)))
2153 (insert text
"\n" hdr
))
2155 (setq hdr
(make-string level ?
#))
2156 (insert hdr
" " text
" " hdr
))))
2157 (markdown-ensure-blank-line-after)
2158 ;; Leave point at end of text
2160 (backward-char (1+ (length text
)))
2161 (backward-char (1+ level
))))
2163 (defun markdown-insert-header-dwim (&optional arg setext
)
2164 "Insert or replace header markup.
2165 The level and type of the header are determined automatically by
2166 the type and level of the previous header, unless a prefix
2167 argument is given via ARG.
2168 With a numeric prefix valued 1 to 6, insert a header of the given
2169 level, with the type being determined automatically (note that
2170 only level 1 or 2 setext headers are possible).
2171 With \\[universal-argument], insert a level-one setext header.
2172 With \\[universal-argument] \\[universal-argument], insert a
2173 level two setext header.
2174 When SETEXT is non-nil, prefer setext-style headers when
2175 possible (levels one and two).
2177 When there is an active region, use it for the header text. When
2178 the point is at an existing header, change the type and level
2179 according to the rules above.
2180 Otherwise, if the line is not empty, create a header using the
2181 text on the current line as the header text.
2182 Finally, if the point is on a blank line, insert empty header
2183 markup (atx) or prompt for text (setext).
2184 See `markdown-insert-header' for more details about how the
2185 header text is determined."
2188 (cond ((equal arg
'(4)) ; level-one setext with C-u
2191 ((equal arg
'(16)) ; level-two setext with C-u C-u
2194 (t ; automatic with numeric override
2196 (when (re-search-backward markdown-regex-header nil t
)
2197 ;; level of previous header
2198 (setq level
(markdown-outline-level))
2199 ;; match groups 1 and 2 indicate setext headers
2200 (setq setext
(or setext
(match-end 1) (match-end 3)))))
2201 ;; use prefix if given, or level of previous header
2202 (setq level
(if arg
(prefix-numeric-value arg
) level
))
2203 ;; setext headers must be level one or two
2204 (and level
(setq setext
(and setext
(<= level
2))))))
2205 (markdown-insert-header level nil setext
)))
2207 (defun markdown-insert-header-setext-dwim (&optional arg
)
2208 "Insert or replace header markup, with preference for setext.
2209 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2211 (markdown-insert-header-dwim arg t
))
2213 (defun markdown-insert-header-atx-1 ()
2214 "Insert a first level atx-style (hash mark) header.
2215 See `markdown-insert-header'."
2217 (markdown-insert-header 1 nil nil
))
2219 (defun markdown-insert-header-atx-2 ()
2220 "Insert a level two atx-style (hash mark) header.
2221 See `markdown-insert-header'."
2223 (markdown-insert-header 2 nil nil
))
2225 (defun markdown-insert-header-atx-3 ()
2226 "Insert a level three atx-style (hash mark) header.
2227 See `markdown-insert-header'."
2229 (markdown-insert-header 3 nil nil
))
2231 (defun markdown-insert-header-atx-4 ()
2232 "Insert a level four atx-style (hash mark) header.
2233 See `markdown-insert-header'."
2235 (markdown-insert-header 4 nil nil
))
2237 (defun markdown-insert-header-atx-5 ()
2238 "Insert a level five atx-style (hash mark) header.
2239 See `markdown-insert-header'."
2241 (markdown-insert-header 5 nil nil
))
2243 (defun markdown-insert-header-atx-6 ()
2244 "Insert a sixth level atx-style (hash mark) header.
2245 See `markdown-insert-header'."
2247 (markdown-insert-header 6 nil nil
))
2249 (defun markdown-insert-header-setext-1 ()
2250 "Insert a setext-style (underlined) first-level header.
2251 See `markdown-insert-header'."
2253 (markdown-insert-header 1 nil t
))
2255 (defun markdown-insert-header-setext-2 ()
2256 "Insert a setext-style (underlined) second-level header.
2257 See `markdown-insert-header'."
2259 (markdown-insert-header 2 nil t
))
2261 (defun markdown-blockquote-indentation (loc)
2262 "Return string containing necessary indentation for a blockquote at LOC.
2263 Also see `markdown-pre-indentation'."
2266 (let* ((list-level (length (markdown-calculate-list-levels)))
2268 (dotimes (count list-level indent
)
2269 (setq indent
(concat indent
" "))))))
2271 (defun markdown-insert-blockquote ()
2272 "Start a blockquote section (or blockquote the region).
2273 If Transient Mark mode is on and a region is active, it is used as
2274 the blockquote text."
2276 (if (markdown-use-region-p)
2277 (markdown-blockquote-region (region-beginning) (region-end))
2278 (markdown-ensure-blank-line-before)
2279 (insert (markdown-blockquote-indentation (point)) "> ")
2280 (markdown-ensure-blank-line-after)))
2282 (defun markdown-block-region (beg end prefix
)
2283 "Format the region using a block prefix.
2284 Arguments BEG and END specify the beginning and end of the
2285 region. The characters PREFIX will appear at the beginning
2288 (let* ((end-marker (make-marker))
2289 (beg-marker (make-marker)))
2290 ;; Ensure blank line after and remove extra whitespace
2292 (skip-syntax-backward "-")
2293 (set-marker end-marker
(point))
2294 (delete-horizontal-space)
2295 (markdown-ensure-blank-line-after)
2296 ;; Ensure blank line before and remove extra whitespace
2298 (skip-syntax-forward "-")
2299 (delete-horizontal-space)
2300 (markdown-ensure-blank-line-before)
2301 (set-marker beg-marker
(point))
2302 ;; Insert PREFIX before each line
2303 (goto-char beg-marker
)
2304 (while (and (< (line-beginning-position) end-marker
)
2309 (defun markdown-blockquote-region (beg end
)
2310 "Blockquote the region.
2311 Arguments BEG and END specify the beginning and end of the region."
2313 (markdown-block-region
2314 beg end
(concat (markdown-blockquote-indentation
2315 (max (point-min) (1- beg
))) "> ")))
2317 (defun markdown-pre-indentation (loc)
2318 "Return string containing necessary whitespace for a pre block at LOC.
2319 Also see `markdown-blockquote-indentation'."
2322 (let* ((list-level (length (markdown-calculate-list-levels)))
2324 (dotimes (count (1+ list-level
) indent
)
2325 (setq indent
(concat indent
" "))))))
2327 (defun markdown-insert-pre ()
2328 "Start a preformatted section (or apply to the region).
2329 If Transient Mark mode is on and a region is active, it is marked
2330 as preformatted text."
2332 (if (markdown-use-region-p)
2333 (markdown-pre-region (region-beginning) (region-end))
2334 (markdown-ensure-blank-line-before)
2335 (insert (markdown-pre-indentation (point)))
2336 (markdown-ensure-blank-line-after)))
2338 (defun markdown-pre-region (beg end
)
2339 "Format the region as preformatted text.
2340 Arguments BEG and END specify the beginning and end of the region."
2342 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
2343 (markdown-block-region beg end indent
)))
2345 (defun markdown-insert-gfm-code-block (&optional lang
)
2346 "Insert GFM code block for language LANG.
2347 If LANG is nil, the language will be queried from user. If a
2348 region is active, wrap this region with the markup instead. If
2349 the region boundaries are not on empty lines, these are added
2350 automatically in order to have the correct markup."
2351 (interactive "sProgramming language: ")
2352 (if (markdown-use-region-p)
2353 (let ((b (region-beginning)) (e (region-end)))
2355 ;; if we're on a blank line, insert the quotes here, otherwise
2356 ;; add a new line first
2357 (unless (looking-at "\n")
2362 (goto-char (+ e
3 (length lang
)))
2363 ;; if we're on a blank line, don't newline, otherwise the ```
2364 ;; should go on its own line
2365 (unless (looking-back "\n")
2374 ;;; Footnotes ======================================================================
2376 (defun markdown-footnote-counter-inc ()
2377 "Increment `markdown-footnote-counter' and return the new value."
2378 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
2380 (goto-char (point-min))
2381 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
2383 (let ((fn (string-to-number (match-string 1))))
2384 (when (> fn markdown-footnote-counter
)
2385 (setq markdown-footnote-counter fn
))))))
2386 (incf markdown-footnote-counter
))
2388 (defun markdown-footnote-new ()
2389 "Insert footnote with a new number and move point to footnote definition."
2391 (let ((fn (markdown-footnote-counter-inc)))
2392 (insert (format "[^%d]" fn
))
2393 (markdown-footnote-text-find-new-location)
2394 (markdown-ensure-blank-line-before)
2395 (unless (markdown-cur-line-blank-p)
2397 (insert (format "[^%d]: " fn
))
2398 (markdown-ensure-blank-line-after)))
2400 (defun markdown-footnote-text-find-new-location ()
2401 "Position the cursor at the proper location for a new footnote text."
2403 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
2404 ((eq markdown-footnote-location
'immediately
) (markdown-end-of-block))
2405 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
2407 (defun markdown-footnote-kill ()
2408 "Kill the footnote at point.
2409 The footnote text is killed (and added to the kill ring), the
2410 footnote marker is deleted. Point has to be either at the
2411 footnote marker or in the footnote text."
2414 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2415 (markdown-footnote-return) ; we first move to the marker
2416 (setq return-pos
'text
)) ; and remember our return position
2417 (let ((marker (markdown-footnote-delete-marker)))
2419 (error "Not at a footnote"))
2420 (let ((text-pos (markdown-footnote-find-text (car marker
))))
2422 (error "No text for footnote `%s'" (car marker
)))
2423 (goto-char text-pos
)
2424 (let ((pos (markdown-footnote-kill-text)))
2426 (if (and pos
(eq return-pos
'text
))
2429 (goto-char return-pos
)))
2431 (defun markdown-footnote-delete-marker ()
2432 "Delete a footnote marker at point.
2433 Returns a list (ID START) containing the footnote ID and the
2434 start position of the marker before deletion. If no footnote
2435 marker was deleted, this function returns NIL."
2436 (let ((marker (markdown-footnote-marker-positions)))
2438 (delete-region (second marker
) (third marker
))
2441 (defun markdown-footnote-kill-text ()
2442 "Kill footnote text at point.
2443 Returns the start position of the footnote text before deletion,
2444 or NIL if point was not inside a footnote text.
2446 The killed text is placed in the kill ring (without the footnote
2448 (let ((fn (markdown-footnote-text-positions)))
2450 (let ((text (delete-and-extract-region (second fn
) (third fn
))))
2451 (string-match (concat "\\[\\" (first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
2452 (kill-new (match-string 1 text
))
2453 (when (and (markdown-cur-line-blank-p)
2454 (markdown-prev-line-blank-p))
2455 (delete-region (1- (point)) (point)))
2458 (defun markdown-footnote-goto-text ()
2459 "Jump to the text of the footnote at point."
2461 (let ((fn (car (markdown-footnote-marker-positions))))
2463 (error "Not at a footnote marker"))
2464 (let ((new-pos (markdown-footnote-find-text fn
)))
2466 (error "No definition found for footnote `%s'" fn
))
2467 (goto-char new-pos
))))
2469 (defun markdown-footnote-return ()
2470 "Return from a footnote to its footnote number in the main text."
2472 (let ((fn (save-excursion
2473 (car (markdown-footnote-text-positions)))))
2475 (error "Not in a footnote"))
2476 (let ((new-pos (markdown-footnote-find-marker fn
)))
2478 (error "Footnote marker `%s' not found" fn
))
2479 (goto-char new-pos
))))
2481 (defun markdown-footnote-find-marker (id)
2482 "Find the location of the footnote marker with ID.
2483 The actual buffer position returned is the position directly
2484 following the marker's closing bracket. If no marker is found,
2487 (goto-char (point-min))
2488 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
2489 (skip-chars-backward "^]")
2492 (defun markdown-footnote-find-text (id)
2493 "Find the location of the text of footnote ID.
2494 The actual buffer position returned is the position of the first
2495 character of the text, after the footnote's identifier. If no
2496 footnote text is found, NIL is returned."
2498 (goto-char (point-min))
2499 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
2500 (skip-chars-forward "[ \t]")
2503 (defun markdown-footnote-marker-positions ()
2504 "Return the position and ID of the footnote marker point is on.
2505 The return value is a list (ID START END). If point is not on a
2506 footnote, NIL is returned."
2507 ;; first make sure we're at a footnote marker
2508 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
2509 (looking-at (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
2511 ;; move point between [ and ^:
2512 (if (looking-at "\\[")
2514 (skip-chars-backward "^["))
2515 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
2516 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2518 (defun markdown-footnote-text-positions ()
2519 "Return the start and end positions of the footnote text point is in.
2520 The exact return value is a list of three elements: (ID START END).
2521 The start position is the position of the opening bracket
2522 of the footnote id. The end position is directly after the
2523 newline that ends the footnote. If point is not in a footnote,
2524 NIL is returned instead."
2527 (backward-paragraph)
2528 ;; if we're in a multiparagraph footnote, we need to back up further
2529 (while (>= (markdown-next-line-indent) 4)
2530 (backward-paragraph))
2532 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:"))
2533 (list (match-string 1) (point))))))
2537 (>= (markdown-next-line-indent) 4)))
2538 (append fn
(list (point)))))))
2541 ;;; Element Removal ===========================================================
2543 (defun markdown-kill-thing-at-point ()
2544 "Kill thing at point and add important text, without markup, to kill ring.
2545 Possible things to kill include (roughly in order of precedence):
2546 inline code, headers, horizonal rules, links (add link text to
2547 kill ring), images (add alt text to kill ring), angle uri, email
2548 addresses, bold, italics, reference definition (add URI to kill
2549 ring), footnote markers and text (kill both marker and text, add
2550 text to kill ring), and list items."
2555 ((thing-at-point-looking-at markdown-regex-code
)
2556 (kill-new (match-string 4))
2557 (delete-region (match-beginning 2) (match-end 2)))
2559 ((thing-at-point-looking-at markdown-regex-header-atx
)
2560 (kill-new (match-string 2))
2561 (delete-region (match-beginning 0) (match-end 0)))
2563 ((thing-at-point-looking-at markdown-regex-header-setext
)
2564 (kill-new (match-string 1))
2565 (delete-region (match-beginning 0) (match-end 0)))
2567 ((thing-at-point-looking-at markdown-regex-hr
)
2568 (kill-new (match-string 0))
2569 (delete-region (match-beginning 0) (match-end 0)))
2570 ;; Inline link or image (add link or alt text to kill ring)
2571 ((thing-at-point-looking-at markdown-regex-link-inline
)
2572 (kill-new (match-string 3))
2573 (delete-region (match-beginning 0) (match-end 0)))
2574 ;; Reference link or image (add link or alt text to kill ring)
2575 ((thing-at-point-looking-at markdown-regex-link-reference
)
2576 (kill-new (match-string 3))
2577 (delete-region (match-beginning 0) (match-end 0)))
2578 ;; Angle URI (add URL to kill ring)
2579 ((thing-at-point-looking-at markdown-regex-angle-uri
)
2580 (kill-new (match-string 2))
2581 (delete-region (match-beginning 0) (match-end 0)))
2582 ;; Email address in angle brackets (add email address to kill ring)
2583 ((thing-at-point-looking-at markdown-regex-email
)
2584 (kill-new (match-string 1))
2585 (delete-region (match-beginning 0) (match-end 0)))
2586 ;; Wiki link (add alias text to kill ring)
2587 ((thing-at-point-looking-at markdown-regex-wiki-link
)
2588 (kill-new (if markdown-wiki-link-alias-first
2589 (match-string-no-properties 2)
2590 (or (match-string-no-properties 2) (match-string-no-properties 4))))
2591 (delete-region (match-beginning 1) (match-end 1)))
2593 ((thing-at-point-looking-at markdown-regex-bold
)
2594 (kill-new (match-string 4))
2595 (delete-region (match-beginning 2) (match-end 2)))
2597 ((thing-at-point-looking-at markdown-regex-italic
)
2598 (kill-new (match-string 4))
2599 (delete-region (match-beginning 2) (match-end 2)))
2600 ;; Footnote marker (add footnote text to kill ring)
2601 ((thing-at-point-looking-at markdown-regex-footnote
)
2602 (markdown-footnote-kill))
2603 ;; Footnote text (add footnote text to kill ring)
2604 ((setq val
(markdown-footnote-text-positions))
2605 (markdown-footnote-kill))
2606 ;; Reference definition (add URL to kill ring)
2607 ((thing-at-point-looking-at markdown-regex-reference-definition
)
2608 (kill-new (match-string 2))
2609 (delete-region (match-beginning 0) (match-end 0)))
2611 ((setq val
(markdown-cur-list-item-bounds))
2612 (kill-new (delete-and-extract-region (first val
) (second val
))))
2614 (error "Nothing found at point to kill")))))
2617 ;;; Indentation ====================================================================
2619 (defun markdown-indent-find-next-position (cur-pos positions
)
2620 "Return the position after the index of CUR-POS in POSITIONS.
2621 Positions are calculated by `markdown-calc-indents'."
2622 (while (and positions
2623 (not (equal cur-pos
(car positions
))))
2624 (setq positions
(cdr positions
)))
2625 (or (cadr positions
) 0))
2627 (defun markdown-exdent-find-next-position (cur-pos positions
)
2628 "Return the maximal element that precedes CUR-POS from POSITIONS.
2629 Positions are calculated by `markdown-calc-indents'."
2631 (dolist (i positions
)
2633 (setq result
(max result i
))))
2636 (defun markdown-indent-line ()
2637 "Indent the current line using some heuristics.
2638 If the _previous_ command was either `markdown-enter-key' or
2639 `markdown-cycle', then we should cycle to the next
2640 reasonable indentation position. Otherwise, we could have been
2641 called directly by `markdown-enter-key', by an initial call of
2642 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2643 these cases, indent to the default position.
2644 Positions are calculated by `markdown-calc-indents'."
2646 (let ((positions (markdown-calc-indents))
2647 (cur-pos (current-column)))
2648 (if (not (equal this-command
'markdown-cycle
))
2649 (indent-line-to (car positions
))
2650 (setq positions
(sort (delete-dups positions
) '<))
2652 (markdown-indent-find-next-position cur-pos positions
)))))
2654 (defun markdown-calc-indents ()
2655 "Return a list of indentation columns to cycle through.
2656 The first element in the returned list should be considered the
2657 default indentation level. This function does not worry about
2658 duplicate positions, which are handled up by calling functions."
2659 (let (pos prev-line-pos positions
)
2661 ;; Indentation of previous line
2662 (setq prev-line-pos
(markdown-prev-line-indent))
2663 (setq positions
(cons prev-line-pos positions
))
2665 ;; Indentation of previous non-list-marker text
2666 (when (setq pos
(markdown-prev-non-list-indent))
2667 (setq positions
(cons pos positions
)))
2669 ;; Indentation required for a pre block in current context
2670 (setq pos
(length (markdown-pre-indentation (point))))
2671 (setq positions
(cons pos positions
))
2673 ;; Indentation of the previous line + tab-width
2675 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
2676 (setq positions
(cons tab-width positions
)))
2678 ;; Indentation of the previous line - tab-width
2679 (if (and prev-line-pos
(> prev-line-pos tab-width
))
2680 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
2682 ;; Indentation of all preceeding list markers (when in a list)
2683 (when (setq pos
(markdown-calculate-list-levels))
2684 (setq positions
(append pos positions
)))
2687 (setq positions
(cons 0 positions
))
2689 ;; Return reversed list
2690 (reverse positions
)))
2692 (defun markdown-do-normal-return ()
2693 "Insert a newline and optionally indent the next line."
2695 (if markdown-indent-on-enter
2696 (funcall indent-line-function
)))
2698 (defun markdown-enter-key ()
2699 "Handle RET according to context.
2700 If there is a wiki link at the point, follow it unless
2701 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2702 it in the usual way."
2704 (if (and markdown-follow-wiki-link-on-enter
(markdown-wiki-link-p))
2705 (markdown-follow-wiki-link-at-point)
2706 (markdown-do-normal-return)))
2708 (defun markdown-exdent-or-delete (arg)
2709 "Handle BACKSPACE by cycling through indentation points.
2710 When BACKSPACE is pressed, if there is only whitespace
2711 before the current point, then exdent the line one level.
2712 Otherwise, do normal delete by repeating
2713 `backward-delete-char-untabify' ARG times."
2715 (let ((cur-pos (current-column))
2716 (start-of-indention (save-excursion
2717 (back-to-indentation)
2719 (positions (markdown-calc-indents)))
2720 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
2721 (indent-line-to (markdown-exdent-find-next-position cur-pos positions
))
2722 (backward-delete-char-untabify arg
))))
2724 (defun markdown-find-leftmost-column (beg end
)
2725 "Find the leftmost column in the region from BEG to END."
2726 (let ((mincol 1000))
2729 (while (< (point) end
)
2730 (back-to-indentation)
2731 (unless (looking-at "[ \t]*$")
2732 (setq mincol
(min mincol
(current-column))))
2737 (defun markdown-indent-region (beg end arg
)
2738 "Indent the region from BEG to END using some heuristics.
2739 When ARG is non-nil, exdent the region instead.
2740 See `markdown-indent-line' and `markdown-indent-line'."
2741 (interactive "*r\nP")
2742 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2743 (leftmostcol (markdown-find-leftmost-column beg end
))
2745 (markdown-exdent-find-next-position leftmostcol positions
)
2746 (markdown-indent-find-next-position leftmostcol positions
))))
2747 (indent-rigidly beg end
(- next-pos leftmostcol
))
2748 (setq deactivate-mark nil
)))
2751 ;;; Markup Completion =========================================================
2753 (defconst markdown-complete-alist
2754 '((markdown-regex-header-atx . markdown-complete-atx
)
2755 (markdown-regex-header-setext . markdown-complete-setext
)
2756 (markdown-regex-hr . markdown-complete-hr
))
2757 "Association list of form (regexp . function) for markup completion.")
2759 (defun markdown-incomplete-atx-p ()
2760 "Return t if ATX header markup is incomplete and nil otherwise.
2761 Assumes match data is available for `markdown-regex-header-atx'.
2762 Checks that the number of trailing hash marks equals the number of leading
2763 hash marks, that there is only a single space before and after the text,
2764 and that there is no extraneous whitespace in the text."
2767 ;; Number of starting and ending hash marks differs
2768 (not (= (length (match-string 1)) (length (match-string 3))))
2769 ;; When the header text is not empty...
2770 (and (> (length (match-string 2)) 0)
2771 ;; ...if there are extra leading, trailing, or interior spaces
2772 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2773 (not (= (match-beginning 3) (1+ (match-end 2))))
2774 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2775 ;; When the header text is empty...
2776 (and (= (length (match-string 2)) 0)
2777 ;; ...if there are too many or too few spaces
2778 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2780 (defun markdown-complete-atx ()
2781 "Complete and normalize ATX headers.
2782 Add or remove hash marks to the end of the header to match the
2783 beginning. Ensure that there is only a single space between hash
2784 marks and header text. Removes extraneous whitespace from header text.
2785 Assumes match data is available for `markdown-regex-header-atx'."
2786 (when (markdown-incomplete-atx-p)
2787 (let* ((new-marker (make-marker))
2788 (new-marker (set-marker new-marker
(match-end 2))))
2789 ;; Hash marks and spacing at end
2790 (goto-char (match-end 2))
2791 (delete-region (match-end 2) (match-end 3))
2792 (insert " " (match-string 1))
2793 ;; Remove extraneous whitespace from title
2794 (replace-match (markdown-compress-whitespace-string (match-string 2))
2796 ;; Spacing at beginning
2797 (goto-char (match-end 1))
2798 (delete-region (match-end 1) (match-beginning 2))
2800 ;; Leave point at end of text
2801 (goto-char new-marker
))))
2803 (defun markdown-incomplete-setext-p ()
2804 "Return t if setext header markup is incomplete and nil otherwise.
2805 Assumes match data is available for `markdown-regex-header-setext'.
2806 Checks that length of underline matches text and that there is no
2807 extraneous whitespace in the text."
2809 (or (not (= (length (match-string 1)) (length (match-string 2))))
2810 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2812 (defun markdown-complete-setext ()
2813 "Complete and normalize setext headers.
2814 Add or remove underline characters to match length of header
2815 text. Removes extraneous whitespace from header text. Assumes
2816 match data is available for `markdown-regex-header-setext'."
2817 (when (markdown-incomplete-setext-p)
2818 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2819 (char (char-after (match-beginning 2)))
2820 (level (if (char-equal char ?-
) 2 1)))
2821 (goto-char (match-beginning 0))
2822 (delete-region (match-beginning 0) (match-end 0))
2823 (markdown-insert-header level text t
))))
2825 (defun markdown-incomplete-hr-p ()
2826 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2827 Assumes match data is available for `markdown-regex-hr'."
2828 (not (member (match-string 0) markdown-hr-strings
)))
2830 (defun markdown-complete-hr ()
2831 "Complete horizontal rules.
2832 If horizontal rule string is a member of `markdown-hr-strings',
2833 do nothing. Otherwise, replace with the car of
2834 `markdown-hr-strings'.
2835 Assumes match data is available for `markdown-regex-hr'."
2836 (replace-match (car markdown-hr-strings
)))
2838 (defun markdown-complete ()
2839 "Complete markup of object near point or in region when active.
2840 Handle all objects in `markdown-complete-alist', in order.
2841 See `markdown-complete-at-point' and `markdown-complete-region'."
2843 (if (markdown-use-region-p)
2844 (markdown-complete-region (region-beginning) (region-end))
2845 (markdown-complete-at-point)))
2847 (defun markdown-complete-at-point ()
2848 "Complete markup of object near point.
2849 Handle all objects in `markdown-complete-alist', in
2852 (loop for
(regexp . function
) in markdown-complete-alist
2853 until
(thing-at-point-looking-at (eval regexp
))
2854 finally
(funcall function
)))
2856 (defun markdown-complete-region (beg end
)
2857 "Complete markup of objects in region from BEG to END.
2858 Handle all objects in `markdown-complete-alist', in
2861 (let* ((end-marker (make-marker))
2862 (end-marker (set-marker end-marker end
)))
2863 (loop for
(regexp . function
) in markdown-complete-alist
2866 (while (re-search-forward (eval regexp
) end-marker t
)
2867 (funcall function
))))))
2869 (defun markdown-complete-buffer ()
2870 "Complete markup for all objects in the current buffer."
2872 (markdown-complete-region (point-min) (point-max)))
2875 ;;; Markup Cycling ============================================================
2877 (defun markdown-cycle-atx (arg &optional remove
)
2878 "Cycle ATX header markup.
2879 Promote header (decrease level) when ARG is 1 and demote
2880 header (increase level) if arg is -1. When REMOVE is non-nil,
2881 remove the header when the level reaches zero and stop cycling
2882 when it reaches six. Otherwise, perform a proper cycling through
2883 levels one through six. Assumes match data is available for
2884 `markdown-regex-header-atx'."
2885 (let* ((old-level (length (match-string 1)))
2886 (new-level (+ old-level arg
))
2887 (text (match-string 2)))
2889 (setq new-level
(% new-level
6))
2890 (setq new-level
(cond ((= new-level
0) 6)
2891 ((< new-level
0) (+ new-level
6))
2895 (markdown-unwrap-thing-at-point nil
0 2))
2897 (goto-char (match-beginning 0))
2898 (delete-region (match-beginning 0) (match-end 0))
2899 (markdown-insert-header new-level text nil
)))))
2901 (defun markdown-cycle-setext (arg &optional remove
)
2902 "Cycle setext header markup.
2903 Promote header (increase level) when ARG is 1 and demote
2904 header (decrease level or remove) if arg is -1. When demoting a
2905 level-two setext header, replace with a level-three atx header.
2906 When REMOVE is non-nil, remove the header when the level reaches
2907 zero. Otherwise, cycle back to a level six atx header. Assumes
2908 match data is available for `markdown-regex-header-setext'."
2909 (let* ((char (char-after (match-beginning 2)))
2910 (old-level (if (char-equal char ?
=) 1 2))
2911 (new-level (+ old-level arg
))
2912 (text (match-string 1)))
2913 (when (and (not remove
) (= new-level
0))
2917 (markdown-unwrap-thing-at-point nil
0 1))
2919 (markdown-insert-header new-level nil t
))
2921 (markdown-insert-header new-level nil nil
)))))
2923 (defun markdown-cycle-hr (arg &optional remove
)
2924 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2925 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
2926 backwards (promote). When REMOVE is non-nil, remove the hr instead
2927 of cycling when the end of the list is reached.
2928 Assumes match data is available for `markdown-regex-hr'."
2929 (let* ((strings (if (= arg -
1)
2930 (reverse markdown-hr-strings
)
2931 markdown-hr-strings
))
2932 (tail (member (match-string 0) strings
))
2933 (new (or (cadr tail
)
2939 (replace-match new
)))
2941 (defun markdown-cycle-bold ()
2942 "Cycle bold markup between underscores and asterisks.
2943 Assumes match data is available for `markdown-regex-bold'."
2945 (let* ((old-delim (match-string 3))
2946 (new-delim (if (string-equal old-delim
"**") "__" "**")))
2947 (replace-match new-delim t t nil
3)
2948 (replace-match new-delim t t nil
5))))
2950 (defun markdown-cycle-italic ()
2951 "Cycle italic markup between underscores and asterisks.
2952 Assumes match data is available for `markdown-regex-italic'."
2954 (let* ((old-delim (match-string 3))
2955 (new-delim (if (string-equal old-delim
"*") "_" "*")))
2956 (replace-match new-delim t t nil
3)
2957 (replace-match new-delim t t nil
5))))
2960 ;;; Keymap ====================================================================
2962 (defvar markdown-mode-map
2963 (let ((map (make-keymap)))
2964 ;; Element insertion
2965 (define-key map
(kbd "C-c l") 'markdown-insert-link
)
2966 (define-key map
(kbd "C-c L") 'markdown-insert-reference-link-dwim
)
2967 (define-key map
(kbd "C-c u") 'markdown-insert-uri
)
2968 (define-key map
(kbd "C-c w") 'markdown-insert-wiki-link
)
2969 (define-key map
(kbd "C-c i") 'markdown-insert-image
)
2970 (define-key map
(kbd "C-c I") 'markdown-insert-reference-image
)
2971 (define-key map
(kbd "C-c 1") 'markdown-insert-header-atx-1
)
2972 (define-key map
(kbd "C-c 2") 'markdown-insert-header-atx-2
)
2973 (define-key map
(kbd "C-c 3") 'markdown-insert-header-atx-3
)
2974 (define-key map
(kbd "C-c 4") 'markdown-insert-header-atx-4
)
2975 (define-key map
(kbd "C-c 5") 'markdown-insert-header-atx-5
)
2976 (define-key map
(kbd "C-c 6") 'markdown-insert-header-atx-6
)
2977 (define-key map
(kbd "C-c !") 'markdown-insert-header-setext-1
)
2978 (define-key map
(kbd "C-c @") 'markdown-insert-header-setext-2
)
2979 (define-key map
(kbd "C-c h") 'markdown-insert-header-dwim
)
2980 (define-key map
(kbd "C-c H") 'markdown-insert-header-setext-dwim
)
2981 (define-key map
(kbd "C-c s") 'markdown-insert-bold
)
2982 (define-key map
(kbd "C-c e") 'markdown-insert-italic
)
2983 (define-key map
(kbd "C-c c") 'markdown-insert-code
)
2984 (define-key map
(kbd "C-c b") 'markdown-insert-blockquote
)
2985 (define-key map
(kbd "C-c B") 'markdown-blockquote-region
)
2986 (define-key map
(kbd "C-c p") 'markdown-insert-pre
)
2987 (define-key map
(kbd "C-c P") 'markdown-pre-region
)
2988 (define-key map
(kbd "C-c -") 'markdown-insert-hr
)
2989 (define-key map
(kbd "C-c f") 'markdown-footnote-new
)
2991 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
2992 ;; Promotion, Demotion, Completion, and Cycling
2993 (define-key map
(kbd "C-c C--") 'markdown-promote
)
2994 (define-key map
(kbd "C-c C-=") 'markdown-demote
)
2995 (define-key map
(kbd "M-<left>") 'markdown-promote
)
2996 (define-key map
(kbd "M-<right>") 'markdown-demote
)
2997 (define-key map
(kbd "C-c C-]") 'markdown-complete-or-cycle
)
2998 (define-key map
(kbd "C-c C-[") (kbd "C-u C-c C-]"))
2999 ;; Following and Jumping
3000 (define-key map
(kbd "C-c C-o") 'markdown-follow-thing-at-point
)
3001 (define-key map
(kbd "C-c C-j") 'markdown-jump
)
3003 (define-key map
(kbd "C-m") 'markdown-enter-key
)
3004 (define-key map
(kbd "<backspace>") 'markdown-exdent-or-delete
)
3005 (define-key map
(kbd "C-c >") 'markdown-indent-region
)
3006 (define-key map
(kbd "C-c <") (kbd "C-u C-c >"))
3007 ;; Visibility cycling
3008 (define-key map
(kbd "<tab>") 'markdown-cycle
)
3009 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
3010 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
3011 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
3012 ;; Header navigation
3013 (define-key map
(kbd "C-c C-n") 'outline-next-visible-heading
)
3014 (define-key map
(kbd "C-c C-p") 'outline-previous-visible-heading
)
3015 (define-key map
(kbd "C-c C-f") 'outline-forward-same-level
)
3016 (define-key map
(kbd "C-c C-b") 'outline-backward-same-level
)
3017 (define-key map
(kbd "C-c C-u") 'outline-up-heading
)
3018 ;; Buffer-wide commands
3019 (define-key map
(kbd "C-c C-c m") 'markdown-other-window
)
3020 (define-key map
(kbd "C-c C-c p") 'markdown-preview
)
3021 (define-key map
(kbd "C-c C-c e") 'markdown-export
)
3022 (define-key map
(kbd "C-c C-c v") 'markdown-export-and-preview
)
3023 (define-key map
(kbd "C-c C-c o") 'markdown-open
)
3024 (define-key map
(kbd "C-c C-c w") 'markdown-kill-ring-save
)
3025 (define-key map
(kbd "C-c C-c c") 'markdown-check-refs
)
3026 (define-key map
(kbd "C-c C-c n") 'markdown-cleanup-list-numbers
)
3027 (define-key map
(kbd "C-c C-c ]") 'markdown-complete-buffer
)
3029 (define-key map
(kbd "M-<up>") 'markdown-move-up
)
3030 (define-key map
(kbd "M-<down>") 'markdown-move-down
)
3031 (define-key map
(kbd "M-<return>") 'markdown-insert-list-item
)
3033 (define-key map
(kbd "M-[") 'markdown-beginning-of-block
)
3034 (define-key map
(kbd "M-]") 'markdown-end-of-block
)
3035 (define-key map
(kbd "M-n") 'markdown-next-link
)
3036 (define-key map
(kbd "M-p") 'markdown-previous-link
)
3038 "Keymap for Markdown major mode.")
3040 (defvar gfm-mode-map
3041 (let ((map (make-sparse-keymap)))
3042 (set-keymap-parent map markdown-mode-map
)
3043 (define-key map
"\C-c\C-sl" 'markdown-insert-gfm-code-block
)
3045 "Keymap for `gfm-mode'.
3046 See also `markdown-mode-map'.")
3049 ;;; Menu ==================================================================
3051 (easy-menu-define markdown-mode-menu markdown-mode-map
3052 "Menu for Markdown mode"
3055 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
3056 ["Cycle global visibility" markdown-shifttab
])
3058 ["Compile" markdown-other-window
]
3059 ["Preview" markdown-preview
]
3060 ["Export" markdown-export
]
3061 ["Export & View" markdown-export-and-preview
]
3062 ["Open" markdown-open
]
3063 ["Kill ring save" markdown-kill-ring-save
]
3066 ["First level" markdown-insert-setext-header-1
]
3067 ["Second level" markdown-insert-setext-header-2
])
3069 ["First level" markdown-insert-header-atx-1
]
3070 ["Second level" markdown-insert-header-atx-2
]
3071 ["Third level" markdown-insert-header-atx-3
]
3072 ["Fourth level" markdown-insert-header-atx-4
]
3073 ["Fifth level" markdown-insert-header-atx-5
]
3074 ["Sixth level" markdown-insert-header-atx-6
])
3076 ["Bold" markdown-insert-bold
]
3077 ["Italic" markdown-insert-italic
]
3078 ["Blockquote" markdown-insert-blockquote
]
3079 ["Preformatted" markdown-insert-pre
]
3080 ["Code" markdown-insert-code
]
3082 ["Insert inline link" markdown-insert-link
]
3083 ["Insert reference link" markdown-insert-reference-link-dwim
]
3084 ["Insert image" markdown-insert-image
]
3085 ["Insert horizontal rule" markdown-insert-hr
]
3088 ["Insert footnote" markdown-footnote-new
]
3089 ["Jump to footnote text" markdown-footnote-goto-text
]
3090 ["Return from footnote" markdown-footnote-return
])
3092 ["Check references" markdown-check-refs
]
3093 ["Clean up list numbering" markdown-cleanup-list-numbers
]
3095 ["Version" markdown-show-version
]
3099 ;;; imenu =====================================================================
3101 (defun markdown-imenu-create-index ()
3102 "Create and return an imenu index alist for the current buffer.
3103 See `imenu-create-index-function' and `imenu--index-alist' for details."
3104 (let* ((root '(nil . nil
))
3109 hashes pos level heading
)
3111 (goto-char (point-min))
3112 (while (re-search-forward markdown-regex-header
(point-max) t
)
3114 ((setq heading
(match-string-no-properties 1))
3115 (setq pos
(match-beginning 1)
3117 ((setq heading
(match-string-no-properties 3))
3118 (setq pos
(match-beginning 3)
3120 ((setq hashes
(match-string-no-properties 5))
3121 (setq heading
(match-string-no-properties 6)
3122 pos
(match-beginning 5)
3123 level
(length hashes
))))
3124 (let ((alist (list (cons heading pos
))))
3126 ((= cur-level level
) ; new sibling
3127 (setcdr cur-alist alist
)
3128 (setq cur-alist alist
))
3129 ((< cur-level level
) ; first child
3130 (dotimes (i (- level cur-level
1))
3131 (setq alist
(list (cons empty-heading alist
))))
3133 (let* ((parent (car cur-alist
))
3134 (self-pos (cdr parent
)))
3135 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
3136 (setcdr root alist
)) ; primogenitor
3137 (setq cur-alist alist
)
3138 (setq cur-level level
))
3139 (t ; new sibling of an ancestor
3140 (let ((sibling-alist (last (cdr root
))))
3141 (dotimes (i (1- level
))
3142 (setq sibling-alist
(last (cdar sibling-alist
))))
3143 (setcdr sibling-alist alist
)
3144 (setq cur-alist alist
))
3145 (setq cur-level level
)))))
3149 ;;; References ================================================================
3151 (defun markdown-insert-reference-definition (ref &optional buffer
)
3152 "Add blank REF definition to the end of BUFFER.
3153 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3154 (or buffer
(setq buffer
(current-buffer)))
3155 (with-current-buffer buffer
3156 (goto-char (point-max))
3157 (indent-new-comment-line)
3158 (insert (concat ref
": "))))
3160 (defun markdown-reference-goto-definition ()
3161 "Jump to the definition of the reference at point or create it."
3163 (when (thing-at-point-looking-at markdown-regex-link-reference
)
3164 (let* ((text (match-string-no-properties 2))
3165 (reference (match-string-no-properties 4))
3166 (target (downcase (if (string= reference
"[]") text reference
)))
3167 (loc (cadr (markdown-reference-definition target
))))
3170 (markdown-insert-reference-definition target
(current-buffer))))))
3172 (defun markdown-reference-find-links (reference)
3173 "Return a list of all links for REFERENCE.
3174 REFERENCE should include the surrounding square brackets like [this].
3175 Elements of the list have the form (text start line), where
3176 text is the link text, start is the location at the beginning of
3177 the link, and line is the line number on which the link appears."
3178 (let* ((ref-quote (regexp-quote (substring reference
1 -
1)))
3179 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3180 ref-quote ref-quote
))
3183 (goto-char (point-min))
3184 (while (re-search-forward regexp nil t
)
3185 (let* ((text (or (match-string-no-properties 1)
3186 (match-string-no-properties 2)))
3187 (start (match-beginning 0))
3188 (line (markdown-line-number-at-pos)))
3189 (add-to-list 'links
(list text start line
)))))
3192 (defun markdown-get-undefined-refs ()
3193 "Return a list of undefined Markdown references.
3194 Result is an alist of pairs (reference . occurrences), where
3195 occurrences is itself another alist of pairs (label . line-number).
3196 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3197 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3198 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3201 (goto-char (point-min))
3203 (re-search-forward markdown-regex-link-reference nil t
)
3204 (let* ((text (match-string-no-properties 2))
3205 (reference (match-string-no-properties 4))
3206 (target (downcase (if (string= reference
"[]") text reference
))))
3207 (unless (markdown-reference-definition target
)
3208 (let ((entry (assoc target missing
)))
3210 (add-to-list 'missing
(cons target
3211 (list (cons text
(markdown-line-number-at-pos)))) t
)
3213 (append (cdr entry
) (list (cons text
(markdown-line-number-at-pos))))))))))
3216 (defconst markdown-reference-check-buffer
3217 "*Undefined references for %buffer%*"
3218 "Pattern for name of buffer for listing undefined references.
3219 The string %buffer% will be replaced by the corresponding
3220 `markdown-mode' buffer name.")
3222 (defun markdown-reference-check-buffer (&optional buffer-name
)
3223 "Name and return buffer for reference checking.
3224 BUFFER-NAME is the name of the main buffer being visited."
3225 (or buffer-name
(setq buffer-name
(buffer-name)))
3226 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3227 "%buffer%" buffer-name
3228 markdown-reference-check-buffer
))))
3229 (with-current-buffer refbuf
3231 (View-exit-and-edit))
3232 (use-local-map button-buffer-map
)
3236 (defconst markdown-reference-links-buffer
3237 "*Reference links for %buffer%*"
3238 "Pattern for name of buffer for listing references.
3239 The string %buffer% will be replaced by the corresponding buffer name.")
3241 (defun markdown-reference-links-buffer (&optional buffer-name
)
3242 "Name, setup, and return a buffer for listing links.
3243 BUFFER-NAME is the name of the main buffer being visited."
3244 (or buffer-name
(setq buffer-name
(buffer-name)))
3245 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3246 "%buffer%" buffer-name
3247 markdown-reference-links-buffer
))))
3248 (with-current-buffer linkbuf
3250 (View-exit-and-edit))
3251 (use-local-map button-buffer-map
)
3255 (when (markdown-use-buttons-p)
3256 ;; Add an empty Markdown reference definition to the end of buffer
3257 ;; specified in the 'target-buffer property. The reference name is
3258 ;; the button's label.
3259 (define-button-type 'markdown-undefined-reference-button
3260 'help-echo
"mouse-1, RET: create definition for undefined reference"
3264 (let ((buffer (button-get b
'target-buffer
)))
3265 (markdown-insert-reference-definition (button-label b
) buffer
)
3266 (switch-to-buffer-other-window buffer
)
3267 (goto-char (point-max))
3268 (markdown-check-refs t
))))
3270 ;; Jump to line in buffer specified by 'target-buffer property.
3271 ;; Line number is button's 'line property.
3272 (define-button-type 'markdown-goto-line-button
3273 'help-echo
"mouse-1, RET: go to line"
3277 (message (button-get b
'buffer
))
3278 (switch-to-buffer-other-window (button-get b
'target-buffer
))
3279 ;; use call-interactively to silence compiler
3280 (let ((current-prefix-arg (button-get b
'target-line
)))
3281 (call-interactively 'goto-line
))))
3283 ;; Jumps to a particular link at location given by 'target-char
3284 ;; property in buffer given by 'target-buffer property.
3285 (define-button-type 'markdown-link-button
3286 'help-echo
"mouse-1, RET: jump to location of link"
3290 (let ((target (button-get b
'target-buffer
))
3291 (loc (button-get b
'target-char
)))
3292 (kill-buffer-and-window)
3293 (switch-to-buffer target
)
3296 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
3297 "Insert a button for creating REFERENCE in buffer OLDBUF.
3298 REFERENCE should be a list of the form (reference . occurrences),
3299 as by `markdown-get-undefined-refs'."
3300 (let ((label (car reference
)))
3301 (if (markdown-use-buttons-p)
3302 ;; Create a reference button in Emacs 22
3303 (insert-button label
3304 :type
'markdown-undefined-reference-button
3305 'target-buffer oldbuf
)
3306 ;; Insert reference as text in Emacs < 22
3309 (dolist (occurrence (cdr reference
))
3310 (let ((line (cdr occurrence
)))
3311 (if (markdown-use-buttons-p)
3312 ;; Create a line number button in Emacs 22
3313 (insert-button (number-to-string line
)
3314 :type
'markdown-goto-line-button
3315 'target-buffer oldbuf
3317 ;; Insert line number as text in Emacs < 22
3318 (insert (number-to-string line
)))
3324 (defun markdown-insert-link-button (link oldbuf
)
3325 "Insert a button for jumping to LINK in buffer OLDBUF.
3326 LINK should be a list of the form (text char line) containing
3327 the link text, location, and line number."
3328 (let ((label (first link
))
3329 (char (second link
))
3330 (line (third link
)))
3331 (if (markdown-use-buttons-p)
3332 ;; Create a reference button in Emacs 22
3333 (insert-button label
3334 :type
'markdown-link-button
3335 'target-buffer oldbuf
3337 ;; Insert reference as text in Emacs < 22
3339 (insert (format " (line %d)\n" line
))))
3341 (defun markdown-reference-goto-link (&optional reference
)
3342 "Jump to the location of the first use of REFERENCE."
3345 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
3346 (setq reference
(match-string-no-properties 1))
3347 (error "No reference definition at point")))
3348 (let ((links (markdown-reference-find-links reference
)))
3349 (cond ((= (length links
) 1)
3350 (goto-char (cadr (car links
))))
3351 ((> (length links
) 1)
3352 (let ((oldbuf (current-buffer))
3353 (linkbuf (markdown-reference-links-buffer)))
3354 (with-current-buffer linkbuf
3355 (insert "Links using reference " reference
":\n\n")
3356 (dolist (link (reverse links
))
3357 (markdown-insert-link-button link oldbuf
)))
3358 (view-buffer-other-window linkbuf
)
3359 (goto-char (point-min))
3362 (error "No links for reference %s" reference
)))))
3364 (defun markdown-check-refs (&optional silent
)
3365 "Show all undefined Markdown references in current `markdown-mode' buffer.
3366 If SILENT is non-nil, do not message anything when no undefined
3368 Links which have empty reference definitions are considered to be
3371 (when (not (eq major-mode
'markdown-mode
))
3372 (error "Not available in current mode"))
3373 (let ((oldbuf (current-buffer))
3374 (refs (markdown-get-undefined-refs))
3375 (refbuf (markdown-reference-check-buffer)))
3379 (message "No undefined references found"))
3380 (kill-buffer refbuf
))
3381 (with-current-buffer refbuf
3382 (insert "The following references are undefined:\n\n")
3384 (markdown-insert-undefined-reference-button ref oldbuf
))
3385 (view-buffer-other-window refbuf
)
3386 (goto-char (point-min))
3387 (forward-line 2)))))
3390 ;;; Lists =====================================================================
3392 (defun markdown-insert-list-item (&optional arg
)
3393 "Insert a new list item.
3394 If the point is inside unordered list, insert a bullet mark. If
3395 the point is inside ordered list, insert the next number followed
3396 by a period. Use the previous list item to determine the amount
3397 of whitespace to place before and after list markers.
3399 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3400 decrease the indentation by one level.
3402 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3403 increase the indentation by one level."
3405 (let (bounds item-indent marker indent new-indent new-loc
)
3407 ;; Look for a list item on current or previous non-blank line
3409 (while (and (not (setq bounds
(markdown-cur-list-item-bounds)))
3411 (markdown-cur-line-blank-p))
3414 (cond ((save-excursion
3415 (skip-chars-backward " \t")
3416 (looking-at markdown-regex-list
))
3420 ((not (markdown-cur-line-blank-p))
3422 (setq new-loc
(point)))
3423 ;; Look ahead for a list item on next non-blank line
3426 (while (and (null bounds
)
3428 (markdown-cur-line-blank-p))
3430 (setq bounds
(markdown-cur-list-item-bounds))))
3432 (setq new-loc
(point))
3433 (unless (markdown-cur-line-blank-p)
3436 ;; When not in a list, start a new unordered one
3438 (unless (markdown-cur-line-blank-p)
3441 ;; Compute indentation for a new list item
3442 (setq item-indent
(nth 2 bounds
))
3443 (setq marker
(nth 4 bounds
))
3445 ((= arg
4) (max (- item-indent
4) 0))
3446 ((= arg
16) (+ item-indent
4))
3448 (setq new-indent
(make-string indent
32))
3452 ((string-match "[0-9]" marker
)
3453 (if (= arg
16) ;; starting a new column indented one more level
3454 (insert (concat new-indent
"1. "))
3455 ;; travel up to the last item and pick the correct number. If
3456 ;; the argument was nil, "new-indent = item-indent" is the same,
3457 ;; so we don't need special treatment. Neat.
3459 (while (not (looking-at (concat new-indent
"\\([0-9]+\\)\\.")))
3461 (insert (concat new-indent
3462 (int-to-string (1+ (string-to-number (match-string 1))))
3465 ((string-match "[\\*\\+-]" marker
)
3466 (insert new-indent marker
)))))))
3468 (defun markdown-move-list-item-up ()
3469 "Move the current list item up in the list when possible."
3472 (when (setq cur
(markdown-cur-list-item-bounds))
3474 (goto-char (nth 0 cur
))
3475 (if (markdown-prev-list-item (nth 3 cur
))
3477 (setq prev
(markdown-cur-list-item-bounds))
3480 (transpose-regions (nth 0 prev
) (nth 1 prev
)
3481 (nth 0 cur
) (nth 1 cur
) t
)
3482 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
3483 ;; Catch error in case regions overlap.
3484 (error (goto-char old
))))
3487 (defun markdown-move-list-item-down ()
3488 "Move the current list item down in the list when possible."
3491 (when (setq cur
(markdown-cur-list-item-bounds))
3493 (if (markdown-next-list-item (nth 3 cur
))
3495 (setq next
(markdown-cur-list-item-bounds))
3498 (transpose-regions (nth 0 cur
) (nth 1 cur
)
3499 (nth 0 next
) (nth 1 next
) nil
)
3500 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
3501 ;; Catch error in case regions overlap.
3502 (error (goto-char old
))))
3505 (defun markdown-demote-list-item (&optional bounds
)
3506 "Indent (or demote) the current list item.
3507 Optionally, BOUNDS of the current list item may be provided if available."
3509 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3512 (let* ((end-marker (make-marker))
3513 (end-marker (set-marker end-marker
(nth 1 bounds
))))
3514 (goto-char (nth 0 bounds
))
3515 (while (< (point) end-marker
)
3516 (unless (markdown-cur-line-blank-p)
3518 (forward-line)))))))
3520 (defun markdown-promote-list-item (&optional bounds
)
3521 "Unindent (or promote) the current list item.
3522 Optionally, BOUNDS of the current list item may be provided if available."
3524 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3527 (let* ((end-marker (make-marker))
3528 (end-marker (set-marker end-marker
(nth 1 bounds
)))
3530 (goto-char (nth 0 bounds
))
3531 (when (looking-at "^[ ]\\{1,4\\}")
3532 (setq num
(- (match-end 0) (match-beginning 0)))
3533 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
3534 (while (and (< (point) end-marker
)
3535 (re-search-forward regexp end-marker t
))
3536 (replace-match "" nil nil
)
3537 (forward-line))))))))
3539 (defun markdown--cleanup-list-numbers-level (&optional pfx
)
3540 "Update the numbering for level PFX (as a string of spaces).
3542 Assume that the previously found match was for a numbered item in
3549 (while (and continue
(not (eobp)))
3552 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3553 (setq cpfx
(match-string-no-properties 1))
3557 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". "))
3561 (setq sep
(markdown--cleanup-list-numbers-level cpfx
))
3566 (setq continue nil
))))
3568 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3569 (setq cpfx
(match-string-no-properties 1))
3571 ;; reset if separated before
3572 ((string= cpfx pfx
) (when sep
(setq idx
0)))
3575 (setq continue nil
))))
3580 (setq continue
(= (forward-line) 0))))
3583 (defun markdown-cleanup-list-numbers ()
3584 "Update the numbering of ordered lists."
3587 (goto-char (point-min))
3588 (markdown--cleanup-list-numbers-level "")))
3591 ;;; Outline ===================================================================
3593 (defvar markdown-cycle-global-status
1)
3594 (defvar markdown-cycle-subtree-status nil
)
3596 (defun markdown-end-of-subtree (&optional invisible-OK
)
3597 "Move to the end of the current subtree.
3598 Only visible heading lines are considered, unless INVISIBLE-OK is
3600 Derived from `org-end-of-subtree'."
3601 (outline-back-to-heading invisible-OK
)
3603 (level (funcall outline-level
)))
3604 (while (and (not (eobp))
3605 (or first
(> (funcall outline-level
) level
)))
3607 (outline-next-heading))
3608 (if (memq (preceding-char) '(?
\n ?\^M
))
3610 ;; Go to end of line before heading
3612 (if (memq (preceding-char) '(?
\n ?\^M
))
3613 ;; leave blank line before heading
3614 (forward-char -
1)))))
3617 (defun markdown-cycle (&optional arg
)
3618 "Visibility cycling for Markdown mode.
3619 If ARG is t, perform global visibility cycling. If the point is
3620 at an atx-style header, cycle visibility of the corresponding
3621 subtree. Otherwise, insert a tab using `indent-relative'.
3622 Derived from `org-cycle'."
3625 ((eq arg t
) ;; Global cycling
3627 ((and (eq last-command this-command
)
3628 (eq markdown-cycle-global-status
2))
3629 ;; Move from overview to contents
3631 (message "CONTENTS")
3632 (setq markdown-cycle-global-status
3))
3634 ((and (eq last-command this-command
)
3635 (eq markdown-cycle-global-status
3))
3636 ;; Move from contents to all
3638 (message "SHOW ALL")
3639 (setq markdown-cycle-global-status
1))
3642 ;; Defaults to overview
3644 (message "OVERVIEW")
3645 (setq markdown-cycle-global-status
2))))
3647 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
3648 ;; At a heading: rotate between three different views
3649 (outline-back-to-heading)
3650 (let ((goal-column 0) eoh eol eos
)
3651 ;; Determine boundaries
3653 (outline-back-to-heading)
3655 (beginning-of-line 2)
3656 (while (and (not (eobp)) ;; this is like `next-line'
3657 (get-char-property (1- (point)) 'invisible
))
3658 (beginning-of-line 2)) (setq eol
(point)))
3659 (outline-end-of-heading) (setq eoh
(point))
3660 (markdown-end-of-subtree t
)
3661 (skip-chars-forward " \t\n")
3662 (beginning-of-line 1) ; in case this is an item
3663 (setq eos
(1- (point))))
3664 ;; Find out what to do next and set `this-command'
3667 ;; Nothing is hidden behind this heading
3668 (message "EMPTY ENTRY")
3669 (setq markdown-cycle-subtree-status nil
))
3671 ;; Entire subtree is hidden in one line: open it
3674 (message "CHILDREN")
3675 (setq markdown-cycle-subtree-status
'children
))
3676 ((and (eq last-command this-command
)
3677 (eq markdown-cycle-subtree-status
'children
))
3678 ;; We just showed the children, now show everything.
3681 (setq markdown-cycle-subtree-status
'subtree
))
3683 ;; Default action: hide the subtree.
3686 (setq markdown-cycle-subtree-status
'folded
)))))
3689 (indent-for-tab-command))))
3691 (defun markdown-shifttab ()
3692 "Global visibility cycling.
3693 Calls `markdown-cycle' with argument t."
3697 (defun markdown-outline-level ()
3698 "Return the depth to which a statement is nested in the outline."
3702 ((- (match-end 5) (match-beginning 5)))))
3705 ;;; Movement ==================================================================
3707 (defun markdown-beginning-of-defun (&optional arg
)
3708 "`beginning-of-defun-function' for Markdown.
3709 Move backward to the beginning of the current or previous section.
3710 When ARG is non-nil, repeat that many times. When ARG is negative,
3711 move forward to the ARG-th following section."
3713 (or arg
(setq arg
1))
3714 (or (re-search-backward markdown-regex-header nil t arg
)
3715 (goto-char (point-min))))
3717 (defun markdown-end-of-defun (&optional arg
)
3718 "`end-of-defun-function' for Markdown.
3719 Move forward to the end of the current or following section.
3720 When ARG is non-nil, repeat that many times. When ARG is negative,
3721 move back to the ARG-th preceding section."
3723 (or arg
(setq arg
1))
3724 (when (looking-at markdown-regex-header
)
3725 (goto-char (match-beginning 0))
3727 (if (re-search-forward markdown-regex-header nil t arg
)
3728 (goto-char (match-beginning 0))
3729 (goto-char (point-max)))
3730 (skip-syntax-backward "-"))
3732 (defun markdown-beginning-of-block ()
3733 "Move the point to the start of the previous text block."
3735 (if (re-search-backward markdown-regex-block-separator nil t
)
3736 (goto-char (or (match-end 2) (match-end 0)))
3737 (goto-char (point-min))))
3739 (defun markdown-end-of-block ()
3740 "Move the point to the start of the next text block."
3743 (skip-syntax-forward "-")
3744 (when (= (point) (point-min))
3746 (if (re-search-forward markdown-regex-block-separator nil t
)
3747 (goto-char (or (match-end 2) (match-end 0)))
3748 (goto-char (point-max)))
3749 (skip-syntax-backward "-")
3752 (defun markdown-end-of-block-element ()
3753 "Move the point to the start of the next block unit.
3754 Stops at blank lines, list items, headers, and horizontal rules."
3757 (while (and (or (not (markdown-prev-line-blank-p))
3758 (markdown-cur-line-blank-p))
3759 (not (or (looking-at markdown-regex-list
)
3760 (looking-at markdown-regex-header
)
3761 (looking-at markdown-regex-hr
)))
3765 (defun markdown-next-link ()
3766 "Jump to next inline, reference, or wiki link.
3767 If successful, return point. Otherwise, return nil.
3768 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3770 (let ((opoint (point)))
3771 (when (or (markdown-link-p) (markdown-wiki-link-p))
3772 ;; At a link already, move past it.
3773 (goto-char (+ (match-end 0) 1)))
3774 ;; Search for the next wiki link and move to the beginning.
3775 (if (re-search-forward markdown-regex-link-generic nil t
)
3776 ;; Group 1 will move past non-escape character in wiki link regexp.
3777 ;; Go to beginning of group zero for all other link types.
3778 (goto-char (or (match-beginning 1) (match-beginning 0)))
3782 (defun markdown-previous-link ()
3783 "Jump to previous wiki link.
3784 If successful, return point. Otherwise, return nil.
3785 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3787 (if (re-search-backward markdown-regex-link-generic nil t
)
3788 (goto-char (or (match-beginning 1) (match-beginning 0)))
3792 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3794 (defun markdown-move-up ()
3796 Calls `markdown-move-list-item-up'."
3798 (markdown-move-list-item-up))
3800 (defun markdown-move-down ()
3801 "Move list item down.
3802 Calls `markdown-move-list-item-down'."
3804 (markdown-move-list-item-down))
3806 (defun markdown-promote ()
3807 "Either promote header or list item at point or cycle markup.
3808 See `markdown-cycle-atx', `markdown-cycle-setext', and
3809 `markdown-demote-list-item'."
3813 ;; Promote atx header
3814 ((thing-at-point-looking-at markdown-regex-header-atx
)
3815 (markdown-cycle-atx -
1 t
))
3816 ;; Promote setext header
3817 ((thing-at-point-looking-at markdown-regex-header-setext
)
3818 (markdown-cycle-setext -
1 t
))
3819 ;; Promote horizonal rule
3820 ((thing-at-point-looking-at markdown-regex-hr
)
3821 (markdown-cycle-hr -
1 t
))
3822 ;; Promote list item
3823 ((setq bounds
(markdown-cur-list-item-bounds))
3824 (markdown-promote-list-item)))))
3826 (defun markdown-demote ()
3827 "Either demote header or list item at point or cycle or remove markup.
3828 See `markdown-cycle-atx', `markdown-cycle-setext', and
3829 `markdown-demote-list-item'."
3833 ;; Demote atx header
3834 ((thing-at-point-looking-at markdown-regex-header-atx
)
3835 (markdown-cycle-atx 1 t
))
3836 ;; Demote setext header
3837 ((thing-at-point-looking-at markdown-regex-header-setext
)
3838 (markdown-cycle-setext 1 t
))
3839 ;; Demote horizonal rule
3840 ((thing-at-point-looking-at markdown-regex-hr
)
3841 (markdown-cycle-hr 1 t
))
3842 ;; Promote list item
3843 ((setq bounds
(markdown-cur-list-item-bounds))
3844 (markdown-demote-list-item))
3845 ;; Create a new level one ATX header
3847 (markdown-insert-header-atx-1)))))
3849 (defun markdown-complete-or-cycle (arg)
3850 "Complete or cycle markup of object at point or complete objects in region.
3851 If there is an active region, complete markup in region.
3852 Otherwise, complete or cycle markup of object near point.
3853 When ARG is non-nil, cycle backwards when cycling."
3855 (if (markdown-use-region-p)
3856 ;; Complete markup in region
3857 (markdown-complete-region (region-beginning) (region-end))
3858 ;; Complete or cycle markup at point
3859 (let ((dir (if arg -
1 1))
3863 ((thing-at-point-looking-at markdown-regex-header-atx
)
3864 (if (markdown-incomplete-atx-p)
3865 (markdown-complete-atx)
3866 (markdown-cycle-atx dir
)))
3868 ((thing-at-point-looking-at markdown-regex-header-setext
)
3869 (if (markdown-incomplete-setext-p)
3870 (markdown-complete-setext)
3871 (markdown-cycle-setext dir
)))
3873 ((thing-at-point-looking-at markdown-regex-hr
)
3874 (if (markdown-incomplete-hr-p)
3875 (markdown-complete-hr)
3876 (markdown-cycle-hr dir
)))
3878 ((thing-at-point-looking-at markdown-regex-bold
)
3879 (markdown-cycle-bold))
3881 ((thing-at-point-looking-at markdown-regex-italic
)
3882 (markdown-cycle-italic))))))
3885 ;;; Commands ==================================================================
3887 (defun markdown (&optional output-buffer-name
)
3888 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3889 The output buffer name defaults to `markdown-output-buffer-name'.
3890 Return the name of the output buffer used."
3892 (save-window-excursion
3893 (let ((begin-region)
3895 (if (markdown-use-region-p)
3896 (setq begin-region
(region-beginning)
3897 end-region
(region-end))
3898 (setq begin-region
(point-min)
3899 end-region
(point-max)))
3901 (unless output-buffer-name
3902 (setq output-buffer-name markdown-output-buffer-name
))
3905 ;; Handle case when `markdown-command' does not read from stdin
3906 (markdown-command-needs-filename
3907 (if (not buffer-file-name
)
3908 (error "Must be visiting a file")
3909 (shell-command (concat markdown-command
" "
3910 (shell-quote-argument buffer-file-name
))
3911 output-buffer-name
)))
3912 ;; Pass region to `markdown-command' via stdin
3914 (shell-command-on-region begin-region end-region markdown-command
3915 output-buffer-name
))))
3916 output-buffer-name
))
3918 (defun markdown-standalone (&optional output-buffer-name
)
3919 "Special function to provide standalone HTML output.
3920 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3922 (setq output-buffer-name
(markdown output-buffer-name
))
3923 (with-current-buffer output-buffer-name
3924 (set-buffer output-buffer-name
)
3925 (goto-char (point-min))
3926 (unless (markdown-output-standalone-p)
3927 (markdown-add-xhtml-header-and-footer output-buffer-name
))
3931 (defun markdown-other-window (&optional output-buffer-name
)
3932 "Run `markdown-command' on current buffer and display in other window.
3933 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3936 (display-buffer (markdown-standalone output-buffer-name
)))
3938 (defun markdown-output-standalone-p ()
3939 "Determine whether `markdown-command' output is standalone XHTML.
3940 Standalone XHTML output is identified by an occurrence of
3941 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3943 markdown-xhtml-standalone-regexp
3944 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3947 (defun markdown-add-xhtml-header-and-footer (title)
3948 "Wrap XHTML header and footer with given TITLE around current buffer."
3949 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3950 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3951 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3952 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3955 (insert "</title>\n")
3956 (when (> (length markdown-content-type
) 0)
3959 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3960 markdown-content-type
3961 (or (and markdown-coding-system
3962 (fboundp 'coding-system-get
)
3963 (coding-system-get markdown-coding-system
3965 (and (fboundp 'coding-system-get
)
3966 (coding-system-get buffer-file-coding-system
3969 (if (> (length markdown-css-path
) 0)
3970 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3973 (when (> (length markdown-xhtml-header-content
) 0)
3974 (insert markdown-xhtml-header-content
))
3975 (insert "\n</head>\n\n"
3977 (goto-char (point-max))
3982 (defun markdown-preview (&optional output-buffer-name
)
3983 "Run `markdown-command' on the current buffer and view output in browser.
3984 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3987 (browse-url-of-buffer (markdown markdown-output-buffer-name
)))
3989 (defun markdown-export-file-name (&optional extension
)
3990 "Attempt to generate a filename for Markdown output.
3991 The file extension will be EXTENSION if given, or .html by default.
3992 If the current buffer is visiting a file, we construct a new
3993 output filename based on that filename. Otherwise, return nil."
3994 (when (buffer-file-name)
3996 (setq extension
".html"))
4000 (file-name-sans-extension (buffer-file-name)))
4004 (defun markdown-export (&optional output-file
)
4005 "Run Markdown on the current buffer, save to file, and return the filename.
4006 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4007 generated by `markdown-export-file-name', which will be constructed using the
4008 current filename, but with the extension removed and replaced with .html."
4011 (setq output-file
(markdown-export-file-name ".html")))
4013 (let ((output-buffer-name))
4014 (setq output-buffer-name
(buffer-name (find-file-noselect output-file
)))
4015 (run-hook-with-args 'markdown-before-export-hooks output-file
)
4016 (markdown-standalone output-buffer-name
)
4017 (with-current-buffer output-buffer-name
4019 (run-hook-with-args 'markdown-after-export-hooks output-file
)
4022 (defun markdown-export-and-preview ()
4023 "Export to XHTML using `markdown-export' and browse the resulting file."
4025 (browse-url (markdown-export)))
4027 (defun markdown-open ()
4028 "Open file for the current buffer with `markdown-open-command'."
4030 (if (not markdown-open-command
)
4031 (error "Variable `markdown-open-command' must be set")
4032 (if (not buffer-file-name
)
4033 (error "Must be visiting a file")
4034 (call-process markdown-open-command
4035 nil nil nil buffer-file-name
))))
4037 (defun markdown-kill-ring-save ()
4038 "Run Markdown on file and store output in the kill ring."
4040 (save-window-excursion
4042 (with-current-buffer markdown-output-buffer-name
4043 (kill-ring-save (point-min) (point-max)))))
4046 ;;; Links =====================================================================
4048 (require 'thingatpt
)
4050 (defun markdown-link-p ()
4051 "Return non-nil when `point' is at a non-wiki link.
4052 See `markdown-wiki-link-p' for more information."
4053 (let ((case-fold-search nil
))
4054 (and (not (markdown-wiki-link-p))
4055 (or (thing-at-point-looking-at markdown-regex-link-inline
)
4056 (thing-at-point-looking-at markdown-regex-link-reference
)
4057 (thing-at-point-looking-at markdown-regex-uri
)
4058 (thing-at-point-looking-at markdown-regex-angle-uri
)))))
4060 (defun markdown-link-link ()
4061 "Return the link part of the regular (non-wiki) link at point.
4062 Works with both inline and reference style links. If point is
4063 not at a link or the link reference is not defined returns nil."
4065 ((thing-at-point-looking-at markdown-regex-link-inline
)
4066 (match-string-no-properties 5))
4067 ((thing-at-point-looking-at markdown-regex-link-reference
)
4068 (let* ((text (match-string-no-properties 2))
4069 (reference (match-string-no-properties 4))
4070 (target (downcase (if (string= reference
"[]") text reference
))))
4071 (car (markdown-reference-definition target
))))
4072 ((thing-at-point-looking-at markdown-regex-uri
)
4073 (match-string-no-properties 0))
4074 ((thing-at-point-looking-at markdown-regex-angle-uri
)
4075 (match-string-no-properties 2))
4078 (defun markdown-follow-link-at-point ()
4079 "Open the current non-wiki link in a browser."
4081 (if (markdown-link-p) (browse-url (markdown-link-link))
4082 (error "Point is not at a Markdown link or URI")))
4085 ;;; WikiLink Following/Markup =================================================
4087 (defun markdown-wiki-link-p ()
4088 "Return non-nil when `point' is at a true wiki link.
4089 A true wiki link name matches `markdown-regex-wiki-link' but does not
4090 match the current file name after conversion. This modifies the data
4091 returned by `match-data'. Note that the potential wiki link name must
4092 be available via `match-string'."
4093 (let ((case-fold-search nil
))
4094 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
4095 (or (not buffer-file-name
)
4096 (not (string-equal (buffer-file-name)
4097 (markdown-convert-wiki-link-to-filename
4098 (markdown-wiki-link-link)))))
4099 (not (save-match-data
4100 (save-excursion))))))
4102 (defun markdown-wiki-link-link ()
4103 "Return the link part of the wiki link using current match data.
4104 The location of the link component depends on the value of
4105 `markdown-wiki-link-alias-first'."
4106 (if markdown-wiki-link-alias-first
4107 (or (match-string-no-properties 4) (match-string-no-properties 2))
4108 (match-string-no-properties 2)))
4110 (defun markdown-convert-wiki-link-to-filename (name)
4111 "Generate a filename from the wiki link NAME.
4112 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4113 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4114 and [[test test]] both map to Test-test.ext."
4115 (let ((basename (markdown-replace-regexp-in-string
4116 "[[:space:]\n]" markdown-link-space-sub-char name
)))
4117 (when (eq major-mode
'gfm-mode
)
4118 (setq basename
(concat (upcase (substring basename
0 1))
4119 (downcase (substring basename
1 nil
)))))
4121 (if (buffer-file-name)
4123 (file-name-extension (buffer-file-name)))))))
4125 (defun markdown-follow-wiki-link (name &optional other
)
4126 "Follow the wiki link NAME.
4127 Convert the name to a file name and call `find-file'. Ensure that
4128 the new buffer remains in `markdown-mode'. Open the link in another
4129 window when OTHER is non-nil."
4130 (let ((filename (markdown-convert-wiki-link-to-filename name
))
4131 (wp (file-name-directory buffer-file-name
)))
4132 (when other
(other-window 1))
4133 (find-file (concat wp filename
)))
4134 (when (not (eq major-mode
'markdown-mode
))
4137 (defun markdown-follow-wiki-link-at-point (&optional arg
)
4138 "Find Wiki Link at point.
4139 With prefix argument ARG, open the file in other window.
4140 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4142 (if (markdown-wiki-link-p)
4143 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
4144 (error "Point is not at a Wiki Link")))
4146 (defun markdown-highlight-wiki-link (from to face
)
4147 "Highlight the wiki link in the region between FROM and TO using FACE."
4148 (put-text-property from to
'font-lock-face face
))
4150 (defun markdown-unfontify-region-wiki-links (from to
)
4151 "Remove wiki link faces from the region specified by FROM and TO."
4152 (interactive "nfrom: \nnto: ")
4153 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
4154 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
)))
4156 (defun markdown-fontify-region-wiki-links (from to
)
4157 "Search region given by FROM and TO for wiki links and fontify them.
4158 If a wiki link is found check to see if the backing file exists
4159 and highlight accordingly."
4162 (while (re-search-forward markdown-regex-wiki-link to t
)
4163 (let ((highlight-beginning (match-beginning 1))
4164 (highlight-end (match-end 1))
4166 (markdown-convert-wiki-link-to-filename
4167 (markdown-wiki-link-link))))
4168 (if (file-exists-p file-name
)
4169 (markdown-highlight-wiki-link
4170 highlight-beginning highlight-end markdown-link-face
)
4171 (markdown-highlight-wiki-link
4172 highlight-beginning highlight-end markdown-link-face
)
4173 (markdown-highlight-wiki-link
4174 highlight-beginning highlight-end markdown-missing-link-face
))))))
4176 (defun markdown-extend-changed-region (from to
)
4177 "Extend region given by FROM and TO so that we can fontify all links.
4178 The region is extended to the first newline before and the first
4180 ;; start looking for the first new line before 'from
4182 (re-search-backward "\n" nil t
)
4183 (let ((new-from (point-min))
4184 (new-to (point-max)))
4185 (if (not (= (point) from
))
4186 (setq new-from
(point)))
4187 ;; do the same thing for the first new line after 'to
4189 (re-search-forward "\n" nil t
)
4190 (if (not (= (point) to
))
4191 (setq new-to
(point)))
4192 (values new-from new-to
)))
4194 (defun markdown-check-change-for-wiki-link (from to change
)
4195 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4196 Designed to be used with the `after-change-functions' hook.
4197 CHANGE is the number of bytes of pre-change text replaced by the
4199 (interactive "nfrom: \nnto: \nnchange: ")
4200 (let* ((modified (buffer-modified-p))
4201 (buffer-undo-list t
)
4202 (inhibit-read-only t
)
4203 (inhibit-point-motion-hooks t
)
4205 buffer-file-truename
)
4210 ;; Extend the region to fontify so that it starts
4211 ;; and ends at safe places.
4212 (multiple-value-bind (new-from new-to
)
4213 (markdown-extend-changed-region from to
)
4214 ;; Unfontify existing fontification (start from scratch)
4215 (markdown-unfontify-region-wiki-links new-from new-to
)
4216 ;; Now do the fontification.
4217 (markdown-fontify-region-wiki-links new-from new-to
)))))
4220 (set-buffer-modified-p nil
)))))
4222 (defun markdown-fontify-buffer-wiki-links ()
4223 "Refontify all wiki links in the buffer."
4225 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4228 ;;; Following and Jumping =====================================================
4230 (defun markdown-follow-thing-at-point (arg)
4231 "Follow thing at point if possible, such as a reference link or wiki link.
4232 Opens inline and reference links in a browser. Opens wiki links
4233 to other files in the current window, or the another window if
4235 See `markdown-follow-link-at-point' and
4236 `markdown-follow-wiki-link-at-point'."
4238 (cond ((markdown-link-p)
4239 (markdown-follow-link-at-point))
4240 ((markdown-wiki-link-p)
4241 (markdown-follow-wiki-link-at-point arg
))
4243 (error "Nothing to follow at point"))))
4245 (defun markdown-jump ()
4246 "Jump to another location based on context at point.
4247 Jumps between reference links and definitions; between footnote
4248 markers and footnote text."
4250 (cond ((markdown-footnote-text-positions)
4251 (markdown-footnote-return))
4252 ((markdown-footnote-marker-positions)
4253 (markdown-footnote-goto-text))
4254 ((thing-at-point-looking-at markdown-regex-link-reference
)
4255 (markdown-reference-goto-definition))
4256 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4257 (markdown-reference-goto-link (match-string-no-properties 1)))
4259 (error "Nothing to jump to from context at point"))))
4262 ;;; Miscellaneous =============================================================
4264 (defun markdown-compress-whitespace-string (str)
4265 "Compress whitespace in STR and return result.
4266 Leading and trailing whitespace is removed. Sequences of multiple
4267 spaces, tabs, and newlines are replaced with single spaces."
4268 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4269 (replace-regexp-in-string "[ \t\n]+" " " str
)))
4271 (defun markdown-line-number-at-pos (&optional pos
)
4272 "Return (narrowed) buffer line number at position POS.
4273 If POS is nil, use current buffer location.
4274 This is an exact copy of `line-number-at-pos' for use in emacs21."
4275 (let ((opoint (or pos
(point))) start
)
4277 (goto-char (point-min))
4278 (setq start
(point))
4281 (1+ (count-lines start
(point))))))
4283 (defun markdown-nobreak-p ()
4284 "Return nil if it is acceptable to break the current line at the point."
4285 ;; inside in square brackets (e.g., link anchor text)
4286 (looking-back "\\[[^]]*"))
4288 (defun markdown-adaptive-fill-function ()
4289 "Return prefix for filling paragraph or nil if not determined."
4291 ;; List item inside blockquote
4292 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4293 (replace-regexp-in-string
4294 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4296 ((looking-at "^[ \t]*>[ \t]*")
4297 (match-string-no-properties 0))
4299 ((looking-at markdown-regex-list
)
4300 (match-string-no-properties 0))
4305 ;;; Extensions ================================================================
4307 (defun markdown-reload-extensions ()
4308 "Check settings, update font-lock keywords, and re-fontify buffer."
4310 (when (eq major-mode
'markdown-mode
)
4311 (setq markdown-mode-font-lock-keywords
4313 (when markdown-enable-math
4314 markdown-mode-font-lock-keywords-math
)
4315 markdown-mode-font-lock-keywords-basic
4316 markdown-mode-font-lock-keywords-core
))
4317 (setq font-lock-defaults
'(markdown-mode-font-lock-keywords))
4318 (font-lock-refresh-defaults)))
4320 (defun markdown-enable-math (&optional arg
)
4321 "Toggle support for inline and display LaTeX math expressions.
4322 With a prefix argument ARG, enable math mode if ARG is positive,
4323 and disable it otherwise. If called from Lisp, enable the mode
4324 if ARG is omitted or nil."
4325 (interactive (list (or current-prefix-arg
'toggle
)))
4326 (setq markdown-enable-math
4327 (if (eq arg
'toggle
)
4328 (not markdown-enable-math
)
4329 (> (prefix-numeric-value arg
) 0)))
4330 (if markdown-enable-math
4331 (message "markdown-mode math support enabled")
4332 (message "markdown-mode math support disabled"))
4333 (markdown-reload-extensions))
4336 ;;; Mode Definition ==========================================================
4338 (defun markdown-show-version ()
4339 "Show the version number in the minibuffer."
4341 (message "markdown-mode, version %s" markdown-mode-version
))
4344 (define-derived-mode markdown-mode text-mode
"Markdown"
4345 "Major mode for editing Markdown files."
4346 ;; Natural Markdown tab width
4349 (make-local-variable 'comment-start
)
4350 (setq comment-start
"<!-- ")
4351 (make-local-variable 'comment-end
)
4352 (setq comment-end
" -->")
4353 (make-local-variable 'comment-start-skip
)
4354 (setq comment-start-skip
"<!--[ \t]*")
4355 (make-local-variable 'comment-column
)
4356 (setq comment-column
0)
4358 (set (make-local-variable 'markdown-mode-font-lock-keywords
) nil
)
4359 (set (make-local-variable 'font-lock-defaults
) nil
)
4360 (set (make-local-variable 'font-lock-multiline
) t
)
4361 (markdown-reload-extensions)
4363 (make-local-variable 'markdown-enable-math
)
4364 (add-hook 'hack-local-variables-hook
'markdown-reload-extensions
)
4365 ;; For imenu support
4366 (setq imenu-create-index-function
'markdown-imenu-create-index
)
4367 ;; For menu support in XEmacs
4368 (easy-menu-add markdown-mode-menu markdown-mode-map
)
4370 (set (make-local-variable 'beginning-of-defun-function
)
4371 'markdown-beginning-of-defun
)
4372 (set (make-local-variable 'end-of-defun-function
)
4373 'markdown-end-of-defun
)
4374 ;; Paragraph filling
4375 (set (make-local-variable 'paragraph-start
)
4376 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4377 (set (make-local-variable 'paragraph-separate
)
4378 "\\(?:[ \t\f]\\|.* \\)*$")
4379 (set (make-local-variable 'adaptive-fill-first-line-regexp
)
4380 "\\`[ \t]*>[ \t]*?\\'")
4381 (set (make-local-variable 'adaptive-fill-function
)
4382 'markdown-adaptive-fill-function
)
4384 (make-local-variable 'outline-regexp
)
4385 (setq outline-regexp markdown-regex-header
)
4386 (make-local-variable 'outline-level
)
4387 (setq outline-level
'markdown-outline-level
)
4388 ;; Cause use of ellipses for invisible text.
4389 (add-to-invisibility-spec '(outline . t
))
4390 ;; Indentation and filling
4391 (make-local-variable 'fill-nobreak-predicate
)
4392 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
4393 (setq indent-line-function markdown-indent-function
)
4395 ;; Prepare hooks for XEmacs compatibility
4396 (when (featurep 'xemacs
)
4397 (make-local-hook 'after-change-functions
)
4398 (make-local-hook 'font-lock-extend-region-functions
)
4399 (make-local-hook 'window-configuration-change-hook
))
4401 ;; Multiline font lock
4402 (add-hook 'font-lock-extend-region-functions
4403 'markdown-font-lock-extend-region
)
4405 ;; Anytime text changes make sure it gets fontified correctly
4406 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
4408 ;; If we left the buffer there is a really good chance we were
4409 ;; creating one of the wiki link documents. Make sure we get
4410 ;; refontified when we come back.
4411 (add-hook 'window-configuration-change-hook
4412 'markdown-fontify-buffer-wiki-links t t
)
4414 ;; do the initial link fontification
4415 (markdown-fontify-buffer-wiki-links))
4417 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4420 ;;; GitHub Flavored Markdown Mode ============================================
4422 (defvar gfm-font-lock-keywords
4424 ;; GFM features to match first
4426 (cons 'markdown-match-gfm-code-blocks
'((1 markdown-pre-face
)
4427 (2 markdown-language-keyword-face
)
4428 (3 markdown-pre-face
)
4429 (4 markdown-pre-face
))))
4430 ;; Basic Markdown features (excluding possibly overridden ones)
4431 markdown-mode-font-lock-keywords-basic
4432 ;; GFM features to match last
4434 (cons markdown-regex-gfm-italic
'(2 markdown-italic-face
))))
4435 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4438 (define-derived-mode gfm-mode markdown-mode
"GFM"
4439 "Major mode for editing GitHub Flavored Markdown files."
4440 (setq markdown-link-space-sub-char
"-")
4441 (set (make-local-variable 'font-lock-defaults
)
4442 '(gfm-font-lock-keywords))
4444 ;; Use visual-line-mode if available, fall back to longlines-mode:
4445 (if (fboundp 'visual-line-mode
)
4446 (visual-line-mode 1)
4448 ;; do the initial link fontification
4449 (markdown-fontify-buffer-wiki-links))
4452 (provide 'markdown-mode
)
4454 ;;; markdown-mode.el ends here