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, but
127 ;; this command must accept input from `stdin`. If it does not, a
128 ;; simple wrapper script can be used to write `stdin` to a file
129 ;; and then pass that file to your Markdown interpreter. Ideally,
130 ;; this command will produce an XHTML fragment around which
131 ;; markdown-mode will wrap a header and footer (which can be
132 ;; further customized). However, it attempts to detect whether
133 ;; the command produces standalone XHTML output (via
134 ;; `markdown-xhtml-standalone-regexp'), in which case no header
135 ;; and footer content will be added.
137 ;; * `markdown-command-needs-filename' - set to non-nil if
138 ;; `markdown-command' does not accept input from stdin (default: nil).
139 ;; Instead, it will be passed a filename as the final command-line
140 ;; option. As a result, you will only be able to run Markdown
141 ;; from buffers which are visiting a file.
143 ;; * `markdown-open-command' - the command used for calling a standalone
144 ;; Markdown previewer which is capable of opening Markdown source files
145 ;; directly (default: `nil'). This command will be called
146 ;; with a single argument, the filename of the current buffer.
147 ;; A representative program is the Mac app [Marked][], a
148 ;; live-updating MultiMarkdown previewer which has a command line
149 ;; utility at `/usr/local/bin/mark`.
151 ;; * `markdown-hr-strings' - list of strings to use when inserting
152 ;; horizontal rules, in decreasing order of priority.
154 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
155 ;; underscores for bold instead of two asterisks (default: `nil').
157 ;; * `markdown-italic-underscore' - set to a non-nil value to use
158 ;; underscores for italic instead of asterisks (default: `nil').
160 ;; * `markdown-indent-function' - the function to use for automatic
161 ;; indentation (default: `markdown-indent-line').
163 ;; * `markdown-indent-on-enter' - set to a non-nil value to
164 ;; automatically indent new lines when the enter key is pressed
167 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
168 ;; to automatically open a linked document in a new buffer if the
169 ;; cursor is an wiki link
172 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
173 ;; treat aliased wiki links like `[[link text|PageName]]`.
174 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
176 ;; * `markdown-uri-types' - a list of protocols for URIs that
177 ;; `markdown-mode' should highlight.
179 ;; * `markdown-enable-math' - syntax highlighting for
180 ;; LaTeX fragments (default: `nil').
182 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
184 ;; * `markdown-content-type' - when set to a nonempty string, an
185 ;; `http-equiv` attribute will be included in the XHTML `<head>`
186 ;; block. If needed, the suggested values are
187 ;; `application/xhtml+xml` or `text/html`.
189 ;; * `markdown-coding-system' - used for specifying the character
190 ;; set identifier in the `http-equiv` attribute (see
191 ;; `markdown-content-type'). When set to `nil',
192 ;; `buffer-file-coding-system' will be used (and falling back to
193 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
194 ;; and `iso-latin-1'.
196 ;; * `markdown-xhtml-header-content' - additional content to include
197 ;; in the XHTML `<head>` block.
199 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
200 ;; indicates whether the output of `markdown-command' is standalone
201 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
202 ;; this is not matched, we assume this output is a fragment and add
203 ;; our own header and footer.
205 ;; * `markdown-link-space-sub-char' - a character to replace spaces
206 ;; when mapping wiki links to filenames (default: `_`).
207 ;; For example, use an underscore for compatibility with the
208 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
209 ;; with GitHub wiki links.
211 ;; Additionally, the faces used for syntax highlighting can be modified to
212 ;; your liking by issuing `M-x customize-group RET markdown-faces`
213 ;; or by using the "Markdown Faces" link at the bottom of the mode
214 ;; customization screen.
216 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
220 ;; Keybindings are grouped by prefixes based on their function. For
221 ;; example, commands dealing with headers begin with `C-c C-t`. The
222 ;; primary commands in each group will are described below. You can
223 ;; obtain a list of all keybindings by pressing `C-c C-h`.
225 ;; * Anchors: `C-c C-a`
227 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
228 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
229 ;; The label definition will be placed at the end of the current
230 ;; block. `C-c C-a w` acts similarly for wiki links of the form
231 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
232 ;; text in the region is used as the link text.
234 ;; * Commands: `C-c C-c`
236 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
237 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
238 ;; runs Markdown on the current buffer and previews, stores the
239 ;; output in a temporary file, and displays the file in a browser.
240 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
241 ;; and save the result in the file `basename.html`, where
242 ;; `basename` is the name of the Markdown file with the extension
243 ;; removed. *Export and View:* press `C-c C-c v` to export the
244 ;; file and view it in a browser. **For both export commands, the
245 ;; output file will be overwritten without notice.**
246 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
247 ;; using `markdown-open-command'.
251 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
252 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
253 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
254 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
255 ;; - `C-c C-c w`: `markdown-command' > kill ring.
256 ;; - `C-c C-c o`: `markdown-open-command'.
258 ;; `C-c C-c c` will check for undefined references. If there are
259 ;; any, a small buffer will open with a list of undefined
260 ;; references and the line numbers on which they appear. In Emacs
261 ;; 22 and greater, selecting a reference from this list and
262 ;; pressing `RET` will insert an empty reference definition at the
263 ;; end of the buffer. Similarly, selecting the line number will
264 ;; jump to the corresponding line.
266 ;; `C-c C-c n` will clean up the numbering of ordered lists.
268 ;; * Images: `C-c C-i`
270 ;; `C-c C-i i` inserts markup for an inline image, using the
271 ;; active region (if any) or the word at point as the alt text.
272 ;; To insert reference-style image markup, provide a `C-u` prefix.
274 ;; * Physical styles: `C-c C-p`
276 ;; These commands all act on text in the active region, if any,
277 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
278 ;; the selected text bold, `C-c C-p f` formats the region as
279 ;; fixed-width text, and `C-c C-p i` is used for italic text.
281 ;; * Logical styles: `C-c C-s`
283 ;; These commands all act on text in the active region, if any,
284 ;; and insert empty markup fragments otherwise. Logical styles
285 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
286 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
289 ;; * Headers: `C-c C-t`
291 ;; All header commands use text in the active region, if any, as
292 ;; the header text. Otherwise, if the current line is not blank,
293 ;; use the text on the current line. Finally, prompt for header
294 ;; text if there is no active region and the current line is
295 ;; blank. To insert an atx or hash style level-n
296 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
297 ;; top-level setext or underline style header press `C-c C-t t`
298 ;; (mnemonic: title) and for a second-level underline-style header
299 ;; press `C-c C-t s` (mnemonic: section).
301 ;; If the point is at a header, these commands will replace the
302 ;; existing markup in order to update the level and/or type of the
303 ;; header. To remove the markup of the header at the point, press
306 ;; * Footnotes: `C-c C-f`
308 ;; To create a new footnote at the point, press `C-c C-f n`.
309 ;; Press `C-c C-f g` with the point at a footnote to jump to the
310 ;; location where the footnote text is defined. Then, press
311 ;; `C-c C-f b` to return to the footnote marker in the main text.
312 ;; When the point is at a footnote marker or in the body of a
313 ;; footnote, press `C-c C-f k` to kill the footnote and add the
314 ;; text to the kill ring.
318 ;; `C-c -` inserts a horizontal rule.
320 ;; * Following Links:
322 ;; Press `C-c C-o` when the point is on an inline or reference
323 ;; link to open the URL in a browser. When the point is at a
324 ;; wiki link, open it in another buffer (in the current window,
325 ;; or in the other window with the `C-u` prefix).
326 ;; To move between links, use `M-p` and `M-n` to quickly jump
327 ;; to the previous or next link of any type.
331 ;; Use `C-c C-j` to jump from the object at point to its counterpart
332 ;; elsewhere in the text, when possible. Jumps between reference
333 ;; links and definitions; between footnote markers and footnote
334 ;; text. If more than one link uses the same reference name, a
335 ;; new buffer will be created containing clickable buttons for jumping
336 ;; to each link. You may press `TAB` or `S-TAB` to jump between
337 ;; buttons in this window.
339 ;; * Killing Elements:
341 ;; Press `C-c C-k` to kill the thing at point and add important
342 ;; text, without markup, to the kill ring. Possible things to
343 ;; kill include (roughly in order of precedece): inline code,
344 ;; headers, horizonal rules, links (add link text to kill ring),
345 ;; images (add alt text to kill ring), angle URIs, email
346 ;; addresses, bold, italics, reference definitions (add URI to
347 ;; kill ring), footnote markers and text (kill both marker and
348 ;; text, add text to kill ring), and list items.
350 ;; * Outline Navigation:
352 ;; Navigation between headings is possible using `outline-mode'.
353 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
354 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
355 ;; next and previous visible headings at the same level as the one
356 ;; at the point. Finally, `C-M-u` will move up to a lower-level
357 ;; (more inclusive) visible heading.
359 ;; * Movement by Block:
361 ;; markdown-mode supports the usual Emacs paragraph movement with
362 ;; `M-{` and `M-}`. These commands treat list items as
363 ;; paragraphs, so they will stop at each line within a block of
364 ;; list items. Additionally, markdown-mode includes movement
365 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
366 ;; of an entire block of text (with blocks being separated by at
367 ;; least one blank line).
369 ;; * Movement by Defun:
371 ;; The usual Emacs commands can be used to move by defuns
372 ;; (top-level major definitions). In markdown-mode, a defun
373 ;; is a section. As usual, `C-M-a` will move the point to
374 ;; the beginning of the current or preceding defun, `C-M-e`
375 ;; will move to the end of the current or following defun,
376 ;; and `C-M-h` will put the region around the entire defun.
378 ;; Many of the commands described above behave differently depending on
379 ;; whether Transient Mark mode is enabled or not. When it makes sense,
380 ;; if Transient Mark mode is on and a region is active, the command
381 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
382 ;; bold). For users who prefer to work outside of Transient Mark mode,
383 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
385 ;; When applicable, commands that specifically act on the region even
386 ;; outside of Transient Mark mode have the same keybinding as the with
387 ;; the exception of an additional `C-` prefix. For example,
388 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
389 ;; the region in Transient Mark mode while `markdown-blockquote-region'
390 ;; is bound to `C-c C-s C-b` and always applies to the region (when
393 ;; markdown-mode attempts to be flexible in how it handles
394 ;; indentation. When you press `TAB` repeatedly, the point will cycle
395 ;; through several possible indentation levels corresponding to things
396 ;; you might have in mind when you press `RET` at the end of a line or
397 ;; `TAB`. For example, you may want to start a new list item,
398 ;; continue a list item with hanging indentation, indent for a nested
399 ;; pre block, and so on.
401 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
402 ;; visibility cycling for atx- or hash-style headers. There are two
403 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
404 ;; the table of contents view (headers only), outline view (top-level
405 ;; headers only), and the full document view. Pressing `TAB` while the
406 ;; point is at a header will cycle through levels of visibility for the
407 ;; subtree: completely folded, visible children, and fully visible.
408 ;; Note that mixing hash and underline style headers will give undesired
413 ;; Besides supporting the basic Markdown syntax, markdown-mode also
414 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
415 ;; links may be followed automatically by pressing the enter key when
416 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
417 ;; auto-following on enter key may be controlled with the
418 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
419 ;; `M-n` to quickly jump to the previous and next wiki links,
420 ;; respectively. Aliased or piped wiki links of the form
421 ;; `[[link text|PageName]]` are also supported. Since some wikis
422 ;; reverse these components, set `markdown-wiki-link-alias-first'
423 ;; to nil to treat them as `[[PageName|link text]]`.
425 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
426 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
427 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
428 ;; You can do this either by using `M-x customize-group markdown`
429 ;; or by placing the following in your `.emacs` file:
431 ;; (defun markdown-custom ()
432 ;; "markdown-mode-hook"
433 ;; (setq markdown-command "markdown | smartypants"))
434 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
436 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
438 ;; Experimental syntax highlighting for mathematical expressions written
439 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
440 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
441 ;; either via customize or by placing `(setq markdown-enable-itex t)`
442 ;; in `.emacs`, and restarting Emacs.
444 ;;; GitHub Flavored Markdown:
446 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
447 ;; available. The GitHub implementation of differs slightly from
448 ;; standard Markdown. The most important differences are that
449 ;; newlines are significant, triggering hard line breaks, and that
450 ;; underscores inside of words (e.g., variable names) need not be
451 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
452 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
453 ;; not available). Underscores inside of words (such as
454 ;; test_variable) will not trigger emphasis.
456 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
457 ;; replacing spaces in filenames and where the first letter of the
458 ;; filename capitalized. For example, `[[wiki link]]' will map to a
459 ;; file named `Wiki-link` with the same extension as the current file.
461 ;; GFM code blocks, with optional programming language keywords, will
462 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
463 ;; is an active region, the text in the region will be placed inside
464 ;; the code block. You will be prompted for the name of the language,
465 ;; but may press enter to continue without naming a language.
467 ;; For a more complete GitHub-flavored markdown experience, consider
468 ;; adding README.md to your `auto-mode-alist':
470 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
472 ;; For GFM preview can be powered by setting `markdown-command' to
473 ;; use [Docter][]. This may also be configured to work with [Marked][]
474 ;; for `markdown-open-command'.
476 ;; [GFM]: http://github.github.com/github-flavored-markdown/
477 ;; [Docter]: https://github.com/alampros/Docter
481 ;; markdown-mode has benefited greatly from the efforts of the
484 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
485 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
486 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
487 ;; GitHub Flavored Markdown mode (`gfm-mode').
488 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
489 ;; `markdown' with an active region.
490 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
491 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
492 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
493 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
494 ;; visibility cycling functionality was derived, and for a bug fix
495 ;; related to orgtbl-mode.
496 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
497 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
498 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
499 ;; compatibility and custom CSS.
500 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
501 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
502 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
503 ;; comment matching functions were derived.
504 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
505 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
506 ;; functions, bug reports regarding indentation, and
507 ;; fixes for byte-compilation warnings.
508 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
510 ;; * George Ogata <george.ogata@gmail.com> for fixing several
511 ;; byte-compilation warnings.
512 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
513 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
514 ;; customizations and XHTML export.
515 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
516 ;; Markdown processors which do not accept input from stdin.
517 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
518 ;; regarding the cl dependency and auto-fill-mode and indentation.
519 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
520 ;; substitution character for mapping wiki links to filenames.
521 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
522 ;; escape shell commands.
523 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
524 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
525 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
526 ;; Emacs Lisp coding conventions.
527 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
528 ;; regexp, refactoring the compilation and preview functions,
529 ;; heading font-lock generalizations, list renumbering,
530 ;; and kill ring save.
531 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
532 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
533 ;; for an autoload token for `gfm-mode'.
534 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
535 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
536 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
537 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
538 ;; declaration in XHTML output.
539 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
540 ;; un-indentation function.
541 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
542 ;; and GFM code block insertion.
543 ;; * Peter Jones <pjones@pmade.com> for link following functions.
544 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
545 ;; externally modified files.
546 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
547 ;; related to orgtbl-mode.
548 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
549 ;; export hooks and unit test improvements.
550 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
554 ;; Although markdown-mode is developed and tested primarily using
555 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
558 ;; If you find any bugs in markdown-mode, please construct a test case
559 ;; or a patch and email me at <jrblevin@sdf.org>.
563 ;; markdown-mode was written and is maintained by Jason Blevins. The
564 ;; first version was released on May 24, 2007.
566 ;; * 2007-05-24: Version 1.1
567 ;; * 2007-05-25: Version 1.2
568 ;; * 2007-06-05: [Version 1.3][]
569 ;; * 2007-06-29: Version 1.4
570 ;; * 2008-05-24: [Version 1.5][]
571 ;; * 2008-06-04: [Version 1.6][]
572 ;; * 2009-10-01: [Version 1.7][]
573 ;; * 2011-08-12: [Version 1.8][]
574 ;; * 2011-08-15: [Version 1.8.1][]
575 ;; * 2013-01-25: [Version 1.9][]
577 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
578 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
579 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
580 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
581 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
582 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
583 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
590 (eval-when-compile (require 'cl
))
593 ;;; Constants =================================================================
595 (defconst markdown-mode-version
"1.9"
596 "Markdown mode version number.")
598 (defconst markdown-output-buffer-name
"*markdown-output*"
599 "Name of temporary buffer for markdown command output.")
602 ;;; Customizable Variables ====================================================
604 (defvar markdown-mode-hook nil
605 "Hook run when entering Markdown mode.")
607 (defvar markdown-before-export-hooks nil
608 "Hook run before output XHTML.
609 This hook is abnormal and registered functions are given an argument that is output filename.")
611 (defvar markdown-after-export-hooks nil
612 "Hook run after output XHTML.
613 This hook is abnormal and registered functions are given an argument that is output filename.")
615 (defgroup markdown nil
616 "Major mode for editing text files in Markdown format."
619 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
621 (defcustom markdown-command
"markdown"
622 "Command to run markdown."
626 (defcustom markdown-command-needs-filename nil
627 "Set to non-nil if `markdown-command' does not accept input from stdin.
628 Instead, it will be passed a filename as the final command line
629 option. As a result, you will only be able to run Markdown from
630 buffers which are visiting a file."
634 (defcustom markdown-open-command nil
635 "Command used for opening Markdown files directly.
636 For example, a standalone Markdown previewer. This command will
637 be called with a single argument: the filename of the current
642 (defcustom markdown-hr-strings
645 "* * * * * * * * * * * * * * * * * * * *"
646 "---------------------------------------"
647 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
648 "-------------------------------------------------------------------------------")
649 "Strings to use when inserting horizontal rules.
650 The first string in the list will be the default when inserting a
651 horizontal rule. Strings should be listed in increasing order of
652 prominence for use with promotion and demotion functions."
656 (defcustom markdown-bold-underscore nil
657 "Use two underscores for bold instead of two asterisks."
661 (defcustom markdown-italic-underscore nil
662 "Use underscores for italic instead of asterisks."
666 (defcustom markdown-indent-function
'markdown-indent-line
667 "Function to use to indent."
671 (defcustom markdown-indent-on-enter t
672 "Automatically indent new lines when enter key is pressed."
676 (defcustom markdown-follow-wiki-link-on-enter t
677 "Follow wiki link at point (if any) when the enter key is pressed."
681 (defcustom markdown-wiki-link-alias-first t
682 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
683 Otherwise, they will be treated as [[PageName|alias text]]."
687 (defcustom markdown-uri-types
688 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
689 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
690 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
691 "Link types for syntax highlighting of URIs."
695 (defcustom markdown-enable-math nil
696 "Syntax highlighting for inline LaTeX expressions.
697 This will not take effect until Emacs is restarted."
701 (defcustom markdown-css-path
""
702 "URL of CSS file to link to in the output XHTML."
706 (defcustom markdown-content-type
""
707 "Content type string for the http-equiv header in XHTML output.
708 When set to a non-empty string, insert the http-equiv attribute.
709 Otherwise, this attribute is omitted."
713 (defcustom markdown-coding-system nil
714 "Character set string for the http-equiv header in XHTML output.
715 Defaults to `buffer-file-coding-system' (and falling back to
716 `iso-8859-1' when not available). Common settings are `utf-8'
717 and `iso-latin-1'. Use `list-coding-systems' for more choices."
719 :type
'coding-system
)
721 (defcustom markdown-xhtml-header-content
""
722 "Additional content to include in the XHTML <head> block."
726 (defcustom markdown-xhtml-standalone-regexp
727 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
728 "Regexp indicating whether `markdown-command' output is standalone XHTML."
732 (defcustom markdown-link-space-sub-char
734 "Character to use instead of spaces when mapping wiki links to filenames."
738 (defcustom markdown-footnote-location
'end
739 "Position where new footnotes are inserted in the document."
741 :type
'(choice (const :tag
"At the end of the document" end
)
742 (const :tag
"Immediately after the paragraph" immediately
)
743 (const :tag
"Before next header" header
)))
746 ;;; Font Lock =================================================================
750 (defvar markdown-italic-face
'markdown-italic-face
751 "Face name to use for italic text.")
753 (defvar markdown-bold-face
'markdown-bold-face
754 "Face name to use for bold text.")
756 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
757 "Face name to use as a base for header delimiters.")
759 (defvar markdown-header-rule-face
'markdown-header-rule-face
760 "Face name to use as a base for header rules.")
762 (defvar markdown-header-face
'markdown-header-face
763 "Face name to use as a base for headers.")
765 (defvar markdown-header-face-1
'markdown-header-face-1
766 "Face name to use for level-1 headers.")
768 (defvar markdown-header-face-2
'markdown-header-face-2
769 "Face name to use for level-2 headers.")
771 (defvar markdown-header-face-3
'markdown-header-face-3
772 "Face name to use for level-3 headers.")
774 (defvar markdown-header-face-4
'markdown-header-face-4
775 "Face name to use for level-4 headers.")
777 (defvar markdown-header-face-5
'markdown-header-face-5
778 "Face name to use for level-5 headers.")
780 (defvar markdown-header-face-6
'markdown-header-face-6
781 "Face name to use for level-6 headers.")
783 (defvar markdown-inline-code-face
'markdown-inline-code-face
784 "Face name to use for inline code.")
786 (defvar markdown-list-face
'markdown-list-face
787 "Face name to use for list markers.")
789 (defvar markdown-blockquote-face
'markdown-blockquote-face
790 "Face name to use for blockquote.")
792 (defvar markdown-pre-face
'markdown-pre-face
793 "Face name to use for preformatted text.")
795 (defvar markdown-language-keyword-face
'markdown-language-keyword-face
796 "Face name to use for programming language identifiers.")
798 (defvar markdown-link-face
'markdown-link-face
799 "Face name to use for links.")
801 (defvar markdown-missing-link-face
'markdown-missing-link-face
802 "Face name to use for links where the linked file does not exist.")
804 (defvar markdown-reference-face
'markdown-reference-face
805 "Face name to use for reference.")
807 (defvar markdown-footnote-face
'markdown-footnote-face
808 "Face name to use for footnote identifiers.")
810 (defvar markdown-url-face
'markdown-url-face
811 "Face name to use for URLs.")
813 (defvar markdown-link-title-face
'markdown-link-title-face
814 "Face name to use for reference link titles.")
816 (defvar markdown-comment-face
'markdown-comment-face
817 "Face name to use for HTML comments.")
819 (defvar markdown-math-face
'markdown-math-face
820 "Face name to use for LaTeX expressions.")
822 (defvar markdown-metadata-key-face
'markdown-metadata-key-face
823 "Face name to use for metadata keys.")
825 (defvar markdown-metadata-value-face
'markdown-metadata-value-face
826 "Face name to use for metadata values.")
828 (defgroup markdown-faces nil
829 "Faces used in Markdown Mode"
833 (defface markdown-italic-face
834 '((t (:inherit font-lock-variable-name-face
:slant italic
)))
835 "Face for italic text."
836 :group
'markdown-faces
)
838 (defface markdown-bold-face
839 '((t (:inherit font-lock-variable-name-face
:weight bold
)))
840 "Face for bold text."
841 :group
'markdown-faces
)
843 (defface markdown-header-rule-face
844 '((t (:inherit font-lock-function-name-face
:weight bold
)))
845 "Base face for headers rules."
846 :group
'markdown-faces
)
848 (defface markdown-header-delimiter-face
849 '((t (:inherit font-lock-function-name-face
:weight bold
)))
850 "Base face for headers hash delimiter."
851 :group
'markdown-faces
)
853 (defface markdown-header-face
854 '((t (:inherit font-lock-function-name-face
:weight bold
)))
855 "Base face for headers."
856 :group
'markdown-faces
)
858 (defface markdown-header-face-1
859 '((t (:inherit markdown-header-face
)))
860 "Face for level-1 headers."
861 :group
'markdown-faces
)
863 (defface markdown-header-face-2
864 '((t (:inherit markdown-header-face
)))
865 "Face for level-2 headers."
866 :group
'markdown-faces
)
868 (defface markdown-header-face-3
869 '((t (:inherit markdown-header-face
)))
870 "Face for level-3 headers."
871 :group
'markdown-faces
)
873 (defface markdown-header-face-4
874 '((t (:inherit markdown-header-face
)))
875 "Face for level-4 headers."
876 :group
'markdown-faces
)
878 (defface markdown-header-face-5
879 '((t (:inherit markdown-header-face
)))
880 "Face for level-5 headers."
881 :group
'markdown-faces
)
883 (defface markdown-header-face-6
884 '((t (:inherit markdown-header-face
)))
885 "Face for level-6 headers."
886 :group
'markdown-faces
)
888 (defface markdown-inline-code-face
889 '((t (:inherit font-lock-constant-face
)))
890 "Face for inline code."
891 :group
'markdown-faces
)
893 (defface markdown-list-face
894 '((t (:inherit font-lock-builtin-face
)))
895 "Face for list item markers."
896 :group
'markdown-faces
)
898 (defface markdown-blockquote-face
899 '((t (:inherit font-lock-doc-face
)))
900 "Face for blockquote sections."
901 :group
'markdown-faces
)
903 (defface markdown-pre-face
904 '((t (:inherit font-lock-constant-face
)))
905 "Face for preformatted text."
906 :group
'markdown-faces
)
908 (defface markdown-language-keyword-face
909 '((t (:inherit font-lock-type-face
)))
910 "Face for programming language identifiers."
911 :group
'markdown-faces
)
913 (defface markdown-link-face
914 '((t (:inherit font-lock-keyword-face
)))
916 :group
'markdown-faces
)
918 (defface markdown-missing-link-face
919 '((t (:inherit font-lock-warning-face
)))
920 "Face for missing links."
921 :group
'markdown-faces
)
923 (defface markdown-reference-face
924 '((t (:inherit font-lock-type-face
)))
925 "Face for link references."
926 :group
'markdown-faces
)
928 (defface markdown-footnote-face
929 '((t (:inherit font-lock-keyword-face
)))
930 "Face for footnote markers."
931 :group
'markdown-faces
)
933 (defface markdown-url-face
934 '((t (:inherit font-lock-string-face
)))
936 :group
'markdown-faces
)
938 (defface markdown-link-title-face
939 '((t (:inherit font-lock-comment-face
)))
940 "Face for reference link titles."
941 :group
'markdown-faces
)
943 (defface markdown-comment-face
944 '((t (:inherit font-lock-comment-face
)))
945 "Face for HTML comments."
946 :group
'markdown-faces
)
948 (defface markdown-math-face
949 '((t (:inherit font-lock-string-face
)))
950 "Face for LaTeX expressions."
951 :group
'markdown-faces
)
953 (defface markdown-metadata-key-face
954 '((t (:inherit font-lock-variable-name-face
)))
955 "Face for metadata keys."
956 :group
'markdown-faces
)
958 (defface markdown-metadata-value-face
959 '((t (:inherit font-lock-string-face
)))
960 "Face for metadata values."
961 :group
'markdown-faces
)
963 (defconst markdown-regex-link-inline
964 "\\(!?\\[\\([^]]*?\\)\\]\\)\\((\\([^\\)]*\\))\\)"
965 "Regular expression for a [text](file) or an image link ![text](file).")
967 (defconst markdown-regex-link-reference
968 "\\(!?\\[\\([^]]+?\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
969 "Regular expression for a reference link [text][id].")
971 (defconst markdown-regex-reference-definition
972 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
973 "Regular expression for a link definition [id]: ...")
975 (defconst markdown-regex-footnote
977 "Regular expression for a footnote marker [^fn].")
979 (defconst markdown-regex-header
980 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
981 "Regexp identifying Markdown headers.")
983 (defconst markdown-regex-header-1-atx
984 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
985 "Regular expression for level 1 atx-style (hash mark) headers.")
987 (defconst markdown-regex-header-2-atx
988 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
989 "Regular expression for level 2 atx-style (hash mark) headers.")
991 (defconst markdown-regex-header-3-atx
992 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
993 "Regular expression for level 3 atx-style (hash mark) headers.")
995 (defconst markdown-regex-header-4-atx
996 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
997 "Regular expression for level 4 atx-style (hash mark) headers.")
999 (defconst markdown-regex-header-5-atx
1000 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
1001 "Regular expression for level 5 atx-style (hash mark) headers.")
1003 (defconst markdown-regex-header-6-atx
1004 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
1005 "Regular expression for level 6 atx-style (hash mark) headers.")
1007 (defconst markdown-regex-header-1-setext
1008 "^\\(.*\\)\n\\(=+\\)$"
1009 "Regular expression for level 1 setext-style (underline) headers.")
1011 (defconst markdown-regex-header-2-setext
1012 "^\\(.*\\)\n\\(-+\\)$"
1013 "Regular expression for level 2 setext-style (underline) headers.")
1015 (defconst markdown-regex-header-setext
1016 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1017 "Regular expression for generic setext-style (underline) headers.")
1019 (defconst markdown-regex-header-atx
1020 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1021 "Regular expression for generic atx-style (hash mark) headers.")
1023 (defconst markdown-regex-hr
1024 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1025 "Regular expression for matching Markdown horizontal rules.")
1027 (defconst markdown-regex-code
1028 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1029 "Regular expression for matching inline code fragments.
1031 The first group ensures that the leading backquote character
1032 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1033 character, including newlines, but not two newlines in a row.
1034 The final group requires that the character following the code
1035 fragment is not a backquote.")
1037 (defconst markdown-regex-pre
1039 "Regular expression for matching preformatted text sections.")
1041 (defconst markdown-regex-list
1042 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1043 "Regular expression for matching list items.")
1045 (defconst markdown-regex-bold
1046 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1047 "Regular expression for matching bold text.
1048 Group 1 matches the character before the opening asterisk or
1049 underscore, if any, ensuring that it is not a backslash escape.
1050 Group 2 matches the entire expression, including delimiters.
1051 Groups 3 and 5 matches the opening and closing delimiters.
1052 Group 4 matches the text inside the delimiters.")
1054 (defconst markdown-regex-italic
1055 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1056 "Regular expression for matching italic text.
1057 Group 1 matches the character before the opening asterisk or
1058 underscore, if any, ensuring that it is not a backslash escape.
1059 Group 2 matches the entire expression, including delimiters.
1060 Groups 3 and 5 matches the opening and closing delimiters.
1061 Group 4 matches the text inside the delimiters.")
1063 (defconst markdown-regex-gfm-italic
1064 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1065 "Regular expression for matching italic text in GitHub-flavored Markdown.
1066 Underscores in words are not treated as special.")
1068 (defconst markdown-regex-blockquote
1070 "Regular expression for matching blockquote lines.")
1072 (defconst markdown-regex-line-break
1074 "Regular expression for matching line breaks.")
1076 (defconst markdown-regex-wiki-link
1077 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1078 "Regular expression for matching wiki links.
1079 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1080 wiki links of the form [[PageName|link text]]. In this regular
1081 expression, #1 matches the page name and #3 matches the link
1084 (defconst markdown-regex-uri
1085 (concat (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;() ]+")
1086 "Regular expression for matching inline URIs.")
1088 (defconst markdown-regex-angle-uri
1089 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1090 "Regular expression for matching inline URIs in angle brackets.")
1092 (defconst markdown-regex-email
1093 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1094 "Regular expression for matching inline email addresses.")
1096 (defconst markdown-regex-link-generic
1097 (concat "\\(?:" markdown-regex-wiki-link
1098 "\\|" markdown-regex-link-inline
1099 "\\|" markdown-regex-link-reference
1100 "\\|" markdown-regex-angle-uri
"\\)")
1101 "Regular expression for matching any recognized link.")
1103 (defconst markdown-regex-block-separator
1104 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1105 "Regular expression for matching block boundaries.")
1107 (defconst markdown-regex-latex-expression
1108 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1109 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1111 (defconst markdown-regex-latex-display
1112 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1113 "Regular expression for itex \[..\] display mode expressions.")
1115 (defconst markdown-regex-multimarkdown-metadata
1116 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1117 "Regular expression for matching MultiMarkdown metadata.")
1119 (defconst markdown-regex-pandoc-metadata
1120 "^\\(%\\)[ \t]*\\(.*\\)$"
1121 "Regular expression for matching Pandoc metadata.")
1123 (defvar markdown-mode-font-lock-keywords-basic
1125 (cons 'markdown-match-multimarkdown-metadata
'((1 markdown-metadata-key-face
)
1126 (2 markdown-metadata-value-face
)))
1127 (cons 'markdown-match-pandoc-metadata
'((1 markdown-comment-face
)
1128 (2 markdown-metadata-value-face
)))
1129 (cons 'markdown-match-pre-blocks
'((0 markdown-pre-face
)))
1130 (cons 'markdown-match-fenced-code-blocks
'((0 markdown-pre-face
)))
1131 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
1132 (cons markdown-regex-header-1-setext
'((1 markdown-header-face-1
)
1133 (2 markdown-header-rule-face
)))
1134 (cons markdown-regex-header-2-setext
'((1 markdown-header-face-2
)
1135 (2 markdown-header-rule-face
)))
1136 (cons markdown-regex-header-1-atx
'((1 markdown-header-delimiter-face
)
1137 (2 markdown-header-face-1
)
1138 (3 markdown-header-delimiter-face
)))
1139 (cons markdown-regex-header-2-atx
'((1 markdown-header-delimiter-face
)
1140 (2 markdown-header-face-2
)
1141 (3 markdown-header-delimiter-face
)))
1142 (cons markdown-regex-header-3-atx
'((1 markdown-header-delimiter-face
)
1143 (2 markdown-header-face-3
)
1144 (3 markdown-header-delimiter-face
)))
1145 (cons markdown-regex-header-4-atx
'((1 markdown-header-delimiter-face
)
1146 (2 markdown-header-face-4
)
1147 (3 markdown-header-delimiter-face
)))
1148 (cons markdown-regex-header-5-atx
'((1 markdown-header-delimiter-face
)
1149 (2 markdown-header-face-5
)
1150 (3 markdown-header-delimiter-face
)))
1151 (cons markdown-regex-header-6-atx
'((1 markdown-header-delimiter-face
)
1152 (2 markdown-header-face-6
)
1153 (3 markdown-header-delimiter-face
)))
1154 (cons markdown-regex-hr
'markdown-header-face
)
1155 (cons 'markdown-match-comments
'((0 markdown-comment-face t t
)))
1156 (cons markdown-regex-code
'(2 markdown-inline-code-face
))
1157 (cons markdown-regex-angle-uri
'markdown-link-face
)
1158 (cons markdown-regex-uri
'markdown-link-face
)
1159 (cons markdown-regex-email
'markdown-link-face
)
1160 (cons markdown-regex-list
'(2 markdown-list-face
))
1161 (cons markdown-regex-link-inline
'((1 markdown-link-face t
)
1162 (3 markdown-url-face t
)))
1163 (cons markdown-regex-link-reference
'((1 markdown-link-face t
)
1164 (3 markdown-reference-face t
)))
1165 (cons markdown-regex-reference-definition
'((1 markdown-reference-face t
)
1166 (2 markdown-url-face t
)
1167 (3 markdown-link-title-face t
)))
1168 (cons markdown-regex-footnote
'markdown-footnote-face
)
1169 (cons markdown-regex-bold
'(2 markdown-bold-face
))
1171 "Syntax highlighting for Markdown files.")
1173 (defvar markdown-mode-font-lock-keywords-core
1175 (cons markdown-regex-italic
'(2 markdown-italic-face
))
1177 "Additional syntax highlighting for Markdown files.
1178 Includes features which are overridden by some variants.")
1180 (defconst markdown-mode-font-lock-keywords-latex
1182 ;; Math mode $..$ or $$..$$
1183 (cons markdown-regex-latex-expression
'(2 markdown-math-face
))
1184 ;; Display mode equations with brackets: \[ \]
1185 (cons markdown-regex-latex-display
'markdown-math-face
)
1186 ;; Equation reference (eq:foo)
1187 (cons "(eq:\\w+)" 'markdown-reference-face
)
1188 ;; Equation reference \eqref{foo}
1189 (cons "\\\\eqref{\\w+}" 'markdown-reference-face
))
1190 "Syntax highlighting for LaTeX fragments.")
1192 (defvar markdown-mode-font-lock-keywords
1194 (if markdown-enable-math
1195 markdown-mode-font-lock-keywords-latex
)
1196 markdown-mode-font-lock-keywords-basic
1197 markdown-mode-font-lock-keywords-core
)
1198 "Default highlighting expressions for Markdown mode.")
1201 (defvar markdown-footnote-counter
0
1202 "Counter for footnote numbers.")
1203 (make-variable-buffer-local 'markdown-footnote-counter
)
1205 (defconst markdown-footnote-chars
1207 "Regular expression maching any character that is allowed in a footnote identifier.")
1210 ;;; Compatibility =============================================================
1212 (defun markdown-replace-regexp-in-string (regexp rep string
)
1213 "Replace all matches for REGEXP with REP in STRING.
1214 This is a compatibility wrapper to provide `replace-regexp-in-string'
1216 (if (featurep 'xemacs
)
1217 (replace-in-string string regexp rep
)
1218 (replace-regexp-in-string regexp rep string
)))
1220 ;; `markdown-use-region-p' is a compatibility function which checks
1221 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1224 ;; Emacs 23 and newer
1225 ((fboundp 'use-region-p
)
1226 (defalias 'markdown-use-region-p
'use-region-p
))
1228 ((and (boundp 'transient-mark-mode
) (boundp 'mark-active
))
1229 (defun markdown-use-region-p ()
1230 "Compatibility wrapper to provide `use-region-p'."
1231 (and transient-mark-mode mark-active
)))
1233 ((fboundp 'region-active-p
)
1234 (defalias 'markdown-use-region-p
'region-active-p
))))
1236 (defun markdown-use-buttons-p ()
1237 "Determine whether this Emacs supports buttons."
1238 (or (featurep 'button
) (locate-library "button")))
1241 ;;; Markdown Parsing Functions ================================================
1243 (defun markdown-cur-line-blank-p ()
1244 "Return t if the current line is blank and nil otherwise."
1247 (re-search-forward "^\\s *$" (line-end-position) t
)))
1249 (defun markdown-prev-line-blank-p ()
1250 "Return t if the previous line is blank and nil otherwise.
1251 If we are at the first line, then consider the previous line to be blank."
1252 (or (= (line-beginning-position) (point-min))
1255 (markdown-cur-line-blank-p))))
1257 (defun markdown-next-line-blank-p ()
1258 "Return t if the next line is blank and nil otherwise.
1259 If we are at the last line, then consider the next line to be blank."
1260 (or (= (line-end-position) (point-max))
1263 (markdown-cur-line-blank-p))))
1265 (defun markdown-prev-line-indent-p ()
1266 "Return t if the previous line is indented and nil otherwise."
1269 (goto-char (line-beginning-position))
1270 (if (re-search-forward "^\\s " (line-end-position) t
) t
)))
1272 (defun markdown-cur-line-indent ()
1273 "Return the number of leading whitespace characters in the current line."
1276 (goto-char (line-beginning-position))
1277 (re-search-forward "^[ \t]+" (line-end-position) t
)
1280 (defun markdown-prev-line-indent ()
1281 "Return the number of leading whitespace characters in the previous line."
1284 (markdown-cur-line-indent)))
1286 (defun markdown-next-line-indent ()
1287 "Return the number of leading whitespace characters in the next line."
1290 (markdown-cur-line-indent)))
1292 (defun markdown-cur-non-list-indent ()
1293 "Return beginning position of list item text (not including the list marker).
1294 Return nil if the current line is not the beginning of a list item."
1298 (when (re-search-forward markdown-regex-list
(line-end-position) t
)
1299 (current-column)))))
1301 (defun markdown-prev-non-list-indent ()
1302 "Return position of the first non-list-marker on the previous line."
1305 (markdown-cur-non-list-indent)))
1307 (defun markdown-new-baseline-p ()
1308 "Determine if the current line begins a new baseline level."
1312 (or (looking-at markdown-regex-header
)
1313 (looking-at markdown-regex-hr
)
1314 (and (null (markdown-cur-non-list-indent))
1315 (= (markdown-cur-line-indent) 0)
1316 (markdown-prev-line-blank-p))))))
1318 (defun markdown-search-backward-baseline ()
1319 "Search backward baseline point with no indentation and not a list item."
1322 (while (not (or stop
(bobp)))
1323 (re-search-backward markdown-regex-block-separator nil t
)
1325 (goto-char (match-end 2))
1327 ((markdown-new-baseline-p)
1329 ((looking-at markdown-regex-list
)
1331 (t (setq stop t
)))))))
1333 (defun markdown-update-list-levels (marker indent levels
)
1334 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1335 Here, MARKER is a string representing the type of list, INDENT is an integer
1336 giving the indentation, in spaces, of the current block, and LEVELS is a
1337 list of the indentation levels of parent list items. When LEVELS is nil,
1338 it means we are at baseline (not inside of a nested list)."
1340 ;; New list item at baseline.
1341 ((and marker
(null levels
))
1342 (setq levels
(list indent
)))
1343 ;; List item with greater indentation (four or more spaces).
1344 ;; Increase list level.
1345 ((and marker
(>= indent
(+ (car levels
) 4)))
1346 (setq levels
(cons indent levels
)))
1347 ;; List item with greater or equal indentation (less than four spaces).
1348 ;; Do not increase list level.
1349 ((and marker
(>= indent
(car levels
)))
1351 ;; Lesser indentation level.
1352 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1353 ;; indentation could move back more than one list level). Note
1354 ;; that this block need not be the beginning of list item.
1355 ((< indent
(car levels
))
1356 (while (and (> (length levels
) 1)
1357 (< indent
(+ (cadr levels
) 4)))
1358 (setq levels
(cdr levels
)))
1360 ;; Otherwise, do nothing.
1363 (defun markdown-calculate-list-levels ()
1364 "Calculate list levels at point.
1365 Return a list of the form (n1 n2 n3 ...) where n1 is the
1366 indentation of the deepest nested list item in the branch of
1367 the list at the point, n2 is the indentation of the parent
1368 list item, and so on. The depth of the list item is therefore
1369 the length of the returned list. If the point is not at or
1370 immediately after a list item, return nil."
1372 (let ((first (point)) levels indent pre-regexp
)
1373 ;; Find a baseline point with zero list indentation
1374 (markdown-search-backward-baseline)
1375 ;; Search for all list items between baseline and LOC
1376 (while (and (< (point) first
)
1377 (re-search-forward markdown-regex-list first t
))
1378 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
1381 ;; Make sure this is not a header or hr
1382 ((markdown-new-baseline-p) (setq levels nil
))
1383 ;; Make sure this is not a line from a pre block
1384 ((looking-at pre-regexp
))
1385 ;; If not, then update levels
1387 (setq indent
(markdown-cur-line-indent))
1388 (setq levels
(markdown-update-list-levels (match-string 2)
1393 (defun markdown-prev-list-item (level)
1394 "Search backward from point for a list item with indentation LEVEL.
1395 Set point to the beginning of the item, and return point, or nil
1397 (let (bounds indent prev
)
1400 (setq indent
(markdown-cur-line-indent))
1403 ;; Stop at beginning of buffer
1404 ((bobp) (setq prev nil
))
1405 ;; Continue if current line is blank
1406 ((markdown-cur-line-blank-p) t
)
1408 ((and (looking-at markdown-regex-list
)
1409 (setq bounds
(markdown-cur-list-item-bounds)))
1411 ;; Continue at item with greater indentation
1412 ((> (nth 3 bounds
) level
) t
)
1413 ;; Stop and return point at item of equal indentation
1414 ((= (nth 3 bounds
) level
)
1417 ;; Stop and return nil at item with lesser indentation
1418 ((< (nth 3 bounds
) level
)
1421 ;; Continue while indentation is the same or greater
1422 ((>= indent level
) t
)
1423 ;; Stop if current indentation is less than list item
1424 ;; and the next is blank
1425 ((and (< indent level
)
1426 (markdown-next-line-blank-p))
1429 ((looking-at markdown-regex-header
) (setq prev nil
))
1430 ;; Stop at a horizontal rule
1431 ((looking-at markdown-regex-hr
) (setq prev nil
))
1432 ;; Otherwise, continue.
1435 (setq indent
(markdown-cur-line-indent)))
1438 (defun markdown-next-list-item (level)
1439 "Search forward from point for the next list item with indentation LEVEL.
1440 Set point to the beginning of the item, and return point, or nil
1442 (let (bounds indent prev next
)
1445 (setq indent
(markdown-cur-line-indent))
1448 ;; Stop at end of the buffer.
1449 ((eobp) (setq prev nil
))
1450 ;; Continue if the current line is blank
1451 ((markdown-cur-line-blank-p) t
)
1453 ((and (looking-at markdown-regex-list
)
1454 (setq bounds
(markdown-cur-list-item-bounds)))
1456 ;; Continue at item with greater indentation
1457 ((> (nth 3 bounds
) level
) t
)
1458 ;; Stop and return point at item of equal indentation
1459 ((= (nth 3 bounds
) level
)
1462 ;; Stop and return nil at item with lesser indentation
1463 ((< (nth 3 bounds
) level
)
1466 ;; Continue while indentation is the same or greater
1467 ((>= indent level
) t
)
1468 ;; Stop if current indentation is less than list item
1469 ;; and the previous line was blank.
1470 ((and (< indent level
)
1471 (markdown-prev-line-blank-p))
1474 ((looking-at markdown-regex-header
) (setq next nil
))
1475 ;; Stop at a horizontal rule
1476 ((looking-at markdown-regex-hr
) (setq next nil
))
1477 ;; Otherwise, continue.
1480 (setq indent
(markdown-cur-line-indent)))
1483 (defun markdown-cur-list-item-end (level)
1484 "Move to the end of the current list item with nonlist indentation LEVEL.
1485 If the point is not in a list item, do nothing."
1488 (setq indent
(markdown-cur-line-indent))
1491 ;; Stop at end of the buffer.
1493 ;; Continue if the current line is blank
1494 ((markdown-cur-line-blank-p) t
)
1495 ;; Continue while indentation is the same or greater
1496 ((>= indent level
) t
)
1497 ;; Stop if current indentation is less than list item
1498 ;; and the previous line was blank.
1499 ((and (< indent level
)
1500 (markdown-prev-line-blank-p))
1502 ;; Stop at a new list item of the same or lesser indentation
1503 ((looking-at markdown-regex-list
) nil
)
1505 ((looking-at markdown-regex-header
) nil
)
1506 ;; Stop at a horizontal rule
1507 ((looking-at markdown-regex-hr
) nil
)
1508 ;; Otherwise, continue.
1511 (setq indent
(markdown-cur-line-indent)))
1512 ;; Don't skip over whitespace for empty list items (marker and
1513 ;; whitespace only), just move to end of whitespace.
1514 (if (looking-back (concat markdown-regex-list
"\\s-*"))
1515 (goto-char (match-end 3))
1516 (skip-syntax-backward "-"))))
1518 (defun markdown-cur-list-item-bounds ()
1519 "Return bounds and indentation of the current list item.
1520 Return a list of the form (begin end indent nonlist-indent).
1521 If the point is not inside a list item, return nil.
1522 Leave match data intact for `markdown-regex-list'."
1523 (let (cur prev-begin prev-end indent nonlist-indent
)
1524 ;; Store current location
1526 ;; Verify that cur is between beginning and end of item
1529 (when (re-search-backward markdown-regex-list nil t
)
1530 (setq prev-begin
(match-beginning 0))
1531 (setq indent
(length (match-string 1)))
1532 (setq nonlist-indent
(length (match-string 0)))
1534 (markdown-cur-list-item-end nonlist-indent
)
1535 (setq prev-end
(point)))
1536 (when (and (>= cur prev-begin
)
1539 (list prev-begin prev-end indent nonlist-indent
))))))
1541 (defun markdown-bounds-of-thing-at-point (thing)
1542 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1543 Does not include trailing newlines when THING is 'line. Handles the
1544 end of buffer case by setting both endpoints equal to the value of
1545 `point-max', since an empty region will trigger empty markup insertion.
1546 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1547 (let* ((bounds (bounds-of-thing-at-point thing
))
1551 (when (eq thing
'line
)
1552 (cond ((and (eobp) (markdown-cur-line-blank-p))
1554 ((char-equal (char-before b
) ?\^J
)
1558 (defun markdown-reference-definition (reference)
1559 "Find out whether Markdown REFERENCE is defined.
1560 REFERENCE should include the square brackets, like [this].
1561 When REFERENCE is defined, return a list of the form (text start end)
1562 containing the definition text itself followed by the start and end
1563 locations of the text. Otherwise, return nil.
1564 Leave match data for `markdown-regex-reference-definition'
1565 intact additional processing."
1566 (let ((reference (downcase reference
)))
1568 (goto-char (point-min))
1570 (while (re-search-forward markdown-regex-reference-definition nil t
)
1571 (when (string= reference
(downcase (match-string-no-properties 1)))
1573 (list (match-string-no-properties 2)
1574 (match-beginning 2) (match-end 2)))))))))
1577 ;;; Markdown Font Lock Matching Functions =====================================
1579 (defun markdown-match-comments (last)
1580 "Match HTML comments from the point to LAST."
1581 (cond ((search-forward "<!--" last t
)
1583 (let ((beg (point)))
1584 (cond ((search-forward-regexp "--[ \t]*>" last t
)
1585 (set-match-data (list beg
(point)))
1590 (defun markdown-match-pre-blocks (last)
1591 "Match Markdown pre blocks from point to LAST."
1592 (let ((levels (markdown-calculate-list-levels))
1593 indent pre-regexp end-regexp begin end stop
)
1594 (while (and (< (point) last
) (not end
))
1595 ;; Search for a region with sufficient indentation
1598 (setq indent
(1+ (length levels
))))
1599 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1600 (setq end-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1603 ;; If not at the beginning of a line, move forward
1604 ((not (bolp)) (forward-line))
1605 ;; Move past blank lines
1606 ((markdown-cur-line-blank-p) (forward-line))
1607 ;; At headers and horizontal rules, reset levels
1608 ((markdown-new-baseline-p) (forward-line) (setq levels nil
))
1609 ;; If the current line has sufficient indentation, mark out pre block
1610 ((looking-at pre-regexp
)
1611 (setq begin
(match-beginning 0))
1612 (while (and (or (looking-at pre-regexp
) (markdown-cur-line-blank-p))
1616 ;; If current line has a list marker, update levels, move to end of block
1617 ((looking-at markdown-regex-list
)
1618 (setq levels
(markdown-update-list-levels
1619 (match-string 2) (markdown-cur-line-indent) levels
))
1620 (markdown-end-of-block-element))
1621 ;; If this is the end of the indentation level, adjust levels accordingly.
1622 ;; Only match end of indentation level if levels is not the empty list.
1623 ((and (car levels
) (looking-at end-regexp
))
1624 (setq levels
(markdown-update-list-levels
1625 nil
(markdown-cur-line-indent) levels
))
1626 (markdown-end-of-block-element))
1627 (t (markdown-end-of-block-element))))
1629 (if (not (and begin end
))
1630 ;; Return nil if no pre block was found
1632 ;; Set match data and return t upon success
1633 (set-match-data (list begin end
))
1636 (defun markdown-match-fenced-code-blocks (last)
1637 "Match fenced code blocks from the point to LAST."
1638 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t
)
1640 (let ((beg (point)))
1642 (cond ((search-forward-regexp
1643 (concat "^" (match-string 1) "~*") last t
)
1644 (set-match-data (list beg
(point)))
1649 (defun markdown-match-gfm-code-blocks (last)
1650 "Match GFM quoted code blocks from point to LAST."
1651 (let (open lang body close all
)
1652 (cond ((and (eq major-mode
'gfm-mode
)
1653 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t
))
1655 (setq open
(list (match-beginning 1) (match-end 1))
1656 lang
(list (match-beginning 2) (match-end 2)))
1658 (setq body
(list (point)))
1659 (cond ((search-forward-regexp "^```$" last t
)
1660 (setq body
(reverse (cons (1- (match-beginning 0)) body
))
1661 close
(list (match-beginning 0) (match-end 0))
1662 all
(list (car open
) (match-end 0)))
1663 (set-match-data (append all open lang body close
))
1668 (defun markdown-match-generic-metadata (regexp last
)
1669 "Match generic metadata specified by REGEXP from the point to LAST."
1670 (let ((header-end (save-excursion
1671 (goto-char (point-min))
1672 (if (re-search-forward "\n\n" (point-max) t
)
1675 (cond ((>= (point) header-end
)
1676 ;; Don't match anything outside of the header.
1678 ((re-search-forward regexp
(min last header-end
) t
)
1679 ;; If a metadata item is found, it may span several lines.
1680 (let ((key-beginning (match-beginning 1))
1681 (key-end (match-end 1))
1682 (value-beginning (match-beginning 2)))
1683 (while (and (not (looking-at regexp
))
1684 (not (> (point) (min last header-end
)))
1690 (set-match-data (list key-beginning
(point) ; complete metadata
1691 key-beginning key-end
; key
1692 value-beginning
(point))) ; value
1696 (defun markdown-match-multimarkdown-metadata (last)
1697 "Match MultiMarkdown metadata from the point to LAST."
1698 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last
))
1700 (defun markdown-match-pandoc-metadata (last)
1701 "Match Pandoc metadata from the point to LAST."
1702 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
1704 (defun markdown-font-lock-extend-region ()
1705 "Extend the search region to include an entire block of text.
1706 This helps improve font locking for block constructs such as pre blocks."
1707 ;; Avoid compiler warnings about these global variables from font-lock.el.
1708 ;; See the documentation for variable `font-lock-extend-region-functions'.
1709 (eval-when-compile (defvar font-lock-beg
) (defvar font-lock-end
))
1711 (goto-char font-lock-beg
)
1712 (let ((found (or (re-search-backward "\n\n" nil t
) (point-min))))
1713 (goto-char font-lock-end
)
1714 (when (re-search-forward "\n\n" nil t
)
1716 (setq font-lock-end
(point)))
1717 (setq font-lock-beg found
))))
1720 ;;; Syntax Table ==============================================================
1722 (defvar markdown-mode-syntax-table
1723 (let ((tab (make-syntax-table text-mode-syntax-table
)))
1724 (modify-syntax-entry ?
\" "." tab
)
1726 "Syntax table for `markdown-mode'.")
1729 ;;; Element Insertion =========================================================
1731 (defun markdown-ensure-blank-line-before ()
1732 "If previous line is not already blank, insert a blank line before point."
1733 (unless (bolp) (insert "\n"))
1734 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1736 (defun markdown-ensure-blank-line-after ()
1737 "If following line is not already blank, insert a blank line after point.
1738 Return the point where it was originally."
1740 (unless (eolp) (insert "\n"))
1741 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1743 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
1744 "Insert the strings S1 and S2, wrapping around region or THING.
1745 If a region is specified by the optional BEG and END arguments,
1746 wrap the strings S1 and S2 around that region.
1747 If there is an active region, wrap the strings S1 and S2 around
1748 the region. If there is not an active region but the point is at
1749 THING, wrap that thing (which defaults to word). Otherwise, just
1750 insert S1 and S2 and place the cursor in between. Return the
1751 bounds of the entire wrapped string, or nil if nothing was wrapped
1752 and S1 and S2 were only inserted."
1753 (let (a b bounds new-point
)
1759 new-point
(+ (point) (length s1
))))
1761 ((markdown-use-region-p)
1762 (setq a
(region-beginning)
1764 new-point
(+ (point) (length s1
))))
1765 ;; Thing (word) at point
1766 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
1767 (setq a
(car bounds
)
1769 new-point
(+ (point) (length s1
))))
1770 ;; No active region and no word
1778 (when new-point
(goto-char new-point
))
1781 (setq b
(+ b
(length s1
) (length s2
)))
1784 (defun markdown-point-after-unwrap (cur prefix suffix
)
1785 "Return desired position of point after an unwrapping operation.
1786 Two cons cells must be provided. PREFIX gives the bounds of the
1787 prefix string and SUFFIX gives the bounds of the suffix string."
1788 (cond ((< cur
(cdr prefix
)) (car prefix
))
1789 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
1790 ((<= cur
(cdr suffix
))
1791 (- cur
(+ (- (cdr prefix
) (car prefix
))
1792 (- cur
(car suffix
)))))
1795 (defun markdown-unwrap-thing-at-point (regexp all text
)
1796 "Remove prefix and suffix of thing at point and reposition the point.
1797 When the thing at point matches REGEXP, replace the subexpression
1798 ALL with the string in subexpression TEXT. Reposition the point
1799 in an appropriate location accounting for the removal of prefix
1800 and suffix strings. Return new bounds of string from group TEXT.
1801 When REGEXP is nil, assumes match data is already set."
1802 (when (or (null regexp
)
1803 (thing-at-point-looking-at regexp
))
1805 (prefix (cons (match-beginning all
) (match-beginning text
)))
1806 (suffix (cons (match-end text
) (match-end all
)))
1807 (bounds (cons (match-beginning text
) (match-end text
))))
1808 ;; Replace the thing at point
1809 (replace-match (match-string text
) t t nil all
)
1810 ;; Reposition the point
1811 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
1813 (setq bounds
(cons (car prefix
)
1814 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
1816 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
1817 "Remove prefix and suffix of all things in region.
1818 When a thing in the region matches REGEXP, replace the
1819 subexpression ALL with the string in subexpression TEXT.
1820 Return a cons cell containing updated bounds for the region."
1823 (let ((removed 0) len-all len-text
)
1824 (while (re-search-forward regexp
(- end removed
) t
)
1825 (setq len-all
(length (match-string-no-properties all
)))
1826 (setq len-text
(length (match-string-no-properties text
)))
1827 (setq removed
(+ removed
(- len-all len-text
)))
1828 (replace-match (match-string text
) t t nil all
))
1829 (cons beg
(- end removed
)))))
1831 (defun markdown-insert-hr (arg)
1832 "Insert or replace a horizonal rule.
1833 By default, use the first element of `markdown-hr-strings'. When
1834 prefixed with C-u, use the last element of `markdown-hr-strings'
1835 instead. When prefixed with an integer from 1 to the length of
1836 `markdown-hr-strings', use the element in that position instead."
1838 (when (thing-at-point-looking-at markdown-regex-hr
)
1839 (delete-region (match-beginning 0) (match-end 0)))
1840 (markdown-ensure-blank-line-before)
1841 (cond ((equal arg
'(4))
1842 (insert (car (reverse markdown-hr-strings
))))
1843 ((and (integerp arg
) (> arg
0)
1844 (<= arg
(length markdown-hr-strings
)))
1845 (insert (nth (1- arg
) markdown-hr-strings
)))
1847 (insert (car markdown-hr-strings
))))
1848 (markdown-ensure-blank-line-after))
1850 (defun markdown-insert-bold ()
1851 "Insert markup to make a region or word bold.
1852 If there is an active region, make the region bold. If the point
1853 is at a non-bold word, make the word bold. If the point is at a
1854 bold word or phrase, remove the bold markup. Otherwise, simply
1855 insert bold delimiters and place the cursor in between them."
1857 (let ((delim (if markdown-bold-underscore
"__" "**")))
1858 (if (markdown-use-region-p)
1860 (let ((bounds (markdown-unwrap-things-in-region
1861 (region-beginning) (region-end)
1862 markdown-regex-bold
2 4)))
1863 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1864 ;; Bold markup removal, bold word at point, or empty markup insertion
1865 (if (thing-at-point-looking-at markdown-regex-bold
)
1866 (markdown-unwrap-thing-at-point nil
2 4)
1867 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1869 (defun markdown-insert-italic ()
1870 "Insert markup to make a region or word italic.
1871 If there is an active region, make the region italic. If the point
1872 is at a non-italic word, make the word italic. If the point is at an
1873 italic word or phrase, remove the italic markup. Otherwise, simply
1874 insert italic delimiters and place the cursor in between them."
1876 (let ((delim (if markdown-italic-underscore
"_" "*")))
1877 (if (markdown-use-region-p)
1879 (let ((bounds (markdown-unwrap-things-in-region
1880 (region-beginning) (region-end)
1881 markdown-regex-italic
2 4)))
1882 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1883 ;; Italic markup removal, italic word at point, or empty markup insertion
1884 (if (thing-at-point-looking-at markdown-regex-italic
)
1885 (markdown-unwrap-thing-at-point nil
2 4)
1886 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1888 (defun markdown-insert-code ()
1889 "Insert markup to make a region or word an inline code fragment.
1890 If there is an active region, make the region an inline code
1891 fragment. If the point is at a word, make the word an inline
1892 code fragment. Otherwise, simply insert code delimiters and
1893 place the cursor in between them."
1895 (if (markdown-use-region-p)
1897 (let ((bounds (markdown-unwrap-things-in-region
1898 (region-beginning) (region-end)
1899 markdown-regex-code
2 4)))
1900 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
1901 ;; Code markup removal, code markup for word, or empty markup insertion
1902 (if (thing-at-point-looking-at markdown-regex-code
)
1903 (markdown-unwrap-thing-at-point nil
2 4)
1904 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
1906 (defun markdown-insert-link ()
1907 "Insert an inline link, using region or word as link text if possible.
1908 If there is an active region, use the region as the link text. If the
1909 point is at a word, use the word as the link text. In these cases, the
1910 point will be left at the position for inserting a URL. If there is no
1911 active region and the point is not at word, simply insert link markup and
1912 place the point in the position to enter link text."
1914 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1916 (goto-char (- (cdr bounds
) 1)))))
1918 (defun markdown-insert-reference-link-dwim ()
1919 "Insert a reference link of the form [text][label] at point.
1920 If Transient Mark mode is on and a region is active, the region
1921 is used as the link text. Otherwise, the link text will be read
1922 from the minibuffer. The link URL, label, and title will be read
1923 from the minibuffer. The link label definition is placed at the
1924 end of the current paragraph."
1926 (if (markdown-use-region-p)
1927 (call-interactively 'markdown-insert-reference-link-region
)
1928 (call-interactively 'markdown-insert-reference-link
)))
1930 (defun markdown-insert-reference-link-region (url label title
)
1931 "Insert a reference link at point using the region as the link text.
1932 The link will point to URL, will be referenced as LABEL, and will have the
1933 optional title text given by TITLE."
1934 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1935 (let ((text (delete-and-extract-region (region-beginning) (region-end))))
1936 (markdown-insert-reference-link text url label title
)))
1938 (defun markdown-insert-reference-link (text url label title
)
1939 "Insert a reference link at point.
1940 The link TEXT will point to the given URL and may be referenced using
1941 LABEL. The link TITLE is optional and will be used to populate the
1942 title attribute when converted to XHTML."
1943 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1945 (insert (concat "[" text
"][" label
"]"))
1949 (if (> (length label
) 0)
1952 (insert (concat "]: " url
))
1953 (unless (> (length url
) 0)
1955 (when (> (length title
) 0)
1956 (insert (concat " \"" title
"\"")))
1958 (unless (looking-at "\n")
1962 (defun markdown-insert-wiki-link ()
1963 "Insert a wiki link of the form [[WikiLink]].
1964 If Transient Mark mode is on and a region is active, it is used
1967 (markdown-wrap-or-insert "[[" "]]")
1970 (defun markdown-insert-image (&optional arg
)
1971 "Insert image markup using region or word as alt text if possible.
1972 If there is an active region, use the region as the alt text. If the
1973 point is at a word, use the word as the alt text. In these cases, the
1974 point will be left at the position for inserting a URL. If there is no
1975 active region and the point is not at word, simply insert image markup and
1976 place the point in the position to enter alt text. If ARG is nil, insert
1977 inline image markup. Otherwise, insert reference image markup."
1979 (let ((bounds (if arg
1980 (markdown-wrap-or-insert "![" "][]")
1981 (markdown-wrap-or-insert "![" "]()"))))
1983 (goto-char (- (cdr bounds
) 1)))))
1985 (defun markdown-remove-header ()
1986 "Remove header markup if point is at a header.
1987 Return bounds of remaining header text if a header was removed
1990 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
1991 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
1993 (defun markdown-insert-header (&optional level text setext
)
1994 "Insert or replace header markup.
1995 The level of the header is specified by LEVEL and header text is
1996 given by TEXT. LEVEL must be an integer from 1 and 6, and the
1998 When TEXT is nil, the header text is obtained as follows.
1999 If there is an active region, it is used as the header text.
2000 Otherwise, the current line will be used as the header text.
2001 If there is not an active region and the point is at a header,
2002 remove the header markup and replace with level N header.
2003 Otherwise, insert empty header markup and place the cursor in
2005 The style of the header will be atx (hash marks) unless
2006 SETEXT is non-nil, in which case a setext-style (underlined)
2007 header will be inserted."
2008 (interactive "p\nsHeader text: ")
2009 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
2010 ;; Determine header text if not given
2012 (if (markdown-use-region-p)
2014 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
2016 (markdown-remove-header)
2017 (setq text
(delete-and-extract-region
2018 (line-beginning-position) (line-end-position)))
2019 (when (and setext
(string-match "^[ \t]*$" text
))
2020 (setq text
(read-string "Header text: "))))
2021 (setq text
(markdown-compress-whitespace-string text
)))
2022 ;; Insertion with given text
2023 (markdown-ensure-blank-line-before)
2028 (dotimes (n (length text
))
2029 (insert (if (= level
2) "-" "="))))
2031 (dotimes (count level
) (insert "#"))
2032 (insert " " text
" ")
2033 (dotimes (count level
) (insert "#")))
2034 (markdown-ensure-blank-line-after)
2035 ;; Leave point at end of text
2037 (backward-char (1+ (length text
)))
2038 (backward-char (1+ level
))))
2040 (defun markdown-insert-header-dwim (&optional arg setext
)
2041 "Insert or replace header markup.
2042 The level and type of the header are determined automatically by
2043 the type and level of the previous header, unless a prefix
2045 With a numeric prefix valued 1 to 6, insert a header of the given
2046 level, with the type being determined automatically (note that
2047 only level 1 or 2 setext headers are possible).
2048 With C-u, insert a level-one setext header.
2049 With C-u C-u, insert a level two setext header.
2051 When there is an active region, use it for the header text. When
2052 the point is at an existing header, change the type and level
2053 according to the rules above.
2054 Otherwise, if the line is not empty, create a header using the
2055 text on the current line as the header text.
2056 Finally, if the point is on a blank line, insert empty header
2057 markup (atx) or prompt for text (setext).
2058 See `markdown-insert-header' for more details about how the
2059 header text is determined."
2062 (cond ((equal arg
'(4)) ; level-one setext with C-u
2065 ((equal arg
'(16)) ; level-two setext with C-u C-u
2068 (t ; automatic with numeric override
2070 (when (re-search-backward markdown-regex-header nil t
)
2071 ;; level of previous header
2072 (setq level
(markdown-outline-level))
2073 ;; match groups 1 and 2 indicate setext headers
2074 (setq setext
(or setext
(match-end 1) (match-end 3)))))
2075 ;; use prefix if given, or level of previous header
2076 (setq level
(if arg
(prefix-numeric-value arg
) level
))
2077 ;; setext headers must be level one or two
2078 (and level
(setq setext
(and setext
(<= level
2))))))
2079 (markdown-insert-header level nil setext
)))
2081 (defun markdown-insert-header-setext-dwim (&optional arg
)
2082 "Insert or replace header markup, with preference for setext.
2083 See `markdown-insert-header-dwim' for details."
2085 (markdown-insert-header-dwim arg t
))
2087 (defun markdown-insert-header-atx-1 ()
2088 "Insert a first level atx-style (hash mark) header.
2089 See `markdown-insert-header'."
2091 (markdown-insert-header 1 nil nil
))
2093 (defun markdown-insert-header-atx-2 ()
2094 "Insert a level two atx-style (hash mark) header.
2095 See `markdown-insert-header'."
2097 (markdown-insert-header 2 nil nil
))
2099 (defun markdown-insert-header-atx-3 ()
2100 "Insert a level three atx-style (hash mark) header.
2101 See `markdown-insert-header'."
2103 (markdown-insert-header 3 nil nil
))
2105 (defun markdown-insert-header-atx-4 ()
2106 "Insert a level four atx-style (hash mark) header.
2107 See `markdown-insert-header'."
2109 (markdown-insert-header 4 nil nil
))
2111 (defun markdown-insert-header-atx-5 ()
2112 "Insert a level five atx-style (hash mark) header.
2113 See `markdown-insert-header'."
2115 (markdown-insert-header 5 nil nil
))
2117 (defun markdown-insert-header-atx-6 ()
2118 "Insert a sixth level atx-style (hash mark) header.
2119 See `markdown-insert-header'."
2121 (markdown-insert-header 6 nil nil
))
2123 (defun markdown-insert-header-setext-1 ()
2124 "Insert a setext-style (underlined) first-level header.
2125 See `markdown-insert-header'."
2127 (markdown-insert-header 1 nil t
))
2129 (defun markdown-insert-header-setext-2 ()
2130 "Insert a setext-style (underlined) second-level header.
2131 See `markdown-insert-header'."
2133 (markdown-insert-header 2 nil t
))
2135 (defun markdown-blockquote-indentation (loc)
2136 "Return string containing necessary indentation for a blockquote at LOC.
2137 Also see `markdown-pre-indentation'."
2140 (let* ((list-level (length (markdown-calculate-list-levels)))
2142 (dotimes (count list-level indent
)
2143 (setq indent
(concat indent
" "))))))
2145 (defun markdown-insert-blockquote ()
2146 "Start a blockquote section (or blockquote the region).
2147 If Transient Mark mode is on and a region is active, it is used as
2148 the blockquote text."
2150 (if (markdown-use-region-p)
2151 (markdown-blockquote-region (region-beginning) (region-end))
2152 (markdown-ensure-blank-line-before)
2153 (insert (markdown-blockquote-indentation (point)) "> ")
2154 (markdown-ensure-blank-line-after)))
2156 (defun markdown-block-region (beg end prefix
)
2157 "Format the region using a block prefix.
2158 Arguments BEG and END specify the beginning and end of the
2159 region. The characters PREFIX will appear at the beginning
2162 (let* ((end-marker (make-marker))
2163 (beg-marker (make-marker)))
2164 ;; Ensure blank line after and remove extra whitespace
2166 (skip-syntax-backward "-")
2167 (set-marker end-marker
(point))
2168 (delete-horizontal-space)
2169 (markdown-ensure-blank-line-after)
2170 ;; Ensure blank line before and remove extra whitespace
2172 (skip-syntax-forward "-")
2173 (delete-horizontal-space)
2174 (markdown-ensure-blank-line-before)
2175 (set-marker beg-marker
(point))
2176 ;; Insert PREFIX before each line
2177 (goto-char beg-marker
)
2178 (while (< (line-beginning-position) end-marker
)
2182 (defun markdown-blockquote-region (beg end
)
2183 "Blockquote the region.
2184 Arguments BEG and END specify the beginning and end of the region."
2186 (markdown-block-region
2187 beg end
(concat (markdown-blockquote-indentation
2188 (max (point-min) (1- beg
))) "> ")))
2190 (defun markdown-pre-indentation (loc)
2191 "Return string containing necessary whitespace for a pre block at LOC.
2192 Also see `markdown-blockquote-indentation'."
2195 (let* ((list-level (length (markdown-calculate-list-levels)))
2197 (dotimes (count (1+ list-level
) indent
)
2198 (setq indent
(concat indent
" "))))))
2200 (defun markdown-insert-pre ()
2201 "Start a preformatted section (or apply to the region).
2202 If Transient Mark mode is on and a region is active, it is marked
2203 as preformatted text."
2205 (if (markdown-use-region-p)
2206 (markdown-pre-region (region-beginning) (region-end))
2207 (markdown-ensure-blank-line-before)
2208 (insert (markdown-pre-indentation (point)))
2209 (markdown-ensure-blank-line-after)))
2211 (defun markdown-pre-region (beg end
)
2212 "Format the region as preformatted text.
2213 Arguments BEG and END specify the beginning and end of the region."
2215 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
2216 (markdown-block-region beg end indent
)))
2218 (defun markdown-insert-gfm-code-block (&optional lang
)
2219 "Insert GFM code block for language LANG.
2220 If LANG is nil, the language will be queried from user. If a
2221 region is active, wrap this region with the markup instead. If
2222 the region boundaries are not on empty lines, these are added
2223 automatically in order to have the correct markup."
2224 (interactive "sProgramming language: ")
2225 (if (markdown-use-region-p)
2226 (let ((b (region-beginning)) (e (region-end)))
2228 ;; if we're on a blank line, insert the quotes here, otherwise
2229 ;; add a new line first
2230 (unless (looking-at "\n")
2235 (goto-char (+ e
3 (length lang
)))
2236 ;; if we're on a blank line, don't newline, otherwise the ```
2237 ;; should go on its own line
2238 (unless (looking-back "\n")
2247 ;;; Footnotes ======================================================================
2249 (defun markdown-footnote-counter-inc ()
2250 "Increment `markdown-footnote-counter' and return the new value."
2251 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
2253 (goto-char (point-min))
2254 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
2256 (let ((fn (string-to-number (match-string 1))))
2257 (when (> fn markdown-footnote-counter
)
2258 (setq markdown-footnote-counter fn
))))))
2259 (incf markdown-footnote-counter
))
2261 (defun markdown-footnote-new ()
2262 "Insert footnote with a new number and move point to footnote definition."
2264 (let ((fn (markdown-footnote-counter-inc)))
2265 (insert (format "[^%d]" fn
))
2266 (markdown-footnote-text-find-new-location)
2267 (markdown-ensure-blank-line-before)
2268 (unless (markdown-cur-line-blank-p)
2270 (insert (format "[^%d]: " fn
))
2271 (markdown-ensure-blank-line-after)))
2273 (defun markdown-footnote-text-find-new-location ()
2274 "Position the cursor at the proper location for a new footnote text."
2276 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
2277 ((eq markdown-footnote-location
'immediately
) (forward-paragraph))
2278 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
2280 (defun markdown-footnote-kill ()
2281 "Kill the footnote at point.
2282 The footnote text is killed (and added to the kill ring), the
2283 footnote marker is deleted. Point has to be either at the
2284 footnote marker or in the footnote text."
2287 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2288 (markdown-footnote-return) ; we first move to the marker
2289 (setq return-pos
'text
)) ; and remember our return position
2290 (let ((marker (markdown-footnote-delete-marker)))
2292 (error "Not at a footnote"))
2293 (let ((text-pos (markdown-footnote-find-text (car marker
))))
2295 (error "No text for footnote `%s'" (car marker
)))
2296 (goto-char text-pos
)
2297 (let ((pos (markdown-footnote-kill-text)))
2299 (if (and pos
(eq return-pos
'text
))
2302 (goto-char return-pos
)))
2304 (defun markdown-footnote-delete-marker ()
2305 "Delete a footnote marker at point.
2306 Returns a list (ID START) containing the footnote ID and the
2307 start position of the marker before deletion. If no footnote
2308 marker was deleted, this function returns NIL."
2309 (let ((marker (markdown-footnote-marker-positions)))
2311 (delete-region (second marker
) (third marker
))
2314 (defun markdown-footnote-kill-text ()
2315 "Kill footnote text at point.
2316 Returns the start position of the footnote text before deletion,
2317 or NIL if point was not inside a footnote text.
2319 The killed text is placed in the kill ring (without the footnote
2321 (let ((fn (markdown-footnote-text-positions)))
2323 (let ((text (delete-and-extract-region (second fn
) (third fn
))))
2324 (string-match (concat "\\[\\" (first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
2325 (kill-new (match-string 1 text
))
2326 (when (and (markdown-cur-line-blank-p)
2327 (markdown-prev-line-blank-p))
2328 (delete-region (1- (point)) (point)))
2331 (defun markdown-footnote-goto-text ()
2332 "Jump to the text of the footnote at point."
2334 (let ((fn (car (markdown-footnote-marker-positions))))
2336 (error "Not at a footnote marker"))
2337 (let ((new-pos (markdown-footnote-find-text fn
)))
2339 (error "No definition found for footnote `%s'" fn
))
2340 (goto-char new-pos
))))
2342 (defun markdown-footnote-return ()
2343 "Return from a footnote to its footnote number in the main text."
2345 (let ((fn (save-excursion
2346 (car (markdown-footnote-text-positions)))))
2348 (error "Not in a footnote"))
2349 (let ((new-pos (markdown-footnote-find-marker fn
)))
2351 (error "Footnote marker `%s' not found" fn
))
2352 (goto-char new-pos
))))
2354 (defun markdown-footnote-find-marker (id)
2355 "Find the location of the footnote marker with ID.
2356 The actual buffer position returned is the position directly
2357 following the marker's closing bracket. If no marker is found,
2360 (goto-char (point-min))
2361 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
2362 (skip-chars-backward "^]")
2365 (defun markdown-footnote-find-text (id)
2366 "Find the location of the text of footnote ID.
2367 The actual buffer position returned is the position of the first
2368 character of the text, after the footnote's identifier. If no
2369 footnote text is found, NIL is returned."
2371 (goto-char (point-min))
2372 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
2373 (skip-chars-forward "[ \t]")
2376 (defun markdown-footnote-marker-positions ()
2377 "Return the position and ID of the footnote marker point is on.
2378 The return value is a list (ID START END). If point is not on a
2379 footnote, NIL is returned."
2380 ;; first make sure we're at a footnote marker
2381 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
2382 (looking-at (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
2384 ;; move point between [ and ^:
2385 (if (looking-at "\\[")
2387 (skip-chars-backward "^["))
2388 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
2389 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2391 (defun markdown-footnote-text-positions ()
2392 "Return the start and end positions of the footnote text point is in.
2393 The exact return value is a list of three elements: (ID START END).
2394 The start position is the position of the opening bracket
2395 of the footnote id. The end position is directly after the
2396 newline that ends the footnote. If point is not in a footnote,
2397 NIL is returned instead."
2400 (backward-paragraph)
2401 ;; if we're in a multiparagraph footnote, we need to back up further
2402 (while (>= (markdown-next-line-indent) 4)
2403 (backward-paragraph))
2405 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:"))
2406 (list (match-string 1) (point))))))
2410 (>= (markdown-next-line-indent) 4)))
2411 (append fn
(list (point)))))))
2414 ;;; Element Removal ===========================================================
2416 (defun markdown-kill-thing-at-point ()
2417 "Kill thing at point and add important text, without markup, to kill ring.
2418 Possible things to kill include (roughly in order of precedence):
2419 inline code, headers, horizonal rules, links (add link text to
2420 kill ring), images (add alt text to kill ring), angle uri, email
2421 addresses, bold, italics, reference definition (add URI to kill
2422 ring), footnote markers and text (kill both marker and text, add
2423 text to kill ring), and list items."
2428 ((thing-at-point-looking-at markdown-regex-code
)
2429 (kill-new (match-string 4))
2430 (delete-region (match-beginning 2) (match-end 2)))
2432 ((thing-at-point-looking-at markdown-regex-header-atx
)
2433 (kill-new (match-string 2))
2434 (delete-region (match-beginning 0) (match-end 0)))
2436 ((thing-at-point-looking-at markdown-regex-header-setext
)
2437 (kill-new (match-string 1))
2438 (delete-region (match-beginning 0) (match-end 0)))
2440 ((thing-at-point-looking-at markdown-regex-hr
)
2441 (kill-new (match-string 0))
2442 (delete-region (match-beginning 0) (match-end 0)))
2443 ;; Inline link or image (add link or alt text to kill ring)
2444 ((thing-at-point-looking-at markdown-regex-link-inline
)
2445 (kill-new (match-string 2))
2446 (delete-region (match-beginning 0) (match-end 0)))
2447 ;; Reference link or image (add link or alt text to kill ring)
2448 ((thing-at-point-looking-at markdown-regex-link-reference
)
2449 (kill-new (match-string 2))
2450 (delete-region (match-beginning 0) (match-end 0)))
2451 ;; Angle URI (add URL to kill ring)
2452 ((thing-at-point-looking-at markdown-regex-angle-uri
)
2453 (kill-new (match-string 2))
2454 (delete-region (match-beginning 0) (match-end 0)))
2455 ;; Email address in angle brackets (add email address to kill ring)
2456 ((thing-at-point-looking-at markdown-regex-email
)
2457 (kill-new (match-string 1))
2458 (delete-region (match-beginning 0) (match-end 0)))
2459 ;; Wiki link (add alias text to kill ring)
2460 ((thing-at-point-looking-at markdown-regex-wiki-link
)
2461 (kill-new (if markdown-wiki-link-alias-first
2462 (match-string-no-properties 2)
2463 (or (match-string-no-properties 2) (match-string-no-properties 4))))
2464 (delete-region (match-beginning 1) (match-end 1)))
2466 ((thing-at-point-looking-at markdown-regex-bold
)
2467 (kill-new (match-string 4))
2468 (delete-region (match-beginning 2) (match-end 2)))
2470 ((thing-at-point-looking-at markdown-regex-italic
)
2471 (kill-new (match-string 4))
2472 (delete-region (match-beginning 2) (match-end 2)))
2473 ;; Reference definition (add URL to kill ring)
2474 ((thing-at-point-looking-at markdown-regex-reference-definition
)
2475 (kill-new (match-string 2))
2476 (delete-region (match-beginning 0) (match-end 0)))
2477 ;; Footnote marker (add footnote text to kill ring)
2478 ((thing-at-point-looking-at markdown-regex-footnote
)
2479 (markdown-footnote-kill))
2480 ;; Footnote text (add footnote text to kill ring)
2481 ((setq val
(markdown-footnote-text-positions))
2482 (markdown-footnote-kill))
2484 ((setq val
(markdown-cur-list-item-bounds))
2485 (kill-new (delete-and-extract-region (first val
) (second val
))))
2487 (error "Nothing found at point to kill")))))
2490 ;;; Indentation ====================================================================
2492 (defun markdown-indent-find-next-position (cur-pos positions
)
2493 "Return the position after the index of CUR-POS in POSITIONS.
2494 Positions are calculated by `markdown-calc-indents'."
2495 (while (and positions
2496 (not (equal cur-pos
(car positions
))))
2497 (setq positions
(cdr positions
)))
2498 (or (cadr positions
) 0))
2500 (defun markdown-indent-line ()
2501 "Indent the current line using some heuristics.
2502 If the _previous_ command was either `markdown-enter-key' or
2503 `markdown-cycle', then we should cycle to the next
2504 reasonable indentation position. Otherwise, we could have been
2505 called directly by `markdown-enter-key', by an initial call of
2506 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2507 these cases, indent to the default position.
2508 Positions are calculated by `markdown-calc-indents'."
2510 (let ((positions (markdown-calc-indents))
2511 (cur-pos (current-column)))
2512 (if (not (equal this-command
'markdown-cycle
))
2513 (indent-line-to (car positions
))
2514 (setq positions
(sort (delete-dups positions
) '<))
2516 (markdown-indent-find-next-position cur-pos positions
)))))
2518 (defun markdown-calc-indents ()
2519 "Return a list of indentation columns to cycle through.
2520 The first element in the returned list should be considered the
2521 default indentation level. This function does not worry about
2522 duplicate positions, which are handled up by calling functions."
2523 (let (pos prev-line-pos positions
)
2525 ;; Indentation of previous line
2526 (setq prev-line-pos
(markdown-prev-line-indent))
2527 (setq positions
(cons prev-line-pos positions
))
2529 ;; Indentation of previous non-list-marker text
2530 (when (setq pos
(markdown-prev-non-list-indent))
2531 (setq positions
(cons pos positions
)))
2533 ;; Indentation required for a pre block in current context
2534 (setq pos
(length (markdown-pre-indentation (point))))
2535 (setq positions
(cons pos positions
))
2537 ;; Indentation of the previous line + tab-width
2539 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
2540 (setq positions
(cons tab-width positions
)))
2542 ;; Indentation of the previous line - tab-width
2543 (if (and prev-line-pos
(> prev-line-pos tab-width
))
2544 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
2546 ;; Indentation of all preceeding list markers (when in a list)
2547 (when (setq pos
(markdown-calculate-list-levels))
2548 (setq positions
(append pos positions
)))
2551 (setq positions
(cons 0 positions
))
2553 ;; Return reversed list
2554 (reverse positions
)))
2556 (defun markdown-do-normal-return ()
2557 "Insert a newline and optionally indent the next line."
2559 (if markdown-indent-on-enter
2560 (funcall indent-line-function
)))
2562 (defun markdown-enter-key ()
2563 "Handle RET according to context.
2564 If there is a wiki link at the point, follow it unless
2565 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2566 it in the usual way."
2568 (if (and markdown-follow-wiki-link-on-enter
(markdown-wiki-link-p))
2569 (markdown-follow-wiki-link-at-point)
2570 (markdown-do-normal-return)))
2572 (defun markdown-dedent-or-delete (arg)
2573 "Handle BACKSPACE by cycling through indentation points.
2574 When BACKSPACE is pressed, if there is only whitespace
2575 before the current point, then dedent the line one level.
2576 Otherwise, do normal delete by repeating
2577 `backward-delete-char-untabify' ARG times."
2579 (let ((cur-pos (current-column))
2580 (start-of-indention (save-excursion
2581 (back-to-indentation)
2583 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
2585 (dolist (i (markdown-calc-indents))
2587 (setq result
(max result i
))))
2588 (indent-line-to result
))
2589 (backward-delete-char-untabify arg
))))
2592 ;;; Markup Completion =========================================================
2594 (defconst markdown-complete-alist
2595 '((markdown-regex-header-atx . markdown-complete-atx
)
2596 (markdown-regex-header-setext . markdown-complete-setext
)
2597 (markdown-regex-hr . markdown-complete-hr
))
2598 "Association list of form (regexp . function) for markup completion.")
2600 (defun markdown-incomplete-atx-p ()
2601 "Return t if ATX header markup is incomplete and nil otherwise.
2602 Assumes match data is available for `markdown-regex-header-atx'.
2603 Checks that the number of trailing hash marks equals the number of leading
2604 hash marks, that there is only a single space before and after the text,
2605 and that there is no extraneous whitespace in the text."
2607 (or (not (= (length (match-string 1)) (length (match-string 3))))
2608 (not (= (match-beginning 2) (1+ (match-end 1))))
2609 (not (= (match-beginning 3) (1+ (match-end 2))))
2610 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2612 (defun markdown-complete-atx ()
2613 "Complete and normalize ATX headers.
2614 Add or remove hash marks to the end of the header to match the
2615 beginning. Ensure that there is only a single space between hash
2616 marks and header text. Removes extraneous whitespace from header text.
2617 Assumes match data is available for `markdown-regex-header-atx'."
2618 (when (markdown-incomplete-atx-p)
2619 (let* ((new-marker (make-marker))
2620 (new-marker (set-marker new-marker
(match-end 2))))
2621 ;; Hash marks and spacing at end
2622 (goto-char (match-end 2))
2623 (delete-region (match-end 2) (match-end 3))
2624 (insert " " (match-string 1))
2625 ;; Remove extraneous whitespace from title
2626 (replace-match (markdown-compress-whitespace-string (match-string 2))
2628 ;; Spacing at beginning
2629 (goto-char (match-end 1))
2630 (delete-region (match-end 1) (match-beginning 2))
2632 ;; Leave point at end of text
2633 (goto-char new-marker
))))
2635 (defun markdown-incomplete-setext-p ()
2636 "Return t if setext header markup is incomplete and nil otherwise.
2637 Assumes match data is available for `markdown-regex-header-setext'.
2638 Checks that length of underline matches text and that there is no
2639 extraneous whitespace in the text."
2641 (or (not (= (length (match-string 1)) (length (match-string 2))))
2642 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2644 (defun markdown-complete-setext ()
2645 "Complete and normalize setext headers.
2646 Add or remove underline characters to match length of header
2647 text. Removes extraneous whitespace from header text. Assumes
2648 match data is available for `markdown-regex-header-setext'."
2649 (when (markdown-incomplete-setext-p)
2650 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2651 (char (char-after (match-beginning 2)))
2652 (level (if (char-equal char ?-
) 2 1)))
2653 (goto-char (match-beginning 0))
2654 (delete-region (match-beginning 0) (match-end 0))
2655 (markdown-insert-header level text t
))))
2657 (defun markdown-incomplete-hr-p ()
2658 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2659 Assumes match data is available for `markdown-regex-hr'."
2660 (not (member (match-string 0) markdown-hr-strings
)))
2662 (defun markdown-complete-hr ()
2663 "Complete horizontal rules.
2664 If horizontal rule string is a member of `markdown-hr-strings',
2665 do nothing. Otherwise, replace with the car of
2666 `markdown-hr-strings'.
2667 Assumes match data is available for `markdown-regex-hr'."
2668 (replace-match (car markdown-hr-strings
)))
2670 (defun markdown-complete ()
2671 "Complete markup of object near point or in region when active.
2672 Handle all objects in `markdown-complete-alist', in order.
2673 See `markdown-complete-at-point' and `markdown-complete-region'."
2675 (if (markdown-use-region-p)
2676 (markdown-complete-region (region-beginning) (region-end))
2677 (markdown-complete-at-point)))
2679 (defun markdown-complete-at-point ()
2680 "Complete markup of object near point.
2681 Handle all objects in `markdown-complete-alist', in
2684 (loop for
(regexp . function
) in markdown-complete-alist
2685 until
(thing-at-point-looking-at (eval regexp
))
2686 finally
(funcall function
)))
2688 (defun markdown-complete-region (beg end
)
2689 "Complete markup of object near point.
2690 Handle all objects in `markdown-complete-alist', in
2693 (let* ((end-marker (make-marker))
2694 (end-marker (set-marker end-marker end
)))
2695 (loop for
(regexp . function
) in markdown-complete-alist
2698 (while (re-search-forward (eval regexp
) end-marker t
)
2699 (funcall function
))))))
2701 (defun markdown-complete-buffer ()
2702 "Complete markup for all objects in the current buffer."
2704 (markdown-complete-region (point-min) (point-max)))
2707 ;;; Markup Cycling ============================================================
2709 (defun markdown-cycle-atx (arg &optional remove
)
2710 "Cycle ATX header markup.
2711 Promote header (decrease level) when ARG is 1 and demote
2712 header (increase level) if arg is -1. When REMOVE is non-nil,
2713 remove the header when the level reaches zero and stop cycling
2714 when it reaches six. Otherwise, perform a proper cycling through
2715 levels one through six. Assumes match data is available for
2716 `markdown-regex-header-atx'."
2717 (let* ((old-level (length (match-string 1)))
2718 (new-level (+ old-level arg
))
2719 (text (match-string 2)))
2721 (setq new-level
(% new-level
6))
2722 (setq new-level
(cond ((= new-level
0) 6)
2723 ((< new-level
0) (+ new-level
6))
2727 (markdown-unwrap-thing-at-point nil
0 2))
2729 (goto-char (match-beginning 0))
2730 (delete-region (match-beginning 0) (match-end 0))
2731 (markdown-insert-header new-level text nil
)))))
2733 (defun markdown-cycle-setext (arg &optional remove
)
2734 "Cycle setext header markup.
2735 Promote header (increase level) when ARG is 1 and demote
2736 header (decrease level or remove) if arg is -1. When demoting a
2737 level-two setext header, replace with a level-three atx header.
2738 When REMOVE is non-nil, remove the header when the level reaches
2739 zero. Otherwise, cycle back to a level six atx header. Assumes
2740 match data is available for `markdown-regex-header-setext'."
2741 (let* ((char (char-after (match-beginning 2)))
2742 (old-level (if (char-equal char ?
=) 1 2))
2743 (new-level (+ old-level arg
))
2744 (text (match-string 1)))
2745 (when (and (not remove
) (= new-level
0))
2749 (markdown-unwrap-thing-at-point nil
0 1))
2751 (markdown-insert-header new-level nil t
))
2753 (markdown-insert-header new-level nil nil
)))))
2755 (defun markdown-cycle-hr (arg &optional remove
)
2756 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2757 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2758 backwards (demote). When REMOVE is non-nil, remove the hr instead
2759 of cycling when the end of the list is reached.
2760 Assumes match data is available for `markdown-regex-hr'."
2761 (let* ((strings (if (= arg
1)
2762 (reverse markdown-hr-strings
)
2763 markdown-hr-strings
))
2764 (tail (member (match-string 0) strings
))
2765 (new (or (cadr tail
)
2771 (replace-match new
)))
2773 (defun markdown-cycle-bold ()
2774 "Cycle bold markup between underscores and asterisks.
2775 Assumes match data is available for `markdown-regex-bold'."
2777 (let* ((old-delim (match-string 3))
2778 (new-delim (if (string-equal old-delim
"**") "__" "**")))
2779 (replace-match new-delim t t nil
3)
2780 (replace-match new-delim t t nil
5))))
2782 (defun markdown-cycle-italic ()
2783 "Cycle italic markup between underscores and asterisks.
2784 Assumes match data is available for `markdown-regex-italic'."
2786 (let* ((old-delim (match-string 3))
2787 (new-delim (if (string-equal old-delim
"*") "_" "*")))
2788 (replace-match new-delim t t nil
3)
2789 (replace-match new-delim t t nil
5))))
2792 ;;; Keymap ====================================================================
2794 (defvar markdown-mode-map
2795 (let ((map (make-keymap)))
2796 ;; Element insertion
2797 (define-key map
"\C-c\C-al" 'markdown-insert-link
)
2798 (define-key map
"\C-c\C-ar" 'markdown-insert-reference-link-dwim
)
2799 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
2800 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
2801 (define-key map
"\C-c\C-t0" 'markdown-remove-header
)
2802 (define-key map
"\C-c\C-t1" 'markdown-insert-header-atx-1
)
2803 (define-key map
"\C-c\C-t2" 'markdown-insert-header-atx-2
)
2804 (define-key map
"\C-c\C-t3" 'markdown-insert-header-atx-3
)
2805 (define-key map
"\C-c\C-t4" 'markdown-insert-header-atx-4
)
2806 (define-key map
"\C-c\C-t5" 'markdown-insert-header-atx-5
)
2807 (define-key map
"\C-c\C-t6" 'markdown-insert-header-atx-6
)
2808 (define-key map
"\C-c\C-th" 'markdown-insert-header-dwim
)
2809 (define-key map
"\C-c\C-pb" 'markdown-insert-bold
)
2810 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
2811 (define-key map
"\C-c\C-pi" 'markdown-insert-italic
)
2812 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
2813 (define-key map
"\C-c\C-pf" 'markdown-insert-code
)
2814 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
2815 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
2816 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
2817 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
2818 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
2819 (define-key map
"\C-c-" 'markdown-insert-hr
)
2820 (define-key map
"\C-c\C-tt" 'markdown-insert-header-setext-1
)
2821 (define-key map
"\C-c\C-ts" 'markdown-insert-header-setext-2
)
2823 (define-key map
(kbd "C-c C-k") 'markdown-kill-thing-at-point
)
2825 (define-key map
"\C-c\C-fn" 'markdown-footnote-new
)
2826 (define-key map
"\C-c\C-fg" 'markdown-footnote-goto-text
)
2827 (define-key map
"\C-c\C-fb" 'markdown-footnote-return
)
2828 (define-key map
"\C-c\C-fk" 'markdown-footnote-kill
)
2829 ;; Promotion, Demotion, Completion, and Cycling
2830 (define-key map
(kbd "M-<left>") 'markdown-promote
)
2831 (define-key map
(kbd "M-<right>") 'markdown-demote
)
2832 (define-key map
(kbd "C-c C-l") 'markdown-promote
)
2833 (define-key map
(kbd "C-c C-r") 'markdown-demote
)
2834 (define-key map
(kbd "C-c C-=") 'markdown-complete-or-cycle
)
2835 (define-key map
(kbd "C-c C-c =") 'markdown-complete-buffer
)
2836 ;; Following and Jumping
2837 (define-key map
"\C-c\C-o" 'markdown-follow-thing-at-point
)
2838 (define-key map
"\C-c\C-j" 'markdown-jump
)
2840 (define-key map
"\C-m" 'markdown-enter-key
)
2841 (define-key map
(kbd "<backspace>") 'markdown-dedent-or-delete
)
2842 ;; Visibility cycling
2843 (define-key map
(kbd "<tab>") 'markdown-cycle
)
2844 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
2845 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
2846 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
2847 ;; Header navigation
2848 (define-key map
(kbd "C-M-n") 'outline-next-visible-heading
)
2849 (define-key map
(kbd "C-M-p") 'outline-previous-visible-heading
)
2850 (define-key map
(kbd "C-M-f") 'outline-forward-same-level
)
2851 (define-key map
(kbd "C-M-b") 'outline-backward-same-level
)
2852 (define-key map
(kbd "C-M-u") 'outline-up-heading
)
2853 ;; Markdown functions
2854 (define-key map
"\C-c\C-cm" 'markdown-other-window
)
2855 (define-key map
"\C-c\C-cp" 'markdown-preview
)
2856 (define-key map
"\C-c\C-ce" 'markdown-export
)
2857 (define-key map
"\C-c\C-cv" 'markdown-export-and-preview
)
2858 (define-key map
"\C-c\C-co" 'markdown-open
)
2859 (define-key map
"\C-c\C-cw" 'markdown-kill-ring-save
)
2861 (define-key map
"\C-c\C-cc" 'markdown-check-refs
)
2863 (define-key map
"\C-c\C-cn" 'markdown-cleanup-list-numbers
)
2864 (define-key map
(kbd "M-<up>") 'markdown-move-up
)
2865 (define-key map
(kbd "M-<down>") 'markdown-move-down
)
2866 (define-key map
(kbd "M-<return>") 'markdown-insert-list-item
)
2868 (define-key map
(kbd "M-[") 'markdown-beginning-of-block
)
2869 (define-key map
(kbd "M-]") 'markdown-end-of-block
)
2870 (define-key map
(kbd "M-n") 'markdown-next-link
)
2871 (define-key map
(kbd "M-p") 'markdown-previous-link
)
2873 "Keymap for Markdown major mode.")
2875 (defvar gfm-mode-map
2876 (let ((map (make-sparse-keymap)))
2877 (set-keymap-parent map markdown-mode-map
)
2878 (define-key map
"\C-c\C-sl" 'markdown-insert-gfm-code-block
)
2880 "Keymap for `gfm-mode'.
2881 See also `markdown-mode-map'.")
2884 ;;; Menu ==================================================================
2886 (easy-menu-define markdown-mode-menu markdown-mode-map
2887 "Menu for Markdown mode"
2890 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
2891 ["Cycle global visibility" markdown-shifttab
])
2893 ["Compile" markdown-other-window
]
2894 ["Preview" markdown-preview
]
2895 ["Export" markdown-export
]
2896 ["Export & View" markdown-export-and-preview
]
2897 ["Open" markdown-open
]
2898 ["Kill ring save" markdown-kill-ring-save
]
2901 ["First level" markdown-insert-setext-header-1
]
2902 ["Second level" markdown-insert-setext-header-2
])
2904 ["First level" markdown-insert-header-atx-1
]
2905 ["Second level" markdown-insert-header-atx-2
]
2906 ["Third level" markdown-insert-header-atx-3
]
2907 ["Fourth level" markdown-insert-header-atx-4
]
2908 ["Fifth level" markdown-insert-header-atx-5
]
2909 ["Sixth level" markdown-insert-header-atx-6
])
2911 ["Bold" markdown-insert-bold
]
2912 ["Italic" markdown-insert-italic
]
2913 ["Blockquote" markdown-insert-blockquote
]
2914 ["Preformatted" markdown-insert-pre
]
2915 ["Code" markdown-insert-code
]
2917 ["Insert inline link" markdown-insert-link
]
2918 ["Insert reference link" markdown-insert-reference-link-dwim
]
2919 ["Insert image" markdown-insert-image
]
2920 ["Insert horizontal rule" markdown-insert-hr
]
2923 ["Insert footnote" markdown-footnote-new
]
2924 ["Jump to footnote text" markdown-footnote-goto-text
]
2925 ["Return from footnote" markdown-footnote-return
])
2927 ["Check references" markdown-check-refs
]
2928 ["Clean up list numbering" markdown-cleanup-list-numbers
]
2930 ["Version" markdown-show-version
]
2934 ;;; imenu =====================================================================
2936 (defun markdown-imenu-create-index ()
2937 "Create and return an imenu index alist for the current buffer.
2938 See `imenu-create-index-function' and `imenu--index-alist' for details."
2939 (let* ((root '(nil . nil
))
2944 hashes pos level heading
)
2946 (goto-char (point-min))
2947 (while (re-search-forward markdown-regex-header
(point-max) t
)
2949 ((setq heading
(match-string-no-properties 1))
2950 (setq pos
(match-beginning 1)
2952 ((setq heading
(match-string-no-properties 3))
2953 (setq pos
(match-beginning 3)
2955 ((setq hashes
(match-string-no-properties 5))
2956 (setq heading
(match-string-no-properties 6)
2957 pos
(match-beginning 5)
2958 level
(length hashes
))))
2959 (let ((alist (list (cons heading pos
))))
2961 ((= cur-level level
) ; new sibling
2962 (setcdr cur-alist alist
)
2963 (setq cur-alist alist
))
2964 ((< cur-level level
) ; first child
2965 (dotimes (i (- level cur-level
1))
2966 (setq alist
(list (cons empty-heading alist
))))
2968 (let* ((parent (car cur-alist
))
2969 (self-pos (cdr parent
)))
2970 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
2971 (setcdr root alist
)) ; primogenitor
2972 (setq cur-alist alist
)
2973 (setq cur-level level
))
2974 (t ; new sibling of an ancestor
2975 (let ((sibling-alist (last (cdr root
))))
2976 (dotimes (i (1- level
))
2977 (setq sibling-alist
(last (cdar sibling-alist
))))
2978 (setcdr sibling-alist alist
)
2979 (setq cur-alist alist
))
2980 (setq cur-level level
)))))
2984 ;;; References ================================================================
2986 (defun markdown-insert-reference-definition (ref &optional buffer
)
2987 "Add blank REF definition to the end of BUFFER.
2988 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
2989 (or buffer
(setq buffer
(current-buffer)))
2990 (with-current-buffer buffer
2991 (goto-char (point-max))
2992 (indent-new-comment-line)
2993 (insert (concat ref
": "))))
2995 (defun markdown-reference-goto-definition ()
2996 "Jump to the definition of the reference at point or create it."
2998 (when (thing-at-point-looking-at markdown-regex-link-reference
)
2999 (let* ((label (match-string-no-properties 1))
3000 (reference (match-string-no-properties 3))
3001 (target (downcase (if (string= reference
"[]") label reference
)))
3002 (loc (cadr (markdown-reference-definition target
))))
3005 (markdown-insert-reference-definition reference
(current-buffer))))))
3007 (defun markdown-reference-find-links (reference)
3008 "Return a list of all links for REFERENCE.
3009 REFERENCE should include the surrounding square brackets like [this].
3010 Elements of the list have the form (text start line), where
3011 text is the link text, start is the location at the beginning of
3012 the link, and line is the line number on which the link appears."
3013 (let* ((ref-quote (regexp-quote (substring reference
1 -
1)))
3014 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3015 ref-quote ref-quote
))
3018 (goto-char (point-min))
3019 (while (re-search-forward regexp nil t
)
3020 (let* ((text (or (match-string-no-properties 1)
3021 (match-string-no-properties 2)))
3022 (start (match-beginning 0))
3023 (line (markdown-line-number-at-pos)))
3024 (add-to-list 'links
(list text start line
)))))
3027 (defun markdown-get-undefined-refs ()
3028 "Return a list of undefined Markdown references.
3029 Result is an alist of pairs (reference . occurrences), where
3030 occurrences is itself another alist of pairs (label . line-number).
3031 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3032 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3033 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3036 (goto-char (point-min))
3038 (re-search-forward markdown-regex-link-reference nil t
)
3039 (let* ((label (match-string-no-properties 1))
3040 (reference (match-string-no-properties 3))
3041 (target (downcase (if (string= reference
"[]") label reference
))))
3042 (unless (markdown-reference-definition target
)
3043 (let ((entry (assoc target missing
)))
3045 (add-to-list 'missing
(cons target
3046 (list (cons label
(markdown-line-number-at-pos)))) t
)
3048 (append (cdr entry
) (list (cons label
(markdown-line-number-at-pos))))))))))
3051 (defconst markdown-reference-check-buffer
3052 "*Undefined references for %buffer%*"
3053 "Pattern for name of buffer for listing undefined references.
3054 The string %buffer% will be replaced by the corresponding
3055 `markdown-mode' buffer name.")
3057 (defun markdown-reference-check-buffer (&optional buffer-name
)
3058 "Name and return buffer for reference checking."
3059 (or buffer-name
(setq buffer-name
(buffer-name)))
3060 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3061 "%buffer%" buffer-name
3062 markdown-reference-check-buffer
))))
3063 (with-current-buffer refbuf
3065 (View-exit-and-edit))
3066 (use-local-map button-buffer-map
)
3070 (defconst markdown-reference-links-buffer
3071 "*Reference links for %buffer%*"
3072 "Pattern for name of buffer for listing references.
3073 The string %buffer% will be replaced by the corresponding buffer name.")
3075 (defun markdown-reference-links-buffer (&optional buffer-name
)
3076 "Name, setup, and return a buffer for listing links."
3077 (or buffer-name
(setq buffer-name
(buffer-name)))
3078 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3079 "%buffer%" buffer-name
3080 markdown-reference-links-buffer
))))
3081 (with-current-buffer linkbuf
3083 (View-exit-and-edit))
3084 (use-local-map button-buffer-map
)
3088 (when (markdown-use-buttons-p)
3089 ;; Add an empty Markdown reference definition to the end of buffer
3090 ;; specified in the 'target-buffer property. The reference name is
3091 ;; the button's label.
3092 (define-button-type 'markdown-undefined-reference-button
3093 'help-echo
"mouse-1, RET: create definition for undefined reference"
3097 (let ((buffer (button-get b
'target-buffer
)))
3098 (markdown-insert-reference-definition (button-label b
) buffer
)
3099 (switch-to-buffer-other-window buffer
)
3100 (goto-char (point-max))
3101 (markdown-check-refs t
))))
3103 ;; Jump to line in buffer specified by 'target-buffer property.
3104 ;; Line number is button's 'line property.
3105 (define-button-type 'markdown-goto-line-button
3106 'help-echo
"mouse-1, RET: go to line"
3110 (message (button-get b
'buffer
))
3111 (switch-to-buffer-other-window (button-get b
'target-buffer
))
3112 ;; use call-interactively to silence compiler
3113 (let ((current-prefix-arg (button-get b
'target-line
)))
3114 (call-interactively 'goto-line
))))
3116 ;; Jumps to a particular link at location given by 'target-char
3117 ;; property in buffer given by 'target-buffer property.
3118 (define-button-type 'markdown-link-button
3119 'help-echo
"mouse-1, RET: jump to location of link"
3123 (let ((target (button-get b
'target-buffer
))
3124 (loc (button-get b
'target-char
)))
3125 (kill-buffer-and-window)
3126 (switch-to-buffer target
)
3129 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
3130 "Insert a button for creating REFERENCE in buffer OLDBUF.
3131 REFERENCE should be a list of the form (reference . occurrences),
3132 as by `markdown-get-undefined-refs'."
3133 (let ((label (car reference
)))
3134 (if (markdown-use-buttons-p)
3135 ;; Create a reference button in Emacs 22
3136 (insert-button label
3137 :type
'markdown-undefined-reference-button
3138 'target-buffer oldbuf
)
3139 ;; Insert reference as text in Emacs < 22
3142 (dolist (occurrence (cdr reference
))
3143 (let ((line (cdr occurrence
)))
3144 (if (markdown-use-buttons-p)
3145 ;; Create a line number button in Emacs 22
3146 (insert-button (number-to-string line
)
3147 :type
'markdown-goto-line-button
3148 'target-buffer oldbuf
3150 ;; Insert line number as text in Emacs < 22
3151 (insert (number-to-string line
)))
3157 (defun markdown-insert-link-button (link oldbuf
)
3158 "Insert a button for jumping to LINK in buffer OLDBUF.
3159 LINK should be a list of the form (text char line) containing
3160 the link text, location, and line number."
3161 (let ((label (first link
))
3162 (char (second link
))
3163 (line (third link
)))
3164 (if (markdown-use-buttons-p)
3165 ;; Create a reference button in Emacs 22
3166 (insert-button label
3167 :type
'markdown-link-button
3168 'target-buffer oldbuf
3170 ;; Insert reference as text in Emacs < 22
3172 (insert (format " (line %d)\n" line
))))
3174 (defun markdown-reference-goto-link (&optional reference
)
3175 "Jump to the location of the first use of reference."
3178 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
3179 (setq reference
(match-string-no-properties 1))
3180 (error "No reference definition at point.")))
3181 (let ((links (markdown-reference-find-links reference
)))
3182 (cond ((= (length links
) 1)
3183 (goto-char (cadr (car links
))))
3184 ((> (length links
) 1)
3185 (let ((oldbuf (current-buffer))
3186 (linkbuf (markdown-reference-links-buffer)))
3187 (with-current-buffer linkbuf
3188 (insert "Links using reference " reference
":\n\n")
3189 (dolist (link (reverse links
))
3190 (markdown-insert-link-button link oldbuf
)))
3191 (view-buffer-other-window linkbuf
)
3192 (goto-char (point-min))
3195 (error "No links for reference %s" reference
)))))
3197 (defun markdown-check-refs (&optional silent
)
3198 "Show all undefined Markdown references in current `markdown-mode' buffer.
3199 If SILENT is non-nil, do not message anything when no undefined
3201 Links which have empty reference definitions are considered to be
3204 (when (not (eq major-mode
'markdown-mode
))
3205 (error "Not available in current mode"))
3206 (let ((oldbuf (current-buffer))
3207 (refs (markdown-get-undefined-refs))
3208 (refbuf (markdown-reference-check-buffer)))
3212 (message "No undefined references found"))
3213 (kill-buffer refbuf
))
3214 (with-current-buffer refbuf
3215 (insert "The following references are undefined:\n\n")
3217 (markdown-insert-undefined-reference-button ref oldbuf
))
3218 (view-buffer-other-window refbuf
)
3219 (goto-char (point-min))
3220 (forward-line 2)))))
3223 ;;; Lists =====================================================================
3225 (defun markdown-insert-list-item (&optional arg
)
3226 "Insert a new list item.
3227 If the point is inside unordered list, insert a bullet mark. If
3228 the point is inside ordered list, insert the next number followed
3229 by a period. Use the previous list item to determine the amount
3230 of whitespace to place before and after list markers.
3232 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3233 decrease the indentation by one level.
3235 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3236 increase the indentation by one level."
3238 (let (bounds item-indent marker indent new-indent end
)
3240 (setq bounds
(markdown-cur-list-item-bounds))
3242 ;; When not in a list, start a new unordered one
3244 (unless (markdown-cur-line-blank-p)
3247 ;; Compute indentation for a new list item
3248 (setq item-indent
(nth 2 bounds
))
3249 (setq marker
(concat (match-string 2) (match-string 3)))
3251 ((= arg
4) (max (- item-indent
4) 0))
3252 ((= arg
16) (+ item-indent
4))
3254 (setq new-indent
(make-string indent
32))
3255 (goto-char (nth 1 bounds
))
3259 ((string-match "[0-9]" marker
)
3260 (if (= arg
16) ;; starting a new column indented one more level
3261 (insert (concat new-indent
"1. "))
3262 ;; travel up to the last item and pick the correct number. If
3263 ;; the argument was nil, "new-indent = item-indent" is the same,
3264 ;; so we don't need special treatment. Neat.
3266 (while (not (looking-at (concat new-indent
"\\([0-9]+\\)\\.")))
3268 (insert (concat new-indent
3269 (int-to-string (1+ (string-to-number (match-string 1))))
3272 ((string-match "[\\*\\+-]" marker
)
3273 (insert (concat new-indent marker
))))))))
3275 (defun markdown-move-list-item-up ()
3276 "Move the current list item up in the list when possible."
3279 (when (setq cur
(markdown-cur-list-item-bounds))
3281 (goto-char (nth 0 cur
))
3282 (if (markdown-prev-list-item (nth 3 cur
))
3284 (setq prev
(markdown-cur-list-item-bounds))
3287 (transpose-regions (nth 0 prev
) (nth 1 prev
)
3288 (nth 0 cur
) (nth 1 cur
) t
)
3289 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
3290 ;; Catch error in case regions overlap.
3291 (error (goto-char old
))))
3294 (defun markdown-move-list-item-down ()
3295 "Move the current list item down in the list when possible."
3298 (when (setq cur
(markdown-cur-list-item-bounds))
3300 (if (markdown-next-list-item (nth 3 cur
))
3302 (setq next
(markdown-cur-list-item-bounds))
3305 (transpose-regions (nth 0 cur
) (nth 1 cur
)
3306 (nth 0 next
) (nth 1 next
) nil
)
3307 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
3308 ;; Catch error in case regions overlap.
3309 (error (goto-char old
))))
3312 (defun markdown-demote-list-item (&optional bounds
)
3313 "Indent (or demote) the current list item.
3314 Optionally, BOUNDS of the current list item may be provided if available."
3316 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3319 (let* ((end-marker (make-marker))
3320 (end-marker (set-marker end-marker
(nth 1 bounds
))))
3321 (goto-char (nth 0 bounds
))
3322 (while (< (point) end-marker
)
3323 (unless (markdown-cur-line-blank-p)
3325 (forward-line)))))))
3327 (defun markdown-promote-list-item (&optional bounds
)
3328 "Unindent (or promote) the current list item.
3329 Optionally, BOUNDS of the current list item may be provided if available."
3331 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3334 (let* ((end-marker (make-marker))
3335 (end-marker (set-marker end-marker
(nth 1 bounds
)))
3337 (goto-char (nth 0 bounds
))
3338 (when (looking-at "^[ ]\\{1,4\\}")
3339 (setq num
(- (match-end 0) (match-beginning 0)))
3340 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
3341 (while (and (< (point) end-marker
)
3342 (re-search-forward regexp end-marker t
))
3343 (replace-match "" nil nil
)
3344 (forward-line))))))))
3346 (defun markdown--cleanup-list-numbers-level (&optional pfx
)
3347 "Update the numbering for level PFX (as a string of spaces).
3349 Assume that the previously found match was for a numbered item in
3356 (while (and continue
(not (eobp)))
3359 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3360 (setq cpfx
(match-string-no-properties 1))
3364 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". "))
3368 (setq sep
(markdown--cleanup-list-numbers-level cpfx
))
3373 (setq continue nil
))))
3375 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3376 (setq cpfx
(match-string-no-properties 1))
3378 ;; reset if separated before
3379 ((string= cpfx pfx
) (when sep
(setq idx
0)))
3382 (setq continue nil
))))
3387 (setq continue
(= (forward-line) 0))))
3390 (defun markdown-cleanup-list-numbers ()
3391 "Update the numbering of ordered lists."
3394 (goto-char (point-min))
3395 (markdown--cleanup-list-numbers-level "")))
3398 ;;; Outline ===================================================================
3400 (defvar markdown-cycle-global-status
1)
3401 (defvar markdown-cycle-subtree-status nil
)
3403 (defun markdown-end-of-subtree (&optional invisible-OK
)
3404 "Move to the end of the current subtree.
3405 Only visible heading lines are considered, unless INVISIBLE-OK is
3407 Derived from `org-end-of-subtree'."
3408 (outline-back-to-heading invisible-OK
)
3410 (level (funcall outline-level
)))
3411 (while (and (not (eobp))
3412 (or first
(> (funcall outline-level
) level
)))
3414 (outline-next-heading))
3415 (if (memq (preceding-char) '(?
\n ?\^M
))
3417 ;; Go to end of line before heading
3419 (if (memq (preceding-char) '(?
\n ?\^M
))
3420 ;; leave blank line before heading
3421 (forward-char -
1)))))
3424 (defun markdown-cycle (&optional arg
)
3425 "Visibility cycling for Markdown mode.
3426 If ARG is t, perform global visibility cycling. If the point is
3427 at an atx-style header, cycle visibility of the corresponding
3428 subtree. Otherwise, insert a tab using `indent-relative'.
3429 Derived from `org-cycle'."
3432 ((eq arg t
) ;; Global cycling
3434 ((and (eq last-command this-command
)
3435 (eq markdown-cycle-global-status
2))
3436 ;; Move from overview to contents
3438 (message "CONTENTS")
3439 (setq markdown-cycle-global-status
3))
3441 ((and (eq last-command this-command
)
3442 (eq markdown-cycle-global-status
3))
3443 ;; Move from contents to all
3445 (message "SHOW ALL")
3446 (setq markdown-cycle-global-status
1))
3449 ;; Defaults to overview
3451 (message "OVERVIEW")
3452 (setq markdown-cycle-global-status
2))))
3454 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
3455 ;; At a heading: rotate between three different views
3456 (outline-back-to-heading)
3457 (let ((goal-column 0) eoh eol eos
)
3458 ;; Determine boundaries
3460 (outline-back-to-heading)
3462 (beginning-of-line 2)
3463 (while (and (not (eobp)) ;; this is like `next-line'
3464 (get-char-property (1- (point)) 'invisible
))
3465 (beginning-of-line 2)) (setq eol
(point)))
3466 (outline-end-of-heading) (setq eoh
(point))
3467 (markdown-end-of-subtree t
)
3468 (skip-chars-forward " \t\n")
3469 (beginning-of-line 1) ; in case this is an item
3470 (setq eos
(1- (point))))
3471 ;; Find out what to do next and set `this-command'
3474 ;; Nothing is hidden behind this heading
3475 (message "EMPTY ENTRY")
3476 (setq markdown-cycle-subtree-status nil
))
3478 ;; Entire subtree is hidden in one line: open it
3481 (message "CHILDREN")
3482 (setq markdown-cycle-subtree-status
'children
))
3483 ((and (eq last-command this-command
)
3484 (eq markdown-cycle-subtree-status
'children
))
3485 ;; We just showed the children, now show everything.
3488 (setq markdown-cycle-subtree-status
'subtree
))
3490 ;; Default action: hide the subtree.
3493 (setq markdown-cycle-subtree-status
'folded
)))))
3496 (indent-for-tab-command))))
3498 (defun markdown-shifttab ()
3499 "Global visibility cycling.
3500 Calls `markdown-cycle' with argument t."
3504 (defun markdown-outline-level ()
3505 "Return the depth to which a statement is nested in the outline."
3509 ((- (match-end 5) (match-beginning 5)))))
3512 ;;; Movement ==================================================================
3514 (defun markdown-beginning-of-defun (&optional arg
)
3515 "`beginning-of-defun-function' for Markdown.
3516 Move backward to the beginning of the current or previous section."
3518 (or arg
(setq arg
1))
3519 (or (re-search-backward markdown-regex-header nil t arg
)
3520 (goto-char (point-min))))
3522 (defun markdown-end-of-defun (&optional arg
)
3523 "`end-of-defun-function' for Markdown.
3524 Move forward to the end of the current or following section."
3526 (or arg
(setq arg
1))
3527 (when (looking-at markdown-regex-header
)
3528 (goto-char (match-beginning 0))
3530 (if (re-search-forward markdown-regex-header nil t arg
)
3531 (goto-char (match-beginning 0))
3532 (goto-char (point-max)))
3533 (skip-syntax-backward "-"))
3535 (defun markdown-beginning-of-block ()
3536 "Move the point to the start of the previous text block."
3538 (if (re-search-backward markdown-regex-block-separator nil t
)
3539 (goto-char (or (match-end 2) (match-end 0)))
3540 (goto-char (point-min))))
3542 (defun markdown-end-of-block ()
3543 "Move the point to the start of the next text block."
3546 (skip-syntax-forward "-")
3547 (when (= (point) (point-min))
3549 (if (re-search-forward markdown-regex-block-separator nil t
)
3550 (goto-char (or (match-end 2) (match-end 0)))
3551 (goto-char (point-max)))
3552 (skip-syntax-backward "-")
3555 (defun markdown-end-of-block-element ()
3556 "Move the point to the start of the next block unit.
3557 Stops at blank lines, list items, headers, and horizontal rules."
3560 (while (and (or (not (markdown-prev-line-blank-p))
3561 (markdown-cur-line-blank-p))
3562 (not (or (looking-at markdown-regex-list
)
3563 (looking-at markdown-regex-header
)
3564 (looking-at markdown-regex-hr
)))
3568 (defun markdown-next-link ()
3569 "Jump to next inline, reference, or wiki link.
3570 If successful, return point. Otherwise, return nil.
3571 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3573 (let ((opoint (point)))
3574 (when (or (markdown-link-p) (markdown-wiki-link-p))
3575 ;; At a link already, move past it.
3576 (goto-char (+ (match-end 0) 1)))
3577 ;; Search for the next wiki link and move to the beginning.
3578 (if (re-search-forward markdown-regex-link-generic nil t
)
3579 ;; Group 1 will move past non-escape character in wiki link regexp.
3580 ;; Go to beginning of group zero for all other link types.
3581 (goto-char (or (match-beginning 1) (match-beginning 0)))
3585 (defun markdown-previous-link ()
3586 "Jump to previous wiki link.
3587 If successful, return point. Otherwise, return nil.
3588 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3590 (if (re-search-backward markdown-regex-link-generic nil t
)
3591 (goto-char (or (match-beginning 1) (match-beginning 0)))
3595 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3597 (defun markdown-move-up ()
3599 Calls `markdown-move-list-item-up'."
3601 (markdown-move-list-item-up))
3603 (defun markdown-move-down ()
3604 "Move list item down.
3605 Calls `markdown-move-list-item-down'."
3607 (markdown-move-list-item-down))
3609 (defun markdown-promote ()
3610 "Either promote header or list item at point or cycle markup.
3611 See `markdown-cycle-atx', `markdown-cycle-setext', and
3612 `markdown-demote-list-item'."
3616 ;; Promote atx header
3617 ((thing-at-point-looking-at markdown-regex-header-atx
)
3618 (markdown-cycle-atx -
1 t
))
3619 ;; Promote setext header
3620 ((thing-at-point-looking-at markdown-regex-header-setext
)
3621 (markdown-cycle-setext -
1 t
))
3622 ;; Promote horizonal rule
3623 ((thing-at-point-looking-at markdown-regex-hr
)
3624 (markdown-cycle-hr -
1 t
))
3625 ;; Promote list item
3626 ((setq bounds
(markdown-cur-list-item-bounds))
3627 (markdown-promote-list-item)))))
3629 (defun markdown-demote ()
3630 "Either demote header or list item at point or cycle or remove markup.
3631 See `markdown-cycle-atx', `markdown-cycle-setext', and
3632 `markdown-demote-list-item'."
3636 ;; Demote atx header
3637 ((thing-at-point-looking-at markdown-regex-header-atx
)
3638 (markdown-cycle-atx 1 t
))
3639 ;; Demote setext header
3640 ((thing-at-point-looking-at markdown-regex-header-setext
)
3641 (markdown-cycle-setext 1 t
))
3642 ;; Demote horizonal rule
3643 ((thing-at-point-looking-at markdown-regex-hr
)
3644 (markdown-cycle-hr 1 t
))
3645 ;; Promote list item
3646 ((setq bounds
(markdown-cur-list-item-bounds))
3647 (markdown-demote-list-item))
3648 ;; Create a new level one ATX header
3650 (markdown-insert-header-atx-1)))))
3652 (defun markdown-complete-or-cycle (arg)
3653 "Complete or cycle markup of object at point or complete objects in region.
3654 If there is an active region, complete markup in region.
3655 Otherwise, complete or cycle markup of object near point.
3656 When ARG is non-nil, cycle backwards when cycling."
3658 (if (markdown-use-region-p)
3659 ;; Complete markup in region
3660 (markdown-complete-region (region-beginning) (region-end))
3661 ;; Complete or cycle markup at point
3662 (let ((dir (if arg -
1 1))
3666 ((thing-at-point-looking-at markdown-regex-header-atx
)
3667 (if (markdown-incomplete-atx-p)
3668 (markdown-complete-atx)
3669 (markdown-cycle-atx dir
)))
3671 ((thing-at-point-looking-at markdown-regex-header-setext
)
3672 (if (markdown-incomplete-setext-p)
3673 (markdown-complete-setext)
3674 (markdown-cycle-setext dir
)))
3676 ((thing-at-point-looking-at markdown-regex-hr
)
3677 (if (markdown-incomplete-hr-p)
3678 (markdown-complete-hr)
3679 (markdown-cycle-hr dir
)))
3681 ((thing-at-point-looking-at markdown-regex-bold
)
3682 (markdown-cycle-bold))
3684 ((thing-at-point-looking-at markdown-regex-italic
)
3685 (markdown-cycle-italic))))))
3688 ;;; Commands ==================================================================
3690 (defun markdown (&optional output-buffer-name
)
3691 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3692 The output buffer name defaults to `markdown-output-buffer-name'.
3693 Return the name of the output buffer used."
3695 (save-window-excursion
3696 (let ((begin-region)
3698 (if (markdown-use-region-p)
3699 (setq begin-region
(region-beginning)
3700 end-region
(region-end))
3701 (setq begin-region
(point-min)
3702 end-region
(point-max)))
3704 (unless output-buffer-name
3705 (setq output-buffer-name markdown-output-buffer-name
))
3708 ;; Handle case when `markdown-command' does not read from stdin
3709 (markdown-command-needs-filename
3710 (if (not buffer-file-name
)
3711 (error "Must be visiting a file")
3712 (shell-command (concat markdown-command
" "
3713 (shell-quote-argument buffer-file-name
))
3714 output-buffer-name
)))
3715 ;; Pass region to `markdown-command' via stdin
3717 (shell-command-on-region begin-region end-region markdown-command
3718 output-buffer-name
))))
3719 output-buffer-name
))
3721 (defun markdown-standalone (&optional output-buffer-name
)
3722 "Special function to provide standalone HTML output.
3723 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3725 (setq output-buffer-name
(markdown output-buffer-name
))
3726 (with-current-buffer output-buffer-name
3727 (set-buffer output-buffer-name
)
3728 (goto-char (point-min))
3729 (unless (markdown-output-standalone-p)
3730 (markdown-add-xhtml-header-and-footer output-buffer-name
))
3734 (defun markdown-other-window (&optional output-buffer-name
)
3735 "Run `markdown-command' on current buffer and display in other window.
3736 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3739 (display-buffer (markdown-standalone output-buffer-name
)))
3741 (defun markdown-output-standalone-p ()
3742 "Determine whether `markdown-command' output is standalone XHTML.
3743 Standalone XHTML output is identified by an occurrence of
3744 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3746 markdown-xhtml-standalone-regexp
3747 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3750 (defun markdown-add-xhtml-header-and-footer (title)
3751 "Wrap XHTML header and footer with given TITLE around current buffer."
3752 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3753 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3754 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3755 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3758 (insert "</title>\n")
3759 (when (> (length markdown-content-type
) 0)
3762 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3763 markdown-content-type
3764 (or (and markdown-coding-system
3765 (fboundp 'coding-system-get
)
3766 (coding-system-get markdown-coding-system
3768 (and (fboundp 'coding-system-get
)
3769 (coding-system-get buffer-file-coding-system
3772 (if (> (length markdown-css-path
) 0)
3773 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3776 (when (> (length markdown-xhtml-header-content
) 0)
3777 (insert markdown-xhtml-header-content
))
3778 (insert "\n</head>\n\n"
3780 (goto-char (point-max))
3785 (defun markdown-preview (&optional output-buffer-name
)
3786 "Run `markdown-command' on the current buffer and view output in browser.
3787 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3790 (browse-url-of-buffer (markdown markdown-output-buffer-name
)))
3792 (defun markdown-export-file-name (&optional extension
)
3793 "Attempt to generate a filename for Markdown output.
3794 The file extension will be EXTENSION if given, or .html by default.
3795 If the current buffer is visiting a file, we construct a new
3796 output filename based on that filename. Otherwise, return nil."
3797 (when (buffer-file-name)
3799 (setq extension
".html"))
3803 (file-name-sans-extension (buffer-file-name)))
3807 (defun markdown-export (&optional output-file
)
3808 "Run Markdown on the current buffer, save to file, and return the filename.
3809 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3810 generated by `markdown-export-file-name', which will be constructed using the
3811 current filename, but with the extension removed and replaced with .html."
3814 (setq output-file
(markdown-export-file-name ".html")))
3816 (let ((output-buffer-name))
3817 (setq output-buffer-name
(buffer-name (find-file-noselect output-file
)))
3818 (run-hook-with-args 'markdown-before-export-hooks output-file
)
3819 (markdown-standalone output-buffer-name
)
3820 (with-current-buffer output-buffer-name
3822 (run-hook-with-args 'markdown-after-export-hooks output-file
)
3825 (defun markdown-export-and-preview ()
3826 "Export to XHTML using `markdown-export' and browse the resulting file."
3828 (browse-url (markdown-export)))
3830 (defun markdown-open ()
3831 "Open file for the current buffer with `markdown-open-command'."
3833 (if (not markdown-open-command
)
3834 (error "Variable `markdown-open-command' must be set")
3835 (if (not buffer-file-name
)
3836 (error "Must be visiting a file")
3837 (call-process markdown-open-command
3838 nil nil nil buffer-file-name
))))
3840 (defun markdown-kill-ring-save ()
3841 "Run Markdown on file and store output in the kill ring."
3843 (save-window-excursion
3845 (with-current-buffer markdown-output-buffer-name
3846 (kill-ring-save (point-min) (point-max)))))
3849 ;;; Links =====================================================================
3851 (require 'thingatpt
)
3853 (defun markdown-link-p ()
3854 "Return non-nil when `point' is at a non-wiki link.
3855 See `markdown-wiki-link-p' for more information."
3856 (let ((case-fold-search nil
))
3857 (and (not (markdown-wiki-link-p))
3858 (or (thing-at-point-looking-at markdown-regex-link-inline
)
3859 (thing-at-point-looking-at markdown-regex-link-reference
)
3860 (thing-at-point-looking-at markdown-regex-uri
)
3861 (thing-at-point-looking-at markdown-regex-angle-uri
)))))
3863 (defun markdown-link-link ()
3864 "Return the link part of the regular (non-wiki) link at point.
3865 Works with both inline and reference style links. If point is
3866 not at a link or the link reference is not defined returns nil."
3868 ((thing-at-point-looking-at markdown-regex-link-inline
)
3869 (match-string-no-properties 4))
3870 ((thing-at-point-looking-at markdown-regex-link-reference
)
3871 (let* ((label (match-string-no-properties 1))
3872 (reference (match-string-no-properties 3))
3873 (target (downcase (if (string= reference
"[]") label reference
))))
3874 (car (markdown-reference-definition target
))))
3875 ((thing-at-point-looking-at markdown-regex-uri
)
3876 (match-string-no-properties 0))
3877 ((thing-at-point-looking-at markdown-regex-angle-uri
)
3878 (match-string-no-properties 2))
3881 (defun markdown-follow-link-at-point ()
3882 "Open the current non-wiki link in a browser."
3884 (if (markdown-link-p) (browse-url (markdown-link-link))
3885 (error "Point is not at a Markdown link or URI")))
3888 ;;; WikiLink Following/Markup =================================================
3890 (defun markdown-wiki-link-p ()
3891 "Return non-nil when `point' is at a true wiki link.
3892 A true wiki link name matches `markdown-regex-wiki-link' but does not
3893 match the current file name after conversion. This modifies the data
3894 returned by `match-data'. Note that the potential wiki link name must
3895 be available via `match-string'."
3896 (let ((case-fold-search nil
))
3897 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
3898 (or (not buffer-file-name
)
3899 (not (string-equal (buffer-file-name)
3900 (markdown-convert-wiki-link-to-filename
3901 (markdown-wiki-link-link)))))
3902 (not (save-match-data
3903 (save-excursion))))))
3905 (defun markdown-wiki-link-link ()
3906 "Return the link part of the wiki link using current match data.
3907 The location of the link component depends on the value of
3908 `markdown-wiki-link-alias-first'."
3909 (if markdown-wiki-link-alias-first
3910 (or (match-string-no-properties 4) (match-string-no-properties 2))
3911 (match-string-no-properties 2)))
3913 (defun markdown-convert-wiki-link-to-filename (name)
3914 "Generate a filename from the wiki link NAME.
3915 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3916 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3917 and [[test test]] both map to Test-test.ext."
3918 (let ((basename (markdown-replace-regexp-in-string
3919 "[[:space:]\n]" markdown-link-space-sub-char name
)))
3920 (when (eq major-mode
'gfm-mode
)
3921 (setq basename
(concat (upcase (substring basename
0 1))
3922 (downcase (substring basename
1 nil
)))))
3924 (if (buffer-file-name)
3926 (file-name-extension (buffer-file-name)))))))
3928 (defun markdown-follow-wiki-link (name &optional other
)
3929 "Follow the wiki link NAME.
3930 Convert the name to a file name and call `find-file'. Ensure that
3931 the new buffer remains in `markdown-mode'. Open the link in another
3932 window when OTHER is non-nil."
3933 (let ((filename (markdown-convert-wiki-link-to-filename name
))
3934 (wp (file-name-directory buffer-file-name
)))
3935 (when other
(other-window 1))
3936 (find-file (concat wp filename
)))
3937 (when (not (eq major-mode
'markdown-mode
))
3940 (defun markdown-follow-wiki-link-at-point (&optional arg
)
3941 "Find Wiki Link at point.
3942 With prefix argument ARG, open the file in other window.
3943 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3945 (if (markdown-wiki-link-p)
3946 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
3947 (error "Point is not at a Wiki Link")))
3949 (defun markdown-highlight-wiki-link (from to face
)
3950 "Highlight the wiki link in the region between FROM and TO using FACE."
3951 (put-text-property from to
'font-lock-face face
))
3953 (defun markdown-unfontify-region-wiki-links (from to
)
3954 "Remove wiki link faces from the region specified by FROM and TO."
3955 (interactive "nfrom: \nnto: ")
3956 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
3957 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
)))
3959 (defun markdown-fontify-region-wiki-links (from to
)
3960 "Search region given by FROM and TO for wiki links and fontify them.
3961 If a wiki link is found check to see if the backing file exists
3962 and highlight accordingly."
3965 (while (re-search-forward markdown-regex-wiki-link to t
)
3966 (let ((highlight-beginning (match-beginning 1))
3967 (highlight-end (match-end 1))
3969 (markdown-convert-wiki-link-to-filename
3970 (markdown-wiki-link-link))))
3971 (if (file-exists-p file-name
)
3972 (markdown-highlight-wiki-link
3973 highlight-beginning highlight-end markdown-link-face
)
3974 (markdown-highlight-wiki-link
3975 highlight-beginning highlight-end markdown-link-face
)
3976 (markdown-highlight-wiki-link
3977 highlight-beginning highlight-end markdown-missing-link-face
))))))
3979 (defun markdown-extend-changed-region (from to
)
3980 "Extend region given by FROM and TO so that we can fontify all links.
3981 The region is extended to the first newline before and the first
3983 ;; start looking for the first new line before 'from
3985 (re-search-backward "\n" nil t
)
3986 (let ((new-from (point-min))
3987 (new-to (point-max)))
3988 (if (not (= (point) from
))
3989 (setq new-from
(point)))
3990 ;; do the same thing for the first new line after 'to
3992 (re-search-forward "\n" nil t
)
3993 (if (not (= (point) to
))
3994 (setq new-to
(point)))
3995 (values new-from new-to
)))
3997 (defun markdown-check-change-for-wiki-link (from to change
)
3998 "Check region between FROM and TO for wiki links and re-fontfy as needed.
3999 Designed to be used with the `after-change-functions' hook.
4000 CHANGE is the number of bytes of pre-change text replaced by the
4002 (interactive "nfrom: \nnto: \nnchange: ")
4003 (let* ((modified (buffer-modified-p))
4004 (buffer-undo-list t
)
4005 (inhibit-read-only t
)
4006 (inhibit-point-motion-hooks t
)
4008 buffer-file-truename
)
4013 ;; Extend the region to fontify so that it starts
4014 ;; and ends at safe places.
4015 (multiple-value-bind (new-from new-to
)
4016 (markdown-extend-changed-region from to
)
4017 ;; Unfontify existing fontification (start from scratch)
4018 (markdown-unfontify-region-wiki-links new-from new-to
)
4019 ;; Now do the fontification.
4020 (markdown-fontify-region-wiki-links new-from new-to
)))))
4023 (set-buffer-modified-p nil
)))))
4025 (defun markdown-fontify-buffer-wiki-links ()
4026 "Refontify all wiki links in the buffer."
4028 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4031 ;;; Following and Jumping =====================================================
4033 (defun markdown-follow-thing-at-point (arg)
4034 "Follow thing at point if possible, such as a reference link or wiki link.
4035 Opens inline and reference links in a browser. Opens wiki links
4036 to other files in the current window, or the another window if
4038 See `markdown-follow-link-at-point' and
4039 `markdown-follow-wiki-link-at-point'."
4041 (cond ((markdown-link-p)
4042 (markdown-follow-link-at-point))
4043 ((markdown-wiki-link-p)
4044 (markdown-follow-wiki-link-at-point arg
))
4046 (error "Nothing to follow at point."))))
4048 (defun markdown-jump ()
4049 "Jump to another location based on context at point.
4050 Jumps between reference links and definitions; between footnote
4051 markers and footnote text."
4053 (cond ((markdown-footnote-text-positions)
4054 (markdown-footnote-return))
4055 ((markdown-footnote-marker-positions)
4056 (markdown-footnote-goto-text))
4057 ((thing-at-point-looking-at markdown-regex-link-reference
)
4058 (markdown-reference-goto-definition))
4059 ((thing-at-point-looking-at markdown-regex-reference-definition
)
4060 (markdown-reference-goto-link (match-string-no-properties 1)))
4062 (error "Nothing to jump to from context at point."))))
4065 ;;; Miscellaneous =============================================================
4067 (defun markdown-compress-whitespace-string (str)
4068 "Compress whitespace in STR and return result.
4069 Leading and trailing whitespace is removed. Sequences of multiple
4070 spaces, tabs, and newlines are replaced with single spaces."
4071 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4072 (replace-regexp-in-string "[ \t\n]+" " " str
)))
4074 (defun markdown-line-number-at-pos (&optional pos
)
4075 "Return (narrowed) buffer line number at position POS.
4076 If POS is nil, use current buffer location.
4077 This is an exact copy of `line-number-at-pos' for use in emacs21."
4078 (let ((opoint (or pos
(point))) start
)
4080 (goto-char (point-min))
4081 (setq start
(point))
4084 (1+ (count-lines start
(point))))))
4086 (defun markdown-nobreak-p ()
4087 "Return nil if it is acceptable to break the current line at the point."
4088 ;; inside in square brackets (e.g., link anchor text)
4089 (looking-back "\\[[^]]*"))
4092 ;;; Mode Definition ==========================================================
4094 (defun markdown-show-version ()
4095 "Show the version number in the minibuffer."
4097 (message "markdown-mode, version %s" markdown-mode-version
))
4100 (define-derived-mode markdown-mode text-mode
"Markdown"
4101 "Major mode for editing Markdown files."
4102 ;; Natural Markdown tab width
4105 (make-local-variable 'comment-start
)
4106 (setq comment-start
"<!-- ")
4107 (make-local-variable 'comment-end
)
4108 (setq comment-end
" -->")
4109 (make-local-variable 'comment-start-skip
)
4110 (setq comment-start-skip
"<!--[ \t]*")
4111 (make-local-variable 'comment-column
)
4112 (setq comment-column
0)
4114 (set (make-local-variable 'font-lock-defaults
)
4115 '(markdown-mode-font-lock-keywords))
4116 (set (make-local-variable 'font-lock-multiline
) t
)
4117 ;; For imenu support
4118 (setq imenu-create-index-function
'markdown-imenu-create-index
)
4119 ;; For menu support in XEmacs
4120 (easy-menu-add markdown-mode-menu markdown-mode-map
)
4122 (set (make-local-variable 'beginning-of-defun-function
)
4123 'markdown-beginning-of-defun
)
4124 (set (make-local-variable 'end-of-defun-function
)
4125 'markdown-end-of-defun
)
4126 ;; Make filling work with lists (unordered, ordered, and definition)
4127 (set (make-local-variable 'paragraph-start
)
4128 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
4130 (make-local-variable 'outline-regexp
)
4131 (setq outline-regexp markdown-regex-header
)
4132 (make-local-variable 'outline-level
)
4133 (setq outline-level
'markdown-outline-level
)
4134 ;; Cause use of ellipses for invisible text.
4135 (add-to-invisibility-spec '(outline . t
))
4136 ;; Indentation and filling
4137 (make-local-variable 'fill-nobreak-predicate
)
4138 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
4139 (setq indent-line-function markdown-indent-function
)
4141 ;; Prepare hooks for XEmacs compatibility
4142 (when (featurep 'xemacs
)
4143 (make-local-hook 'after-change-functions
)
4144 (make-local-hook 'font-lock-extend-region-functions
)
4145 (make-local-hook 'window-configuration-change-hook
))
4147 ;; Multiline font lock
4148 (add-hook 'font-lock-extend-region-functions
4149 'markdown-font-lock-extend-region
)
4151 ;; Anytime text changes make sure it gets fontified correctly
4152 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
4154 ;; If we left the buffer there is a really good chance we were
4155 ;; creating one of the wiki link documents. Make sure we get
4156 ;; refontified when we come back.
4157 (add-hook 'window-configuration-change-hook
4158 'markdown-fontify-buffer-wiki-links t t
)
4160 ;; do the initial link fontification
4161 (markdown-fontify-buffer-wiki-links))
4163 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4166 ;;; GitHub Flavored Markdown Mode ============================================
4168 (defvar gfm-font-lock-keywords
4170 ;; GFM features to match first
4172 (cons 'markdown-match-gfm-code-blocks
'((1 markdown-pre-face
)
4173 (2 markdown-language-keyword-face
)
4174 (3 markdown-pre-face
)
4175 (4 markdown-pre-face
))))
4176 ;; Basic Markdown features (excluding possibly overridden ones)
4177 markdown-mode-font-lock-keywords-basic
4178 ;; GFM features to match last
4180 (cons markdown-regex-gfm-italic
'(2 markdown-italic-face
))))
4181 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4184 (define-derived-mode gfm-mode markdown-mode
"GFM"
4185 "Major mode for editing GitHub Flavored Markdown files."
4186 (setq markdown-link-space-sub-char
"-")
4187 (set (make-local-variable 'font-lock-defaults
)
4188 '(gfm-font-lock-keywords))
4190 ;; Use visual-line-mode if available, fall back to longlines-mode:
4191 (if (fboundp 'visual-line-mode
)
4192 (visual-line-mode 1)
4194 ;; do the initial link fontification
4195 (markdown-fontify-buffer-wiki-links))
4198 (provide 'markdown-mode
)
4200 ;;; markdown-mode.el ends here