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 an image, using the active region (if any)
273 ;; * Physical styles: `C-c C-p`
275 ;; These commands all act on text in the active region, if any,
276 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
277 ;; the selected text bold, `C-c C-p f` formats the region as
278 ;; fixed-width text, and `C-c C-p i` is used for italic text.
280 ;; * Logical styles: `C-c C-s`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. Logical styles
284 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
285 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
288 ;; * Headers: `C-c C-t`
290 ;; All header commands use text in the active region, if any, as
291 ;; the header text. Otherwise, if the current line is not blank,
292 ;; use the text on the current line. Finally, prompt for header
293 ;; text if there is no active region and the current line is
294 ;; blank. To insert an atx or hash style level-n
295 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
296 ;; top-level setext or underline style header press `C-c C-t t`
297 ;; (mnemonic: title) and for a second-level underline-style header
298 ;; press `C-c C-t s` (mnemonic: section).
300 ;; If the point is at a header, these commands will replace the
301 ;; existing markup in order to update the level and/or type of the
302 ;; header. To remove the markup of the header at the point, press
305 ;; * Footnotes: `C-c C-f`
307 ;; To create a new footnote at the point, press `C-c C-f n`.
308 ;; Press `C-c C-f g` with the point at a footnote to jump to the
309 ;; location where the footnote text is defined. Then, press
310 ;; `C-c C-f b` to return to the footnote marker in the main text.
311 ;; When the point is at a footnote marker or in the body of a
312 ;; footnote, press `C-c C-f k` to kill the footnote and add the
313 ;; text to the kill ring.
317 ;; `C-c -` inserts a horizontal rule.
319 ;; * Following Links:
321 ;; Press `C-c C-o` when the point is on an inline or reference
322 ;; link to open the URL in a browser. When the point is at a
323 ;; wiki link, open it in another buffer (in the current window,
324 ;; or in the other window with the `C-u` prefix).
325 ;; To move between links, use `M-p` and `M-n` to quickly jump
326 ;; to the previous or next link of any type.
330 ;; Use `C-c C-j` to jump from the object at point to its counterpart
331 ;; elsewhere in the text, when possible. Jumps between reference
332 ;; links and definitions; between footnote markers and footnote
333 ;; text. If more than one link uses the same reference name, a
334 ;; new buffer will be created containing clickable buttons for jumping
335 ;; to each link. You may press `TAB` or `S-TAB` to jump between
336 ;; buttons in this window.
338 ;; * Outline Navigation:
340 ;; Navigation between headings is possible using `outline-mode'.
341 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
342 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
343 ;; next and previous visible headings at the same level as the one
344 ;; at the point. Finally, `C-M-u` will move up to a lower-level
345 ;; (more inclusive) visible heading.
347 ;; * Movement by Block:
349 ;; markdown-mode supports the usual Emacs paragraph movement with
350 ;; `M-{` and `M-}`. These commands treat list items as
351 ;; paragraphs, so they will stop at each line within a block of
352 ;; list items. Additionally, markdown-mode includes movement
353 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
354 ;; of an entire block of text (with blocks being separated by at
355 ;; least one blank line).
357 ;; * Movement by Defun:
359 ;; The usual Emacs commands can be used to move by defuns
360 ;; (top-level major definitions). In markdown-mode, a defun
361 ;; is a section. As usual, `C-M-a` will move the point to
362 ;; the beginning of the current or preceding defun, `C-M-e`
363 ;; will move to the end of the current or following defun,
364 ;; and `C-M-h` will put the region around the entire defun.
366 ;; Many of the commands described above behave differently depending on
367 ;; whether Transient Mark mode is enabled or not. When it makes sense,
368 ;; if Transient Mark mode is on and a region is active, the command
369 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
370 ;; bold). For users who prefer to work outside of Transient Mark mode,
371 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
373 ;; When applicable, commands that specifically act on the region even
374 ;; outside of Transient Mark mode have the same keybinding as the with
375 ;; the exception of an additional `C-` prefix. For example,
376 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
377 ;; the region in Transient Mark mode while `markdown-blockquote-region'
378 ;; is bound to `C-c C-s C-b` and always applies to the region (when
381 ;; markdown-mode attempts to be flexible in how it handles
382 ;; indentation. When you press `TAB` repeatedly, the point will cycle
383 ;; through several possible indentation levels corresponding to things
384 ;; you might have in mind when you press `RET` at the end of a line or
385 ;; `TAB`. For example, you may want to start a new list item,
386 ;; continue a list item with hanging indentation, indent for a nested
387 ;; pre block, and so on.
389 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
390 ;; visibility cycling for atx- or hash-style headers. There are two
391 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
392 ;; the table of contents view (headers only), outline view (top-level
393 ;; headers only), and the full document view. Pressing `TAB` while the
394 ;; point is at a header will cycle through levels of visibility for the
395 ;; subtree: completely folded, visible children, and fully visible.
396 ;; Note that mixing hash and underline style headers will give undesired
401 ;; Besides supporting the basic Markdown syntax, markdown-mode also
402 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
403 ;; links may be followed automatically by pressing the enter key when
404 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
405 ;; auto-following on enter key may be controlled with the
406 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
407 ;; `M-n` to quickly jump to the previous and next wiki links,
408 ;; respectively. Aliased or piped wiki links of the form
409 ;; `[[link text|PageName]]` are also supported. Since some wikis
410 ;; reverse these components, set `markdown-wiki-link-alias-first'
411 ;; to nil to treat them as `[[PageName|link text]]`.
413 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
414 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
415 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
416 ;; You can do this either by using `M-x customize-group markdown`
417 ;; or by placing the following in your `.emacs` file:
419 ;; (defun markdown-custom ()
420 ;; "markdown-mode-hook"
421 ;; (setq markdown-command "markdown | smartypants"))
422 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
424 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
426 ;; Experimental syntax highlighting for mathematical expressions written
427 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
428 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
429 ;; either via customize or by placing `(setq markdown-enable-itex t)`
430 ;; in `.emacs`, and restarting Emacs.
432 ;;; GitHub Flavored Markdown:
434 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
435 ;; available. The GitHub implementation of differs slightly from
436 ;; standard Markdown. The most important differences are that
437 ;; newlines are significant, triggering hard line breaks, and that
438 ;; underscores inside of words (e.g., variable names) need not be
439 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
440 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
441 ;; not available). Underscores inside of words (such as
442 ;; test_variable) will not trigger emphasis.
444 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
445 ;; replacing spaces in filenames and where the first letter of the
446 ;; filename capitalized. For example, `[[wiki link]]' will map to a
447 ;; file named `Wiki-link` with the same extension as the current file.
449 ;; GFM code blocks, with optional programming language keywords, will
450 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
451 ;; is an active region, the text in the region will be placed inside
452 ;; the code block. You will be prompted for the name of the language,
453 ;; but may press enter to continue without naming a language.
455 ;; For a more complete GitHub-flavored markdown experience, consider
456 ;; adding README.md to your `auto-mode-alist':
458 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
460 ;; For GFM preview can be powered by setting `markdown-command' to
461 ;; use [Docter][]. This may also be configured to work with [Marked][]
462 ;; for `markdown-open-command'.
464 ;; [GFM]: http://github.github.com/github-flavored-markdown/
465 ;; [Docter]: https://github.com/alampros/Docter
469 ;; markdown-mode has benefited greatly from the efforts of the
472 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
473 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
474 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
475 ;; GitHub Flavored Markdown mode (`gfm-mode').
476 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
477 ;; `markdown' with an active region.
478 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
479 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
480 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
481 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
482 ;; visibility cycling functionality was derived, and for a bug fix
483 ;; related to orgtbl-mode.
484 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
485 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
486 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
487 ;; compatibility and custom CSS.
488 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
489 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
490 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
491 ;; comment matching functions were derived.
492 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
493 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
494 ;; functions, bug reports regarding indentation, and
495 ;; fixes for byte-compilation warnings.
496 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
498 ;; * George Ogata <george.ogata@gmail.com> for fixing several
499 ;; byte-compilation warnings.
500 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
501 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
502 ;; customizations and XHTML export.
503 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
504 ;; Markdown processors which do not accept input from stdin.
505 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
506 ;; regarding the cl dependency and auto-fill-mode and indentation.
507 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
508 ;; substitution character for mapping wiki links to filenames.
509 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
510 ;; escape shell commands.
511 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
512 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
513 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
514 ;; Emacs Lisp coding conventions.
515 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
516 ;; regexp, refactoring the compilation and preview functions,
517 ;; heading font-lock generalizations, list renumbering,
518 ;; and kill ring save.
519 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
520 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
521 ;; for an autoload token for `gfm-mode'.
522 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
523 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
524 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
525 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
526 ;; declaration in XHTML output.
527 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
528 ;; un-indentation function.
529 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
530 ;; and GFM code block insertion.
531 ;; * Peter Jones <pjones@pmade.com> for link following functions.
532 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
533 ;; externally modified files.
534 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
535 ;; related to orgtbl-mode.
536 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
537 ;; export hooks and unit test improvements.
538 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
542 ;; Although markdown-mode is developed and tested primarily using
543 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
546 ;; If you find any bugs in markdown-mode, please construct a test case
547 ;; or a patch and email me at <jrblevin@sdf.org>.
551 ;; markdown-mode was written and is maintained by Jason Blevins. The
552 ;; first version was released on May 24, 2007.
554 ;; * 2007-05-24: Version 1.1
555 ;; * 2007-05-25: Version 1.2
556 ;; * 2007-06-05: [Version 1.3][]
557 ;; * 2007-06-29: Version 1.4
558 ;; * 2008-05-24: [Version 1.5][]
559 ;; * 2008-06-04: [Version 1.6][]
560 ;; * 2009-10-01: [Version 1.7][]
561 ;; * 2011-08-12: [Version 1.8][]
562 ;; * 2011-08-15: [Version 1.8.1][]
563 ;; * 2013-01-25: [Version 1.9][]
565 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
566 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
567 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
568 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
569 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
570 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
571 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
578 (eval-when-compile (require 'cl
))
581 ;;; Constants =================================================================
583 (defconst markdown-mode-version
"1.9"
584 "Markdown mode version number.")
586 (defconst markdown-output-buffer-name
"*markdown-output*"
587 "Name of temporary buffer for markdown command output.")
590 ;;; Customizable Variables ====================================================
592 (defvar markdown-mode-hook nil
593 "Hook run when entering Markdown mode.")
595 (defvar markdown-before-export-hooks nil
596 "Hook run before output XHTML.
597 This hook is abnormal and registered functions are given an argument that is output filename.")
599 (defvar markdown-after-export-hooks nil
600 "Hook run after output XHTML.
601 This hook is abnormal and registered functions are given an argument that is output filename.")
603 (defgroup markdown nil
604 "Major mode for editing text files in Markdown format."
607 :link
'(url-link "http://jblevins.org/projects/markdown-mode/"))
609 (defcustom markdown-command
"markdown"
610 "Command to run markdown."
614 (defcustom markdown-command-needs-filename nil
615 "Set to non-nil if `markdown-command' does not accept input from stdin.
616 Instead, it will be passed a filename as the final command line
617 option. As a result, you will only be able to run Markdown from
618 buffers which are visiting a file."
622 (defcustom markdown-open-command nil
623 "Command used for opening Markdown files directly.
624 For example, a standalone Markdown previewer. This command will
625 be called with a single argument: the filename of the current
630 (defcustom markdown-hr-strings
633 "* * * * * * * * * * * * * * * * * * * *"
634 "---------------------------------------"
635 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
636 "-------------------------------------------------------------------------------")
637 "Strings to use when inserting horizontal rules.
638 The first string in the list will be the default when inserting a
639 horizontal rule. Strings should be listed in increasing order of
640 prominence for use with promotion and demotion functions."
644 (defcustom markdown-bold-underscore nil
645 "Use two underscores for bold instead of two asterisks."
649 (defcustom markdown-italic-underscore nil
650 "Use underscores for italic instead of asterisks."
654 (defcustom markdown-indent-function
'markdown-indent-line
655 "Function to use to indent."
659 (defcustom markdown-indent-on-enter t
660 "Automatically indent new lines when enter key is pressed."
664 (defcustom markdown-follow-wiki-link-on-enter t
665 "Follow wiki link at point (if any) when the enter key is pressed."
669 (defcustom markdown-wiki-link-alias-first t
670 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
671 Otherwise, they will be treated as [[PageName|alias text]]."
675 (defcustom markdown-uri-types
676 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
677 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
678 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
679 "Link types for syntax highlighting of URIs."
683 (defcustom markdown-enable-math nil
684 "Syntax highlighting for inline LaTeX expressions.
685 This will not take effect until Emacs is restarted."
689 (defcustom markdown-css-path
""
690 "URL of CSS file to link to in the output XHTML."
694 (defcustom markdown-content-type
""
695 "Content type string for the http-equiv header in XHTML output.
696 When set to a non-empty string, insert the http-equiv attribute.
697 Otherwise, this attribute is omitted."
701 (defcustom markdown-coding-system nil
702 "Character set string for the http-equiv header in XHTML output.
703 Defaults to `buffer-file-coding-system' (and falling back to
704 `iso-8859-1' when not available). Common settings are `utf-8'
705 and `iso-latin-1'. Use `list-coding-systems' for more choices."
707 :type
'coding-system
)
709 (defcustom markdown-xhtml-header-content
""
710 "Additional content to include in the XHTML <head> block."
714 (defcustom markdown-xhtml-standalone-regexp
715 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
716 "Regexp indicating whether `markdown-command' output is standalone XHTML."
720 (defcustom markdown-link-space-sub-char
722 "Character to use instead of spaces when mapping wiki links to filenames."
726 (defcustom markdown-footnote-location
'end
727 "Position where new footnotes are inserted in the document."
729 :type
'(choice (const :tag
"At the end of the document" end
)
730 (const :tag
"Immediately after the paragraph" immediately
)
731 (const :tag
"Before next header" header
)))
734 ;;; Font Lock =================================================================
738 (defvar markdown-italic-face
'markdown-italic-face
739 "Face name to use for italic text.")
741 (defvar markdown-bold-face
'markdown-bold-face
742 "Face name to use for bold text.")
744 (defvar markdown-header-delimiter-face
'markdown-header-delimiter-face
745 "Face name to use as a base for header delimiters.")
747 (defvar markdown-header-rule-face
'markdown-header-rule-face
748 "Face name to use as a base for header rules.")
750 (defvar markdown-header-face
'markdown-header-face
751 "Face name to use as a base for headers.")
753 (defvar markdown-header-face-1
'markdown-header-face-1
754 "Face name to use for level-1 headers.")
756 (defvar markdown-header-face-2
'markdown-header-face-2
757 "Face name to use for level-2 headers.")
759 (defvar markdown-header-face-3
'markdown-header-face-3
760 "Face name to use for level-3 headers.")
762 (defvar markdown-header-face-4
'markdown-header-face-4
763 "Face name to use for level-4 headers.")
765 (defvar markdown-header-face-5
'markdown-header-face-5
766 "Face name to use for level-5 headers.")
768 (defvar markdown-header-face-6
'markdown-header-face-6
769 "Face name to use for level-6 headers.")
771 (defvar markdown-inline-code-face
'markdown-inline-code-face
772 "Face name to use for inline code.")
774 (defvar markdown-list-face
'markdown-list-face
775 "Face name to use for list markers.")
777 (defvar markdown-blockquote-face
'markdown-blockquote-face
778 "Face name to use for blockquote.")
780 (defvar markdown-pre-face
'markdown-pre-face
781 "Face name to use for preformatted text.")
783 (defvar markdown-language-keyword-face
'markdown-language-keyword-face
784 "Face name to use for programming language identifiers.")
786 (defvar markdown-link-face
'markdown-link-face
787 "Face name to use for links.")
789 (defvar markdown-missing-link-face
'markdown-missing-link-face
790 "Face name to use for links where the linked file does not exist.")
792 (defvar markdown-reference-face
'markdown-reference-face
793 "Face name to use for reference.")
795 (defvar markdown-footnote-face
'markdown-footnote-face
796 "Face name to use for footnote identifiers.")
798 (defvar markdown-url-face
'markdown-url-face
799 "Face name to use for URLs.")
801 (defvar markdown-link-title-face
'markdown-link-title-face
802 "Face name to use for reference link titles.")
804 (defvar markdown-comment-face
'markdown-comment-face
805 "Face name to use for HTML comments.")
807 (defvar markdown-math-face
'markdown-math-face
808 "Face name to use for LaTeX expressions.")
810 (defvar markdown-metadata-key-face
'markdown-metadata-key-face
811 "Face name to use for metadata keys.")
813 (defvar markdown-metadata-value-face
'markdown-metadata-value-face
814 "Face name to use for metadata values.")
816 (defgroup markdown-faces nil
817 "Faces used in Markdown Mode"
821 (defface markdown-italic-face
822 '((t (:inherit font-lock-variable-name-face
:slant italic
)))
823 "Face for italic text."
824 :group
'markdown-faces
)
826 (defface markdown-bold-face
827 '((t (:inherit font-lock-variable-name-face
:weight bold
)))
828 "Face for bold text."
829 :group
'markdown-faces
)
831 (defface markdown-header-rule-face
832 '((t (:inherit font-lock-function-name-face
:weight bold
)))
833 "Base face for headers rules."
834 :group
'markdown-faces
)
836 (defface markdown-header-delimiter-face
837 '((t (:inherit font-lock-function-name-face
:weight bold
)))
838 "Base face for headers hash delimiter."
839 :group
'markdown-faces
)
841 (defface markdown-header-face
842 '((t (:inherit font-lock-function-name-face
:weight bold
)))
843 "Base face for headers."
844 :group
'markdown-faces
)
846 (defface markdown-header-face-1
847 '((t (:inherit markdown-header-face
)))
848 "Face for level-1 headers."
849 :group
'markdown-faces
)
851 (defface markdown-header-face-2
852 '((t (:inherit markdown-header-face
)))
853 "Face for level-2 headers."
854 :group
'markdown-faces
)
856 (defface markdown-header-face-3
857 '((t (:inherit markdown-header-face
)))
858 "Face for level-3 headers."
859 :group
'markdown-faces
)
861 (defface markdown-header-face-4
862 '((t (:inherit markdown-header-face
)))
863 "Face for level-4 headers."
864 :group
'markdown-faces
)
866 (defface markdown-header-face-5
867 '((t (:inherit markdown-header-face
)))
868 "Face for level-5 headers."
869 :group
'markdown-faces
)
871 (defface markdown-header-face-6
872 '((t (:inherit markdown-header-face
)))
873 "Face for level-6 headers."
874 :group
'markdown-faces
)
876 (defface markdown-inline-code-face
877 '((t (:inherit font-lock-constant-face
)))
878 "Face for inline code."
879 :group
'markdown-faces
)
881 (defface markdown-list-face
882 '((t (:inherit font-lock-builtin-face
)))
883 "Face for list item markers."
884 :group
'markdown-faces
)
886 (defface markdown-blockquote-face
887 '((t (:inherit font-lock-doc-face
)))
888 "Face for blockquote sections."
889 :group
'markdown-faces
)
891 (defface markdown-pre-face
892 '((t (:inherit font-lock-constant-face
)))
893 "Face for preformatted text."
894 :group
'markdown-faces
)
896 (defface markdown-language-keyword-face
897 '((t (:inherit font-lock-type-face
)))
898 "Face for programming language identifiers."
899 :group
'markdown-faces
)
901 (defface markdown-link-face
902 '((t (:inherit font-lock-keyword-face
)))
904 :group
'markdown-faces
)
906 (defface markdown-missing-link-face
907 '((t (:inherit font-lock-warning-face
)))
908 "Face for missing links."
909 :group
'markdown-faces
)
911 (defface markdown-reference-face
912 '((t (:inherit font-lock-type-face
)))
913 "Face for link references."
914 :group
'markdown-faces
)
916 (defface markdown-footnote-face
917 '((t (:inherit font-lock-keyword-face
)))
918 "Face for footnote markers."
919 :group
'markdown-faces
)
921 (defface markdown-url-face
922 '((t (:inherit font-lock-string-face
)))
924 :group
'markdown-faces
)
926 (defface markdown-link-title-face
927 '((t (:inherit font-lock-comment-face
)))
928 "Face for reference link titles."
929 :group
'markdown-faces
)
931 (defface markdown-comment-face
932 '((t (:inherit font-lock-comment-face
)))
933 "Face for HTML comments."
934 :group
'markdown-faces
)
936 (defface markdown-math-face
937 '((t (:inherit font-lock-string-face
)))
938 "Face for LaTeX expressions."
939 :group
'markdown-faces
)
941 (defface markdown-metadata-key-face
942 '((t (:inherit font-lock-variable-name-face
)))
943 "Face for metadata keys."
944 :group
'markdown-faces
)
946 (defface markdown-metadata-value-face
947 '((t (:inherit font-lock-string-face
)))
948 "Face for metadata values."
949 :group
'markdown-faces
)
951 (defconst markdown-regex-link-inline
952 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
953 "Regular expression for a [text](file) or an image link ![text](file).")
955 (defconst markdown-regex-link-reference
956 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
957 "Regular expression for a reference link [text][id].")
959 (defconst markdown-regex-reference-definition
960 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
961 "Regular expression for a link definition [id]: ...")
963 (defconst markdown-regex-footnote
965 "Regular expression for a footnote marker [^fn].")
967 (defconst markdown-regex-header
968 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
969 "Regexp identifying Markdown headers.")
971 (defconst markdown-regex-header-1-atx
972 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
973 "Regular expression for level 1 atx-style (hash mark) headers.")
975 (defconst markdown-regex-header-2-atx
976 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
977 "Regular expression for level 2 atx-style (hash mark) headers.")
979 (defconst markdown-regex-header-3-atx
980 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
981 "Regular expression for level 3 atx-style (hash mark) headers.")
983 (defconst markdown-regex-header-4-atx
984 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
985 "Regular expression for level 4 atx-style (hash mark) headers.")
987 (defconst markdown-regex-header-5-atx
988 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
989 "Regular expression for level 5 atx-style (hash mark) headers.")
991 (defconst markdown-regex-header-6-atx
992 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
993 "Regular expression for level 6 atx-style (hash mark) headers.")
995 (defconst markdown-regex-header-1-setext
996 "^\\(.*\\)\n\\(=+\\)$"
997 "Regular expression for level 1 setext-style (underline) headers.")
999 (defconst markdown-regex-header-2-setext
1000 "^\\(.*\\)\n\\(-+\\)$"
1001 "Regular expression for level 2 setext-style (underline) headers.")
1003 (defconst markdown-regex-header-setext
1004 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1005 "Regular expression for generic setext-style (underline) headers.")
1007 (defconst markdown-regex-header-atx
1008 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1009 "Regular expression for generic atx-style (hash mark) headers.")
1011 (defconst markdown-regex-hr
1012 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1013 "Regular expression for matching Markdown horizontal rules.")
1015 (defconst markdown-regex-code
1016 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1017 "Regular expression for matching inline code fragments.
1019 The first group ensures that the leading backquote character
1020 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1021 character, including newlines, but not two newlines in a row.
1022 The final group requires that the character following the code
1023 fragment is not a backquote.")
1025 (defconst markdown-regex-pre
1027 "Regular expression for matching preformatted text sections.")
1029 (defconst markdown-regex-list
1030 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1031 "Regular expression for matching list items.")
1033 (defconst markdown-regex-bold
1034 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1035 "Regular expression for matching bold text.
1036 Group 1 matches the character before the opening asterisk or
1037 underscore, if any, ensuring that it is not a backslash escape.
1038 Group 2 matches the entire expression, including delimiters.
1039 Groups 3 and 5 matches the opening and closing delimiters.
1040 Group 4 matches the text inside the delimiters.")
1042 (defconst markdown-regex-italic
1043 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1044 "Regular expression for matching italic text.
1045 Group 1 matches the character before the opening asterisk or
1046 underscore, if any, ensuring that it is not a backslash escape.
1047 Group 2 matches the entire expression, including delimiters.
1048 Groups 3 and 5 matches the opening and closing delimiters.
1049 Group 4 matches the text inside the delimiters.")
1051 (defconst markdown-regex-gfm-italic
1052 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1053 "Regular expression for matching italic text in GitHub-flavored Markdown.
1054 Underscores in words are not treated as special.")
1056 (defconst markdown-regex-blockquote
1058 "Regular expression for matching blockquote lines.")
1060 (defconst markdown-regex-line-break
1062 "Regular expression for matching line breaks.")
1064 (defconst markdown-regex-wiki-link
1065 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1066 "Regular expression for matching wiki links.
1067 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1068 wiki links of the form [[PageName|link text]]. In this regular
1069 expression, #1 matches the page name and #3 matches the link
1072 (defconst markdown-regex-uri
1073 (concat (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;() ]+")
1074 "Regular expression for matching inline URIs.")
1076 (defconst markdown-regex-angle-uri
1077 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types
) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1078 "Regular expression for matching inline URIs in angle brackets.")
1080 (defconst markdown-regex-email
1081 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
1082 "Regular expression for matching inline email addresses.")
1084 (defconst markdown-regex-link-generic
1085 (concat "\\(?:" markdown-regex-wiki-link
1086 "\\|" markdown-regex-link-inline
1087 "\\|" markdown-regex-link-reference
1088 "\\|" markdown-regex-angle-uri
"\\)")
1089 "Regular expression for matching any recognized link.")
1091 (defconst markdown-regex-block-separator
1092 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1093 "Regular expression for matching block boundaries.")
1095 (defconst markdown-regex-latex-expression
1096 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1097 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1099 (defconst markdown-regex-latex-display
1100 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1101 "Regular expression for itex \[..\] display mode expressions.")
1103 (defconst markdown-regex-multimarkdown-metadata
1104 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1105 "Regular expression for matching MultiMarkdown metadata.")
1107 (defconst markdown-regex-pandoc-metadata
1108 "^\\(%\\)[ \t]*\\(.*\\)$"
1109 "Regular expression for matching Pandoc metadata.")
1111 (defvar markdown-mode-font-lock-keywords-basic
1113 (cons 'markdown-match-multimarkdown-metadata
'((1 markdown-metadata-key-face
)
1114 (2 markdown-metadata-value-face
)))
1115 (cons 'markdown-match-pandoc-metadata
'((1 markdown-comment-face
)
1116 (2 markdown-metadata-value-face
)))
1117 (cons 'markdown-match-pre-blocks
'((0 markdown-pre-face
)))
1118 (cons 'markdown-match-fenced-code-blocks
'((0 markdown-pre-face
)))
1119 (cons markdown-regex-blockquote
'markdown-blockquote-face
)
1120 (cons markdown-regex-header-1-setext
'((1 markdown-header-face-1
)
1121 (2 markdown-header-rule-face
)))
1122 (cons markdown-regex-header-2-setext
'((1 markdown-header-face-2
)
1123 (2 markdown-header-rule-face
)))
1124 (cons markdown-regex-header-1-atx
'((1 markdown-header-delimiter-face
)
1125 (2 markdown-header-face-1
)
1126 (3 markdown-header-delimiter-face
)))
1127 (cons markdown-regex-header-2-atx
'((1 markdown-header-delimiter-face
)
1128 (2 markdown-header-face-2
)
1129 (3 markdown-header-delimiter-face
)))
1130 (cons markdown-regex-header-3-atx
'((1 markdown-header-delimiter-face
)
1131 (2 markdown-header-face-3
)
1132 (3 markdown-header-delimiter-face
)))
1133 (cons markdown-regex-header-4-atx
'((1 markdown-header-delimiter-face
)
1134 (2 markdown-header-face-4
)
1135 (3 markdown-header-delimiter-face
)))
1136 (cons markdown-regex-header-5-atx
'((1 markdown-header-delimiter-face
)
1137 (2 markdown-header-face-5
)
1138 (3 markdown-header-delimiter-face
)))
1139 (cons markdown-regex-header-6-atx
'((1 markdown-header-delimiter-face
)
1140 (2 markdown-header-face-6
)
1141 (3 markdown-header-delimiter-face
)))
1142 (cons markdown-regex-hr
'markdown-header-face
)
1143 (cons 'markdown-match-comments
'((0 markdown-comment-face t t
)))
1144 (cons markdown-regex-code
'(2 markdown-inline-code-face
))
1145 (cons markdown-regex-angle-uri
'markdown-link-face
)
1146 (cons markdown-regex-uri
'markdown-link-face
)
1147 (cons markdown-regex-email
'markdown-link-face
)
1148 (cons markdown-regex-list
'(2 markdown-list-face
))
1149 (cons markdown-regex-link-inline
'((1 markdown-link-face t
)
1150 (2 markdown-url-face t
)))
1151 (cons markdown-regex-link-reference
'((1 markdown-link-face t
)
1152 (2 markdown-reference-face t
)))
1153 (cons markdown-regex-reference-definition
'((1 markdown-reference-face t
)
1154 (2 markdown-url-face t
)
1155 (3 markdown-link-title-face t
)))
1156 (cons markdown-regex-footnote
'markdown-footnote-face
)
1157 (cons markdown-regex-bold
'(2 markdown-bold-face
))
1159 "Syntax highlighting for Markdown files.")
1161 (defvar markdown-mode-font-lock-keywords-core
1163 (cons markdown-regex-italic
'(2 markdown-italic-face
))
1165 "Additional syntax highlighting for Markdown files.
1166 Includes features which are overridden by some variants.")
1168 (defconst markdown-mode-font-lock-keywords-latex
1170 ;; Math mode $..$ or $$..$$
1171 (cons markdown-regex-latex-expression
'(2 markdown-math-face
))
1172 ;; Display mode equations with brackets: \[ \]
1173 (cons markdown-regex-latex-display
'markdown-math-face
)
1174 ;; Equation reference (eq:foo)
1175 (cons "(eq:\\w+)" 'markdown-reference-face
)
1176 ;; Equation reference \eqref{foo}
1177 (cons "\\\\eqref{\\w+}" 'markdown-reference-face
))
1178 "Syntax highlighting for LaTeX fragments.")
1180 (defvar markdown-mode-font-lock-keywords
1182 (if markdown-enable-math
1183 markdown-mode-font-lock-keywords-latex
)
1184 markdown-mode-font-lock-keywords-basic
1185 markdown-mode-font-lock-keywords-core
)
1186 "Default highlighting expressions for Markdown mode.")
1189 (defvar markdown-footnote-counter
0
1190 "Counter for footnote numbers.")
1191 (make-variable-buffer-local 'markdown-footnote-counter
)
1193 (defconst markdown-footnote-chars
1195 "Regular expression maching any character that is allowed in a footnote identifier.")
1198 ;;; Compatibility =============================================================
1200 (defun markdown-replace-regexp-in-string (regexp rep string
)
1201 "Replace all matches for REGEXP with REP in STRING.
1202 This is a compatibility wrapper to provide `replace-regexp-in-string'
1204 (if (featurep 'xemacs
)
1205 (replace-in-string string regexp rep
)
1206 (replace-regexp-in-string regexp rep string
)))
1208 ;; `markdown-use-region-p' is a compatibility function which checks
1209 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1212 ;; Emacs 23 and newer
1213 ((fboundp 'use-region-p
)
1214 (defalias 'markdown-use-region-p
'use-region-p
))
1216 ((and (boundp 'transient-mark-mode
) (boundp 'mark-active
))
1217 (defun markdown-use-region-p ()
1218 "Compatibility wrapper to provide `use-region-p'."
1219 (and transient-mark-mode mark-active
)))
1221 ((fboundp 'region-active-p
)
1222 (defalias 'markdown-use-region-p
'region-active-p
))))
1224 (defun markdown-use-buttons-p ()
1225 "Determine whether this Emacs supports buttons."
1226 (or (featurep 'button
) (locate-library "button")))
1229 ;;; Markdown Parsing Functions ================================================
1231 (defun markdown-cur-line-blank-p ()
1232 "Return t if the current line is blank and nil otherwise."
1235 (re-search-forward "^\\s *$" (line-end-position) t
)))
1237 (defun markdown-prev-line-blank-p ()
1238 "Return t if the previous line is blank and nil otherwise.
1239 If we are at the first line, then consider the previous line to be blank."
1240 (or (= (line-beginning-position) (point-min))
1243 (markdown-cur-line-blank-p))))
1245 (defun markdown-next-line-blank-p ()
1246 "Return t if the next line is blank and nil otherwise.
1247 If we are at the last line, then consider the next line to be blank."
1248 (or (= (line-end-position) (point-max))
1251 (markdown-cur-line-blank-p))))
1253 (defun markdown-prev-line-indent-p ()
1254 "Return t if the previous line is indented and nil otherwise."
1257 (goto-char (line-beginning-position))
1258 (if (re-search-forward "^\\s " (line-end-position) t
) t
)))
1260 (defun markdown-cur-line-indent ()
1261 "Return the number of leading whitespace characters in the current line."
1264 (goto-char (line-beginning-position))
1265 (re-search-forward "^[ \t]+" (line-end-position) t
)
1268 (defun markdown-prev-line-indent ()
1269 "Return the number of leading whitespace characters in the previous line."
1272 (markdown-cur-line-indent)))
1274 (defun markdown-next-line-indent ()
1275 "Return the number of leading whitespace characters in the next line."
1278 (markdown-cur-line-indent)))
1280 (defun markdown-cur-non-list-indent ()
1281 "Return beginning position of list item text (not including the list marker).
1282 Return nil if the current line is not the beginning of a list item."
1286 (when (re-search-forward markdown-regex-list
(line-end-position) t
)
1287 (current-column)))))
1289 (defun markdown-prev-non-list-indent ()
1290 "Return position of the first non-list-marker on the previous line."
1293 (markdown-cur-non-list-indent)))
1295 (defun markdown-new-baseline-p ()
1296 "Determine if the current line begins a new baseline level."
1300 (or (looking-at markdown-regex-header
)
1301 (looking-at markdown-regex-hr
)
1302 (and (null (markdown-cur-non-list-indent))
1303 (= (markdown-cur-line-indent) 0)
1304 (markdown-prev-line-blank-p))))))
1306 (defun markdown-search-backward-baseline ()
1307 "Search backward baseline point with no indentation and not a list item."
1310 (while (not (or stop
(bobp)))
1311 (re-search-backward markdown-regex-block-separator nil t
)
1313 (goto-char (match-end 2))
1315 ((markdown-new-baseline-p)
1317 ((looking-at markdown-regex-list
)
1319 (t (setq stop t
)))))))
1321 (defun markdown-update-list-levels (marker indent levels
)
1322 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1323 Here, MARKER is a string representing the type of list, INDENT is an integer
1324 giving the indentation, in spaces, of the current block, and LEVELS is a
1325 list of the indentation levels of parent list items. When LEVELS is nil,
1326 it means we are at baseline (not inside of a nested list)."
1328 ;; New list item at baseline.
1329 ((and marker
(null levels
))
1330 (setq levels
(list indent
)))
1331 ;; List item with greater indentation (four or more spaces).
1332 ;; Increase list level.
1333 ((and marker
(>= indent
(+ (car levels
) 4)))
1334 (setq levels
(cons indent levels
)))
1335 ;; List item with greater or equal indentation (less than four spaces).
1336 ;; Do not increase list level.
1337 ((and marker
(>= indent
(car levels
)))
1339 ;; Lesser indentation level.
1340 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1341 ;; indentation could move back more than one list level). Note
1342 ;; that this block need not be the beginning of list item.
1343 ((< indent
(car levels
))
1344 (while (and (> (length levels
) 1)
1345 (< indent
(+ (cadr levels
) 4)))
1346 (setq levels
(cdr levels
)))
1348 ;; Otherwise, do nothing.
1351 (defun markdown-calculate-list-levels ()
1352 "Calculate list levels at point.
1353 Return a list of the form (n1 n2 n3 ...) where n1 is the
1354 indentation of the deepest nested list item in the branch of
1355 the list at the point, n2 is the indentation of the parent
1356 list item, and so on. The depth of the list item is therefore
1357 the length of the returned list. If the point is not at or
1358 immediately after a list item, return nil."
1360 (let ((first (point)) levels indent pre-regexp
)
1361 ;; Find a baseline point with zero list indentation
1362 (markdown-search-backward-baseline)
1363 ;; Search for all list items between baseline and LOC
1364 (while (and (< (point) first
)
1365 (re-search-forward markdown-regex-list first t
))
1366 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels
))))
1369 ;; Make sure this is not a header or hr
1370 ((markdown-new-baseline-p) (setq levels nil
))
1371 ;; Make sure this is not a line from a pre block
1372 ((looking-at pre-regexp
))
1373 ;; If not, then update levels
1375 (setq indent
(markdown-cur-line-indent))
1376 (setq levels
(markdown-update-list-levels (match-string 2)
1381 (defun markdown-prev-list-item (level)
1382 "Search backward from point for a list item with indentation LEVEL.
1383 Set point to the beginning of the item, and return point, or nil
1385 (let (bounds indent prev
)
1388 (setq indent
(markdown-cur-line-indent))
1391 ;; Stop at beginning of buffer
1392 ((bobp) (setq prev nil
))
1393 ;; Continue if current line is blank
1394 ((markdown-cur-line-blank-p) t
)
1396 ((and (looking-at markdown-regex-list
)
1397 (setq bounds
(markdown-cur-list-item-bounds)))
1399 ;; Continue at item with greater indentation
1400 ((> (nth 3 bounds
) level
) t
)
1401 ;; Stop and return point at item of equal indentation
1402 ((= (nth 3 bounds
) level
)
1405 ;; Stop and return nil at item with lesser indentation
1406 ((< (nth 3 bounds
) level
)
1409 ;; Continue while indentation is the same or greater
1410 ((>= indent level
) t
)
1411 ;; Stop if current indentation is less than list item
1412 ;; and the next is blank
1413 ((and (< indent level
)
1414 (markdown-next-line-blank-p))
1417 ((looking-at markdown-regex-header
) (setq prev nil
))
1418 ;; Stop at a horizontal rule
1419 ((looking-at markdown-regex-hr
) (setq prev nil
))
1420 ;; Otherwise, continue.
1423 (setq indent
(markdown-cur-line-indent)))
1426 (defun markdown-next-list-item (level)
1427 "Search forward from point for the next list item with indentation LEVEL.
1428 Set point to the beginning of the item, and return point, or nil
1430 (let (bounds indent prev next
)
1433 (setq indent
(markdown-cur-line-indent))
1436 ;; Stop at end of the buffer.
1437 ((eobp) (setq prev nil
))
1438 ;; Continue if the current line is blank
1439 ((markdown-cur-line-blank-p) t
)
1441 ((and (looking-at markdown-regex-list
)
1442 (setq bounds
(markdown-cur-list-item-bounds)))
1444 ;; Continue at item with greater indentation
1445 ((> (nth 3 bounds
) level
) t
)
1446 ;; Stop and return point at item of equal indentation
1447 ((= (nth 3 bounds
) level
)
1450 ;; Stop and return nil at item with lesser indentation
1451 ((< (nth 3 bounds
) level
)
1454 ;; Continue while indentation is the same or greater
1455 ((>= indent level
) t
)
1456 ;; Stop if current indentation is less than list item
1457 ;; and the previous line was blank.
1458 ((and (< indent level
)
1459 (markdown-prev-line-blank-p))
1462 ((looking-at markdown-regex-header
) (setq next nil
))
1463 ;; Stop at a horizontal rule
1464 ((looking-at markdown-regex-hr
) (setq next nil
))
1465 ;; Otherwise, continue.
1468 (setq indent
(markdown-cur-line-indent)))
1471 (defun markdown-cur-list-item-end (level)
1472 "Move to the end of the current list item with nonlist indentation LEVEL.
1473 If the point is not in a list item, do nothing."
1476 (setq indent
(markdown-cur-line-indent))
1479 ;; Stop at end of the buffer.
1481 ;; Continue if the current line is blank
1482 ((markdown-cur-line-blank-p) t
)
1483 ;; Continue while indentation is the same or greater
1484 ((>= indent level
) t
)
1485 ;; Stop if current indentation is less than list item
1486 ;; and the previous line was blank.
1487 ((and (< indent level
)
1488 (markdown-prev-line-blank-p))
1490 ;; Stop at a new list item of the same or lesser indentation
1491 ((looking-at markdown-regex-list
) nil
)
1493 ((looking-at markdown-regex-header
) nil
)
1494 ;; Stop at a horizontal rule
1495 ((looking-at markdown-regex-hr
) nil
)
1496 ;; Otherwise, continue.
1499 (setq indent
(markdown-cur-line-indent)))
1500 ;; Don't skip over whitespace for empty list items (marker and
1501 ;; whitespace only), just move to end of whitespace.
1502 (if (looking-back (concat markdown-regex-list
"\\s-*"))
1503 (goto-char (match-end 3))
1504 (skip-syntax-backward "-"))))
1506 (defun markdown-cur-list-item-bounds ()
1507 "Return bounds and indentation of the current list item.
1508 Return a list of the form (begin end indent nonlist-indent).
1509 If the point is not inside a list item, return nil.
1510 Leave match data intact for `markdown-regex-list'."
1511 (let (cur prev-begin prev-end indent nonlist-indent
)
1512 ;; Store current location
1514 ;; Verify that cur is between beginning and end of item
1517 (when (re-search-backward markdown-regex-list nil t
)
1518 (setq prev-begin
(match-beginning 0))
1519 (setq indent
(length (match-string 1)))
1520 (setq nonlist-indent
(length (match-string 0)))
1522 (markdown-cur-list-item-end nonlist-indent
)
1523 (setq prev-end
(point)))
1524 (when (and (>= cur prev-begin
)
1527 (list prev-begin prev-end indent nonlist-indent
))))))
1529 (defun markdown-bounds-of-thing-at-point (thing)
1530 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1531 Does not include trailing newlines when THING is 'line. Handles the
1532 end of buffer case by setting both endpoints equal to the value of
1533 `point-max', since an empty region will trigger empty markup insertion.
1534 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1535 (let* ((bounds (bounds-of-thing-at-point thing
))
1539 (when (eq thing
'line
)
1540 (cond ((and (eobp) (markdown-cur-line-blank-p))
1542 ((char-equal (char-before b
) ?\^J
)
1546 (defun markdown-reference-definition (reference)
1547 "Find out whether Markdown REFERENCE is defined.
1548 REFERENCE should include the square brackets, like [this].
1549 When REFERENCE is defined, return a list of the form (text start end)
1550 containing the definition text itself followed by the start and end
1551 locations of the text. Otherwise, return nil.
1552 Leave match data for `markdown-regex-reference-definition'
1553 intact additional processing."
1554 (let ((reference (downcase reference
)))
1556 (goto-char (point-min))
1558 (while (re-search-forward markdown-regex-reference-definition nil t
)
1559 (when (string= reference
(downcase (match-string-no-properties 1)))
1561 (list (match-string-no-properties 2)
1562 (match-beginning 2) (match-end 2)))))))))
1565 ;;; Markdown Font Lock Matching Functions =====================================
1567 (defun markdown-match-comments (last)
1568 "Match HTML comments from the point to LAST."
1569 (cond ((search-forward "<!--" last t
)
1571 (let ((beg (point)))
1572 (cond ((search-forward-regexp "--[ \t]*>" last t
)
1573 (set-match-data (list beg
(point)))
1578 (defun markdown-match-pre-blocks (last)
1579 "Match Markdown pre blocks from point to LAST."
1580 (let ((levels (markdown-calculate-list-levels))
1581 indent pre-regexp end-regexp begin end stop
)
1582 (while (and (< (point) last
) (not end
))
1583 ;; Search for a region with sufficient indentation
1586 (setq indent
(1+ (length levels
))))
1587 (setq pre-regexp
(format "^\\( \\|\t\\)\\{%d\\}" indent
))
1588 (setq end-regexp
(format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent
)))
1591 ;; If not at the beginning of a line, move forward
1592 ((not (bolp)) (forward-line))
1593 ;; Move past blank lines
1594 ((markdown-cur-line-blank-p) (forward-line))
1595 ;; At headers and horizontal rules, reset levels
1596 ((markdown-new-baseline-p) (forward-line) (setq levels nil
))
1597 ;; If the current line has sufficient indentation, mark out pre block
1598 ((looking-at pre-regexp
)
1599 (setq begin
(match-beginning 0))
1600 (while (and (or (looking-at pre-regexp
) (markdown-cur-line-blank-p))
1604 ;; If current line has a list marker, update levels, move to end of block
1605 ((looking-at markdown-regex-list
)
1606 (setq levels
(markdown-update-list-levels
1607 (match-string 2) (markdown-cur-line-indent) levels
))
1608 (markdown-end-of-block-element))
1609 ;; If this is the end of the indentation level, adjust levels accordingly.
1610 ;; Only match end of indentation level if levels is not the empty list.
1611 ((and (car levels
) (looking-at end-regexp
))
1612 (setq levels
(markdown-update-list-levels
1613 nil
(markdown-cur-line-indent) levels
))
1614 (markdown-end-of-block-element))
1615 (t (markdown-end-of-block-element))))
1617 (if (not (and begin end
))
1618 ;; Return nil if no pre block was found
1620 ;; Set match data and return t upon success
1621 (set-match-data (list begin end
))
1624 (defun markdown-match-fenced-code-blocks (last)
1625 "Match fenced code blocks from the point to LAST."
1626 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t
)
1628 (let ((beg (point)))
1630 (cond ((search-forward-regexp
1631 (concat "^" (match-string 1) "~*") last t
)
1632 (set-match-data (list beg
(point)))
1637 (defun markdown-match-gfm-code-blocks (last)
1638 "Match GFM quoted code blocks from point to LAST."
1639 (let (open lang body close all
)
1640 (cond ((and (eq major-mode
'gfm-mode
)
1641 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t
))
1643 (setq open
(list (match-beginning 1) (match-end 1))
1644 lang
(list (match-beginning 2) (match-end 2)))
1646 (setq body
(list (point)))
1647 (cond ((search-forward-regexp "^```$" last t
)
1648 (setq body
(reverse (cons (1- (match-beginning 0)) body
))
1649 close
(list (match-beginning 0) (match-end 0))
1650 all
(list (car open
) (match-end 0)))
1651 (set-match-data (append all open lang body close
))
1656 (defun markdown-match-generic-metadata (regexp last
)
1657 "Match generic metadata specified by REGEXP from the point to LAST."
1658 (let ((header-end (save-excursion
1659 (goto-char (point-min))
1660 (if (re-search-forward "\n\n" (point-max) t
)
1663 (cond ((>= (point) header-end
)
1664 ;; Don't match anything outside of the header.
1666 ((re-search-forward regexp
(min last header-end
) t
)
1667 ;; If a metadata item is found, it may span several lines.
1668 (let ((key-beginning (match-beginning 1))
1669 (key-end (match-end 1))
1670 (value-beginning (match-beginning 2)))
1671 (while (and (not (looking-at regexp
))
1672 (not (> (point) (min last header-end
)))
1678 (set-match-data (list key-beginning
(point) ; complete metadata
1679 key-beginning key-end
; key
1680 value-beginning
(point))) ; value
1684 (defun markdown-match-multimarkdown-metadata (last)
1685 "Match MultiMarkdown metadata from the point to LAST."
1686 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last
))
1688 (defun markdown-match-pandoc-metadata (last)
1689 "Match Pandoc metadata from the point to LAST."
1690 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last
))
1692 (defun markdown-font-lock-extend-region ()
1693 "Extend the search region to include an entire block of text.
1694 This helps improve font locking for block constructs such as pre blocks."
1695 ;; Avoid compiler warnings about these global variables from font-lock.el.
1696 ;; See the documentation for variable `font-lock-extend-region-functions'.
1697 (eval-when-compile (defvar font-lock-beg
) (defvar font-lock-end
))
1699 (goto-char font-lock-beg
)
1700 (let ((found (or (re-search-backward "\n\n" nil t
) (point-min))))
1701 (goto-char font-lock-end
)
1702 (when (re-search-forward "\n\n" nil t
)
1704 (setq font-lock-end
(point)))
1705 (setq font-lock-beg found
))))
1708 ;;; Syntax Table ==============================================================
1710 (defvar markdown-mode-syntax-table
1711 (let ((tab (make-syntax-table text-mode-syntax-table
)))
1712 (modify-syntax-entry ?
\" "." tab
)
1714 "Syntax table for `markdown-mode'.")
1717 ;;; Element Insertion =========================================================
1719 (defun markdown-ensure-blank-line-before ()
1720 "If previous line is not already blank, insert a blank line before point."
1721 (unless (bolp) (insert "\n"))
1722 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1724 (defun markdown-ensure-blank-line-after ()
1725 "If following line is not already blank, insert a blank line after point.
1726 Return the point where it was originally."
1728 (unless (eolp) (insert "\n"))
1729 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1731 (defun markdown-wrap-or-insert (s1 s2
&optional thing beg end
)
1732 "Insert the strings S1 and S2, wrapping around region or THING.
1733 If a region is specified by the optional BEG and END arguments,
1734 wrap the strings S1 and S2 around that region.
1735 If there is an active region, wrap the strings S1 and S2 around
1736 the region. If there is not an active region but the point is at
1737 THING, wrap that thing (which defaults to word). Otherwise, just
1738 insert S1 and S2 and place the cursor in between. Return the
1739 bounds of the entire wrapped string, or nil if nothing was wrapped
1740 and S1 and S2 were only inserted."
1741 (let (a b bounds new-point
)
1747 new-point
(+ (point) (length s1
))))
1749 ((markdown-use-region-p)
1750 (setq a
(region-beginning)
1752 new-point
(+ (point) (length s1
))))
1753 ;; Thing (word) at point
1754 ((setq bounds
(markdown-bounds-of-thing-at-point (or thing
'word
)))
1755 (setq a
(car bounds
)
1757 new-point
(+ (point) (length s1
))))
1758 ;; No active region and no word
1766 (when new-point
(goto-char new-point
))
1769 (setq b
(+ b
(length s1
) (length s2
)))
1772 (defun markdown-point-after-unwrap (cur prefix suffix
)
1773 "Return desired position of point after an unwrapping operation.
1774 Two cons cells must be provided. PREFIX gives the bounds of the
1775 prefix string and SUFFIX gives the bounds of the suffix string."
1776 (cond ((< cur
(cdr prefix
)) (car prefix
))
1777 ((< cur
(car suffix
)) (- cur
(- (cdr prefix
) (car prefix
))))
1778 ((<= cur
(cdr suffix
))
1779 (- cur
(+ (- (cdr prefix
) (car prefix
))
1780 (- cur
(car suffix
)))))
1783 (defun markdown-unwrap-thing-at-point (regexp all text
)
1784 "Remove prefix and suffix of thing at point and reposition the point.
1785 When the thing at point matches REGEXP, replace the subexpression
1786 ALL with the string in subexpression TEXT. Reposition the point
1787 in an appropriate location accounting for the removal of prefix
1788 and suffix strings. Return new bounds of string from group TEXT.
1789 When REGEXP is nil, assumes match data is already set."
1790 (when (or (null regexp
)
1791 (thing-at-point-looking-at regexp
))
1793 (prefix (cons (match-beginning all
) (match-beginning text
)))
1794 (suffix (cons (match-end text
) (match-end all
)))
1795 (bounds (cons (match-beginning text
) (match-end text
))))
1796 ;; Replace the thing at point
1797 (replace-match (match-string text
) t t nil all
)
1798 ;; Reposition the point
1799 (goto-char (markdown-point-after-unwrap cur prefix suffix
))
1801 (setq bounds
(cons (car prefix
)
1802 (- (cdr bounds
) (- (cdr prefix
) (car prefix
))))))))
1804 (defun markdown-unwrap-things-in-region (beg end regexp all text
)
1805 "Remove prefix and suffix of all things in region.
1806 When a thing in the region matches REGEXP, replace the
1807 subexpression ALL with the string in subexpression TEXT.
1808 Return a cons cell containing updated bounds for the region."
1811 (let ((removed 0) len-all len-text
)
1812 (while (re-search-forward regexp
(- end removed
) t
)
1813 (setq len-all
(length (match-string-no-properties all
)))
1814 (setq len-text
(length (match-string-no-properties text
)))
1815 (setq removed
(+ removed
(- len-all len-text
)))
1816 (replace-match (match-string text
) t t nil all
))
1817 (cons beg
(- end removed
)))))
1819 (defun markdown-insert-hr (arg)
1820 "Insert or replace a horizonal rule.
1821 By default, use the first element of `markdown-hr-strings'. When
1822 prefixed with C-u, use the last element of `markdown-hr-strings'
1823 instead. When prefixed with an integer from 1 to the length of
1824 `markdown-hr-strings', use the element in that position instead."
1826 (when (thing-at-point-looking-at markdown-regex-hr
)
1827 (delete-region (match-beginning 0) (match-end 0)))
1828 (markdown-ensure-blank-line-before)
1829 (cond ((equal arg
'(4))
1830 (insert (car (reverse markdown-hr-strings
))))
1831 ((and (integerp arg
) (> arg
0)
1832 (<= arg
(length markdown-hr-strings
)))
1833 (insert (nth (1- arg
) markdown-hr-strings
)))
1835 (insert (car markdown-hr-strings
))))
1836 (markdown-ensure-blank-line-after))
1838 (defun markdown-insert-bold ()
1839 "Insert markup to make a region or word bold.
1840 If there is an active region, make the region bold. If the point
1841 is at a non-bold word, make the word bold. If the point is at a
1842 bold word or phrase, remove the bold markup. Otherwise, simply
1843 insert bold delimiters and place the cursor in between them."
1845 (let ((delim (if markdown-bold-underscore
"__" "**")))
1846 (if (markdown-use-region-p)
1848 (let ((bounds (markdown-unwrap-things-in-region
1849 (region-beginning) (region-end)
1850 markdown-regex-bold
2 4)))
1851 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1852 ;; Bold markup removal, bold word at point, or empty markup insertion
1853 (if (thing-at-point-looking-at markdown-regex-bold
)
1854 (markdown-unwrap-thing-at-point nil
2 4)
1855 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1857 (defun markdown-insert-italic ()
1858 "Insert markup to make a region or word italic.
1859 If there is an active region, make the region italic. If the point
1860 is at a non-italic word, make the word italic. If the point is at an
1861 italic word or phrase, remove the italic markup. Otherwise, simply
1862 insert italic delimiters and place the cursor in between them."
1864 (let ((delim (if markdown-italic-underscore
"_" "*")))
1865 (if (markdown-use-region-p)
1867 (let ((bounds (markdown-unwrap-things-in-region
1868 (region-beginning) (region-end)
1869 markdown-regex-italic
2 4)))
1870 (markdown-wrap-or-insert delim delim nil
(car bounds
) (cdr bounds
)))
1871 ;; Italic markup removal, italic word at point, or empty markup insertion
1872 (if (thing-at-point-looking-at markdown-regex-italic
)
1873 (markdown-unwrap-thing-at-point nil
2 4)
1874 (markdown-wrap-or-insert delim delim
'word nil nil
)))))
1876 (defun markdown-insert-code ()
1877 "Insert markup to make a region or word an inline code fragment.
1878 If there is an active region, make the region an inline code
1879 fragment. If the point is at a word, make the word an inline
1880 code fragment. Otherwise, simply insert code delimiters and
1881 place the cursor in between them."
1883 (if (markdown-use-region-p)
1885 (let ((bounds (markdown-unwrap-things-in-region
1886 (region-beginning) (region-end)
1887 markdown-regex-code
2 4)))
1888 (markdown-wrap-or-insert "`" "`" nil
(car bounds
) (cdr bounds
)))
1889 ;; Code markup removal, code markup for word, or empty markup insertion
1890 (if (thing-at-point-looking-at markdown-regex-code
)
1891 (markdown-unwrap-thing-at-point nil
2 4)
1892 (markdown-wrap-or-insert "`" "`" 'word nil nil
))))
1894 (defun markdown-insert-link ()
1895 "Insert an inline link, using region or word as link text if possible.
1896 If there is an active region, use the region as the link text. If the
1897 point is at a word, use the word as the link text. In these cases, the
1898 point will be left at the position for inserting a URL. If there is no
1899 active region and the point is not at word, simply insert link markup and
1900 place the point in the position to enter link text."
1902 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1904 (goto-char (- (cdr bounds
) 1)))))
1906 (defun markdown-insert-reference-link-dwim ()
1907 "Insert a reference link of the form [text][label] at point.
1908 If Transient Mark mode is on and a region is active, the region
1909 is used as the link text. Otherwise, the link text will be read
1910 from the minibuffer. The link URL, label, and title will be read
1911 from the minibuffer. The link label definition is placed at the
1912 end of the current paragraph."
1914 (if (markdown-use-region-p)
1915 (call-interactively 'markdown-insert-reference-link-region
)
1916 (call-interactively 'markdown-insert-reference-link
)))
1918 (defun markdown-insert-reference-link-region (url label title
)
1919 "Insert a reference link at point using the region as the link text.
1920 The link will point to URL, will be referenced as LABEL, and will have the
1921 optional title text given by TITLE."
1922 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1923 (let ((text (delete-and-extract-region (region-beginning) (region-end))))
1924 (markdown-insert-reference-link text url label title
)))
1926 (defun markdown-insert-reference-link (text url label title
)
1927 "Insert a reference link at point.
1928 The link TEXT will point to the given URL and may be referenced using
1929 LABEL. The link TITLE is optional and will be used to populate the
1930 title attribute when converted to XHTML."
1931 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1933 (insert (concat "[" text
"][" label
"]"))
1937 (if (> (length label
) 0)
1940 (insert (concat "]: " url
))
1941 (unless (> (length url
) 0)
1943 (when (> (length title
) 0)
1944 (insert (concat " \"" title
"\"")))
1946 (unless (looking-at "\n")
1950 (defun markdown-insert-wiki-link ()
1951 "Insert a wiki link of the form [[WikiLink]].
1952 If Transient Mark mode is on and a region is active, it is used
1955 (markdown-wrap-or-insert "[[" "]]")
1958 (defun markdown-insert-image ()
1959 "Insert inline image markup using region or word as alt text if possible.
1960 If there is an active region, use the region as the alt text. If the
1961 point is at a word, use the word as the alt text. In these cases, the
1962 point will be left at the position for inserting a URL. If there is no
1963 active region and the point is not at word, simply insert image markup and
1964 place the point in the position to enter alt text."
1966 (let ((bounds (markdown-wrap-or-insert "![" "]()")))
1968 (goto-char (- (cdr bounds
) 1)))))
1970 (defun markdown-remove-header ()
1971 "Remove header markup if point is at a header.
1972 Return bounds of remaining header text if a header was removed
1975 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx
0 2)
1976 (markdown-unwrap-thing-at-point markdown-regex-header-setext
0 1)))
1978 (defun markdown-insert-header (&optional level text setext
)
1979 "Insert or replace header markup.
1980 The level of the header is specified by LEVEL and header text is
1981 given by TEXT. LEVEL must be an integer from 1 and 6, and the
1983 When TEXT is nil, the header text is obtained as follows.
1984 If there is an active region, it is used as the header text.
1985 Otherwise, the current line will be used as the header text.
1986 If there is not an active region and the point is at a header,
1987 remove the header markup and replace with level N header.
1988 Otherwise, insert empty header markup and place the cursor in
1990 The style of the header will be atx (hash marks) unless
1991 SETEXT is non-nil, in which case a setext-style (underlined)
1992 header will be inserted."
1993 (interactive "p\nsHeader text: ")
1994 (setq level
(min (max (or level
1) 1) (if setext
2 6)))
1995 ;; Determine header text if not given
1997 (if (markdown-use-region-p)
1999 (setq text
(delete-and-extract-region (region-beginning) (region-end)))
2001 (markdown-remove-header)
2002 (setq text
(delete-and-extract-region
2003 (line-beginning-position) (line-end-position)))
2004 (when (and setext
(string-match "^[ \t]*$" text
))
2005 (setq text
(read-string "Header text: "))))
2006 (setq text
(markdown-compress-whitespace-string text
)))
2007 ;; Insertion with given text
2008 (markdown-ensure-blank-line-before)
2013 (dotimes (n (length text
))
2014 (insert (if (= level
2) "-" "="))))
2016 (dotimes (count level
) (insert "#"))
2017 (insert " " text
" ")
2018 (dotimes (count level
) (insert "#")))
2019 (markdown-ensure-blank-line-after)
2020 ;; Leave point at end of text
2022 (backward-char (1+ (length text
)))
2023 (backward-char (1+ level
))))
2025 (defun markdown-insert-header-dwim (&optional arg setext
)
2026 "Insert or replace header markup.
2027 The level and type of the header are determined automatically by
2028 the type and level of the previous header, unless a prefix
2030 With a numeric prefix valued 1 to 6, insert a header of the given
2031 level, with the type being determined automatically (note that
2032 only level 1 or 2 setext headers are possible).
2033 With C-u, insert a level-one setext header.
2034 With C-u C-u, insert a level two setext header.
2036 When there is an active region, use it for the header text. When
2037 the point is at an existing header, change the type and level
2038 according to the rules above.
2039 Otherwise, if the line is not empty, create a header using the
2040 text on the current line as the header text.
2041 Finally, if the point is on a blank line, insert empty header
2042 markup (atx) or prompt for text (setext).
2043 See `markdown-insert-header' for more details about how the
2044 header text is determined."
2047 (cond ((equal arg
'(4)) ; level-one setext with C-u
2050 ((equal arg
'(16)) ; level-two setext with C-u C-u
2053 (t ; automatic with numeric override
2055 (when (re-search-backward markdown-regex-header nil t
)
2056 ;; level of previous header
2057 (setq level
(markdown-outline-level))
2058 ;; match groups 1 and 2 indicate setext headers
2059 (setq setext
(or setext
(match-end 1) (match-end 3)))))
2060 ;; use prefix if given, or level of previous header
2061 (setq level
(if arg
(prefix-numeric-value arg
) level
))
2062 ;; setext headers must be level one or two
2063 (and level
(setq setext
(and setext
(<= level
2))))))
2064 (markdown-insert-header level nil setext
)))
2066 (defun markdown-insert-header-setext-dwim (&optional arg
)
2067 "Insert or replace header markup, with preference for setext.
2068 See `markdown-insert-header-dwim' for details."
2070 (markdown-insert-header-dwim arg t
))
2072 (defun markdown-insert-header-atx-1 ()
2073 "Insert a first level atx-style (hash mark) header.
2074 See `markdown-insert-header'."
2076 (markdown-insert-header 1 nil nil
))
2078 (defun markdown-insert-header-atx-2 ()
2079 "Insert a level two atx-style (hash mark) header.
2080 See `markdown-insert-header'."
2082 (markdown-insert-header 2 nil nil
))
2084 (defun markdown-insert-header-atx-3 ()
2085 "Insert a level three atx-style (hash mark) header.
2086 See `markdown-insert-header'."
2088 (markdown-insert-header 3 nil nil
))
2090 (defun markdown-insert-header-atx-4 ()
2091 "Insert a level four atx-style (hash mark) header.
2092 See `markdown-insert-header'."
2094 (markdown-insert-header 4 nil nil
))
2096 (defun markdown-insert-header-atx-5 ()
2097 "Insert a level five atx-style (hash mark) header.
2098 See `markdown-insert-header'."
2100 (markdown-insert-header 5 nil nil
))
2102 (defun markdown-insert-header-atx-6 ()
2103 "Insert a sixth level atx-style (hash mark) header.
2104 See `markdown-insert-header'."
2106 (markdown-insert-header 6 nil nil
))
2108 (defun markdown-insert-header-setext-1 ()
2109 "Insert a setext-style (underlined) first-level header.
2110 See `markdown-insert-header'."
2112 (markdown-insert-header 1 nil t
))
2114 (defun markdown-insert-header-setext-2 ()
2115 "Insert a setext-style (underlined) second-level header.
2116 See `markdown-insert-header'."
2118 (markdown-insert-header 2 nil t
))
2120 (defun markdown-blockquote-indentation (loc)
2121 "Return string containing necessary indentation for a blockquote at LOC.
2122 Also see `markdown-pre-indentation'."
2125 (let* ((list-level (length (markdown-calculate-list-levels)))
2127 (dotimes (count list-level indent
)
2128 (setq indent
(concat indent
" "))))))
2130 (defun markdown-insert-blockquote ()
2131 "Start a blockquote section (or blockquote the region).
2132 If Transient Mark mode is on and a region is active, it is used as
2133 the blockquote text."
2135 (if (markdown-use-region-p)
2136 (markdown-blockquote-region (region-beginning) (region-end))
2137 (markdown-ensure-blank-line-before)
2138 (insert (markdown-blockquote-indentation (point)) "> ")
2139 (markdown-ensure-blank-line-after)))
2141 (defun markdown-block-region (beg end prefix
)
2142 "Format the region using a block prefix.
2143 Arguments BEG and END specify the beginning and end of the
2144 region. The characters PREFIX will appear at the beginning
2147 (let* ((end-marker (make-marker))
2148 (beg-marker (make-marker)))
2149 ;; Ensure blank line after and remove extra whitespace
2151 (skip-syntax-backward "-")
2152 (set-marker end-marker
(point))
2153 (delete-horizontal-space)
2154 (markdown-ensure-blank-line-after)
2155 ;; Ensure blank line before and remove extra whitespace
2157 (skip-syntax-forward "-")
2158 (delete-horizontal-space)
2159 (markdown-ensure-blank-line-before)
2160 (set-marker beg-marker
(point))
2161 ;; Insert PREFIX before each line
2162 (goto-char beg-marker
)
2163 (while (< (line-beginning-position) end-marker
)
2167 (defun markdown-blockquote-region (beg end
)
2168 "Blockquote the region.
2169 Arguments BEG and END specify the beginning and end of the region."
2171 (markdown-block-region
2172 beg end
(concat (markdown-blockquote-indentation
2173 (max (point-min) (1- beg
))) "> ")))
2175 (defun markdown-pre-indentation (loc)
2176 "Return string containing necessary whitespace for a pre block at LOC.
2177 Also see `markdown-blockquote-indentation'."
2180 (let* ((list-level (length (markdown-calculate-list-levels)))
2182 (dotimes (count (1+ list-level
) indent
)
2183 (setq indent
(concat indent
" "))))))
2185 (defun markdown-insert-pre ()
2186 "Start a preformatted section (or apply to the region).
2187 If Transient Mark mode is on and a region is active, it is marked
2188 as preformatted text."
2190 (if (markdown-use-region-p)
2191 (markdown-pre-region (region-beginning) (region-end))
2192 (markdown-ensure-blank-line-before)
2193 (insert (markdown-pre-indentation (point)))
2194 (markdown-ensure-blank-line-after)))
2196 (defun markdown-pre-region (beg end
)
2197 "Format the region as preformatted text.
2198 Arguments BEG and END specify the beginning and end of the region."
2200 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg
)))))
2201 (markdown-block-region beg end indent
)))
2203 (defun markdown-insert-gfm-code-block (&optional lang
)
2204 "Insert GFM code block for language LANG.
2205 If LANG is nil, the language will be queried from user. If a
2206 region is active, wrap this region with the markup instead. If
2207 the region boundaries are not on empty lines, these are added
2208 automatically in order to have the correct markup."
2209 (interactive "sProgramming language: ")
2210 (if (markdown-use-region-p)
2211 (let ((b (region-beginning)) (e (region-end)))
2213 ;; if we're on a blank line, insert the quotes here, otherwise
2214 ;; add a new line first
2215 (unless (looking-at "\n")
2220 (goto-char (+ e
3 (length lang
)))
2221 ;; if we're on a blank line, don't newline, otherwise the ```
2222 ;; should go on its own line
2223 (unless (looking-back "\n")
2232 ;;; Footnotes ======================================================================
2234 (defun markdown-footnote-counter-inc ()
2235 "Increment `markdown-footnote-counter' and return the new value."
2236 (when (= markdown-footnote-counter
0) ; hasn't been updated in this buffer yet.
2238 (goto-char (point-min))
2239 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars
"*?\\)\\]:")
2241 (let ((fn (string-to-number (match-string 1))))
2242 (when (> fn markdown-footnote-counter
)
2243 (setq markdown-footnote-counter fn
))))))
2244 (incf markdown-footnote-counter
))
2246 (defun markdown-footnote-new ()
2247 "Insert footnote with a new number and move point to footnote definition."
2249 (let ((fn (markdown-footnote-counter-inc)))
2250 (insert (format "[^%d]" fn
))
2251 (markdown-footnote-text-find-new-location)
2252 (markdown-ensure-blank-line-before)
2253 (unless (markdown-cur-line-blank-p)
2255 (insert (format "[^%d]: " fn
))
2256 (markdown-ensure-blank-line-after)))
2258 (defun markdown-footnote-text-find-new-location ()
2259 "Position the cursor at the proper location for a new footnote text."
2261 ((eq markdown-footnote-location
'end
) (goto-char (point-max)))
2262 ((eq markdown-footnote-location
'immediately
) (forward-paragraph))
2263 ((eq markdown-footnote-location
'header
) (markdown-end-of-defun))))
2265 (defun markdown-footnote-kill ()
2266 "Kill the footnote at point.
2267 The footnote text is killed (and added to the kill ring), the
2268 footnote marker is deleted. Point has to be either at the
2269 footnote marker or in the footnote text."
2272 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2273 (markdown-footnote-return) ; we first move to the marker
2274 (setq return-pos
'text
)) ; and remember our return position
2275 (let ((marker (markdown-footnote-delete-marker)))
2277 (error "Not at a footnote"))
2278 (let ((text-pos (markdown-footnote-find-text (car marker
))))
2280 (error "No text for footnote `%s'" (car marker
)))
2281 (goto-char text-pos
)
2282 (let ((pos (markdown-footnote-kill-text)))
2284 (if (and pos
(eq return-pos
'text
))
2287 (goto-char return-pos
)))
2289 (defun markdown-footnote-delete-marker ()
2290 "Delete a footnote marker at point.
2291 Returns a list (ID START) containing the footnote ID and the
2292 start position of the marker before deletion. If no footnote
2293 marker was deleted, this function returns NIL."
2294 (let ((marker (markdown-footnote-marker-positions)))
2296 (delete-region (second marker
) (third marker
))
2299 (defun markdown-footnote-kill-text ()
2300 "Kill footnote text at point.
2301 Returns the start position of the footnote text before deletion,
2302 or NIL if point was not inside a footnote text.
2304 The killed text is placed in the kill ring (without the footnote
2306 (let ((fn (markdown-footnote-text-positions)))
2308 (let ((text (delete-and-extract-region (second fn
) (third fn
))))
2309 (string-match (concat "\\[\\" (first fn
) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text
)
2310 (kill-new (match-string 1 text
))
2311 (when (and (markdown-cur-line-blank-p)
2312 (markdown-prev-line-blank-p))
2313 (delete-region (1- (point)) (point)))
2316 (defun markdown-footnote-goto-text ()
2317 "Jump to the text of the footnote at point."
2319 (let ((fn (car (markdown-footnote-marker-positions))))
2321 (error "Not at a footnote marker"))
2322 (let ((new-pos (markdown-footnote-find-text fn
)))
2324 (error "No definition found for footnote `%s'" fn
))
2325 (goto-char new-pos
))))
2327 (defun markdown-footnote-return ()
2328 "Return from a footnote to its footnote number in the main text."
2330 (let ((fn (save-excursion
2331 (car (markdown-footnote-text-positions)))))
2333 (error "Not in a footnote"))
2334 (let ((new-pos (markdown-footnote-find-marker fn
)))
2336 (error "Footnote marker `%s' not found" fn
))
2337 (goto-char new-pos
))))
2339 (defun markdown-footnote-find-marker (id)
2340 "Find the location of the footnote marker with ID.
2341 The actual buffer position returned is the position directly
2342 following the marker's closing bracket. If no marker is found,
2345 (goto-char (point-min))
2346 (when (re-search-forward (concat "\\[" id
"\\]\\([^:]\\|\\'\\)") nil t
)
2347 (skip-chars-backward "^]")
2350 (defun markdown-footnote-find-text (id)
2351 "Find the location of the text of footnote ID.
2352 The actual buffer position returned is the position of the first
2353 character of the text, after the footnote's identifier. If no
2354 footnote text is found, NIL is returned."
2356 (goto-char (point-min))
2357 (when (re-search-forward (concat "^\\[" id
"\\]:") nil t
)
2358 (skip-chars-forward "[ \t]")
2361 (defun markdown-footnote-marker-positions ()
2362 "Return the position and ID of the footnote marker point is on.
2363 The return value is a list (ID START END). If point is not on a
2364 footnote, NIL is returned."
2365 ;; first make sure we're at a footnote marker
2366 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars
"*\\]?") (line-beginning-position))
2367 (looking-at (concat "\\[?\\^" markdown-footnote-chars
"*?\\]")))
2369 ;; move point between [ and ^:
2370 (if (looking-at "\\[")
2372 (skip-chars-backward "^["))
2373 (looking-at (concat "\\(\\^" markdown-footnote-chars
"*?\\)\\]"))
2374 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2376 (defun markdown-footnote-text-positions ()
2377 "Return the start and end positions of the footnote text point is in.
2378 The exact return value is a list of three elements: (ID START END).
2379 The start position is the position of the opening bracket
2380 of the footnote id. The end position is directly after the
2381 newline that ends the footnote. If point is not in a footnote,
2382 NIL is returned instead."
2385 (backward-paragraph)
2386 ;; if we're in a multiparagraph footnote, we need to back up further
2387 (while (>= (markdown-next-line-indent) 4)
2388 (backward-paragraph))
2390 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars
"*?\\)\\]:"))
2391 (list (match-string 1) (point))))))
2395 (>= (markdown-next-line-indent) 4)))
2396 (append fn
(list (point)))))))
2399 ;;; Indentation ====================================================================
2401 (defun markdown-indent-find-next-position (cur-pos positions
)
2402 "Return the position after the index of CUR-POS in POSITIONS.
2403 Positions are calculated by `markdown-calc-indents'."
2404 (while (and positions
2405 (not (equal cur-pos
(car positions
))))
2406 (setq positions
(cdr positions
)))
2407 (or (cadr positions
) 0))
2409 (defun markdown-indent-line ()
2410 "Indent the current line using some heuristics.
2411 If the _previous_ command was either `markdown-enter-key' or
2412 `markdown-cycle', then we should cycle to the next
2413 reasonable indentation position. Otherwise, we could have been
2414 called directly by `markdown-enter-key', by an initial call of
2415 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2416 these cases, indent to the default position.
2417 Positions are calculated by `markdown-calc-indents'."
2419 (let ((positions (markdown-calc-indents))
2420 (cur-pos (current-column)))
2421 (if (not (equal this-command
'markdown-cycle
))
2422 (indent-line-to (car positions
))
2423 (setq positions
(sort (delete-dups positions
) '<))
2425 (markdown-indent-find-next-position cur-pos positions
)))))
2427 (defun markdown-calc-indents ()
2428 "Return a list of indentation columns to cycle through.
2429 The first element in the returned list should be considered the
2430 default indentation level. This function does not worry about
2431 duplicate positions, which are handled up by calling functions."
2432 (let (pos prev-line-pos positions
)
2434 ;; Indentation of previous line
2435 (setq prev-line-pos
(markdown-prev-line-indent))
2436 (setq positions
(cons prev-line-pos positions
))
2438 ;; Indentation of previous non-list-marker text
2439 (when (setq pos
(markdown-prev-non-list-indent))
2440 (setq positions
(cons pos positions
)))
2442 ;; Indentation required for a pre block in current context
2443 (setq pos
(length (markdown-pre-indentation (point))))
2444 (setq positions
(cons pos positions
))
2446 ;; Indentation of the previous line + tab-width
2448 (setq positions
(cons (+ prev-line-pos tab-width
) positions
))
2449 (setq positions
(cons tab-width positions
)))
2451 ;; Indentation of the previous line - tab-width
2452 (if (and prev-line-pos
(> prev-line-pos tab-width
))
2453 (setq positions
(cons (- prev-line-pos tab-width
) positions
)))
2455 ;; Indentation of all preceeding list markers (when in a list)
2456 (when (setq pos
(markdown-calculate-list-levels))
2457 (setq positions
(append pos positions
)))
2460 (setq positions
(cons 0 positions
))
2462 ;; Return reversed list
2463 (reverse positions
)))
2465 (defun markdown-do-normal-return ()
2466 "Insert a newline and optionally indent the next line."
2468 (if markdown-indent-on-enter
2469 (funcall indent-line-function
)))
2471 (defun markdown-enter-key ()
2472 "Handle RET according to context.
2473 If there is a wiki link at the point, follow it unless
2474 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2475 it in the usual way."
2477 (if (and markdown-follow-wiki-link-on-enter
(markdown-wiki-link-p))
2478 (markdown-follow-wiki-link-at-point)
2479 (markdown-do-normal-return)))
2481 (defun markdown-dedent-or-delete (arg)
2482 "Handle BACKSPACE by cycling through indentation points.
2483 When BACKSPACE is pressed, if there is only whitespace
2484 before the current point, then dedent the line one level.
2485 Otherwise, do normal delete by repeating
2486 `backward-delete-char-untabify' ARG times."
2488 (let ((cur-pos (current-column))
2489 (start-of-indention (save-excursion
2490 (back-to-indentation)
2492 (if (and (> cur-pos
0) (= cur-pos start-of-indention
))
2494 (dolist (i (markdown-calc-indents))
2496 (setq result
(max result i
))))
2497 (indent-line-to result
))
2498 (backward-delete-char-untabify arg
))))
2501 ;;; Markup Completion =========================================================
2503 (defconst markdown-complete-alist
2504 '((markdown-regex-header-atx . markdown-complete-atx
)
2505 (markdown-regex-header-setext . markdown-complete-setext
)
2506 (markdown-regex-hr . markdown-complete-hr
))
2507 "Association list of form (regexp . function) for markup completion.")
2509 (defun markdown-incomplete-atx-p ()
2510 "Return t if ATX header markup is incomplete and nil otherwise.
2511 Assumes match data is available for `markdown-regex-header-atx'.
2512 Checks that the number of trailing hash marks equals the number of leading
2513 hash marks, that there is only a single space before and after the text,
2514 and that there is no extraneous whitespace in the text."
2516 (or (not (= (length (match-string 1)) (length (match-string 3))))
2517 (not (= (match-beginning 2) (1+ (match-end 1))))
2518 (not (= (match-beginning 3) (1+ (match-end 2))))
2519 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2521 (defun markdown-complete-atx ()
2522 "Complete and normalize ATX headers.
2523 Add or remove hash marks to the end of the header to match the
2524 beginning. Ensure that there is only a single space between hash
2525 marks and header text. Removes extraneous whitespace from header text.
2526 Assumes match data is available for `markdown-regex-header-atx'."
2527 (when (markdown-incomplete-atx-p)
2528 (let* ((new-marker (make-marker))
2529 (new-marker (set-marker new-marker
(match-end 2))))
2530 ;; Hash marks and spacing at end
2531 (goto-char (match-end 2))
2532 (delete-region (match-end 2) (match-end 3))
2533 (insert " " (match-string 1))
2534 ;; Remove extraneous whitespace from title
2535 (replace-match (markdown-compress-whitespace-string (match-string 2))
2537 ;; Spacing at beginning
2538 (goto-char (match-end 1))
2539 (delete-region (match-end 1) (match-beginning 2))
2541 ;; Leave point at end of text
2542 (goto-char new-marker
))))
2544 (defun markdown-incomplete-setext-p ()
2545 "Return t if setext header markup is incomplete and nil otherwise.
2546 Assumes match data is available for `markdown-regex-header-setext'.
2547 Checks that length of underline matches text and that there is no
2548 extraneous whitespace in the text."
2550 (or (not (= (length (match-string 1)) (length (match-string 2))))
2551 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2553 (defun markdown-complete-setext ()
2554 "Complete and normalize setext headers.
2555 Add or remove underline characters to match length of header
2556 text. Removes extraneous whitespace from header text. Assumes
2557 match data is available for `markdown-regex-header-setext'."
2558 (when (markdown-incomplete-setext-p)
2559 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2560 (char (char-after (match-beginning 2)))
2561 (level (if (char-equal char ?-
) 2 1)))
2562 (goto-char (match-beginning 0))
2563 (delete-region (match-beginning 0) (match-end 0))
2564 (markdown-insert-header level text t
))))
2566 (defun markdown-incomplete-hr-p ()
2567 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2568 Assumes match data is available for `markdown-regex-hr'."
2569 (not (member (match-string 0) markdown-hr-strings
)))
2571 (defun markdown-complete-hr ()
2572 "Complete horizontal rules.
2573 If horizontal rule string is a member of `markdown-hr-strings',
2574 do nothing. Otherwise, replace with the car of
2575 `markdown-hr-strings'.
2576 Assumes match data is available for `markdown-regex-hr'."
2577 (replace-match (car markdown-hr-strings
)))
2579 (defun markdown-complete ()
2580 "Complete markup of object near point or in region when active.
2581 Handle all objects in `markdown-complete-alist', in order.
2582 See `markdown-complete-at-point' and `markdown-complete-region'."
2584 (if (markdown-use-region-p)
2585 (markdown-complete-region (region-beginning) (region-end))
2586 (markdown-complete-at-point)))
2588 (defun markdown-complete-at-point ()
2589 "Complete markup of object near point.
2590 Handle all objects in `markdown-complete-alist', in
2593 (loop for
(regexp . function
) in markdown-complete-alist
2594 until
(thing-at-point-looking-at (eval regexp
))
2595 finally
(funcall function
)))
2597 (defun markdown-complete-region (beg end
)
2598 "Complete markup of object near point.
2599 Handle all objects in `markdown-complete-alist', in
2602 (let* ((end-marker (make-marker))
2603 (end-marker (set-marker end-marker end
)))
2604 (loop for
(regexp . function
) in markdown-complete-alist
2607 (while (re-search-forward (eval regexp
) end-marker t
)
2608 (funcall function
))))))
2610 (defun markdown-complete-buffer ()
2611 "Complete markup for all objects in the current buffer."
2613 (markdown-complete-region (point-min) (point-max)))
2616 ;;; Markup Cycling ============================================================
2618 (defun markdown-cycle-atx (arg &optional remove
)
2619 "Cycle ATX header markup.
2620 Promote header (decrease level) when ARG is 1 and demote
2621 header (increase level) if arg is -1. When REMOVE is non-nil,
2622 remove the header when the level reaches zero and stop cycling
2623 when it reaches six. Otherwise, perform a proper cycling through
2624 levels one through six. Assumes match data is available for
2625 `markdown-regex-header-atx'."
2626 (let* ((old-level (length (match-string 1)))
2627 (new-level (+ old-level arg
))
2628 (text (match-string 2)))
2630 (setq new-level
(% new-level
6))
2631 (setq new-level
(cond ((= new-level
0) 6)
2632 ((< new-level
0) (+ new-level
6))
2636 (markdown-unwrap-thing-at-point nil
0 2))
2638 (goto-char (match-beginning 0))
2639 (delete-region (match-beginning 0) (match-end 0))
2640 (markdown-insert-header new-level text nil
)))))
2642 (defun markdown-cycle-setext (arg &optional remove
)
2643 "Cycle setext header markup.
2644 Promote header (increase level) when ARG is 1 and demote
2645 header (decrease level or remove) if arg is -1. When demoting a
2646 level-two setext header, replace with a level-three atx header.
2647 When REMOVE is non-nil, remove the header when the level reaches
2648 zero. Otherwise, cycle back to a level six atx header. Assumes
2649 match data is available for `markdown-regex-header-setext'."
2650 (let* ((char (char-after (match-beginning 2)))
2651 (old-level (if (char-equal char ?
=) 1 2))
2652 (new-level (+ old-level arg
))
2653 (text (match-string 1)))
2654 (when (and (not remove
) (= new-level
0))
2658 (markdown-unwrap-thing-at-point nil
0 1))
2660 (markdown-insert-header new-level nil t
))
2662 (markdown-insert-header new-level nil nil
)))))
2664 (defun markdown-cycle-hr (arg &optional remove
)
2665 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2666 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2667 backwards (demote). When REMOVE is non-nil, remove the hr instead
2668 of cycling when the end of the list is reached.
2669 Assumes match data is available for `markdown-regex-hr'."
2670 (let* ((strings (if (= arg
1)
2671 (reverse markdown-hr-strings
)
2672 markdown-hr-strings
))
2673 (tail (member (match-string 0) strings
))
2674 (new (or (cadr tail
)
2680 (replace-match new
)))
2682 (defun markdown-cycle-bold ()
2683 "Cycle bold markup between underscores and asterisks.
2684 Assumes match data is available for `markdown-regex-bold'."
2686 (let* ((old-delim (match-string 3))
2687 (new-delim (if (string-equal old-delim
"**") "__" "**")))
2688 (replace-match new-delim t t nil
3)
2689 (replace-match new-delim t t nil
5))))
2691 (defun markdown-cycle-italic ()
2692 "Cycle italic markup between underscores and asterisks.
2693 Assumes match data is available for `markdown-regex-italic'."
2695 (let* ((old-delim (match-string 3))
2696 (new-delim (if (string-equal old-delim
"*") "_" "*")))
2697 (replace-match new-delim t t nil
3)
2698 (replace-match new-delim t t nil
5))))
2701 ;;; Keymap ====================================================================
2703 (defvar markdown-mode-map
2704 (let ((map (make-keymap)))
2705 ;; Element insertion
2706 (define-key map
"\C-c\C-al" 'markdown-insert-link
)
2707 (define-key map
"\C-c\C-ar" 'markdown-insert-reference-link-dwim
)
2708 (define-key map
"\C-c\C-aw" 'markdown-insert-wiki-link
)
2709 (define-key map
"\C-c\C-ii" 'markdown-insert-image
)
2710 (define-key map
"\C-c\C-t0" 'markdown-remove-header
)
2711 (define-key map
"\C-c\C-t1" 'markdown-insert-header-atx-1
)
2712 (define-key map
"\C-c\C-t2" 'markdown-insert-header-atx-2
)
2713 (define-key map
"\C-c\C-t3" 'markdown-insert-header-atx-3
)
2714 (define-key map
"\C-c\C-t4" 'markdown-insert-header-atx-4
)
2715 (define-key map
"\C-c\C-t5" 'markdown-insert-header-atx-5
)
2716 (define-key map
"\C-c\C-t6" 'markdown-insert-header-atx-6
)
2717 (define-key map
"\C-c\C-th" 'markdown-insert-header-dwim
)
2718 (define-key map
"\C-c\C-pb" 'markdown-insert-bold
)
2719 (define-key map
"\C-c\C-ss" 'markdown-insert-bold
)
2720 (define-key map
"\C-c\C-pi" 'markdown-insert-italic
)
2721 (define-key map
"\C-c\C-se" 'markdown-insert-italic
)
2722 (define-key map
"\C-c\C-pf" 'markdown-insert-code
)
2723 (define-key map
"\C-c\C-sc" 'markdown-insert-code
)
2724 (define-key map
"\C-c\C-sb" 'markdown-insert-blockquote
)
2725 (define-key map
"\C-c\C-s\C-b" 'markdown-blockquote-region
)
2726 (define-key map
"\C-c\C-sp" 'markdown-insert-pre
)
2727 (define-key map
"\C-c\C-s\C-p" 'markdown-pre-region
)
2728 (define-key map
"\C-c-" 'markdown-insert-hr
)
2729 (define-key map
"\C-c\C-tt" 'markdown-insert-header-setext-1
)
2730 (define-key map
"\C-c\C-ts" 'markdown-insert-header-setext-2
)
2732 (define-key map
"\C-c\C-fn" 'markdown-footnote-new
)
2733 (define-key map
"\C-c\C-fg" 'markdown-footnote-goto-text
)
2734 (define-key map
"\C-c\C-fb" 'markdown-footnote-return
)
2735 (define-key map
"\C-c\C-fk" 'markdown-footnote-kill
)
2736 ;; Promotion, Demotion, Completion, and Cycling
2737 (define-key map
(kbd "M-<left>") 'markdown-promote
)
2738 (define-key map
(kbd "M-<right>") 'markdown-demote
)
2739 (define-key map
(kbd "C-c C-l") 'markdown-promote
)
2740 (define-key map
(kbd "C-c C-r") 'markdown-demote
)
2741 (define-key map
(kbd "C-c C-=") 'markdown-complete-or-cycle
)
2742 (define-key map
(kbd "C-c C-c =") 'markdown-complete-buffer
)
2743 ;; Following and Jumping
2744 (define-key map
"\C-c\C-o" 'markdown-follow-thing-at-point
)
2745 (define-key map
"\C-c\C-j" 'markdown-jump
)
2747 (define-key map
"\C-m" 'markdown-enter-key
)
2748 (define-key map
(kbd "<backspace>") 'markdown-dedent-or-delete
)
2749 ;; Visibility cycling
2750 (define-key map
(kbd "<tab>") 'markdown-cycle
)
2751 (define-key map
(kbd "<S-iso-lefttab>") 'markdown-shifttab
)
2752 (define-key map
(kbd "<S-tab>") 'markdown-shifttab
)
2753 (define-key map
(kbd "<backtab>") 'markdown-shifttab
)
2754 ;; Header navigation
2755 (define-key map
(kbd "C-M-n") 'outline-next-visible-heading
)
2756 (define-key map
(kbd "C-M-p") 'outline-previous-visible-heading
)
2757 (define-key map
(kbd "C-M-f") 'outline-forward-same-level
)
2758 (define-key map
(kbd "C-M-b") 'outline-backward-same-level
)
2759 (define-key map
(kbd "C-M-u") 'outline-up-heading
)
2760 ;; Markdown functions
2761 (define-key map
"\C-c\C-cm" 'markdown-other-window
)
2762 (define-key map
"\C-c\C-cp" 'markdown-preview
)
2763 (define-key map
"\C-c\C-ce" 'markdown-export
)
2764 (define-key map
"\C-c\C-cv" 'markdown-export-and-preview
)
2765 (define-key map
"\C-c\C-co" 'markdown-open
)
2766 (define-key map
"\C-c\C-cw" 'markdown-kill-ring-save
)
2768 (define-key map
"\C-c\C-cc" 'markdown-check-refs
)
2770 (define-key map
"\C-c\C-cn" 'markdown-cleanup-list-numbers
)
2771 (define-key map
(kbd "M-<up>") 'markdown-move-up
)
2772 (define-key map
(kbd "M-<down>") 'markdown-move-down
)
2773 (define-key map
(kbd "M-<return>") 'markdown-insert-list-item
)
2775 (define-key map
(kbd "M-[") 'markdown-beginning-of-block
)
2776 (define-key map
(kbd "M-]") 'markdown-end-of-block
)
2777 (define-key map
(kbd "M-n") 'markdown-next-link
)
2778 (define-key map
(kbd "M-p") 'markdown-previous-link
)
2780 "Keymap for Markdown major mode.")
2782 (defvar gfm-mode-map
2783 (let ((map (make-sparse-keymap)))
2784 (set-keymap-parent map markdown-mode-map
)
2785 (define-key map
"\C-c\C-sl" 'markdown-insert-gfm-code-block
)
2787 "Keymap for `gfm-mode'.
2788 See also `markdown-mode-map'.")
2791 ;;; Menu ==================================================================
2793 (easy-menu-define markdown-mode-menu markdown-mode-map
2794 "Menu for Markdown mode"
2797 ["Cycle visibility" markdown-cycle
(outline-on-heading-p)]
2798 ["Cycle global visibility" markdown-shifttab
])
2800 ["Compile" markdown-other-window
]
2801 ["Preview" markdown-preview
]
2802 ["Export" markdown-export
]
2803 ["Export & View" markdown-export-and-preview
]
2804 ["Open" markdown-open
]
2805 ["Kill ring save" markdown-kill-ring-save
]
2808 ["First level" markdown-insert-setext-header-1
]
2809 ["Second level" markdown-insert-setext-header-2
])
2811 ["First level" markdown-insert-header-atx-1
]
2812 ["Second level" markdown-insert-header-atx-2
]
2813 ["Third level" markdown-insert-header-atx-3
]
2814 ["Fourth level" markdown-insert-header-atx-4
]
2815 ["Fifth level" markdown-insert-header-atx-5
]
2816 ["Sixth level" markdown-insert-header-atx-6
])
2818 ["Bold" markdown-insert-bold
]
2819 ["Italic" markdown-insert-italic
]
2820 ["Blockquote" markdown-insert-blockquote
]
2821 ["Preformatted" markdown-insert-pre
]
2822 ["Code" markdown-insert-code
]
2824 ["Insert inline link" markdown-insert-link
]
2825 ["Insert reference link" markdown-insert-reference-link-dwim
]
2826 ["Insert image" markdown-insert-image
]
2827 ["Insert horizontal rule" markdown-insert-hr
]
2830 ["Insert footnote" markdown-footnote-new
]
2831 ["Jump to footnote text" markdown-footnote-goto-text
]
2832 ["Return from footnote" markdown-footnote-return
])
2834 ["Check references" markdown-check-refs
]
2835 ["Clean up list numbering" markdown-cleanup-list-numbers
]
2837 ["Version" markdown-show-version
]
2841 ;;; imenu =====================================================================
2843 (defun markdown-imenu-create-index ()
2844 "Create and return an imenu index alist for the current buffer.
2845 See `imenu-create-index-function' and `imenu--index-alist' for details."
2846 (let* ((root '(nil . nil
))
2851 hashes pos level heading
)
2853 (goto-char (point-min))
2854 (while (re-search-forward markdown-regex-header
(point-max) t
)
2856 ((setq heading
(match-string-no-properties 1))
2857 (setq pos
(match-beginning 1)
2859 ((setq heading
(match-string-no-properties 3))
2860 (setq pos
(match-beginning 3)
2862 ((setq hashes
(match-string-no-properties 5))
2863 (setq heading
(match-string-no-properties 6)
2864 pos
(match-beginning 5)
2865 level
(length hashes
))))
2866 (let ((alist (list (cons heading pos
))))
2868 ((= cur-level level
) ; new sibling
2869 (setcdr cur-alist alist
)
2870 (setq cur-alist alist
))
2871 ((< cur-level level
) ; first child
2872 (dotimes (i (- level cur-level
1))
2873 (setq alist
(list (cons empty-heading alist
))))
2875 (let* ((parent (car cur-alist
))
2876 (self-pos (cdr parent
)))
2877 (setcdr parent
(cons (cons self-heading self-pos
) alist
)))
2878 (setcdr root alist
)) ; primogenitor
2879 (setq cur-alist alist
)
2880 (setq cur-level level
))
2881 (t ; new sibling of an ancestor
2882 (let ((sibling-alist (last (cdr root
))))
2883 (dotimes (i (1- level
))
2884 (setq sibling-alist
(last (cdar sibling-alist
))))
2885 (setcdr sibling-alist alist
)
2886 (setq cur-alist alist
))
2887 (setq cur-level level
)))))
2891 ;;; References ================================================================
2893 (defun markdown-insert-reference-definition (ref &optional buffer
)
2894 "Add blank REF definition to the end of BUFFER.
2895 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
2896 (or buffer
(setq buffer
(current-buffer)))
2897 (with-current-buffer buffer
2898 (goto-char (point-max))
2899 (indent-new-comment-line)
2900 (insert (concat ref
": "))))
2902 (defun markdown-reference-goto-definition ()
2903 "Jump to the definition of the reference at point or create it."
2905 (when (thing-at-point-looking-at markdown-regex-link-reference
)
2906 (let* ((label (match-string-no-properties 1))
2907 (reference (match-string-no-properties 2))
2908 (target (downcase (if (string= reference
"[]") label reference
)))
2909 (loc (cadr (markdown-reference-definition target
))))
2912 (markdown-insert-reference-definition reference
(current-buffer))))))
2914 (defun markdown-reference-find-links (reference)
2915 "Return a list of all links for REFERENCE.
2916 REFERENCE should include the surrounding square brackets like [this].
2917 Elements of the list have the form (text start line), where
2918 text is the link text, start is the location at the beginning of
2919 the link, and line is the line number on which the link appears."
2920 (let* ((ref-quote (regexp-quote (substring reference
1 -
1)))
2921 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
2922 ref-quote ref-quote
))
2925 (goto-char (point-min))
2926 (while (re-search-forward regexp nil t
)
2927 (let* ((text (or (match-string-no-properties 1)
2928 (match-string-no-properties 2)))
2929 (start (match-beginning 0))
2930 (line (markdown-line-number-at-pos)))
2931 (add-to-list 'links
(list text start line
)))))
2934 (defun markdown-get-undefined-refs ()
2935 "Return a list of undefined Markdown references.
2936 Result is an alist of pairs (reference . occurrences), where
2937 occurrences is itself another alist of pairs (label . line-number).
2938 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2939 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2940 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2943 (goto-char (point-min))
2945 (re-search-forward markdown-regex-link-reference nil t
)
2946 (let* ((label (match-string-no-properties 1))
2947 (reference (match-string-no-properties 2))
2948 (target (downcase (if (string= reference
"[]") label reference
))))
2949 (unless (markdown-reference-definition target
)
2950 (let ((entry (assoc target missing
)))
2952 (add-to-list 'missing
(cons target
2953 (list (cons label
(markdown-line-number-at-pos)))) t
)
2955 (append (cdr entry
) (list (cons label
(markdown-line-number-at-pos))))))))))
2958 (defconst markdown-reference-check-buffer
2959 "*Undefined references for %buffer%*"
2960 "Pattern for name of buffer for listing undefined references.
2961 The string %buffer% will be replaced by the corresponding
2962 `markdown-mode' buffer name.")
2964 (defun markdown-reference-check-buffer (&optional buffer-name
)
2965 "Name and return buffer for reference checking."
2966 (or buffer-name
(setq buffer-name
(buffer-name)))
2967 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
2968 "%buffer%" buffer-name
2969 markdown-reference-check-buffer
))))
2970 (with-current-buffer refbuf
2972 (View-exit-and-edit))
2973 (use-local-map button-buffer-map
)
2977 (defconst markdown-reference-links-buffer
2978 "*Reference links for %buffer%*"
2979 "Pattern for name of buffer for listing references.
2980 The string %buffer% will be replaced by the corresponding buffer name.")
2982 (defun markdown-reference-links-buffer (&optional buffer-name
)
2983 "Name, setup, and return a buffer for listing links."
2984 (or buffer-name
(setq buffer-name
(buffer-name)))
2985 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
2986 "%buffer%" buffer-name
2987 markdown-reference-links-buffer
))))
2988 (with-current-buffer linkbuf
2990 (View-exit-and-edit))
2991 (use-local-map button-buffer-map
)
2995 (when (markdown-use-buttons-p)
2996 ;; Add an empty Markdown reference definition to the end of buffer
2997 ;; specified in the 'target-buffer property. The reference name is
2998 ;; the button's label.
2999 (define-button-type 'markdown-undefined-reference-button
3000 'help-echo
"mouse-1, RET: create definition for undefined reference"
3004 (let ((buffer (button-get b
'target-buffer
)))
3005 (markdown-insert-reference-definition (button-label b
) buffer
)
3006 (switch-to-buffer-other-window buffer
)
3007 (goto-char (point-max))
3008 (markdown-check-refs t
))))
3010 ;; Jump to line in buffer specified by 'target-buffer property.
3011 ;; Line number is button's 'line property.
3012 (define-button-type 'markdown-goto-line-button
3013 'help-echo
"mouse-1, RET: go to line"
3017 (message (button-get b
'buffer
))
3018 (switch-to-buffer-other-window (button-get b
'target-buffer
))
3019 ;; use call-interactively to silence compiler
3020 (let ((current-prefix-arg (button-get b
'target-line
)))
3021 (call-interactively 'goto-line
))))
3023 ;; Jumps to a particular link at location given by 'target-char
3024 ;; property in buffer given by 'target-buffer property.
3025 (define-button-type 'markdown-link-button
3026 'help-echo
"mouse-1, RET: jump to location of link"
3030 (let ((target (button-get b
'target-buffer
))
3031 (loc (button-get b
'target-char
)))
3032 (kill-buffer-and-window)
3033 (switch-to-buffer target
)
3036 (defun markdown-insert-undefined-reference-button (reference oldbuf
)
3037 "Insert a button for creating REFERENCE in buffer OLDBUF.
3038 REFERENCE should be a list of the form (reference . occurrences),
3039 as by `markdown-get-undefined-refs'."
3040 (let ((label (car reference
)))
3041 (if (markdown-use-buttons-p)
3042 ;; Create a reference button in Emacs 22
3043 (insert-button label
3044 :type
'markdown-undefined-reference-button
3045 'target-buffer oldbuf
)
3046 ;; Insert reference as text in Emacs < 22
3049 (dolist (occurrence (cdr reference
))
3050 (let ((line (cdr occurrence
)))
3051 (if (markdown-use-buttons-p)
3052 ;; Create a line number button in Emacs 22
3053 (insert-button (number-to-string line
)
3054 :type
'markdown-goto-line-button
3055 'target-buffer oldbuf
3057 ;; Insert line number as text in Emacs < 22
3058 (insert (number-to-string line
)))
3064 (defun markdown-insert-link-button (link oldbuf
)
3065 "Insert a button for jumping to LINK in buffer OLDBUF.
3066 LINK should be a list of the form (text char line) containing
3067 the link text, location, and line number."
3068 (let ((label (first link
))
3069 (char (second link
))
3070 (line (third link
)))
3071 (if (markdown-use-buttons-p)
3072 ;; Create a reference button in Emacs 22
3073 (insert-button label
3074 :type
'markdown-link-button
3075 'target-buffer oldbuf
3077 ;; Insert reference as text in Emacs < 22
3079 (insert (format " (line %d)\n" line
))))
3081 (defun markdown-reference-goto-link (&optional reference
)
3082 "Jump to the location of the first use of reference."
3085 (if (thing-at-point-looking-at markdown-regex-reference-definition
)
3086 (setq reference
(match-string-no-properties 1))
3087 (error "No reference definition at point.")))
3088 (let ((links (markdown-reference-find-links reference
)))
3089 (cond ((= (length links
) 1)
3090 (goto-char (cadr (car links
))))
3091 ((> (length links
) 1)
3092 (let ((oldbuf (current-buffer))
3093 (linkbuf (markdown-reference-links-buffer)))
3094 (with-current-buffer linkbuf
3095 (insert "Links using reference " reference
":\n\n")
3096 (dolist (link (reverse links
))
3097 (markdown-insert-link-button link oldbuf
)))
3098 (view-buffer-other-window linkbuf
)
3099 (goto-char (point-min))
3102 (error "No links for reference %s" reference
)))))
3104 (defun markdown-check-refs (&optional silent
)
3105 "Show all undefined Markdown references in current `markdown-mode' buffer.
3106 If SILENT is non-nil, do not message anything when no undefined
3108 Links which have empty reference definitions are considered to be
3111 (when (not (eq major-mode
'markdown-mode
))
3112 (error "Not available in current mode"))
3113 (let ((oldbuf (current-buffer))
3114 (refs (markdown-get-undefined-refs))
3115 (refbuf (markdown-reference-check-buffer)))
3119 (message "No undefined references found"))
3120 (kill-buffer refbuf
))
3121 (with-current-buffer refbuf
3122 (insert "The following references are undefined:\n\n")
3124 (markdown-insert-undefined-reference-button ref oldbuf
))
3125 (view-buffer-other-window refbuf
)
3126 (goto-char (point-min))
3127 (forward-line 2)))))
3130 ;;; Lists =====================================================================
3132 (defun markdown-insert-list-item (&optional arg
)
3133 "Insert a new list item.
3134 If the point is inside unordered list, insert a bullet mark. If
3135 the point is inside ordered list, insert the next number followed
3136 by a period. Use the previous list item to determine the amount
3137 of whitespace to place before and after list markers.
3139 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3140 decrease the indentation by one level.
3142 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3143 increase the indentation by one level."
3145 (let (bounds item-indent marker indent new-indent end
)
3147 (setq bounds
(markdown-cur-list-item-bounds))
3149 ;; When not in a list, start a new unordered one
3151 (unless (markdown-cur-line-blank-p)
3154 ;; Compute indentation for a new list item
3155 (setq item-indent
(nth 2 bounds
))
3156 (setq marker
(concat (match-string 2) (match-string 3)))
3158 ((= arg
4) (max (- item-indent
4) 0))
3159 ((= arg
16) (+ item-indent
4))
3161 (setq new-indent
(make-string indent
32))
3162 (goto-char (nth 1 bounds
))
3166 ((string-match "[0-9]" marker
)
3167 (if (= arg
16) ;; starting a new column indented one more level
3168 (insert (concat new-indent
"1. "))
3169 ;; travel up to the last item and pick the correct number. If
3170 ;; the argument was nil, "new-indent = item-indent" is the same,
3171 ;; so we don't need special treatment. Neat.
3173 (while (not (looking-at (concat new-indent
"\\([0-9]+\\)\\.")))
3175 (insert (concat new-indent
3176 (int-to-string (1+ (string-to-number (match-string 1))))
3179 ((string-match "[\\*\\+-]" marker
)
3180 (insert (concat new-indent marker
))))))))
3182 (defun markdown-move-list-item-up ()
3183 "Move the current list item up in the list when possible."
3186 (when (setq cur
(markdown-cur-list-item-bounds))
3188 (goto-char (nth 0 cur
))
3189 (if (markdown-prev-list-item (nth 3 cur
))
3191 (setq prev
(markdown-cur-list-item-bounds))
3194 (transpose-regions (nth 0 prev
) (nth 1 prev
)
3195 (nth 0 cur
) (nth 1 cur
) t
)
3196 (goto-char (+ (nth 0 prev
) (- old
(nth 0 cur
)))))
3197 ;; Catch error in case regions overlap.
3198 (error (goto-char old
))))
3201 (defun markdown-move-list-item-down ()
3202 "Move the current list item down in the list when possible."
3205 (when (setq cur
(markdown-cur-list-item-bounds))
3207 (if (markdown-next-list-item (nth 3 cur
))
3209 (setq next
(markdown-cur-list-item-bounds))
3212 (transpose-regions (nth 0 cur
) (nth 1 cur
)
3213 (nth 0 next
) (nth 1 next
) nil
)
3214 (goto-char (+ old
(- (nth 1 next
) (nth 1 cur
)))))
3215 ;; Catch error in case regions overlap.
3216 (error (goto-char old
))))
3219 (defun markdown-demote-list-item (&optional bounds
)
3220 "Indent (or demote) the current list item.
3221 Optionally, BOUNDS of the current list item may be provided if available."
3223 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3226 (let* ((end-marker (make-marker))
3227 (end-marker (set-marker end-marker
(nth 1 bounds
))))
3228 (goto-char (nth 0 bounds
))
3229 (while (< (point) end-marker
)
3230 (unless (markdown-cur-line-blank-p)
3232 (forward-line)))))))
3234 (defun markdown-promote-list-item (&optional bounds
)
3235 "Unindent (or promote) the current list item.
3236 Optionally, BOUNDS of the current list item may be provided if available."
3238 (when (or bounds
(setq bounds
(markdown-cur-list-item-bounds)))
3241 (let* ((end-marker (make-marker))
3242 (end-marker (set-marker end-marker
(nth 1 bounds
)))
3244 (goto-char (nth 0 bounds
))
3245 (when (looking-at "^[ ]\\{1,4\\}")
3246 (setq num
(- (match-end 0) (match-beginning 0)))
3247 (setq regexp
(format "^[ ]\\{1,%d\\}" num
))
3248 (while (and (< (point) end-marker
)
3249 (re-search-forward regexp end-marker t
))
3250 (replace-match "" nil nil
)
3251 (forward-line))))))))
3253 (defun markdown--cleanup-list-numbers-level (&optional pfx
)
3254 "Update the numbering for level PFX (as a string of spaces).
3256 Assume that the previously found match was for a numbered item in
3263 (while (and continue
(not (eobp)))
3266 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3267 (setq cpfx
(match-string-no-properties 1))
3271 (concat pfx
(number-to-string (setq idx
(1+ idx
))) ". "))
3275 (setq sep
(markdown--cleanup-list-numbers-level cpfx
))
3280 (setq continue nil
))))
3282 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3283 (setq cpfx
(match-string-no-properties 1))
3285 ;; reset if separated before
3286 ((string= cpfx pfx
) (when sep
(setq idx
0)))
3289 (setq continue nil
))))
3294 (setq continue
(= (forward-line) 0))))
3297 (defun markdown-cleanup-list-numbers ()
3298 "Update the numbering of ordered lists."
3301 (goto-char (point-min))
3302 (markdown--cleanup-list-numbers-level "")))
3305 ;;; Outline ===================================================================
3307 (defvar markdown-cycle-global-status
1)
3308 (defvar markdown-cycle-subtree-status nil
)
3310 (defun markdown-end-of-subtree (&optional invisible-OK
)
3311 "Move to the end of the current subtree.
3312 Only visible heading lines are considered, unless INVISIBLE-OK is
3314 Derived from `org-end-of-subtree'."
3315 (outline-back-to-heading invisible-OK
)
3317 (level (funcall outline-level
)))
3318 (while (and (not (eobp))
3319 (or first
(> (funcall outline-level
) level
)))
3321 (outline-next-heading))
3322 (if (memq (preceding-char) '(?
\n ?\^M
))
3324 ;; Go to end of line before heading
3326 (if (memq (preceding-char) '(?
\n ?\^M
))
3327 ;; leave blank line before heading
3328 (forward-char -
1)))))
3331 (defun markdown-cycle (&optional arg
)
3332 "Visibility cycling for Markdown mode.
3333 If ARG is t, perform global visibility cycling. If the point is
3334 at an atx-style header, cycle visibility of the corresponding
3335 subtree. Otherwise, insert a tab using `indent-relative'.
3336 Derived from `org-cycle'."
3339 ((eq arg t
) ;; Global cycling
3341 ((and (eq last-command this-command
)
3342 (eq markdown-cycle-global-status
2))
3343 ;; Move from overview to contents
3345 (message "CONTENTS")
3346 (setq markdown-cycle-global-status
3))
3348 ((and (eq last-command this-command
)
3349 (eq markdown-cycle-global-status
3))
3350 ;; Move from contents to all
3352 (message "SHOW ALL")
3353 (setq markdown-cycle-global-status
1))
3356 ;; Defaults to overview
3358 (message "OVERVIEW")
3359 (setq markdown-cycle-global-status
2))))
3361 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp
))
3362 ;; At a heading: rotate between three different views
3363 (outline-back-to-heading)
3364 (let ((goal-column 0) eoh eol eos
)
3365 ;; Determine boundaries
3367 (outline-back-to-heading)
3369 (beginning-of-line 2)
3370 (while (and (not (eobp)) ;; this is like `next-line'
3371 (get-char-property (1- (point)) 'invisible
))
3372 (beginning-of-line 2)) (setq eol
(point)))
3373 (outline-end-of-heading) (setq eoh
(point))
3374 (markdown-end-of-subtree t
)
3375 (skip-chars-forward " \t\n")
3376 (beginning-of-line 1) ; in case this is an item
3377 (setq eos
(1- (point))))
3378 ;; Find out what to do next and set `this-command'
3381 ;; Nothing is hidden behind this heading
3382 (message "EMPTY ENTRY")
3383 (setq markdown-cycle-subtree-status nil
))
3385 ;; Entire subtree is hidden in one line: open it
3388 (message "CHILDREN")
3389 (setq markdown-cycle-subtree-status
'children
))
3390 ((and (eq last-command this-command
)
3391 (eq markdown-cycle-subtree-status
'children
))
3392 ;; We just showed the children, now show everything.
3395 (setq markdown-cycle-subtree-status
'subtree
))
3397 ;; Default action: hide the subtree.
3400 (setq markdown-cycle-subtree-status
'folded
)))))
3403 (indent-for-tab-command))))
3405 (defun markdown-shifttab ()
3406 "Global visibility cycling.
3407 Calls `markdown-cycle' with argument t."
3411 (defun markdown-outline-level ()
3412 "Return the depth to which a statement is nested in the outline."
3416 ((- (match-end 5) (match-beginning 5)))))
3419 ;;; Movement ==================================================================
3421 (defun markdown-beginning-of-defun (&optional arg
)
3422 "`beginning-of-defun-function' for Markdown.
3423 Move backward to the beginning of the current or previous section."
3425 (or arg
(setq arg
1))
3426 (or (re-search-backward markdown-regex-header nil t arg
)
3427 (goto-char (point-min))))
3429 (defun markdown-end-of-defun (&optional arg
)
3430 "`end-of-defun-function' for Markdown.
3431 Move forward to the end of the current or following section."
3433 (or arg
(setq arg
1))
3434 (when (looking-at markdown-regex-header
)
3435 (goto-char (match-beginning 0))
3437 (if (re-search-forward markdown-regex-header nil t arg
)
3438 (goto-char (match-beginning 0))
3439 (goto-char (point-max)))
3440 (skip-syntax-backward "-"))
3442 (defun markdown-beginning-of-block ()
3443 "Move the point to the start of the previous text block."
3445 (if (re-search-backward markdown-regex-block-separator nil t
)
3446 (goto-char (or (match-end 2) (match-end 0)))
3447 (goto-char (point-min))))
3449 (defun markdown-end-of-block ()
3450 "Move the point to the start of the next text block."
3453 (skip-syntax-forward "-")
3454 (when (= (point) (point-min))
3456 (if (re-search-forward markdown-regex-block-separator nil t
)
3457 (goto-char (or (match-end 2) (match-end 0)))
3458 (goto-char (point-max)))
3459 (skip-syntax-backward "-")
3462 (defun markdown-end-of-block-element ()
3463 "Move the point to the start of the next block unit.
3464 Stops at blank lines, list items, headers, and horizontal rules."
3467 (while (and (or (not (markdown-prev-line-blank-p))
3468 (markdown-cur-line-blank-p))
3469 (not (or (looking-at markdown-regex-list
)
3470 (looking-at markdown-regex-header
)
3471 (looking-at markdown-regex-hr
)))
3475 (defun markdown-next-link ()
3476 "Jump to next inline, reference, or wiki link.
3477 If successful, return point. Otherwise, return nil.
3478 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3480 (let ((opoint (point)))
3481 (when (or (markdown-link-p) (markdown-wiki-link-p))
3482 ;; At a link already, move past it.
3483 (goto-char (+ (match-end 0) 1)))
3484 ;; Search for the next wiki link and move to the beginning.
3485 (if (re-search-forward markdown-regex-link-generic nil t
)
3486 ;; Group 1 will move past non-escape character in wiki link regexp.
3487 ;; Go to beginning of group zero for all other link types.
3488 (goto-char (or (match-beginning 1) (match-beginning 0)))
3492 (defun markdown-previous-link ()
3493 "Jump to previous wiki link.
3494 If successful, return point. Otherwise, return nil.
3495 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3497 (if (re-search-backward markdown-regex-link-generic nil t
)
3498 (goto-char (or (match-beginning 1) (match-beginning 0)))
3502 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3504 (defun markdown-move-up ()
3506 Calls `markdown-move-list-item-up'."
3508 (markdown-move-list-item-up))
3510 (defun markdown-move-down ()
3511 "Move list item down.
3512 Calls `markdown-move-list-item-down'."
3514 (markdown-move-list-item-down))
3516 (defun markdown-promote ()
3517 "Either promote header or list item at point or cycle markup.
3518 See `markdown-cycle-atx', `markdown-cycle-setext', and
3519 `markdown-demote-list-item'."
3523 ;; Promote atx header
3524 ((thing-at-point-looking-at markdown-regex-header-atx
)
3525 (markdown-cycle-atx -
1 t
))
3526 ;; Promote setext header
3527 ((thing-at-point-looking-at markdown-regex-header-setext
)
3528 (markdown-cycle-setext -
1 t
))
3529 ;; Promote horizonal rule
3530 ((thing-at-point-looking-at markdown-regex-hr
)
3531 (markdown-cycle-hr -
1 t
))
3532 ;; Promote list item
3533 ((setq bounds
(markdown-cur-list-item-bounds))
3534 (markdown-promote-list-item)))))
3536 (defun markdown-demote ()
3537 "Either demote header or list item at point or cycle or remove markup.
3538 See `markdown-cycle-atx', `markdown-cycle-setext', and
3539 `markdown-demote-list-item'."
3543 ;; Demote atx header
3544 ((thing-at-point-looking-at markdown-regex-header-atx
)
3545 (markdown-cycle-atx 1 t
))
3546 ;; Demote setext header
3547 ((thing-at-point-looking-at markdown-regex-header-setext
)
3548 (markdown-cycle-setext 1 t
))
3549 ;; Demote horizonal rule
3550 ((thing-at-point-looking-at markdown-regex-hr
)
3551 (markdown-cycle-hr 1 t
))
3552 ;; Promote list item
3553 ((setq bounds
(markdown-cur-list-item-bounds))
3554 (markdown-demote-list-item))
3555 ;; Create a new level one ATX header
3557 (markdown-insert-header-atx-1)))))
3559 (defun markdown-complete-or-cycle (arg)
3560 "Complete or cycle markup of object at point or complete objects in region.
3561 If there is an active region, complete markup in region.
3562 Otherwise, complete or cycle markup of object near point.
3563 When ARG is non-nil, cycle backwards when cycling."
3565 (if (markdown-use-region-p)
3566 ;; Complete markup in region
3567 (markdown-complete-region (region-beginning) (region-end))
3568 ;; Complete or cycle markup at point
3569 (let ((dir (if arg -
1 1))
3573 ((thing-at-point-looking-at markdown-regex-header-atx
)
3574 (if (markdown-incomplete-atx-p)
3575 (markdown-complete-atx)
3576 (markdown-cycle-atx dir
)))
3578 ((thing-at-point-looking-at markdown-regex-header-setext
)
3579 (if (markdown-incomplete-setext-p)
3580 (markdown-complete-setext)
3581 (markdown-cycle-setext dir
)))
3583 ((thing-at-point-looking-at markdown-regex-hr
)
3584 (if (markdown-incomplete-hr-p)
3585 (markdown-complete-hr)
3586 (markdown-cycle-hr dir
)))
3588 ((thing-at-point-looking-at markdown-regex-bold
)
3589 (markdown-cycle-bold))
3591 ((thing-at-point-looking-at markdown-regex-italic
)
3592 (markdown-cycle-italic))))))
3595 ;;; Commands ==================================================================
3597 (defun markdown (&optional output-buffer-name
)
3598 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3599 The output buffer name defaults to `markdown-output-buffer-name'.
3600 Return the name of the output buffer used."
3602 (save-window-excursion
3603 (let ((begin-region)
3605 (if (markdown-use-region-p)
3606 (setq begin-region
(region-beginning)
3607 end-region
(region-end))
3608 (setq begin-region
(point-min)
3609 end-region
(point-max)))
3611 (unless output-buffer-name
3612 (setq output-buffer-name markdown-output-buffer-name
))
3615 ;; Handle case when `markdown-command' does not read from stdin
3616 (markdown-command-needs-filename
3617 (if (not buffer-file-name
)
3618 (error "Must be visiting a file")
3619 (shell-command (concat markdown-command
" "
3620 (shell-quote-argument buffer-file-name
))
3621 output-buffer-name
)))
3622 ;; Pass region to `markdown-command' via stdin
3624 (shell-command-on-region begin-region end-region markdown-command
3625 output-buffer-name
))))
3626 output-buffer-name
))
3628 (defun markdown-standalone (&optional output-buffer-name
)
3629 "Special function to provide standalone HTML output.
3630 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3632 (setq output-buffer-name
(markdown output-buffer-name
))
3633 (with-current-buffer output-buffer-name
3634 (set-buffer output-buffer-name
)
3635 (goto-char (point-min))
3636 (unless (markdown-output-standalone-p)
3637 (markdown-add-xhtml-header-and-footer output-buffer-name
))
3641 (defun markdown-other-window (&optional output-buffer-name
)
3642 "Run `markdown-command' on current buffer and display in other window.
3643 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3646 (display-buffer (markdown-standalone output-buffer-name
)))
3648 (defun markdown-output-standalone-p ()
3649 "Determine whether `markdown-command' output is standalone XHTML.
3650 Standalone XHTML output is identified by an occurrence of
3651 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3653 markdown-xhtml-standalone-regexp
3654 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3657 (defun markdown-add-xhtml-header-and-footer (title)
3658 "Wrap XHTML header and footer with given TITLE around current buffer."
3659 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3660 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3661 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3662 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3665 (insert "</title>\n")
3666 (when (> (length markdown-content-type
) 0)
3669 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3670 markdown-content-type
3671 (or (and markdown-coding-system
3672 (fboundp 'coding-system-get
)
3673 (coding-system-get markdown-coding-system
3675 (and (fboundp 'coding-system-get
)
3676 (coding-system-get buffer-file-coding-system
3679 (if (> (length markdown-css-path
) 0)
3680 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3683 (when (> (length markdown-xhtml-header-content
) 0)
3684 (insert markdown-xhtml-header-content
))
3685 (insert "\n</head>\n\n"
3687 (goto-char (point-max))
3692 (defun markdown-preview (&optional output-buffer-name
)
3693 "Run `markdown-command' on the current buffer and view output in browser.
3694 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3697 (browse-url-of-buffer (markdown markdown-output-buffer-name
)))
3699 (defun markdown-export-file-name (&optional extension
)
3700 "Attempt to generate a filename for Markdown output.
3701 The file extension will be EXTENSION if given, or .html by default.
3702 If the current buffer is visiting a file, we construct a new
3703 output filename based on that filename. Otherwise, return nil."
3704 (when (buffer-file-name)
3706 (setq extension
".html"))
3710 (file-name-sans-extension (buffer-file-name)))
3714 (defun markdown-export (&optional output-file
)
3715 "Run Markdown on the current buffer, save to file, and return the filename.
3716 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3717 generated by `markdown-export-file-name', which will be constructed using the
3718 current filename, but with the extension removed and replaced with .html."
3721 (setq output-file
(markdown-export-file-name ".html")))
3723 (let ((output-buffer-name))
3724 (setq output-buffer-name
(buffer-name (find-file-noselect output-file
)))
3725 (run-hook-with-args 'markdown-before-export-hooks output-file
)
3726 (markdown-standalone output-buffer-name
)
3727 (with-current-buffer output-buffer-name
3729 (run-hook-with-args 'markdown-after-export-hooks output-file
)
3732 (defun markdown-export-and-preview ()
3733 "Export to XHTML using `markdown-export' and browse the resulting file."
3735 (browse-url (markdown-export)))
3737 (defun markdown-open ()
3738 "Open file for the current buffer with `markdown-open-command'."
3740 (if (not markdown-open-command
)
3741 (error "Variable `markdown-open-command' must be set")
3742 (if (not buffer-file-name
)
3743 (error "Must be visiting a file")
3744 (call-process markdown-open-command
3745 nil nil nil buffer-file-name
))))
3747 (defun markdown-kill-ring-save ()
3748 "Run Markdown on file and store output in the kill ring."
3750 (save-window-excursion
3752 (with-current-buffer markdown-output-buffer-name
3753 (kill-ring-save (point-min) (point-max)))))
3756 ;;; Links =====================================================================
3758 (require 'thingatpt
)
3760 (defun markdown-link-p ()
3761 "Return non-nil when `point' is at a non-wiki link.
3762 See `markdown-wiki-link-p' for more information."
3763 (let ((case-fold-search nil
))
3764 (and (not (markdown-wiki-link-p))
3765 (or (thing-at-point-looking-at markdown-regex-link-inline
)
3766 (thing-at-point-looking-at markdown-regex-link-reference
)
3767 (thing-at-point-looking-at markdown-regex-uri
)
3768 (thing-at-point-looking-at markdown-regex-angle-uri
)))))
3770 (defun markdown-link-link ()
3771 "Return the link part of the regular (non-wiki) link at point.
3772 Works with both inline and reference style links. If point is
3773 not at a link or the link reference is not defined returns nil."
3775 ((thing-at-point-looking-at markdown-regex-link-inline
)
3776 (substring-no-properties (match-string 2) 1 -
1))
3777 ((thing-at-point-looking-at markdown-regex-link-reference
)
3778 (let* ((label (match-string-no-properties 1))
3779 (reference (match-string-no-properties 2))
3780 (target (downcase (if (string= reference
"[]") label reference
))))
3781 (car (markdown-reference-definition target
))))
3782 ((thing-at-point-looking-at markdown-regex-uri
)
3783 (match-string-no-properties 0))
3784 ((thing-at-point-looking-at markdown-regex-angle-uri
)
3785 (match-string-no-properties 2))
3788 (defun markdown-follow-link-at-point ()
3789 "Open the current non-wiki link in a browser."
3791 (if (markdown-link-p) (browse-url (markdown-link-link))
3792 (error "Point is not at a Markdown link or URI")))
3795 ;;; WikiLink Following/Markup =================================================
3797 (defun markdown-wiki-link-p ()
3798 "Return non-nil when `point' is at a true wiki link.
3799 A true wiki link name matches `markdown-regex-wiki-link' but does not
3800 match the current file name after conversion. This modifies the data
3801 returned by `match-data'. Note that the potential wiki link name must
3802 be available via `match-string'."
3803 (let ((case-fold-search nil
))
3804 (and (thing-at-point-looking-at markdown-regex-wiki-link
)
3805 (or (not buffer-file-name
)
3806 (not (string-equal (buffer-file-name)
3807 (markdown-convert-wiki-link-to-filename
3808 (markdown-wiki-link-link)))))
3809 (not (save-match-data
3810 (save-excursion))))))
3812 (defun markdown-wiki-link-link ()
3813 "Return the link part of the wiki link using current match data.
3814 The location of the link component depends on the value of
3815 `markdown-wiki-link-alias-first'."
3816 (if markdown-wiki-link-alias-first
3817 (or (match-string-no-properties 4) (match-string-no-properties 2))
3818 (match-string-no-properties 2)))
3820 (defun markdown-convert-wiki-link-to-filename (name)
3821 "Generate a filename from the wiki link NAME.
3822 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3823 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3824 and [[test test]] both map to Test-test.ext."
3825 (let ((basename (markdown-replace-regexp-in-string
3826 "[[:space:]\n]" markdown-link-space-sub-char name
)))
3827 (when (eq major-mode
'gfm-mode
)
3828 (setq basename
(concat (upcase (substring basename
0 1))
3829 (downcase (substring basename
1 nil
)))))
3831 (if (buffer-file-name)
3833 (file-name-extension (buffer-file-name)))))))
3835 (defun markdown-follow-wiki-link (name &optional other
)
3836 "Follow the wiki link NAME.
3837 Convert the name to a file name and call `find-file'. Ensure that
3838 the new buffer remains in `markdown-mode'. Open the link in another
3839 window when OTHER is non-nil."
3840 (let ((filename (markdown-convert-wiki-link-to-filename name
))
3841 (wp (file-name-directory buffer-file-name
)))
3842 (when other
(other-window 1))
3843 (find-file (concat wp filename
)))
3844 (when (not (eq major-mode
'markdown-mode
))
3847 (defun markdown-follow-wiki-link-at-point (&optional arg
)
3848 "Find Wiki Link at point.
3849 With prefix argument ARG, open the file in other window.
3850 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3852 (if (markdown-wiki-link-p)
3853 (markdown-follow-wiki-link (markdown-wiki-link-link) arg
)
3854 (error "Point is not at a Wiki Link")))
3856 (defun markdown-highlight-wiki-link (from to face
)
3857 "Highlight the wiki link in the region between FROM and TO using FACE."
3858 (put-text-property from to
'font-lock-face face
))
3860 (defun markdown-unfontify-region-wiki-links (from to
)
3861 "Remove wiki link faces from the region specified by FROM and TO."
3862 (interactive "nfrom: \nnto: ")
3863 (remove-text-properties from to
'(font-lock-face markdown-link-face
))
3864 (remove-text-properties from to
'(font-lock-face markdown-missing-link-face
)))
3866 (defun markdown-fontify-region-wiki-links (from to
)
3867 "Search region given by FROM and TO for wiki links and fontify them.
3868 If a wiki link is found check to see if the backing file exists
3869 and highlight accordingly."
3872 (while (re-search-forward markdown-regex-wiki-link to t
)
3873 (let ((highlight-beginning (match-beginning 1))
3874 (highlight-end (match-end 1))
3876 (markdown-convert-wiki-link-to-filename
3877 (markdown-wiki-link-link))))
3878 (if (file-exists-p file-name
)
3879 (markdown-highlight-wiki-link
3880 highlight-beginning highlight-end markdown-link-face
)
3881 (markdown-highlight-wiki-link
3882 highlight-beginning highlight-end markdown-link-face
)
3883 (markdown-highlight-wiki-link
3884 highlight-beginning highlight-end markdown-missing-link-face
))))))
3886 (defun markdown-extend-changed-region (from to
)
3887 "Extend region given by FROM and TO so that we can fontify all links.
3888 The region is extended to the first newline before and the first
3890 ;; start looking for the first new line before 'from
3892 (re-search-backward "\n" nil t
)
3893 (let ((new-from (point-min))
3894 (new-to (point-max)))
3895 (if (not (= (point) from
))
3896 (setq new-from
(point)))
3897 ;; do the same thing for the first new line after 'to
3899 (re-search-forward "\n" nil t
)
3900 (if (not (= (point) to
))
3901 (setq new-to
(point)))
3902 (values new-from new-to
)))
3904 (defun markdown-check-change-for-wiki-link (from to change
)
3905 "Check region between FROM and TO for wiki links and re-fontfy as needed.
3906 Designed to be used with the `after-change-functions' hook.
3907 CHANGE is the number of bytes of pre-change text replaced by the
3909 (interactive "nfrom: \nnto: \nnchange: ")
3910 (let* ((modified (buffer-modified-p))
3911 (buffer-undo-list t
)
3912 (inhibit-read-only t
)
3913 (inhibit-point-motion-hooks t
)
3915 buffer-file-truename
)
3920 ;; Extend the region to fontify so that it starts
3921 ;; and ends at safe places.
3922 (multiple-value-bind (new-from new-to
)
3923 (markdown-extend-changed-region from to
)
3924 ;; Unfontify existing fontification (start from scratch)
3925 (markdown-unfontify-region-wiki-links new-from new-to
)
3926 ;; Now do the fontification.
3927 (markdown-fontify-region-wiki-links new-from new-to
)))))
3930 (set-buffer-modified-p nil
)))))
3932 (defun markdown-fontify-buffer-wiki-links ()
3933 "Refontify all wiki links in the buffer."
3935 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
3938 ;;; Following and Jumping =====================================================
3940 (defun markdown-follow-thing-at-point (arg)
3941 "Follow thing at point if possible, such as a reference link or wiki link.
3942 Opens inline and reference links in a browser. Opens wiki links
3943 to other files in the current window, or the another window if
3945 See `markdown-follow-link-at-point' and
3946 `markdown-follow-wiki-link-at-point'."
3948 (cond ((markdown-link-p)
3949 (markdown-follow-link-at-point))
3950 ((markdown-wiki-link-p)
3951 (markdown-follow-wiki-link-at-point arg
))
3953 (error "Nothing to follow at point."))))
3955 (defun markdown-jump ()
3956 "Jump to another location based on context at point.
3957 Jumps between reference links and definitions; between footnote
3958 markers and footnote text."
3960 (cond ((markdown-footnote-text-positions)
3961 (markdown-footnote-return))
3962 ((markdown-footnote-marker-positions)
3963 (markdown-footnote-goto-text))
3964 ((thing-at-point-looking-at markdown-regex-link-reference
)
3965 (markdown-reference-goto-definition))
3966 ((thing-at-point-looking-at markdown-regex-reference-definition
)
3967 (markdown-reference-goto-link (match-string-no-properties 1)))
3969 (error "Nothing to jump to from context at point."))))
3972 ;;; Miscellaneous =============================================================
3974 (defun markdown-compress-whitespace-string (str)
3975 "Compress whitespace in STR and return result.
3976 Leading and trailing whitespace is removed. Sequences of multiple
3977 spaces, tabs, and newlines are replaced with single spaces."
3978 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
3979 (replace-regexp-in-string "[ \t\n]+" " " str
)))
3981 (defun markdown-line-number-at-pos (&optional pos
)
3982 "Return (narrowed) buffer line number at position POS.
3983 If POS is nil, use current buffer location.
3984 This is an exact copy of `line-number-at-pos' for use in emacs21."
3985 (let ((opoint (or pos
(point))) start
)
3987 (goto-char (point-min))
3988 (setq start
(point))
3991 (1+ (count-lines start
(point))))))
3993 (defun markdown-nobreak-p ()
3994 "Return nil if it is acceptable to break the current line at the point."
3995 ;; inside in square brackets (e.g., link anchor text)
3996 (looking-back "\\[[^]]*"))
3999 ;;; Mode Definition ==========================================================
4001 (defun markdown-show-version ()
4002 "Show the version number in the minibuffer."
4004 (message "markdown-mode, version %s" markdown-mode-version
))
4007 (define-derived-mode markdown-mode text-mode
"Markdown"
4008 "Major mode for editing Markdown files."
4009 ;; Natural Markdown tab width
4012 (make-local-variable 'comment-start
)
4013 (setq comment-start
"<!-- ")
4014 (make-local-variable 'comment-end
)
4015 (setq comment-end
" -->")
4016 (make-local-variable 'comment-start-skip
)
4017 (setq comment-start-skip
"<!--[ \t]*")
4018 (make-local-variable 'comment-column
)
4019 (setq comment-column
0)
4021 (set (make-local-variable 'font-lock-defaults
)
4022 '(markdown-mode-font-lock-keywords))
4023 (set (make-local-variable 'font-lock-multiline
) t
)
4024 ;; For imenu support
4025 (setq imenu-create-index-function
'markdown-imenu-create-index
)
4026 ;; For menu support in XEmacs
4027 (easy-menu-add markdown-mode-menu markdown-mode-map
)
4029 (set (make-local-variable 'beginning-of-defun-function
)
4030 'markdown-beginning-of-defun
)
4031 (set (make-local-variable 'end-of-defun-function
)
4032 'markdown-end-of-defun
)
4033 ;; Make filling work with lists (unordered, ordered, and definition)
4034 (set (make-local-variable 'paragraph-start
)
4035 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
4037 (make-local-variable 'outline-regexp
)
4038 (setq outline-regexp markdown-regex-header
)
4039 (make-local-variable 'outline-level
)
4040 (setq outline-level
'markdown-outline-level
)
4041 ;; Cause use of ellipses for invisible text.
4042 (add-to-invisibility-spec '(outline . t
))
4043 ;; Indentation and filling
4044 (make-local-variable 'fill-nobreak-predicate
)
4045 (add-hook 'fill-nobreak-predicate
'markdown-nobreak-p
)
4046 (setq indent-line-function markdown-indent-function
)
4048 ;; Prepare hooks for XEmacs compatibility
4049 (when (featurep 'xemacs
)
4050 (make-local-hook 'after-change-functions
)
4051 (make-local-hook 'font-lock-extend-region-functions
)
4052 (make-local-hook 'window-configuration-change-hook
))
4054 ;; Multiline font lock
4055 (add-hook 'font-lock-extend-region-functions
4056 'markdown-font-lock-extend-region
)
4058 ;; Anytime text changes make sure it gets fontified correctly
4059 (add-hook 'after-change-functions
'markdown-check-change-for-wiki-link t t
)
4061 ;; If we left the buffer there is a really good chance we were
4062 ;; creating one of the wiki link documents. Make sure we get
4063 ;; refontified when we come back.
4064 (add-hook 'window-configuration-change-hook
4065 'markdown-fontify-buffer-wiki-links t t
)
4067 ;; do the initial link fontification
4068 (markdown-fontify-buffer-wiki-links))
4070 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4073 ;;; GitHub Flavored Markdown Mode ============================================
4075 (defvar gfm-font-lock-keywords
4077 ;; GFM features to match first
4079 (cons 'markdown-match-gfm-code-blocks
'((1 markdown-pre-face
)
4080 (2 markdown-language-keyword-face
)
4081 (3 markdown-pre-face
)
4082 (4 markdown-pre-face
))))
4083 ;; Basic Markdown features (excluding possibly overridden ones)
4084 markdown-mode-font-lock-keywords-basic
4085 ;; GFM features to match last
4087 (cons markdown-regex-gfm-italic
'(2 markdown-italic-face
))))
4088 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4091 (define-derived-mode gfm-mode markdown-mode
"GFM"
4092 "Major mode for editing GitHub Flavored Markdown files."
4093 (setq markdown-link-space-sub-char
"-")
4094 (set (make-local-variable 'font-lock-defaults
)
4095 '(gfm-font-lock-keywords))
4097 ;; Use visual-line-mode if available, fall back to longlines-mode:
4098 (if (fboundp 'visual-line-mode
)
4099 (visual-line-mode 1)
4101 ;; do the initial link fontification
4102 (markdown-fontify-buffer-wiki-links))
4105 (provide 'markdown-mode
)
4107 ;;; markdown-mode.el ends here