Separate exdent function from position calculation
[markdown-mode.git] / markdown-mode.el
blob2ef3af41247cde261ed1035b31231e666ab664a6
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
29 ;; Version: 1.9
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)
38 ;; any later version.
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.
50 ;;; Commentary:
52 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
53 ;; text files in GNU Emacs. markdown-mode is free software, licensed
54 ;; under the GNU GPL.
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
93 ;; by running
95 ;; git clone git://jblevins.org/git/markdown-mode.git
97 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
99 ;;; Dependencies:
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.
105 ;;; Installation:
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.
118 ;;; Customization:
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
165 ;; (default: `t')
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
170 ;; (default: `t')
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
218 ;;; Usage:
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'.
249 ;; To summarize:
251 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
252 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
253 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
254 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
255 ;; - `C-c C-c w`: `markdown-command' > kill ring.
256 ;; - `C-c C-c o`: `markdown-open-command'.
258 ;; `C-c C-c c` will check for undefined references. If there are
259 ;; any, a small buffer will open with a list of undefined
260 ;; references and the line numbers on which they appear. In Emacs
261 ;; 22 and greater, selecting a reference from this list and
262 ;; pressing `RET` will insert an empty reference definition at the
263 ;; end of the buffer. Similarly, selecting the line number will
264 ;; jump to the corresponding line.
266 ;; `C-c C-c n` will clean up the numbering of ordered lists.
268 ;; * Images: `C-c C-i`
270 ;; `C-c C-i i` inserts markup for an inline image, using the
271 ;; active region (if any) or the word at point as the alt text.
272 ;; To insert reference-style image markup, provide a `C-u` prefix.
274 ;; * Physical styles: `C-c C-p`
276 ;; These commands all act on text in the active region, if any,
277 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
278 ;; the selected text bold, `C-c C-p f` formats the region as
279 ;; fixed-width text, and `C-c C-p i` is used for italic text.
281 ;; * Logical styles: `C-c C-s`
283 ;; These commands all act on text in the active region, if any,
284 ;; and insert empty markup fragments otherwise. Logical styles
285 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
286 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
287 ;; (`C-c C-s s`).
289 ;; * Headers: `C-c C-t`
291 ;; All header commands use text in the active region, if any, as
292 ;; the header text. Otherwise, if the current line is not blank,
293 ;; use the text on the current line. Finally, prompt for header
294 ;; text if there is no active region and the current line is
295 ;; blank. To insert an atx or hash style level-n
296 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
297 ;; top-level setext or underline style header press `C-c C-t t`
298 ;; (mnemonic: title) and for a second-level underline-style header
299 ;; press `C-c C-t s` (mnemonic: section).
301 ;; If the point is at a header, these commands will replace the
302 ;; existing markup in order to update the level and/or type of the
303 ;; header. To remove the markup of the header at the point, press
304 ;; `C-c C-t 0`.
306 ;; * Footnotes: `C-c C-f`
308 ;; To create a new footnote at the point, press `C-c C-f n`.
309 ;; Press `C-c C-f g` with the point at a footnote to jump to the
310 ;; location where the footnote text is defined. Then, press
311 ;; `C-c C-f b` to return to the footnote marker in the main text.
312 ;; When the point is at a footnote marker or in the body of a
313 ;; footnote, press `C-c C-f k` to kill the footnote and add the
314 ;; text to the kill ring.
316 ;; * Other elements:
318 ;; `C-c -` inserts a horizontal rule.
320 ;; * Following Links:
322 ;; Press `C-c C-o` when the point is on an inline or reference
323 ;; link to open the URL in a browser. When the point is at a
324 ;; wiki link, open it in another buffer (in the current window,
325 ;; or in the other window with the `C-u` prefix).
326 ;; To move between links, use `M-p` and `M-n` to quickly jump
327 ;; to the previous or next link of any type.
329 ;; * Jumping:
331 ;; Use `C-c C-j` to jump from the object at point to its counterpart
332 ;; elsewhere in the text, when possible. Jumps between reference
333 ;; links and definitions; between footnote markers and footnote
334 ;; text. If more than one link uses the same reference name, a
335 ;; new buffer will be created containing clickable buttons for jumping
336 ;; to each link. You may press `TAB` or `S-TAB` to jump between
337 ;; buttons in this window.
339 ;; * Killing Elements:
341 ;; Press `C-c C-k` to kill the thing at point and add important
342 ;; text, without markup, to the kill ring. Possible things to
343 ;; kill include (roughly in order of precedece): inline code,
344 ;; headers, horizonal rules, links (add link text to kill ring),
345 ;; images (add alt text to kill ring), angle URIs, email
346 ;; addresses, bold, italics, reference definitions (add URI to
347 ;; kill ring), footnote markers and text (kill both marker and
348 ;; text, add text to kill ring), and list items.
350 ;; * Outline Navigation:
352 ;; Navigation between headings is possible using `outline-mode'.
353 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
354 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
355 ;; next and previous visible headings at the same level as the one
356 ;; at the point. Finally, `C-M-u` will move up to a lower-level
357 ;; (more inclusive) visible heading.
359 ;; * Movement by Block:
361 ;; markdown-mode supports the usual Emacs paragraph movement with
362 ;; `M-{` and `M-}`. These commands treat list items as
363 ;; paragraphs, so they will stop at each line within a block of
364 ;; list items. Additionally, markdown-mode includes movement
365 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
366 ;; of an entire block of text (with blocks being separated by at
367 ;; least one blank line).
369 ;; * Movement by Defun:
371 ;; The usual Emacs commands can be used to move by defuns
372 ;; (top-level major definitions). In markdown-mode, a defun
373 ;; is a section. As usual, `C-M-a` will move the point to
374 ;; the beginning of the current or preceding defun, `C-M-e`
375 ;; will move to the end of the current or following defun,
376 ;; and `C-M-h` will put the region around the entire defun.
378 ;; Many of the commands described above behave differently depending on
379 ;; whether Transient Mark mode is enabled or not. When it makes sense,
380 ;; if Transient Mark mode is on and a region is active, the command
381 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
382 ;; bold). For users who prefer to work outside of Transient Mark mode,
383 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
385 ;; When applicable, commands that specifically act on the region even
386 ;; outside of Transient Mark mode have the same keybinding as the with
387 ;; the exception of an additional `C-` prefix. For example,
388 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
389 ;; the region in Transient Mark mode while `markdown-blockquote-region'
390 ;; is bound to `C-c C-s C-b` and always applies to the region (when
391 ;; nonempty).
393 ;; Note that these region-specific functions are useful in many
394 ;; cases where it may not be obvious. For example, yanking text from
395 ;; the kill ring sets the mark at the beginning of the yanked text
396 ;; and moves the point to the end. Therefore, the (inactive) region
397 ;; contains the yanked text. So, `C-y` then `C-c C-s C-b` will yank
398 ;; text and make it a blockquote.
400 ;; markdown-mode attempts to be flexible in how it handles
401 ;; indentation. When you press `TAB` repeatedly, the point will cycle
402 ;; through several possible indentation levels corresponding to things
403 ;; you might have in mind when you press `RET` at the end of a line or
404 ;; `TAB`. For example, you may want to start a new list item,
405 ;; continue a list item with hanging indentation, indent for a nested
406 ;; pre block, and so on.
408 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
409 ;; visibility cycling for atx- or hash-style headers. There are two
410 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
411 ;; the table of contents view (headers only), outline view (top-level
412 ;; headers only), and the full document view. Pressing `TAB` while the
413 ;; point is at a header will cycle through levels of visibility for the
414 ;; subtree: completely folded, visible children, and fully visible.
415 ;; Note that mixing hash and underline style headers will give undesired
416 ;; results.
418 ;;; Extensions:
420 ;; Besides supporting the basic Markdown syntax, markdown-mode also
421 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
422 ;; links may be followed automatically by pressing the enter key when
423 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
424 ;; auto-following on enter key may be controlled with the
425 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
426 ;; `M-n` to quickly jump to the previous and next wiki links,
427 ;; respectively. Aliased or piped wiki links of the form
428 ;; `[[link text|PageName]]` are also supported. Since some wikis
429 ;; reverse these components, set `markdown-wiki-link-alias-first'
430 ;; to nil to treat them as `[[PageName|link text]]`.
432 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
433 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
434 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
435 ;; You can do this either by using `M-x customize-group markdown`
436 ;; or by placing the following in your `.emacs` file:
438 ;; (defun markdown-custom ()
439 ;; "markdown-mode-hook"
440 ;; (setq markdown-command "markdown | smartypants"))
441 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
443 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
445 ;; Experimental syntax highlighting for mathematical expressions written
446 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
447 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
448 ;; either via customize or by placing `(setq markdown-enable-itex t)`
449 ;; in `.emacs`, and restarting Emacs.
451 ;;; GitHub Flavored Markdown:
453 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
454 ;; available. The GitHub implementation of differs slightly from
455 ;; standard Markdown. The most important differences are that
456 ;; newlines are significant, triggering hard line breaks, and that
457 ;; underscores inside of words (e.g., variable names) need not be
458 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
459 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
460 ;; not available). Underscores inside of words (such as
461 ;; test_variable) will not trigger emphasis.
463 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
464 ;; replacing spaces in filenames and where the first letter of the
465 ;; filename capitalized. For example, `[[wiki link]]' will map to a
466 ;; file named `Wiki-link` with the same extension as the current file.
468 ;; GFM code blocks, with optional programming language keywords, will
469 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
470 ;; is an active region, the text in the region will be placed inside
471 ;; the code block. You will be prompted for the name of the language,
472 ;; but may press enter to continue without naming a language.
474 ;; For a more complete GitHub-flavored markdown experience, consider
475 ;; adding README.md to your `auto-mode-alist':
477 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
479 ;; For GFM preview can be powered by setting `markdown-command' to
480 ;; use [Docter][]. This may also be configured to work with [Marked][]
481 ;; for `markdown-open-command'.
483 ;; [GFM]: http://github.github.com/github-flavored-markdown/
484 ;; [Docter]: https://github.com/alampros/Docter
486 ;;; Acknowledgments:
488 ;; markdown-mode has benefited greatly from the efforts of the
489 ;; following people:
491 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
492 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
493 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
494 ;; GitHub Flavored Markdown mode (`gfm-mode').
495 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
496 ;; `markdown' with an active region.
497 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
498 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
499 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
500 ;; * Carsten Dominik <carsten@orgmode.org> for org-mode, from which the
501 ;; visibility cycling functionality was derived, and for a bug fix
502 ;; related to orgtbl-mode.
503 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
504 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
505 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
506 ;; compatibility and custom CSS.
507 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
508 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
509 ;; * Nelson Minar <nelson@santafe.edu> for html-helper-mode, from which
510 ;; comment matching functions were derived.
511 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
512 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
513 ;; functions, bug reports regarding indentation, and
514 ;; fixes for byte-compilation warnings.
515 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
516 ;; enhancements.
517 ;; * George Ogata <george.ogata@gmail.com> for fixing several
518 ;; byte-compilation warnings.
519 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
520 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
521 ;; customizations and XHTML export.
522 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
523 ;; Markdown processors which do not accept input from stdin.
524 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
525 ;; regarding the cl dependency and auto-fill-mode and indentation.
526 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
527 ;; substitution character for mapping wiki links to filenames.
528 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
529 ;; escape shell commands.
530 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
531 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
532 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
533 ;; Emacs Lisp coding conventions.
534 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
535 ;; regexp, refactoring the compilation and preview functions,
536 ;; heading font-lock generalizations, list renumbering,
537 ;; and kill ring save.
538 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
539 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
540 ;; for an autoload token for `gfm-mode'.
541 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
542 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
543 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
544 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
545 ;; declaration in XHTML output.
546 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
547 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
548 ;; and GFM code block insertion.
549 ;; * Peter Jones <pjones@pmade.com> for link following functions.
550 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
551 ;; externally modified files.
552 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
553 ;; related to orgtbl-mode.
554 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
555 ;; export hooks and unit test improvements.
556 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
557 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
558 ;; completion.
560 ;;; Bugs:
562 ;; Although markdown-mode is developed and tested primarily using
563 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
564 ;; priority.
566 ;; If you find any bugs in markdown-mode, please construct a test case
567 ;; or a patch and email me at <jrblevin@sdf.org>.
569 ;;; History:
571 ;; markdown-mode was written and is maintained by Jason Blevins. The
572 ;; first version was released on May 24, 2007.
574 ;; * 2007-05-24: Version 1.1
575 ;; * 2007-05-25: Version 1.2
576 ;; * 2007-06-05: [Version 1.3][]
577 ;; * 2007-06-29: Version 1.4
578 ;; * 2008-05-24: [Version 1.5][]
579 ;; * 2008-06-04: [Version 1.6][]
580 ;; * 2009-10-01: [Version 1.7][]
581 ;; * 2011-08-12: [Version 1.8][]
582 ;; * 2011-08-15: [Version 1.8.1][]
583 ;; * 2013-01-25: [Version 1.9][]
585 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
586 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
587 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
588 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
589 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
590 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
591 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
594 ;;; Code:
596 (require 'easymenu)
597 (require 'outline)
598 (eval-when-compile (require 'cl))
601 ;;; Constants =================================================================
603 (defconst markdown-mode-version "1.9"
604 "Markdown mode version number.")
606 (defconst markdown-output-buffer-name "*markdown-output*"
607 "Name of temporary buffer for markdown command output.")
610 ;;; Global Variables ==========================================================
612 (defvar markdown-reference-label-history nil
613 "History of used reference labels.")
616 ;;; Customizable Variables ====================================================
618 (defvar markdown-mode-hook nil
619 "Hook run when entering Markdown mode.")
621 (defvar markdown-before-export-hooks nil
622 "Hook run before output XHTML.
623 This hook is abnormal and registered functions are given an argument that is output filename.")
625 (defvar markdown-after-export-hooks nil
626 "Hook run after output XHTML.
627 This hook is abnormal and registered functions are given an argument that is output filename.")
629 (defgroup markdown nil
630 "Major mode for editing text files in Markdown format."
631 :prefix "markdown-"
632 :group 'wp
633 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
635 (defcustom markdown-command "markdown"
636 "Command to run markdown."
637 :group 'markdown
638 :type 'string)
640 (defcustom markdown-command-needs-filename nil
641 "Set to non-nil if `markdown-command' does not accept input from stdin.
642 Instead, it will be passed a filename as the final command line
643 option. As a result, you will only be able to run Markdown from
644 buffers which are visiting a file."
645 :group 'markdown
646 :type 'boolean)
648 (defcustom markdown-open-command nil
649 "Command used for opening Markdown files directly.
650 For example, a standalone Markdown previewer. This command will
651 be called with a single argument: the filename of the current
652 buffer."
653 :group 'markdown
654 :type 'string)
656 (defcustom markdown-hr-strings
657 '("* * * * *"
658 "---------"
659 "* * * * * * * * * * * * * * * * * * * *"
660 "---------------------------------------"
661 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
662 "-------------------------------------------------------------------------------")
663 "Strings to use when inserting horizontal rules.
664 The first string in the list will be the default when inserting a
665 horizontal rule. Strings should be listed in increasing order of
666 prominence for use with promotion and demotion functions."
667 :group 'markdown
668 :type 'list)
670 (defcustom markdown-bold-underscore nil
671 "Use two underscores for bold instead of two asterisks."
672 :group 'markdown
673 :type 'boolean)
675 (defcustom markdown-italic-underscore nil
676 "Use underscores for italic instead of asterisks."
677 :group 'markdown
678 :type 'boolean)
680 (defcustom markdown-indent-function 'markdown-indent-line
681 "Function to use to indent."
682 :group 'markdown
683 :type 'function)
685 (defcustom markdown-indent-on-enter t
686 "Automatically indent new lines when enter key is pressed."
687 :group 'markdown
688 :type 'boolean)
690 (defcustom markdown-follow-wiki-link-on-enter t
691 "Follow wiki link at point (if any) when the enter key is pressed."
692 :group 'markdown
693 :type 'boolean)
695 (defcustom markdown-wiki-link-alias-first t
696 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
697 Otherwise, they will be treated as [[PageName|alias text]]."
698 :group 'markdown
699 :type 'boolean)
701 (defcustom markdown-uri-types
702 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
703 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
704 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
705 "Link types for syntax highlighting of URIs."
706 :group 'markdown
707 :type 'list)
709 (defcustom markdown-enable-math nil
710 "Syntax highlighting for inline LaTeX expressions.
711 This will not take effect until Emacs is restarted."
712 :group 'markdown
713 :type 'boolean)
715 (defcustom markdown-css-path ""
716 "URL of CSS file to link to in the output XHTML."
717 :group 'markdown
718 :type 'string)
720 (defcustom markdown-content-type ""
721 "Content type string for the http-equiv header in XHTML output.
722 When set to a non-empty string, insert the http-equiv attribute.
723 Otherwise, this attribute is omitted."
724 :group 'markdown
725 :type 'string)
727 (defcustom markdown-coding-system nil
728 "Character set string for the http-equiv header in XHTML output.
729 Defaults to `buffer-file-coding-system' (and falling back to
730 `iso-8859-1' when not available). Common settings are `utf-8'
731 and `iso-latin-1'. Use `list-coding-systems' for more choices."
732 :group 'markdown
733 :type 'coding-system)
735 (defcustom markdown-xhtml-header-content ""
736 "Additional content to include in the XHTML <head> block."
737 :group 'markdown
738 :type 'string)
740 (defcustom markdown-xhtml-standalone-regexp
741 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
742 "Regexp indicating whether `markdown-command' output is standalone XHTML."
743 :group 'markdown
744 :type 'regexp)
746 (defcustom markdown-link-space-sub-char
748 "Character to use instead of spaces when mapping wiki links to filenames."
749 :group 'markdown
750 :type 'string)
752 (defcustom markdown-footnote-location 'end
753 "Position where new footnotes are inserted in the document."
754 :group 'markdown
755 :type '(choice (const :tag "At the end of the document" end)
756 (const :tag "Immediately after the paragraph" immediately)
757 (const :tag "Before next header" header)))
760 ;;; Font Lock =================================================================
762 (require 'font-lock)
764 (defvar markdown-italic-face 'markdown-italic-face
765 "Face name to use for italic text.")
767 (defvar markdown-bold-face 'markdown-bold-face
768 "Face name to use for bold text.")
770 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
771 "Face name to use as a base for header delimiters.")
773 (defvar markdown-header-rule-face 'markdown-header-rule-face
774 "Face name to use as a base for header rules.")
776 (defvar markdown-header-face 'markdown-header-face
777 "Face name to use as a base for headers.")
779 (defvar markdown-header-face-1 'markdown-header-face-1
780 "Face name to use for level-1 headers.")
782 (defvar markdown-header-face-2 'markdown-header-face-2
783 "Face name to use for level-2 headers.")
785 (defvar markdown-header-face-3 'markdown-header-face-3
786 "Face name to use for level-3 headers.")
788 (defvar markdown-header-face-4 'markdown-header-face-4
789 "Face name to use for level-4 headers.")
791 (defvar markdown-header-face-5 'markdown-header-face-5
792 "Face name to use for level-5 headers.")
794 (defvar markdown-header-face-6 'markdown-header-face-6
795 "Face name to use for level-6 headers.")
797 (defvar markdown-inline-code-face 'markdown-inline-code-face
798 "Face name to use for inline code.")
800 (defvar markdown-list-face 'markdown-list-face
801 "Face name to use for list markers.")
803 (defvar markdown-blockquote-face 'markdown-blockquote-face
804 "Face name to use for blockquote.")
806 (defvar markdown-pre-face 'markdown-pre-face
807 "Face name to use for preformatted text.")
809 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
810 "Face name to use for programming language identifiers.")
812 (defvar markdown-link-face 'markdown-link-face
813 "Face name to use for links.")
815 (defvar markdown-missing-link-face 'markdown-missing-link-face
816 "Face name to use for links where the linked file does not exist.")
818 (defvar markdown-reference-face 'markdown-reference-face
819 "Face name to use for reference.")
821 (defvar markdown-footnote-face 'markdown-footnote-face
822 "Face name to use for footnote identifiers.")
824 (defvar markdown-url-face 'markdown-url-face
825 "Face name to use for URLs.")
827 (defvar markdown-link-title-face 'markdown-link-title-face
828 "Face name to use for reference link titles.")
830 (defvar markdown-line-break-face 'markdown-line-break-face
831 "Face name to use for hard line breaks.")
833 (defvar markdown-comment-face 'markdown-comment-face
834 "Face name to use for HTML comments.")
836 (defvar markdown-math-face 'markdown-math-face
837 "Face name to use for LaTeX expressions.")
839 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
840 "Face name to use for metadata keys.")
842 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
843 "Face name to use for metadata values.")
845 (defgroup markdown-faces nil
846 "Faces used in Markdown Mode"
847 :group 'markdown
848 :group 'faces)
850 (defface markdown-italic-face
851 '((t (:inherit font-lock-variable-name-face :slant italic)))
852 "Face for italic text."
853 :group 'markdown-faces)
855 (defface markdown-bold-face
856 '((t (:inherit font-lock-variable-name-face :weight bold)))
857 "Face for bold text."
858 :group 'markdown-faces)
860 (defface markdown-header-rule-face
861 '((t (:inherit font-lock-function-name-face :weight bold)))
862 "Base face for headers rules."
863 :group 'markdown-faces)
865 (defface markdown-header-delimiter-face
866 '((t (:inherit font-lock-function-name-face :weight bold)))
867 "Base face for headers hash delimiter."
868 :group 'markdown-faces)
870 (defface markdown-header-face
871 '((t (:inherit font-lock-function-name-face :weight bold)))
872 "Base face for headers."
873 :group 'markdown-faces)
875 (defface markdown-header-face-1
876 '((t (:inherit markdown-header-face)))
877 "Face for level-1 headers."
878 :group 'markdown-faces)
880 (defface markdown-header-face-2
881 '((t (:inherit markdown-header-face)))
882 "Face for level-2 headers."
883 :group 'markdown-faces)
885 (defface markdown-header-face-3
886 '((t (:inherit markdown-header-face)))
887 "Face for level-3 headers."
888 :group 'markdown-faces)
890 (defface markdown-header-face-4
891 '((t (:inherit markdown-header-face)))
892 "Face for level-4 headers."
893 :group 'markdown-faces)
895 (defface markdown-header-face-5
896 '((t (:inherit markdown-header-face)))
897 "Face for level-5 headers."
898 :group 'markdown-faces)
900 (defface markdown-header-face-6
901 '((t (:inherit markdown-header-face)))
902 "Face for level-6 headers."
903 :group 'markdown-faces)
905 (defface markdown-inline-code-face
906 '((t (:inherit font-lock-constant-face)))
907 "Face for inline code."
908 :group 'markdown-faces)
910 (defface markdown-list-face
911 '((t (:inherit font-lock-builtin-face)))
912 "Face for list item markers."
913 :group 'markdown-faces)
915 (defface markdown-blockquote-face
916 '((t (:inherit font-lock-doc-face)))
917 "Face for blockquote sections."
918 :group 'markdown-faces)
920 (defface markdown-pre-face
921 '((t (:inherit font-lock-constant-face)))
922 "Face for preformatted text."
923 :group 'markdown-faces)
925 (defface markdown-language-keyword-face
926 '((t (:inherit font-lock-type-face)))
927 "Face for programming language identifiers."
928 :group 'markdown-faces)
930 (defface markdown-link-face
931 '((t (:inherit font-lock-keyword-face)))
932 "Face for links."
933 :group 'markdown-faces)
935 (defface markdown-missing-link-face
936 '((t (:inherit font-lock-warning-face)))
937 "Face for missing links."
938 :group 'markdown-faces)
940 (defface markdown-reference-face
941 '((t (:inherit font-lock-type-face)))
942 "Face for link references."
943 :group 'markdown-faces)
945 (defface markdown-footnote-face
946 '((t (:inherit font-lock-keyword-face)))
947 "Face for footnote markers."
948 :group 'markdown-faces)
950 (defface markdown-url-face
951 '((t (:inherit font-lock-string-face)))
952 "Face for URLs."
953 :group 'markdown-faces)
955 (defface markdown-link-title-face
956 '((t (:inherit font-lock-comment-face)))
957 "Face for reference link titles."
958 :group 'markdown-faces)
960 (defface markdown-line-break-face
961 '((t (:inherit font-lock-constant-face :underline t)))
962 "Face for hard line breaks."
963 :group 'markdown-faces)
965 (defface markdown-comment-face
966 '((t (:inherit font-lock-comment-face)))
967 "Face for HTML comments."
968 :group 'markdown-faces)
970 (defface markdown-math-face
971 '((t (:inherit font-lock-string-face)))
972 "Face for LaTeX expressions."
973 :group 'markdown-faces)
975 (defface markdown-metadata-key-face
976 '((t (:inherit font-lock-variable-name-face)))
977 "Face for metadata keys."
978 :group 'markdown-faces)
980 (defface markdown-metadata-value-face
981 '((t (:inherit font-lock-string-face)))
982 "Face for metadata values."
983 :group 'markdown-faces)
985 (defconst markdown-regex-link-inline
986 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
987 "Regular expression for a [text](file) or an image link ![text](file).
988 Group 1 matches the leading exclamation point, if any.
989 Group 2 matchs the entire square bracket term, including the text.
990 Group 3 matches the text inside the square brackets.
991 Group 4 matches the entire parenthesis term, including the URL and title.
992 Group 5 matches the URL.
993 Group 6 matches (optional) title.")
995 (defconst markdown-regex-link-reference
996 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
997 "Regular expression for a reference link [text][id].
998 Group 1 matches the leading exclamation point, if any.
999 Group 2 matchs the entire first square bracket term, including the text.
1000 Group 3 matches the text inside the square brackets.
1001 Group 4 matches the entire second square bracket term.
1002 Group 5 matches the reference label.")
1004 (defconst markdown-regex-reference-definition
1005 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1006 "Regular expression for a link definition [id]: ...")
1008 (defconst markdown-regex-footnote
1009 "\\(\\[\\^.+?\\]\\)"
1010 "Regular expression for a footnote marker [^fn].")
1012 (defconst markdown-regex-header
1013 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1014 "Regexp identifying Markdown headers.")
1016 (defconst markdown-regex-header-1-atx
1017 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
1018 "Regular expression for level 1 atx-style (hash mark) headers.")
1020 (defconst markdown-regex-header-2-atx
1021 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
1022 "Regular expression for level 2 atx-style (hash mark) headers.")
1024 (defconst markdown-regex-header-3-atx
1025 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
1026 "Regular expression for level 3 atx-style (hash mark) headers.")
1028 (defconst markdown-regex-header-4-atx
1029 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
1030 "Regular expression for level 4 atx-style (hash mark) headers.")
1032 (defconst markdown-regex-header-5-atx
1033 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
1034 "Regular expression for level 5 atx-style (hash mark) headers.")
1036 (defconst markdown-regex-header-6-atx
1037 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
1038 "Regular expression for level 6 atx-style (hash mark) headers.")
1040 (defconst markdown-regex-header-1-setext
1041 "^\\(.*\\)\n\\(=+\\)$"
1042 "Regular expression for level 1 setext-style (underline) headers.")
1044 (defconst markdown-regex-header-2-setext
1045 "^\\(.*\\)\n\\(-+\\)$"
1046 "Regular expression for level 2 setext-style (underline) headers.")
1048 (defconst markdown-regex-header-setext
1049 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1050 "Regular expression for generic setext-style (underline) headers.")
1052 (defconst markdown-regex-header-atx
1053 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1054 "Regular expression for generic atx-style (hash mark) headers.")
1056 (defconst markdown-regex-hr
1057 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1058 "Regular expression for matching Markdown horizontal rules.")
1060 (defconst markdown-regex-code
1061 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1062 "Regular expression for matching inline code fragments.
1064 The first group ensures that the leading backquote character
1065 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1066 character, including newlines, but not two newlines in a row.
1067 The final group requires that the character following the code
1068 fragment is not a backquote.")
1070 (defconst markdown-regex-pre
1071 "^\\( \\|\t\\).*$"
1072 "Regular expression for matching preformatted text sections.")
1074 (defconst markdown-regex-list
1075 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1076 "Regular expression for matching list items.")
1078 (defconst markdown-regex-bold
1079 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1080 "Regular expression for matching bold text.
1081 Group 1 matches the character before the opening asterisk or
1082 underscore, if any, ensuring that it is not a backslash escape.
1083 Group 2 matches the entire expression, including delimiters.
1084 Groups 3 and 5 matches the opening and closing delimiters.
1085 Group 4 matches the text inside the delimiters.")
1087 (defconst markdown-regex-italic
1088 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1089 "Regular expression for matching italic text.
1090 Group 1 matches the character before the opening asterisk or
1091 underscore, if any, ensuring that it is not a backslash escape.
1092 Group 2 matches the entire expression, including delimiters.
1093 Groups 3 and 5 matches the opening and closing delimiters.
1094 Group 4 matches the text inside the delimiters.")
1096 (defconst markdown-regex-gfm-italic
1097 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1098 "Regular expression for matching italic text in GitHub-flavored Markdown.
1099 Underscores in words are not treated as special.")
1101 (defconst markdown-regex-blockquote
1102 "^[ \t]*\\(>\\).*$"
1103 "Regular expression for matching blockquote lines.")
1105 (defconst markdown-regex-line-break
1106 "[^ \n\t][ \t]*\\( \\)$"
1107 "Regular expression for matching line breaks.")
1109 (defconst markdown-regex-wiki-link
1110 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1111 "Regular expression for matching wiki links.
1112 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1113 wiki links of the form [[PageName|link text]]. In this regular
1114 expression, #1 matches the page name and #3 matches the link
1115 text.")
1117 (defconst markdown-regex-uri
1118 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1119 "Regular expression for matching inline URIs.")
1121 (defconst markdown-regex-angle-uri
1122 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1123 "Regular expression for matching inline URIs in angle brackets.")
1125 (defconst markdown-regex-email
1126 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1127 "Regular expression for matching inline email addresses.")
1129 (defconst markdown-regex-link-generic
1130 (concat "\\(?:" markdown-regex-wiki-link
1131 "\\|" markdown-regex-link-inline
1132 "\\|" markdown-regex-link-reference
1133 "\\|" markdown-regex-angle-uri "\\)")
1134 "Regular expression for matching any recognized link.")
1136 (defconst markdown-regex-block-separator
1137 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1138 "Regular expression for matching block boundaries.")
1140 (defconst markdown-regex-latex-expression
1141 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1142 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1144 (defconst markdown-regex-latex-display
1145 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1146 "Regular expression for itex \[..\] display mode expressions.")
1148 (defconst markdown-regex-multimarkdown-metadata
1149 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1150 "Regular expression for matching MultiMarkdown metadata.")
1152 (defconst markdown-regex-pandoc-metadata
1153 "^\\(%\\)[ \t]*\\(.*\\)$"
1154 "Regular expression for matching Pandoc metadata.")
1156 (defvar markdown-mode-font-lock-keywords-basic
1157 (list
1158 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1159 (2 markdown-metadata-value-face)))
1160 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1161 (2 markdown-metadata-value-face)))
1162 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1163 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1164 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1165 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1166 (2 markdown-header-rule-face)))
1167 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1168 (2 markdown-header-rule-face)))
1169 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1170 (2 markdown-header-face-1)
1171 (3 markdown-header-delimiter-face)))
1172 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1173 (2 markdown-header-face-2)
1174 (3 markdown-header-delimiter-face)))
1175 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1176 (2 markdown-header-face-3)
1177 (3 markdown-header-delimiter-face)))
1178 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1179 (2 markdown-header-face-4)
1180 (3 markdown-header-delimiter-face)))
1181 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1182 (2 markdown-header-face-5)
1183 (3 markdown-header-delimiter-face)))
1184 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1185 (2 markdown-header-face-6)
1186 (3 markdown-header-delimiter-face)))
1187 (cons markdown-regex-hr 'markdown-header-face)
1188 (cons 'markdown-match-comments '((0 markdown-comment-face t t)))
1189 (cons 'markdown-match-code '((0 markdown-inline-code-face)))
1190 (cons markdown-regex-angle-uri 'markdown-link-face)
1191 (cons markdown-regex-uri 'markdown-link-face)
1192 (cons markdown-regex-email 'markdown-link-face)
1193 (cons markdown-regex-list '(2 markdown-list-face))
1194 (cons markdown-regex-footnote 'markdown-footnote-face)
1195 (cons markdown-regex-link-inline '((1 markdown-link-face t t)
1196 (2 markdown-link-face t)
1197 (4 markdown-url-face t)
1198 (6 markdown-link-title-face t t)))
1199 (cons markdown-regex-link-reference '((1 markdown-link-face t t)
1200 (2 markdown-link-face t)
1201 (4 markdown-reference-face t)))
1202 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1203 (2 markdown-url-face t)
1204 (3 markdown-link-title-face t)))
1205 (cons markdown-regex-bold '(2 markdown-bold-face))
1206 (cons markdown-regex-line-break '(1 markdown-line-break-face prepend))
1208 "Syntax highlighting for Markdown files.")
1210 (defvar markdown-mode-font-lock-keywords-core
1211 (list
1212 (cons markdown-regex-italic '(2 markdown-italic-face))
1214 "Additional syntax highlighting for Markdown files.
1215 Includes features which are overridden by some variants.")
1217 (defconst markdown-mode-font-lock-keywords-latex
1218 (list
1219 ;; Math mode $..$ or $$..$$
1220 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1221 ;; Display mode equations with brackets: \[ \]
1222 (cons markdown-regex-latex-display 'markdown-math-face)
1223 ;; Equation reference (eq:foo)
1224 (cons "(eq:\\w+)" 'markdown-reference-face)
1225 ;; Equation reference \eqref{foo}
1226 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1227 "Syntax highlighting for LaTeX fragments.")
1229 (defvar markdown-mode-font-lock-keywords
1230 (append
1231 (if markdown-enable-math
1232 markdown-mode-font-lock-keywords-latex)
1233 markdown-mode-font-lock-keywords-basic
1234 markdown-mode-font-lock-keywords-core)
1235 "Default highlighting expressions for Markdown mode.")
1237 ;; Footnotes
1238 (defvar markdown-footnote-counter 0
1239 "Counter for footnote numbers.")
1240 (make-variable-buffer-local 'markdown-footnote-counter)
1242 (defconst markdown-footnote-chars
1243 "[[:alnum:]-]"
1244 "Regular expression maching any character that is allowed in a footnote identifier.")
1247 ;;; Compatibility =============================================================
1249 (defun markdown-replace-regexp-in-string (regexp rep string)
1250 "Replace all matches for REGEXP with REP in STRING.
1251 This is a compatibility wrapper to provide `replace-regexp-in-string'
1252 in XEmacs 21."
1253 (if (featurep 'xemacs)
1254 (replace-in-string string regexp rep)
1255 (replace-regexp-in-string regexp rep string)))
1257 ;; `markdown-use-region-p' is a compatibility function which checks
1258 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1259 (eval-and-compile
1260 (cond
1261 ;; Emacs 23 and newer
1262 ((fboundp 'use-region-p)
1263 (defalias 'markdown-use-region-p 'use-region-p))
1264 ;; Older Emacsen
1265 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1266 (defun markdown-use-region-p ()
1267 "Compatibility wrapper to provide `use-region-p'."
1268 (and transient-mark-mode mark-active)))
1269 ;; XEmacs
1270 ((fboundp 'region-active-p)
1271 (defalias 'markdown-use-region-p 'region-active-p))))
1273 (defun markdown-use-buttons-p ()
1274 "Determine whether this Emacs supports buttons."
1275 (or (featurep 'button) (locate-library "button")))
1278 ;;; Markdown Parsing Functions ================================================
1280 (defun markdown-cur-line-blank-p ()
1281 "Return t if the current line is blank and nil otherwise."
1282 (save-excursion
1283 (beginning-of-line)
1284 (re-search-forward "^\\s *$" (line-end-position) t)))
1286 (defun markdown-prev-line-blank-p ()
1287 "Return t if the previous line is blank and nil otherwise.
1288 If we are at the first line, then consider the previous line to be blank."
1289 (or (= (line-beginning-position) (point-min))
1290 (save-excursion
1291 (forward-line -1)
1292 (markdown-cur-line-blank-p))))
1294 (defun markdown-next-line-blank-p ()
1295 "Return t if the next line is blank and nil otherwise.
1296 If we are at the last line, then consider the next line to be blank."
1297 (or (= (line-end-position) (point-max))
1298 (save-excursion
1299 (forward-line 1)
1300 (markdown-cur-line-blank-p))))
1302 (defun markdown-prev-line-indent-p ()
1303 "Return t if the previous line is indented and nil otherwise."
1304 (save-excursion
1305 (forward-line -1)
1306 (goto-char (line-beginning-position))
1307 (if (re-search-forward "^\\s " (line-end-position) t) t)))
1309 (defun markdown-cur-line-indent ()
1310 "Return the number of leading whitespace characters in the current line."
1311 (save-match-data
1312 (save-excursion
1313 (goto-char (line-beginning-position))
1314 (re-search-forward "^[ \t]+" (line-end-position) t)
1315 (current-column))))
1317 (defun markdown-prev-line-indent ()
1318 "Return the number of leading whitespace characters in the previous line."
1319 (save-excursion
1320 (forward-line -1)
1321 (markdown-cur-line-indent)))
1323 (defun markdown-next-line-indent ()
1324 "Return the number of leading whitespace characters in the next line."
1325 (save-excursion
1326 (forward-line 1)
1327 (markdown-cur-line-indent)))
1329 (defun markdown-cur-non-list-indent ()
1330 "Return beginning position of list item text (not including the list marker).
1331 Return nil if the current line is not the beginning of a list item."
1332 (save-match-data
1333 (save-excursion
1334 (beginning-of-line)
1335 (when (re-search-forward markdown-regex-list (line-end-position) t)
1336 (current-column)))))
1338 (defun markdown-prev-non-list-indent ()
1339 "Return position of the first non-list-marker on the previous line."
1340 (save-excursion
1341 (forward-line -1)
1342 (markdown-cur-non-list-indent)))
1344 (defun markdown-new-baseline-p ()
1345 "Determine if the current line begins a new baseline level."
1346 (save-excursion
1347 (beginning-of-line)
1348 (save-match-data
1349 (or (looking-at markdown-regex-header)
1350 (looking-at markdown-regex-hr)
1351 (and (null (markdown-cur-non-list-indent))
1352 (= (markdown-cur-line-indent) 0)
1353 (markdown-prev-line-blank-p))))))
1355 (defun markdown-search-backward-baseline ()
1356 "Search backward baseline point with no indentation and not a list item."
1357 (end-of-line)
1358 (let (stop)
1359 (while (not (or stop (bobp)))
1360 (re-search-backward markdown-regex-block-separator nil t)
1361 (when (match-end 2)
1362 (goto-char (match-end 2))
1363 (cond
1364 ((markdown-new-baseline-p)
1365 (setq stop t))
1366 ((looking-at markdown-regex-list)
1367 (setq stop nil))
1368 (t (setq stop t)))))))
1370 (defun markdown-update-list-levels (marker indent levels)
1371 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1372 Here, MARKER is a string representing the type of list, INDENT is an integer
1373 giving the indentation, in spaces, of the current block, and LEVELS is a
1374 list of the indentation levels of parent list items. When LEVELS is nil,
1375 it means we are at baseline (not inside of a nested list)."
1376 (cond
1377 ;; New list item at baseline.
1378 ((and marker (null levels))
1379 (setq levels (list indent)))
1380 ;; List item with greater indentation (four or more spaces).
1381 ;; Increase list level.
1382 ((and marker (>= indent (+ (car levels) 4)))
1383 (setq levels (cons indent levels)))
1384 ;; List item with greater or equal indentation (less than four spaces).
1385 ;; Do not increase list level.
1386 ((and marker (>= indent (car levels)))
1387 levels)
1388 ;; Lesser indentation level.
1389 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1390 ;; indentation could move back more than one list level). Note
1391 ;; that this block need not be the beginning of list item.
1392 ((< indent (car levels))
1393 (while (and (> (length levels) 1)
1394 (< indent (+ (cadr levels) 4)))
1395 (setq levels (cdr levels)))
1396 levels)
1397 ;; Otherwise, do nothing.
1398 (t levels)))
1400 (defun markdown-calculate-list-levels ()
1401 "Calculate list levels at point.
1402 Return a list of the form (n1 n2 n3 ...) where n1 is the
1403 indentation of the deepest nested list item in the branch of
1404 the list at the point, n2 is the indentation of the parent
1405 list item, and so on. The depth of the list item is therefore
1406 the length of the returned list. If the point is not at or
1407 immediately after a list item, return nil."
1408 (save-excursion
1409 (let ((first (point)) levels indent pre-regexp)
1410 ;; Find a baseline point with zero list indentation
1411 (markdown-search-backward-baseline)
1412 ;; Search for all list items between baseline and LOC
1413 (while (and (< (point) first)
1414 (re-search-forward markdown-regex-list first t))
1415 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1416 (beginning-of-line)
1417 (cond
1418 ;; Make sure this is not a header or hr
1419 ((markdown-new-baseline-p) (setq levels nil))
1420 ;; Make sure this is not a line from a pre block
1421 ((looking-at pre-regexp))
1422 ;; If not, then update levels
1424 (setq indent (markdown-cur-line-indent))
1425 (setq levels (markdown-update-list-levels (match-string 2)
1426 indent levels))))
1427 (end-of-line))
1428 levels)))
1430 (defun markdown-prev-list-item (level)
1431 "Search backward from point for a list item with indentation LEVEL.
1432 Set point to the beginning of the item, and return point, or nil
1433 upon failure."
1434 (let (bounds indent prev)
1435 (setq prev (point))
1436 (forward-line -1)
1437 (setq indent (markdown-cur-line-indent))
1438 (while
1439 (cond
1440 ;; Stop at beginning of buffer
1441 ((bobp) (setq prev nil))
1442 ;; Continue if current line is blank
1443 ((markdown-cur-line-blank-p) t)
1444 ;; List item
1445 ((and (looking-at markdown-regex-list)
1446 (setq bounds (markdown-cur-list-item-bounds)))
1447 (cond
1448 ;; Continue at item with greater indentation
1449 ((> (nth 3 bounds) level) t)
1450 ;; Stop and return point at item of equal indentation
1451 ((= (nth 3 bounds) level)
1452 (setq prev (point))
1453 nil)
1454 ;; Stop and return nil at item with lesser indentation
1455 ((< (nth 3 bounds) level)
1456 (setq prev nil)
1457 nil)))
1458 ;; Continue while indentation is the same or greater
1459 ((>= indent level) t)
1460 ;; Stop if current indentation is less than list item
1461 ;; and the next is blank
1462 ((and (< indent level)
1463 (markdown-next-line-blank-p))
1464 (setq prev nil))
1465 ;; Stop at a header
1466 ((looking-at markdown-regex-header) (setq prev nil))
1467 ;; Stop at a horizontal rule
1468 ((looking-at markdown-regex-hr) (setq prev nil))
1469 ;; Otherwise, continue.
1470 (t t))
1471 (forward-line -1)
1472 (setq indent (markdown-cur-line-indent)))
1473 prev))
1475 (defun markdown-next-list-item (level)
1476 "Search forward from point for the next list item with indentation LEVEL.
1477 Set point to the beginning of the item, and return point, or nil
1478 upon failure."
1479 (let (bounds indent prev next)
1480 (setq next (point))
1481 (forward-line)
1482 (setq indent (markdown-cur-line-indent))
1483 (while
1484 (cond
1485 ;; Stop at end of the buffer.
1486 ((eobp) (setq prev nil))
1487 ;; Continue if the current line is blank
1488 ((markdown-cur-line-blank-p) t)
1489 ;; List item
1490 ((and (looking-at markdown-regex-list)
1491 (setq bounds (markdown-cur-list-item-bounds)))
1492 (cond
1493 ;; Continue at item with greater indentation
1494 ((> (nth 3 bounds) level) t)
1495 ;; Stop and return point at item of equal indentation
1496 ((= (nth 3 bounds) level)
1497 (setq next (point))
1498 nil)
1499 ;; Stop and return nil at item with lesser indentation
1500 ((< (nth 3 bounds) level)
1501 (setq next nil)
1502 nil)))
1503 ;; Continue while indentation is the same or greater
1504 ((>= indent level) t)
1505 ;; Stop if current indentation is less than list item
1506 ;; and the previous line was blank.
1507 ((and (< indent level)
1508 (markdown-prev-line-blank-p))
1509 (setq next nil))
1510 ;; Stop at a header
1511 ((looking-at markdown-regex-header) (setq next nil))
1512 ;; Stop at a horizontal rule
1513 ((looking-at markdown-regex-hr) (setq next nil))
1514 ;; Otherwise, continue.
1515 (t t))
1516 (forward-line)
1517 (setq indent (markdown-cur-line-indent)))
1518 next))
1520 (defun markdown-cur-list-item-end (level)
1521 "Move to the end of the current list item with nonlist indentation LEVEL.
1522 If the point is not in a list item, do nothing."
1523 (let (indent)
1524 (forward-line)
1525 (setq indent (markdown-cur-line-indent))
1526 (while
1527 (cond
1528 ;; Stop at end of the buffer.
1529 ((eobp) nil)
1530 ;; Continue if the current line is blank
1531 ((markdown-cur-line-blank-p) t)
1532 ;; Continue while indentation is the same or greater
1533 ((>= indent level) t)
1534 ;; Stop if current indentation is less than list item
1535 ;; and the previous line was blank.
1536 ((and (< indent level)
1537 (markdown-prev-line-blank-p))
1538 nil)
1539 ;; Stop at a new list item of the same or lesser indentation
1540 ((looking-at markdown-regex-list) nil)
1541 ;; Stop at a header
1542 ((looking-at markdown-regex-header) nil)
1543 ;; Stop at a horizontal rule
1544 ((looking-at markdown-regex-hr) nil)
1545 ;; Otherwise, continue.
1546 (t t))
1547 (forward-line)
1548 (setq indent (markdown-cur-line-indent)))
1549 ;; Don't skip over whitespace for empty list items (marker and
1550 ;; whitespace only), just move to end of whitespace.
1551 (if (looking-back (concat markdown-regex-list "\\s-*"))
1552 (goto-char (match-end 3))
1553 (skip-syntax-backward "-"))))
1555 (defun markdown-cur-list-item-bounds ()
1556 "Return bounds and indentation of the current list item.
1557 Return a list of the form (begin end indent nonlist-indent marker).
1558 If the point is not inside a list item, return nil.
1559 Leave match data intact for `markdown-regex-list'."
1560 (let (cur prev-begin prev-end indent nonlist-indent marker)
1561 ;; Store current location
1562 (setq cur (point))
1563 ;; Verify that cur is between beginning and end of item
1564 (save-excursion
1565 (end-of-line)
1566 (when (re-search-backward markdown-regex-list nil t)
1567 (setq prev-begin (match-beginning 0))
1568 (setq indent (length (match-string 1)))
1569 (setq nonlist-indent (length (match-string 0)))
1570 (setq marker (concat (match-string 2) (match-string 3)))
1571 (save-match-data
1572 (markdown-cur-list-item-end nonlist-indent)
1573 (setq prev-end (point)))
1574 (when (and (>= cur prev-begin)
1575 (<= cur prev-end)
1576 nonlist-indent)
1577 (list prev-begin prev-end indent nonlist-indent marker))))))
1579 (defun markdown-bounds-of-thing-at-point (thing)
1580 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1581 Does not include trailing newlines when THING is 'line. Handles the
1582 end of buffer case by setting both endpoints equal to the value of
1583 `point-max', since an empty region will trigger empty markup insertion.
1584 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1585 (let* ((bounds (bounds-of-thing-at-point thing))
1586 (a (car bounds))
1587 (b (cdr bounds)))
1588 (when bounds
1589 (when (eq thing 'line)
1590 (cond ((and (eobp) (markdown-cur-line-blank-p))
1591 (setq a b))
1592 ((char-equal (char-before b) ?\^J)
1593 (setq b (1- b)))))
1594 (cons a b))))
1596 (defun markdown-reference-definition (reference)
1597 "Find out whether Markdown REFERENCE is defined.
1598 REFERENCE should include the square brackets, like [this].
1599 When REFERENCE is defined, return a list of the form (text start end)
1600 containing the definition text itself followed by the start and end
1601 locations of the text. Otherwise, return nil.
1602 Leave match data for `markdown-regex-reference-definition'
1603 intact additional processing."
1604 (let ((reference (downcase reference)))
1605 (save-excursion
1606 (goto-char (point-min))
1607 (catch 'found
1608 (while (re-search-forward markdown-regex-reference-definition nil t)
1609 (when (string= reference (downcase (match-string-no-properties 1)))
1610 (throw 'found
1611 (list (match-string-no-properties 2)
1612 (match-beginning 2) (match-end 2)))))))))
1614 (defun markdown-get-defined-references ()
1615 "Return a list of all defined reference labels (including square brackets)."
1616 (save-excursion
1617 (goto-char (point-min))
1618 (let (refs)
1619 (while (re-search-forward markdown-regex-reference-definition nil t)
1620 (let ((target (match-string-no-properties 1)))
1621 (add-to-list 'refs target t)))
1622 refs)))
1625 ;;; Markdown Font Lock Matching Functions =====================================
1627 (defun markdown-match-comments (last)
1628 "Match HTML comments from the point to LAST."
1629 (cond ((search-forward "<!--" last t)
1630 (backward-char 4)
1631 (let ((beg (point)))
1632 (cond ((search-forward-regexp "--[ \t]*>" last t)
1633 (set-match-data (list beg (point)))
1635 (t nil))))
1636 (t nil)))
1638 (defun markdown-match-code (last)
1639 "Match inline code from the point to LAST."
1640 (unless (bobp)
1641 (backward-char 1))
1642 (cond ((re-search-forward markdown-regex-code last t)
1643 (set-match-data (list (match-beginning 2) (match-end 2)))
1644 (goto-char (match-end 0))
1646 (t (forward-char 2) nil)))
1648 (defun markdown-match-pre-blocks (last)
1649 "Match Markdown pre blocks from point to LAST."
1650 (let ((levels (markdown-calculate-list-levels))
1651 indent pre-regexp end-regexp begin end stop)
1652 (while (and (< (point) last) (not end))
1653 ;; Search for a region with sufficient indentation
1654 (if (null levels)
1655 (setq indent 1)
1656 (setq indent (1+ (length levels))))
1657 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1658 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1660 (cond
1661 ;; If not at the beginning of a line, move forward
1662 ((not (bolp)) (forward-line))
1663 ;; Move past blank lines
1664 ((markdown-cur-line-blank-p) (forward-line))
1665 ;; At headers and horizontal rules, reset levels
1666 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1667 ;; If the current line has sufficient indentation, mark out pre block
1668 ((looking-at pre-regexp)
1669 (setq begin (match-beginning 0))
1670 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1671 (not (eobp)))
1672 (forward-line))
1673 (setq end (point)))
1674 ;; If current line has a list marker, update levels, move to end of block
1675 ((looking-at markdown-regex-list)
1676 (setq levels (markdown-update-list-levels
1677 (match-string 2) (markdown-cur-line-indent) levels))
1678 (markdown-end-of-block-element))
1679 ;; If this is the end of the indentation level, adjust levels accordingly.
1680 ;; Only match end of indentation level if levels is not the empty list.
1681 ((and (car levels) (looking-at end-regexp))
1682 (setq levels (markdown-update-list-levels
1683 nil (markdown-cur-line-indent) levels))
1684 (markdown-end-of-block-element))
1685 (t (markdown-end-of-block-element))))
1687 (if (not (and begin end))
1688 ;; Return nil if no pre block was found
1690 ;; Set match data and return t upon success
1691 (set-match-data (list begin end))
1692 t)))
1694 (defun markdown-match-fenced-code-blocks (last)
1695 "Match fenced code blocks from the point to LAST."
1696 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1697 (beginning-of-line)
1698 (let ((beg (point)))
1699 (forward-line)
1700 (cond ((search-forward-regexp
1701 (concat "^" (match-string 1) "~*") last t)
1702 (set-match-data (list beg (point)))
1704 (t nil))))
1705 (t nil)))
1707 (defun markdown-match-gfm-code-blocks (last)
1708 "Match GFM quoted code blocks from point to LAST."
1709 (let (open lang body close all)
1710 (cond ((and (eq major-mode 'gfm-mode)
1711 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1712 (beginning-of-line)
1713 (setq open (list (match-beginning 1) (match-end 1))
1714 lang (list (match-beginning 2) (match-end 2)))
1715 (forward-line)
1716 (setq body (list (point)))
1717 (cond ((search-forward-regexp "^```$" last t)
1718 (setq body (reverse (cons (1- (match-beginning 0)) body))
1719 close (list (match-beginning 0) (match-end 0))
1720 all (list (car open) (match-end 0)))
1721 (set-match-data (append all open lang body close))
1723 (t nil)))
1724 (t nil))))
1726 (defun markdown-match-generic-metadata (regexp last)
1727 "Match generic metadata specified by REGEXP from the point to LAST."
1728 (let ((header-end (save-excursion
1729 (goto-char (point-min))
1730 (if (re-search-forward "\n\n" (point-max) t)
1731 (match-beginning 0)
1732 (point-max)))))
1733 (cond ((>= (point) header-end)
1734 ;; Don't match anything outside of the header.
1735 nil)
1736 ((re-search-forward regexp (min last header-end) t)
1737 ;; If a metadata item is found, it may span several lines.
1738 (let ((key-beginning (match-beginning 1))
1739 (key-end (match-end 1))
1740 (value-beginning (match-beginning 2)))
1741 (while (and (not (looking-at regexp))
1742 (not (> (point) (min last header-end)))
1743 (not (eobp)))
1744 (forward-line))
1745 (unless (eobp)
1746 (forward-line -1)
1747 (end-of-line))
1748 (set-match-data (list key-beginning (point) ; complete metadata
1749 key-beginning key-end ; key
1750 value-beginning (point))) ; value
1752 (t nil))))
1754 (defun markdown-match-multimarkdown-metadata (last)
1755 "Match MultiMarkdown metadata from the point to LAST."
1756 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1758 (defun markdown-match-pandoc-metadata (last)
1759 "Match Pandoc metadata from the point to LAST."
1760 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1762 (defun markdown-font-lock-extend-region ()
1763 "Extend the search region to include an entire block of text.
1764 This helps improve font locking for block constructs such as pre blocks."
1765 ;; Avoid compiler warnings about these global variables from font-lock.el.
1766 ;; See the documentation for variable `font-lock-extend-region-functions'.
1767 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1768 (save-excursion
1769 (goto-char font-lock-beg)
1770 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1771 (goto-char font-lock-end)
1772 (when (re-search-forward "\n\n" nil t)
1773 (beginning-of-line)
1774 (setq font-lock-end (point)))
1775 (setq font-lock-beg found))))
1778 ;;; Syntax Table ==============================================================
1780 (defvar markdown-mode-syntax-table
1781 (let ((tab (make-syntax-table text-mode-syntax-table)))
1782 (modify-syntax-entry ?\" "." tab)
1783 tab)
1784 "Syntax table for `markdown-mode'.")
1787 ;;; Element Insertion =========================================================
1789 (defun markdown-ensure-blank-line-before ()
1790 "If previous line is not already blank, insert a blank line before point."
1791 (unless (bolp) (insert "\n"))
1792 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1794 (defun markdown-ensure-blank-line-after ()
1795 "If following line is not already blank, insert a blank line after point.
1796 Return the point where it was originally."
1797 (save-excursion
1798 (unless (eolp) (insert "\n"))
1799 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1801 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1802 "Insert the strings S1 and S2, wrapping around region or THING.
1803 If a region is specified by the optional BEG and END arguments,
1804 wrap the strings S1 and S2 around that region.
1805 If there is an active region, wrap the strings S1 and S2 around
1806 the region. If there is not an active region but the point is at
1807 THING, wrap that thing (which defaults to word). Otherwise, just
1808 insert S1 and S2 and place the cursor in between. Return the
1809 bounds of the entire wrapped string, or nil if nothing was wrapped
1810 and S1 and S2 were only inserted."
1811 (let (a b bounds new-point)
1812 (cond
1813 ;; Given region
1814 ((and beg end)
1815 (setq a beg
1816 b end
1817 new-point (+ (point) (length s1))))
1818 ;; Active region
1819 ((markdown-use-region-p)
1820 (setq a (region-beginning)
1821 b (region-end)
1822 new-point (+ (point) (length s1))))
1823 ;; Thing (word) at point
1824 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1825 (setq a (car bounds)
1826 b (cdr bounds)
1827 new-point (+ (point) (length s1))))
1828 ;; No active region and no word
1830 (setq a (point)
1831 b (point))))
1832 (goto-char b)
1833 (insert s2)
1834 (goto-char a)
1835 (insert s1)
1836 (when new-point (goto-char new-point))
1837 (if (= a b)
1839 (setq b (+ b (length s1) (length s2)))
1840 (cons a b))))
1842 (defun markdown-point-after-unwrap (cur prefix suffix)
1843 "Return desired position of point after an unwrapping operation.
1844 Two cons cells must be provided. PREFIX gives the bounds of the
1845 prefix string and SUFFIX gives the bounds of the suffix string."
1846 (cond ((< cur (cdr prefix)) (car prefix))
1847 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1848 ((<= cur (cdr suffix))
1849 (- cur (+ (- (cdr prefix) (car prefix))
1850 (- cur (car suffix)))))
1851 (t cur)))
1853 (defun markdown-unwrap-thing-at-point (regexp all text)
1854 "Remove prefix and suffix of thing at point and reposition the point.
1855 When the thing at point matches REGEXP, replace the subexpression
1856 ALL with the string in subexpression TEXT. Reposition the point
1857 in an appropriate location accounting for the removal of prefix
1858 and suffix strings. Return new bounds of string from group TEXT.
1859 When REGEXP is nil, assumes match data is already set."
1860 (when (or (null regexp)
1861 (thing-at-point-looking-at regexp))
1862 (let ((cur (point))
1863 (prefix (cons (match-beginning all) (match-beginning text)))
1864 (suffix (cons (match-end text) (match-end all)))
1865 (bounds (cons (match-beginning text) (match-end text))))
1866 ;; Replace the thing at point
1867 (replace-match (match-string text) t t nil all)
1868 ;; Reposition the point
1869 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1870 ;; Adjust bounds
1871 (setq bounds (cons (car prefix)
1872 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1874 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1875 "Remove prefix and suffix of all things in region.
1876 When a thing in the region matches REGEXP, replace the
1877 subexpression ALL with the string in subexpression TEXT.
1878 Return a cons cell containing updated bounds for the region."
1879 (save-excursion
1880 (goto-char beg)
1881 (let ((removed 0) len-all len-text)
1882 (while (re-search-forward regexp (- end removed) t)
1883 (setq len-all (length (match-string-no-properties all)))
1884 (setq len-text (length (match-string-no-properties text)))
1885 (setq removed (+ removed (- len-all len-text)))
1886 (replace-match (match-string text) t t nil all))
1887 (cons beg (- end removed)))))
1889 (defun markdown-insert-hr (arg)
1890 "Insert or replace a horizonal rule.
1891 By default, use the first element of `markdown-hr-strings'. When
1892 prefixed with C-u, use the last element of `markdown-hr-strings'
1893 instead. When prefixed with an integer from 1 to the length of
1894 `markdown-hr-strings', use the element in that position instead."
1895 (interactive "*P")
1896 (when (thing-at-point-looking-at markdown-regex-hr)
1897 (delete-region (match-beginning 0) (match-end 0)))
1898 (markdown-ensure-blank-line-before)
1899 (cond ((equal arg '(4))
1900 (insert (car (reverse markdown-hr-strings))))
1901 ((and (integerp arg) (> arg 0)
1902 (<= arg (length markdown-hr-strings)))
1903 (insert (nth (1- arg) markdown-hr-strings)))
1905 (insert (car markdown-hr-strings))))
1906 (markdown-ensure-blank-line-after))
1908 (defun markdown-insert-bold ()
1909 "Insert markup to make a region or word bold.
1910 If there is an active region, make the region bold. If the point
1911 is at a non-bold word, make the word bold. If the point is at a
1912 bold word or phrase, remove the bold markup. Otherwise, simply
1913 insert bold delimiters and place the cursor in between them."
1914 (interactive)
1915 (let ((delim (if markdown-bold-underscore "__" "**")))
1916 (if (markdown-use-region-p)
1917 ;; Active region
1918 (let ((bounds (markdown-unwrap-things-in-region
1919 (region-beginning) (region-end)
1920 markdown-regex-bold 2 4)))
1921 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1922 ;; Bold markup removal, bold word at point, or empty markup insertion
1923 (if (thing-at-point-looking-at markdown-regex-bold)
1924 (markdown-unwrap-thing-at-point nil 2 4)
1925 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1927 (defun markdown-insert-italic ()
1928 "Insert markup to make a region or word italic.
1929 If there is an active region, make the region italic. If the point
1930 is at a non-italic word, make the word italic. If the point is at an
1931 italic word or phrase, remove the italic markup. Otherwise, simply
1932 insert italic delimiters and place the cursor in between them."
1933 (interactive)
1934 (let ((delim (if markdown-italic-underscore "_" "*")))
1935 (if (markdown-use-region-p)
1936 ;; Active region
1937 (let ((bounds (markdown-unwrap-things-in-region
1938 (region-beginning) (region-end)
1939 markdown-regex-italic 2 4)))
1940 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1941 ;; Italic markup removal, italic word at point, or empty markup insertion
1942 (if (thing-at-point-looking-at markdown-regex-italic)
1943 (markdown-unwrap-thing-at-point nil 2 4)
1944 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1946 (defun markdown-insert-code ()
1947 "Insert markup to make a region or word an inline code fragment.
1948 If there is an active region, make the region an inline code
1949 fragment. If the point is at a word, make the word an inline
1950 code fragment. Otherwise, simply insert code delimiters and
1951 place the cursor in between them."
1952 (interactive)
1953 (if (markdown-use-region-p)
1954 ;; Active region
1955 (let ((bounds (markdown-unwrap-things-in-region
1956 (region-beginning) (region-end)
1957 markdown-regex-code 2 4)))
1958 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1959 ;; Code markup removal, code markup for word, or empty markup insertion
1960 (if (thing-at-point-looking-at markdown-regex-code)
1961 (markdown-unwrap-thing-at-point nil 2 4)
1962 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1964 (defun markdown-insert-link ()
1965 "Insert an inline link, using region or word as link text if possible.
1966 If there is an active region, use the region as the link text. If the
1967 point is at a word, use the word as the link text. In these cases, the
1968 point will be left at the position for inserting a URL. If there is no
1969 active region and the point is not at word, simply insert link markup and
1970 place the point in the position to enter link text."
1971 (interactive)
1972 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1973 (when bounds
1974 (goto-char (- (cdr bounds) 1)))))
1976 (defun markdown-insert-reference-link (text label &optional url title)
1977 "Insert a reference link and, optionally, a reference definition.
1978 The link TEXT will be inserted followed by the optional LABEL.
1979 If a URL is given, also insert a definition for the reference
1980 LABEL after the end of the paragraph. If a TITLE is given, it
1981 will be added to the end of the reference definition and will be
1982 used to populate the title attribute when converted to XHTML. If
1983 URL is nil, insert only the link portion (for example, when a
1984 reference label is already defined)."
1985 (let (end)
1986 (insert (concat "[" text "][" label "]"))
1987 (setq end (point))
1988 (when url
1989 (forward-paragraph)
1990 (unless (markdown-cur-line-blank-p) (insert "\n"))
1991 (insert "\n[" (if (> (length label) 0) label text) "]: " url)
1992 (unless (> (length url) 0)
1993 (setq end (point)))
1994 (when (> (length title) 0)
1995 (insert " \"" title "\""))
1996 (insert "\n")
1997 (unless (or (eobp) (looking-at "\n"))
1998 (insert "\n"))
1999 (goto-char end))))
2001 (defun markdown-insert-reference-link-dwim ()
2002 "Insert a reference link of the form [text][label] at point.
2003 If there is an active region, the text in the region will be used
2004 as the link text. If the point is at a word, it will be used as
2005 the link text. Otherwise, the link text will be read from the
2006 minibuffer. The link label will be read from the minibuffer in
2007 both cases, with completion from the set of currently defined
2008 references. To create an implicit reference link, press RET to
2009 accept the default, an empty label. If the entered referenced
2010 label is not defined, additionally prompt for the URL
2011 and (optional) title. The reference definition is placed at the
2012 end of the current paragraph."
2013 (interactive)
2014 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2015 (markdown-get-defined-references)))
2016 (bounds (or (and (markdown-use-region-p)
2017 (cons (region-beginning) (region-end)))
2018 (markdown-bounds-of-thing-at-point 'word)))
2019 (text (if bounds
2020 (buffer-substring (car bounds) (cdr bounds))
2021 (read-string "Link Text: ")))
2022 (label (completing-read
2023 "Link Label (default: none): " defined-labels
2024 nil nil nil 'markdown-reference-label-history nil))
2025 (ref (markdown-reference-definition
2026 (concat "[" (if (> (length label) 0) label text) "]")))
2027 (url (unless ref (read-string "Link URL: ")))
2028 (title (when (> (length url) 0)
2029 (read-string "Link Title (optional): "))))
2030 (when bounds (delete-region (car bounds) (cdr bounds)))
2031 (markdown-insert-reference-link text label url title)))
2033 (defun markdown-insert-wiki-link ()
2034 "Insert a wiki link of the form [[WikiLink]].
2035 If Transient Mark mode is on and a region is active, it is used
2036 as the link text."
2037 (interactive)
2038 (markdown-wrap-or-insert "[[" "]]")
2039 (backward-char 2))
2041 (defun markdown-insert-image (&optional arg)
2042 "Insert image markup using region or word as alt text if possible.
2043 If there is an active region, use the region as the alt text. If the
2044 point is at a word, use the word as the alt text. In these cases, the
2045 point will be left at the position for inserting a URL. If there is no
2046 active region and the point is not at word, simply insert image markup and
2047 place the point in the position to enter alt text. If ARG is nil, insert
2048 inline image markup. Otherwise, insert reference image markup."
2049 (interactive "*P")
2050 (let ((bounds (if arg
2051 (markdown-wrap-or-insert "![" "][]")
2052 (markdown-wrap-or-insert "![" "]()"))))
2053 (when bounds
2054 (goto-char (- (cdr bounds) 1)))))
2056 (defun markdown-remove-header ()
2057 "Remove header markup if point is at a header.
2058 Return bounds of remaining header text if a header was removed
2059 and nil otherwise."
2060 (interactive "*")
2061 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2062 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2064 (defun markdown-insert-header (&optional level text setext)
2065 "Insert or replace header markup.
2066 The level of the header is specified by LEVEL and header text is
2067 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2068 default value is 1.
2069 When TEXT is nil, the header text is obtained as follows.
2070 If there is an active region, it is used as the header text.
2071 Otherwise, the current line will be used as the header text.
2072 If there is not an active region and the point is at a header,
2073 remove the header markup and replace with level N header.
2074 Otherwise, insert empty header markup and place the cursor in
2075 between.
2076 The style of the header will be atx (hash marks) unless
2077 SETEXT is non-nil, in which case a setext-style (underlined)
2078 header will be inserted."
2079 (interactive "p\nsHeader text: ")
2080 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2081 ;; Determine header text if not given
2082 (when (null text)
2083 (if (markdown-use-region-p)
2084 ;; Active region
2085 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2086 ;; No active region
2087 (markdown-remove-header)
2088 (setq text (delete-and-extract-region
2089 (line-beginning-position) (line-end-position)))
2090 (when (and setext (string-match "^[ \t]*$" text))
2091 (setq text (read-string "Header text: "))))
2092 (setq text (markdown-compress-whitespace-string text)))
2093 ;; Insertion with given text
2094 (markdown-ensure-blank-line-before)
2095 (let (hdr)
2096 (cond (setext
2097 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2098 (insert text "\n" hdr))
2100 (setq hdr (make-string level ?#))
2101 (insert hdr " " text " " hdr))))
2102 (markdown-ensure-blank-line-after)
2103 ;; Leave point at end of text
2104 (if setext
2105 (backward-char (1+ (length text)))
2106 (backward-char (1+ level))))
2108 (defun markdown-insert-header-dwim (&optional arg setext)
2109 "Insert or replace header markup.
2110 The level and type of the header are determined automatically by
2111 the type and level of the previous header, unless a prefix
2112 argument is given.
2113 With a numeric prefix valued 1 to 6, insert a header of the given
2114 level, with the type being determined automatically (note that
2115 only level 1 or 2 setext headers are possible).
2116 With C-u, insert a level-one setext header.
2117 With C-u C-u, insert a level two setext header.
2119 When there is an active region, use it for the header text. When
2120 the point is at an existing header, change the type and level
2121 according to the rules above.
2122 Otherwise, if the line is not empty, create a header using the
2123 text on the current line as the header text.
2124 Finally, if the point is on a blank line, insert empty header
2125 markup (atx) or prompt for text (setext).
2126 See `markdown-insert-header' for more details about how the
2127 header text is determined."
2128 (interactive "*P")
2129 (let (level)
2130 (cond ((equal arg '(4)) ; level-one setext with C-u
2131 (setq setext t)
2132 (setq level 1))
2133 ((equal arg '(16)) ; level-two setext with C-u C-u
2134 (setq setext t)
2135 (setq level 2))
2136 (t ; automatic with numeric override
2137 (save-excursion
2138 (when (re-search-backward markdown-regex-header nil t)
2139 ;; level of previous header
2140 (setq level (markdown-outline-level))
2141 ;; match groups 1 and 2 indicate setext headers
2142 (setq setext (or setext (match-end 1) (match-end 3)))))
2143 ;; use prefix if given, or level of previous header
2144 (setq level (if arg (prefix-numeric-value arg) level))
2145 ;; setext headers must be level one or two
2146 (and level (setq setext (and setext (<= level 2))))))
2147 (markdown-insert-header level nil setext)))
2149 (defun markdown-insert-header-setext-dwim (&optional arg)
2150 "Insert or replace header markup, with preference for setext.
2151 See `markdown-insert-header-dwim' for details."
2152 (interactive "*P")
2153 (markdown-insert-header-dwim arg t))
2155 (defun markdown-insert-header-atx-1 ()
2156 "Insert a first level atx-style (hash mark) header.
2157 See `markdown-insert-header'."
2158 (interactive "*")
2159 (markdown-insert-header 1 nil nil))
2161 (defun markdown-insert-header-atx-2 ()
2162 "Insert a level two atx-style (hash mark) header.
2163 See `markdown-insert-header'."
2164 (interactive "*")
2165 (markdown-insert-header 2 nil nil))
2167 (defun markdown-insert-header-atx-3 ()
2168 "Insert a level three atx-style (hash mark) header.
2169 See `markdown-insert-header'."
2170 (interactive "*")
2171 (markdown-insert-header 3 nil nil))
2173 (defun markdown-insert-header-atx-4 ()
2174 "Insert a level four atx-style (hash mark) header.
2175 See `markdown-insert-header'."
2176 (interactive "*")
2177 (markdown-insert-header 4 nil nil))
2179 (defun markdown-insert-header-atx-5 ()
2180 "Insert a level five atx-style (hash mark) header.
2181 See `markdown-insert-header'."
2182 (interactive "*")
2183 (markdown-insert-header 5 nil nil))
2185 (defun markdown-insert-header-atx-6 ()
2186 "Insert a sixth level atx-style (hash mark) header.
2187 See `markdown-insert-header'."
2188 (interactive "*")
2189 (markdown-insert-header 6 nil nil))
2191 (defun markdown-insert-header-setext-1 ()
2192 "Insert a setext-style (underlined) first-level header.
2193 See `markdown-insert-header'."
2194 (interactive "*")
2195 (markdown-insert-header 1 nil t))
2197 (defun markdown-insert-header-setext-2 ()
2198 "Insert a setext-style (underlined) second-level header.
2199 See `markdown-insert-header'."
2200 (interactive "*")
2201 (markdown-insert-header 2 nil t))
2203 (defun markdown-blockquote-indentation (loc)
2204 "Return string containing necessary indentation for a blockquote at LOC.
2205 Also see `markdown-pre-indentation'."
2206 (save-excursion
2207 (goto-char loc)
2208 (let* ((list-level (length (markdown-calculate-list-levels)))
2209 (indent ""))
2210 (dotimes (count list-level indent)
2211 (setq indent (concat indent " "))))))
2213 (defun markdown-insert-blockquote ()
2214 "Start a blockquote section (or blockquote the region).
2215 If Transient Mark mode is on and a region is active, it is used as
2216 the blockquote text."
2217 (interactive)
2218 (if (markdown-use-region-p)
2219 (markdown-blockquote-region (region-beginning) (region-end))
2220 (markdown-ensure-blank-line-before)
2221 (insert (markdown-blockquote-indentation (point)) "> ")
2222 (markdown-ensure-blank-line-after)))
2224 (defun markdown-block-region (beg end prefix)
2225 "Format the region using a block prefix.
2226 Arguments BEG and END specify the beginning and end of the
2227 region. The characters PREFIX will appear at the beginning
2228 of each line."
2229 (save-excursion
2230 (let* ((end-marker (make-marker))
2231 (beg-marker (make-marker)))
2232 ;; Ensure blank line after and remove extra whitespace
2233 (goto-char end)
2234 (skip-syntax-backward "-")
2235 (set-marker end-marker (point))
2236 (delete-horizontal-space)
2237 (markdown-ensure-blank-line-after)
2238 ;; Ensure blank line before and remove extra whitespace
2239 (goto-char beg)
2240 (skip-syntax-forward "-")
2241 (delete-horizontal-space)
2242 (markdown-ensure-blank-line-before)
2243 (set-marker beg-marker (point))
2244 ;; Insert PREFIX before each line
2245 (goto-char beg-marker)
2246 (while (and (< (line-beginning-position) end-marker)
2247 (not (eobp)))
2248 (insert prefix)
2249 (forward-line)))))
2251 (defun markdown-blockquote-region (beg end)
2252 "Blockquote the region.
2253 Arguments BEG and END specify the beginning and end of the region."
2254 (interactive "*r")
2255 (markdown-block-region
2256 beg end (concat (markdown-blockquote-indentation
2257 (max (point-min) (1- beg))) "> ")))
2259 (defun markdown-pre-indentation (loc)
2260 "Return string containing necessary whitespace for a pre block at LOC.
2261 Also see `markdown-blockquote-indentation'."
2262 (save-excursion
2263 (goto-char loc)
2264 (let* ((list-level (length (markdown-calculate-list-levels)))
2265 indent)
2266 (dotimes (count (1+ list-level) indent)
2267 (setq indent (concat indent " "))))))
2269 (defun markdown-insert-pre ()
2270 "Start a preformatted section (or apply to the region).
2271 If Transient Mark mode is on and a region is active, it is marked
2272 as preformatted text."
2273 (interactive)
2274 (if (markdown-use-region-p)
2275 (markdown-pre-region (region-beginning) (region-end))
2276 (markdown-ensure-blank-line-before)
2277 (insert (markdown-pre-indentation (point)))
2278 (markdown-ensure-blank-line-after)))
2280 (defun markdown-pre-region (beg end)
2281 "Format the region as preformatted text.
2282 Arguments BEG and END specify the beginning and end of the region."
2283 (interactive "*r")
2284 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2285 (markdown-block-region beg end indent)))
2287 (defun markdown-insert-gfm-code-block (&optional lang)
2288 "Insert GFM code block for language LANG.
2289 If LANG is nil, the language will be queried from user. If a
2290 region is active, wrap this region with the markup instead. If
2291 the region boundaries are not on empty lines, these are added
2292 automatically in order to have the correct markup."
2293 (interactive "sProgramming language: ")
2294 (if (markdown-use-region-p)
2295 (let ((b (region-beginning)) (e (region-end)))
2296 (goto-char b)
2297 ;; if we're on a blank line, insert the quotes here, otherwise
2298 ;; add a new line first
2299 (unless (looking-at "\n")
2300 (newline)
2301 (forward-line -1)
2302 (setq e (1+ e)))
2303 (insert "```" lang)
2304 (goto-char (+ e 3 (length lang)))
2305 ;; if we're on a blank line, don't newline, otherwise the ```
2306 ;; should go on its own line
2307 (unless (looking-back "\n")
2308 (newline))
2309 (insert "```"))
2310 (insert "```" lang)
2311 (newline 2)
2312 (insert "```")
2313 (forward-line -1)))
2316 ;;; Footnotes ======================================================================
2318 (defun markdown-footnote-counter-inc ()
2319 "Increment `markdown-footnote-counter' and return the new value."
2320 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2321 (save-excursion
2322 (goto-char (point-min))
2323 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2324 (point-max) t)
2325 (let ((fn (string-to-number (match-string 1))))
2326 (when (> fn markdown-footnote-counter)
2327 (setq markdown-footnote-counter fn))))))
2328 (incf markdown-footnote-counter))
2330 (defun markdown-footnote-new ()
2331 "Insert footnote with a new number and move point to footnote definition."
2332 (interactive)
2333 (let ((fn (markdown-footnote-counter-inc)))
2334 (insert (format "[^%d]" fn))
2335 (markdown-footnote-text-find-new-location)
2336 (markdown-ensure-blank-line-before)
2337 (unless (markdown-cur-line-blank-p)
2338 (insert "\n"))
2339 (insert (format "[^%d]: " fn))
2340 (markdown-ensure-blank-line-after)))
2342 (defun markdown-footnote-text-find-new-location ()
2343 "Position the cursor at the proper location for a new footnote text."
2344 (cond
2345 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2346 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
2347 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2349 (defun markdown-footnote-kill ()
2350 "Kill the footnote at point.
2351 The footnote text is killed (and added to the kill ring), the
2352 footnote marker is deleted. Point has to be either at the
2353 footnote marker or in the footnote text."
2354 (interactive)
2355 (let (return-pos)
2356 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2357 (markdown-footnote-return) ; we first move to the marker
2358 (setq return-pos 'text)) ; and remember our return position
2359 (let ((marker (markdown-footnote-delete-marker)))
2360 (unless marker
2361 (error "Not at a footnote"))
2362 (let ((text-pos (markdown-footnote-find-text (car marker))))
2363 (unless text-pos
2364 (error "No text for footnote `%s'" (car marker)))
2365 (goto-char text-pos)
2366 (let ((pos (markdown-footnote-kill-text)))
2367 (setq return-pos
2368 (if (and pos (eq return-pos 'text))
2370 (cadr marker))))))
2371 (goto-char return-pos)))
2373 (defun markdown-footnote-delete-marker ()
2374 "Delete a footnote marker at point.
2375 Returns a list (ID START) containing the footnote ID and the
2376 start position of the marker before deletion. If no footnote
2377 marker was deleted, this function returns NIL."
2378 (let ((marker (markdown-footnote-marker-positions)))
2379 (when marker
2380 (delete-region (second marker) (third marker))
2381 (butlast marker))))
2383 (defun markdown-footnote-kill-text ()
2384 "Kill footnote text at point.
2385 Returns the start position of the footnote text before deletion,
2386 or NIL if point was not inside a footnote text.
2388 The killed text is placed in the kill ring (without the footnote
2389 number)."
2390 (let ((fn (markdown-footnote-text-positions)))
2391 (when fn
2392 (let ((text (delete-and-extract-region (second fn) (third fn))))
2393 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2394 (kill-new (match-string 1 text))
2395 (when (and (markdown-cur-line-blank-p)
2396 (markdown-prev-line-blank-p))
2397 (delete-region (1- (point)) (point)))
2398 (second fn)))))
2400 (defun markdown-footnote-goto-text ()
2401 "Jump to the text of the footnote at point."
2402 (interactive)
2403 (let ((fn (car (markdown-footnote-marker-positions))))
2404 (unless fn
2405 (error "Not at a footnote marker"))
2406 (let ((new-pos (markdown-footnote-find-text fn)))
2407 (unless new-pos
2408 (error "No definition found for footnote `%s'" fn))
2409 (goto-char new-pos))))
2411 (defun markdown-footnote-return ()
2412 "Return from a footnote to its footnote number in the main text."
2413 (interactive)
2414 (let ((fn (save-excursion
2415 (car (markdown-footnote-text-positions)))))
2416 (unless fn
2417 (error "Not in a footnote"))
2418 (let ((new-pos (markdown-footnote-find-marker fn)))
2419 (unless new-pos
2420 (error "Footnote marker `%s' not found" fn))
2421 (goto-char new-pos))))
2423 (defun markdown-footnote-find-marker (id)
2424 "Find the location of the footnote marker with ID.
2425 The actual buffer position returned is the position directly
2426 following the marker's closing bracket. If no marker is found,
2427 NIL is returned."
2428 (save-excursion
2429 (goto-char (point-min))
2430 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2431 (skip-chars-backward "^]")
2432 (point))))
2434 (defun markdown-footnote-find-text (id)
2435 "Find the location of the text of footnote ID.
2436 The actual buffer position returned is the position of the first
2437 character of the text, after the footnote's identifier. If no
2438 footnote text is found, NIL is returned."
2439 (save-excursion
2440 (goto-char (point-min))
2441 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2442 (skip-chars-forward "[ \t]")
2443 (point))))
2445 (defun markdown-footnote-marker-positions ()
2446 "Return the position and ID of the footnote marker point is on.
2447 The return value is a list (ID START END). If point is not on a
2448 footnote, NIL is returned."
2449 ;; first make sure we're at a footnote marker
2450 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2451 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2452 (save-excursion
2453 ;; move point between [ and ^:
2454 (if (looking-at "\\[")
2455 (forward-char 1)
2456 (skip-chars-backward "^["))
2457 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2458 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2460 (defun markdown-footnote-text-positions ()
2461 "Return the start and end positions of the footnote text point is in.
2462 The exact return value is a list of three elements: (ID START END).
2463 The start position is the position of the opening bracket
2464 of the footnote id. The end position is directly after the
2465 newline that ends the footnote. If point is not in a footnote,
2466 NIL is returned instead."
2467 (save-excursion
2468 (let ((fn (progn
2469 (backward-paragraph)
2470 ;; if we're in a multiparagraph footnote, we need to back up further
2471 (while (>= (markdown-next-line-indent) 4)
2472 (backward-paragraph))
2473 (forward-line)
2474 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2475 (list (match-string 1) (point))))))
2476 (when fn
2477 (while (progn
2478 (forward-paragraph)
2479 (>= (markdown-next-line-indent) 4)))
2480 (append fn (list (point)))))))
2483 ;;; Element Removal ===========================================================
2485 (defun markdown-kill-thing-at-point ()
2486 "Kill thing at point and add important text, without markup, to kill ring.
2487 Possible things to kill include (roughly in order of precedence):
2488 inline code, headers, horizonal rules, links (add link text to
2489 kill ring), images (add alt text to kill ring), angle uri, email
2490 addresses, bold, italics, reference definition (add URI to kill
2491 ring), footnote markers and text (kill both marker and text, add
2492 text to kill ring), and list items."
2493 (interactive "*")
2494 (let (val tmp)
2495 (cond
2496 ;; Inline code
2497 ((thing-at-point-looking-at markdown-regex-code)
2498 (kill-new (match-string 4))
2499 (delete-region (match-beginning 2) (match-end 2)))
2500 ;; ATX header
2501 ((thing-at-point-looking-at markdown-regex-header-atx)
2502 (kill-new (match-string 2))
2503 (delete-region (match-beginning 0) (match-end 0)))
2504 ;; Setext header
2505 ((thing-at-point-looking-at markdown-regex-header-setext)
2506 (kill-new (match-string 1))
2507 (delete-region (match-beginning 0) (match-end 0)))
2508 ;; Horizonal rule
2509 ((thing-at-point-looking-at markdown-regex-hr)
2510 (kill-new (match-string 0))
2511 (delete-region (match-beginning 0) (match-end 0)))
2512 ;; Inline link or image (add link or alt text to kill ring)
2513 ((thing-at-point-looking-at markdown-regex-link-inline)
2514 (kill-new (match-string 3))
2515 (delete-region (match-beginning 0) (match-end 0)))
2516 ;; Reference link or image (add link or alt text to kill ring)
2517 ((thing-at-point-looking-at markdown-regex-link-reference)
2518 (kill-new (match-string 3))
2519 (delete-region (match-beginning 0) (match-end 0)))
2520 ;; Angle URI (add URL to kill ring)
2521 ((thing-at-point-looking-at markdown-regex-angle-uri)
2522 (kill-new (match-string 2))
2523 (delete-region (match-beginning 0) (match-end 0)))
2524 ;; Email address in angle brackets (add email address to kill ring)
2525 ((thing-at-point-looking-at markdown-regex-email)
2526 (kill-new (match-string 1))
2527 (delete-region (match-beginning 0) (match-end 0)))
2528 ;; Wiki link (add alias text to kill ring)
2529 ((thing-at-point-looking-at markdown-regex-wiki-link)
2530 (kill-new (if markdown-wiki-link-alias-first
2531 (match-string-no-properties 2)
2532 (or (match-string-no-properties 2) (match-string-no-properties 4))))
2533 (delete-region (match-beginning 1) (match-end 1)))
2534 ;; Bold
2535 ((thing-at-point-looking-at markdown-regex-bold)
2536 (kill-new (match-string 4))
2537 (delete-region (match-beginning 2) (match-end 2)))
2538 ;; Italics
2539 ((thing-at-point-looking-at markdown-regex-italic)
2540 (kill-new (match-string 4))
2541 (delete-region (match-beginning 2) (match-end 2)))
2542 ;; Reference definition (add URL to kill ring)
2543 ((thing-at-point-looking-at markdown-regex-reference-definition)
2544 (kill-new (match-string 2))
2545 (delete-region (match-beginning 0) (match-end 0)))
2546 ;; Footnote marker (add footnote text to kill ring)
2547 ((thing-at-point-looking-at markdown-regex-footnote)
2548 (markdown-footnote-kill))
2549 ;; Footnote text (add footnote text to kill ring)
2550 ((setq val (markdown-footnote-text-positions))
2551 (markdown-footnote-kill))
2552 ;; List item
2553 ((setq val (markdown-cur-list-item-bounds))
2554 (kill-new (delete-and-extract-region (first val) (second val))))
2556 (error "Nothing found at point to kill")))))
2559 ;;; Indentation ====================================================================
2561 (defun markdown-indent-find-next-position (cur-pos positions)
2562 "Return the position after the index of CUR-POS in POSITIONS.
2563 Positions are calculated by `markdown-calc-indents'."
2564 (while (and positions
2565 (not (equal cur-pos (car positions))))
2566 (setq positions (cdr positions)))
2567 (or (cadr positions) 0))
2569 (defun markdown-exdent-find-next-position (cur-pos positions)
2570 "Return the maximal position in POSITIONS that precedes CUR-POS.
2571 Positions are calculated by `markdown-calc-indents'."
2572 (let ((result 0))
2573 (dolist (i positions)
2574 (when (< i cur-pos)
2575 (setq result (max result i))))
2576 result))
2578 (defun markdown-indent-line ()
2579 "Indent the current line using some heuristics.
2580 If the _previous_ command was either `markdown-enter-key' or
2581 `markdown-cycle', then we should cycle to the next
2582 reasonable indentation position. Otherwise, we could have been
2583 called directly by `markdown-enter-key', by an initial call of
2584 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2585 these cases, indent to the default position.
2586 Positions are calculated by `markdown-calc-indents'."
2587 (interactive)
2588 (let ((positions (markdown-calc-indents))
2589 (cur-pos (current-column)))
2590 (if (not (equal this-command 'markdown-cycle))
2591 (indent-line-to (car positions))
2592 (setq positions (sort (delete-dups positions) '<))
2593 (indent-line-to
2594 (markdown-indent-find-next-position cur-pos positions)))))
2596 (defun markdown-calc-indents ()
2597 "Return a list of indentation columns to cycle through.
2598 The first element in the returned list should be considered the
2599 default indentation level. This function does not worry about
2600 duplicate positions, which are handled up by calling functions."
2601 (let (pos prev-line-pos positions)
2603 ;; Indentation of previous line
2604 (setq prev-line-pos (markdown-prev-line-indent))
2605 (setq positions (cons prev-line-pos positions))
2607 ;; Indentation of previous non-list-marker text
2608 (when (setq pos (markdown-prev-non-list-indent))
2609 (setq positions (cons pos positions)))
2611 ;; Indentation required for a pre block in current context
2612 (setq pos (length (markdown-pre-indentation (point))))
2613 (setq positions (cons pos positions))
2615 ;; Indentation of the previous line + tab-width
2616 (if prev-line-pos
2617 (setq positions (cons (+ prev-line-pos tab-width) positions))
2618 (setq positions (cons tab-width positions)))
2620 ;; Indentation of the previous line - tab-width
2621 (if (and prev-line-pos (> prev-line-pos tab-width))
2622 (setq positions (cons (- prev-line-pos tab-width) positions)))
2624 ;; Indentation of all preceeding list markers (when in a list)
2625 (when (setq pos (markdown-calculate-list-levels))
2626 (setq positions (append pos positions)))
2628 ;; First column
2629 (setq positions (cons 0 positions))
2631 ;; Return reversed list
2632 (reverse positions)))
2634 (defun markdown-do-normal-return ()
2635 "Insert a newline and optionally indent the next line."
2636 (newline)
2637 (if markdown-indent-on-enter
2638 (funcall indent-line-function)))
2640 (defun markdown-enter-key ()
2641 "Handle RET according to context.
2642 If there is a wiki link at the point, follow it unless
2643 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2644 it in the usual way."
2645 (interactive)
2646 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2647 (markdown-follow-wiki-link-at-point)
2648 (markdown-do-normal-return)))
2650 (defun markdown-exdent-or-delete (arg)
2651 "Handle BACKSPACE by cycling through indentation points.
2652 When BACKSPACE is pressed, if there is only whitespace
2653 before the current point, then exdent the line one level.
2654 Otherwise, do normal delete by repeating
2655 `backward-delete-char-untabify' ARG times."
2656 (interactive "*p")
2657 (let ((cur-pos (current-column))
2658 (start-of-indention (save-excursion
2659 (back-to-indentation)
2660 (current-column)))
2661 (positions (markdown-calc-indents)))
2662 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2663 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
2664 (backward-delete-char-untabify arg))))
2667 ;;; Markup Completion =========================================================
2669 (defconst markdown-complete-alist
2670 '((markdown-regex-header-atx . markdown-complete-atx)
2671 (markdown-regex-header-setext . markdown-complete-setext)
2672 (markdown-regex-hr . markdown-complete-hr))
2673 "Association list of form (regexp . function) for markup completion.")
2675 (defun markdown-incomplete-atx-p ()
2676 "Return t if ATX header markup is incomplete and nil otherwise.
2677 Assumes match data is available for `markdown-regex-header-atx'.
2678 Checks that the number of trailing hash marks equals the number of leading
2679 hash marks, that there is only a single space before and after the text,
2680 and that there is no extraneous whitespace in the text."
2681 (save-match-data
2682 (or (not (= (length (match-string 1)) (length (match-string 3))))
2683 (not (= (match-beginning 2) (1+ (match-end 1))))
2684 (not (= (match-beginning 3) (1+ (match-end 2))))
2685 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2687 (defun markdown-complete-atx ()
2688 "Complete and normalize ATX headers.
2689 Add or remove hash marks to the end of the header to match the
2690 beginning. Ensure that there is only a single space between hash
2691 marks and header text. Removes extraneous whitespace from header text.
2692 Assumes match data is available for `markdown-regex-header-atx'."
2693 (when (markdown-incomplete-atx-p)
2694 (let* ((new-marker (make-marker))
2695 (new-marker (set-marker new-marker (match-end 2))))
2696 ;; Hash marks and spacing at end
2697 (goto-char (match-end 2))
2698 (delete-region (match-end 2) (match-end 3))
2699 (insert " " (match-string 1))
2700 ;; Remove extraneous whitespace from title
2701 (replace-match (markdown-compress-whitespace-string (match-string 2))
2702 t t nil 2)
2703 ;; Spacing at beginning
2704 (goto-char (match-end 1))
2705 (delete-region (match-end 1) (match-beginning 2))
2706 (insert " ")
2707 ;; Leave point at end of text
2708 (goto-char new-marker))))
2710 (defun markdown-incomplete-setext-p ()
2711 "Return t if setext header markup is incomplete and nil otherwise.
2712 Assumes match data is available for `markdown-regex-header-setext'.
2713 Checks that length of underline matches text and that there is no
2714 extraneous whitespace in the text."
2715 (save-match-data
2716 (or (not (= (length (match-string 1)) (length (match-string 2))))
2717 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2719 (defun markdown-complete-setext ()
2720 "Complete and normalize setext headers.
2721 Add or remove underline characters to match length of header
2722 text. Removes extraneous whitespace from header text. Assumes
2723 match data is available for `markdown-regex-header-setext'."
2724 (when (markdown-incomplete-setext-p)
2725 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2726 (char (char-after (match-beginning 2)))
2727 (level (if (char-equal char ?-) 2 1)))
2728 (goto-char (match-beginning 0))
2729 (delete-region (match-beginning 0) (match-end 0))
2730 (markdown-insert-header level text t))))
2732 (defun markdown-incomplete-hr-p ()
2733 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2734 Assumes match data is available for `markdown-regex-hr'."
2735 (not (member (match-string 0) markdown-hr-strings)))
2737 (defun markdown-complete-hr ()
2738 "Complete horizontal rules.
2739 If horizontal rule string is a member of `markdown-hr-strings',
2740 do nothing. Otherwise, replace with the car of
2741 `markdown-hr-strings'.
2742 Assumes match data is available for `markdown-regex-hr'."
2743 (replace-match (car markdown-hr-strings)))
2745 (defun markdown-complete ()
2746 "Complete markup of object near point or in region when active.
2747 Handle all objects in `markdown-complete-alist', in order.
2748 See `markdown-complete-at-point' and `markdown-complete-region'."
2749 (interactive "*")
2750 (if (markdown-use-region-p)
2751 (markdown-complete-region (region-beginning) (region-end))
2752 (markdown-complete-at-point)))
2754 (defun markdown-complete-at-point ()
2755 "Complete markup of object near point.
2756 Handle all objects in `markdown-complete-alist', in
2757 order."
2758 (interactive "*")
2759 (loop for (regexp . function) in markdown-complete-alist
2760 until (thing-at-point-looking-at (eval regexp))
2761 finally (funcall function)))
2763 (defun markdown-complete-region (beg end)
2764 "Complete markup of object near point.
2765 Handle all objects in `markdown-complete-alist', in
2766 order."
2767 (interactive "*r")
2768 (let* ((end-marker (make-marker))
2769 (end-marker (set-marker end-marker end)))
2770 (loop for (regexp . function) in markdown-complete-alist
2771 do (save-excursion
2772 (goto-char beg)
2773 (while (re-search-forward (eval regexp) end-marker t)
2774 (funcall function))))))
2776 (defun markdown-complete-buffer ()
2777 "Complete markup for all objects in the current buffer."
2778 (interactive "*")
2779 (markdown-complete-region (point-min) (point-max)))
2782 ;;; Markup Cycling ============================================================
2784 (defun markdown-cycle-atx (arg &optional remove)
2785 "Cycle ATX header markup.
2786 Promote header (decrease level) when ARG is 1 and demote
2787 header (increase level) if arg is -1. When REMOVE is non-nil,
2788 remove the header when the level reaches zero and stop cycling
2789 when it reaches six. Otherwise, perform a proper cycling through
2790 levels one through six. Assumes match data is available for
2791 `markdown-regex-header-atx'."
2792 (let* ((old-level (length (match-string 1)))
2793 (new-level (+ old-level arg))
2794 (text (match-string 2)))
2795 (when (not remove)
2796 (setq new-level (% new-level 6))
2797 (setq new-level (cond ((= new-level 0) 6)
2798 ((< new-level 0) (+ new-level 6))
2799 (t new-level))))
2800 (cond
2801 ((= new-level 0)
2802 (markdown-unwrap-thing-at-point nil 0 2))
2803 ((<= new-level 6)
2804 (goto-char (match-beginning 0))
2805 (delete-region (match-beginning 0) (match-end 0))
2806 (markdown-insert-header new-level text nil)))))
2808 (defun markdown-cycle-setext (arg &optional remove)
2809 "Cycle setext header markup.
2810 Promote header (increase level) when ARG is 1 and demote
2811 header (decrease level or remove) if arg is -1. When demoting a
2812 level-two setext header, replace with a level-three atx header.
2813 When REMOVE is non-nil, remove the header when the level reaches
2814 zero. Otherwise, cycle back to a level six atx header. Assumes
2815 match data is available for `markdown-regex-header-setext'."
2816 (let* ((char (char-after (match-beginning 2)))
2817 (old-level (if (char-equal char ?=) 1 2))
2818 (new-level (+ old-level arg))
2819 (text (match-string 1)))
2820 (when (and (not remove) (= new-level 0))
2821 (setq new-level 6))
2822 (cond
2823 ((= new-level 0)
2824 (markdown-unwrap-thing-at-point nil 0 1))
2825 ((<= new-level 2)
2826 (markdown-insert-header new-level nil t))
2827 ((<= new-level 6)
2828 (markdown-insert-header new-level nil nil)))))
2830 (defun markdown-cycle-hr (arg &optional remove)
2831 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2832 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2833 backwards (demote). When REMOVE is non-nil, remove the hr instead
2834 of cycling when the end of the list is reached.
2835 Assumes match data is available for `markdown-regex-hr'."
2836 (let* ((strings (if (= arg 1)
2837 (reverse markdown-hr-strings)
2838 markdown-hr-strings))
2839 (tail (member (match-string 0) strings))
2840 (new (or (cadr tail)
2841 (if remove
2842 (if (= arg 1)
2844 (car tail))
2845 (car strings)))))
2846 (replace-match new)))
2848 (defun markdown-cycle-bold ()
2849 "Cycle bold markup between underscores and asterisks.
2850 Assumes match data is available for `markdown-regex-bold'."
2851 (save-excursion
2852 (let* ((old-delim (match-string 3))
2853 (new-delim (if (string-equal old-delim "**") "__" "**")))
2854 (replace-match new-delim t t nil 3)
2855 (replace-match new-delim t t nil 5))))
2857 (defun markdown-cycle-italic ()
2858 "Cycle italic markup between underscores and asterisks.
2859 Assumes match data is available for `markdown-regex-italic'."
2860 (save-excursion
2861 (let* ((old-delim (match-string 3))
2862 (new-delim (if (string-equal old-delim "*") "_" "*")))
2863 (replace-match new-delim t t nil 3)
2864 (replace-match new-delim t t nil 5))))
2867 ;;; Keymap ====================================================================
2869 (defvar markdown-mode-map
2870 (let ((map (make-keymap)))
2871 ;; Element insertion
2872 (define-key map "\C-c\C-al" 'markdown-insert-link)
2873 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
2874 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
2875 (define-key map "\C-c\C-ii" 'markdown-insert-image)
2876 (define-key map "\C-c\C-t0" 'markdown-remove-header)
2877 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
2878 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
2879 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
2880 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
2881 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
2882 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
2883 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
2884 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
2885 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
2886 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
2887 (define-key map "\C-c\C-se" 'markdown-insert-italic)
2888 (define-key map "\C-c\C-pf" 'markdown-insert-code)
2889 (define-key map "\C-c\C-sc" 'markdown-insert-code)
2890 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
2891 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
2892 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
2893 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
2894 (define-key map "\C-c-" 'markdown-insert-hr)
2895 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
2896 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
2897 ;; Element removal
2898 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
2899 ;; Footnotes
2900 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
2901 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
2902 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
2903 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
2904 ;; Promotion, Demotion, Completion, and Cycling
2905 (define-key map (kbd "M-<left>") 'markdown-promote)
2906 (define-key map (kbd "M-<right>") 'markdown-demote)
2907 (define-key map (kbd "C-c C-l") 'markdown-promote)
2908 (define-key map (kbd "C-c C-r") 'markdown-demote)
2909 (define-key map (kbd "C-c C-=") 'markdown-complete-or-cycle)
2910 (define-key map (kbd "C-c C-c =") 'markdown-complete-buffer)
2911 ;; Following and Jumping
2912 (define-key map "\C-c\C-o" 'markdown-follow-thing-at-point)
2913 (define-key map "\C-c\C-j" 'markdown-jump)
2914 ;; Indentation
2915 (define-key map (kbd "C-m") 'markdown-enter-key)
2916 (define-key map (kbd "<backspace>") 'markdown-exdent-or-delete)
2917 ;; Visibility cycling
2918 (define-key map (kbd "<tab>") 'markdown-cycle)
2919 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
2920 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
2921 (define-key map (kbd "<backtab>") 'markdown-shifttab)
2922 ;; Header navigation
2923 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
2924 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
2925 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
2926 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
2927 (define-key map (kbd "C-M-u") 'outline-up-heading)
2928 ;; Markdown functions
2929 (define-key map "\C-c\C-cm" 'markdown-other-window)
2930 (define-key map "\C-c\C-cp" 'markdown-preview)
2931 (define-key map "\C-c\C-ce" 'markdown-export)
2932 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
2933 (define-key map "\C-c\C-co" 'markdown-open)
2934 (define-key map "\C-c\C-cw" 'markdown-kill-ring-save)
2935 ;; References
2936 (define-key map "\C-c\C-cc" 'markdown-check-refs)
2937 ;; Lists
2938 (define-key map "\C-c\C-cn" 'markdown-cleanup-list-numbers)
2939 (define-key map (kbd "M-<up>") 'markdown-move-up)
2940 (define-key map (kbd "M-<down>") 'markdown-move-down)
2941 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
2942 ;; Movement
2943 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
2944 (define-key map (kbd "M-]") 'markdown-end-of-block)
2945 (define-key map (kbd "M-n") 'markdown-next-link)
2946 (define-key map (kbd "M-p") 'markdown-previous-link)
2947 map)
2948 "Keymap for Markdown major mode.")
2950 (defvar gfm-mode-map
2951 (let ((map (make-sparse-keymap)))
2952 (set-keymap-parent map markdown-mode-map)
2953 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
2954 map)
2955 "Keymap for `gfm-mode'.
2956 See also `markdown-mode-map'.")
2959 ;;; Menu ==================================================================
2961 (easy-menu-define markdown-mode-menu markdown-mode-map
2962 "Menu for Markdown mode"
2963 '("Markdown"
2964 ("Show/Hide"
2965 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
2966 ["Cycle global visibility" markdown-shifttab])
2967 "---"
2968 ["Compile" markdown-other-window]
2969 ["Preview" markdown-preview]
2970 ["Export" markdown-export]
2971 ["Export & View" markdown-export-and-preview]
2972 ["Open" markdown-open]
2973 ["Kill ring save" markdown-kill-ring-save]
2974 "---"
2975 ("Headers (setext)"
2976 ["First level" markdown-insert-setext-header-1]
2977 ["Second level" markdown-insert-setext-header-2])
2978 ("Headers (atx)"
2979 ["First level" markdown-insert-header-atx-1]
2980 ["Second level" markdown-insert-header-atx-2]
2981 ["Third level" markdown-insert-header-atx-3]
2982 ["Fourth level" markdown-insert-header-atx-4]
2983 ["Fifth level" markdown-insert-header-atx-5]
2984 ["Sixth level" markdown-insert-header-atx-6])
2985 "---"
2986 ["Bold" markdown-insert-bold]
2987 ["Italic" markdown-insert-italic]
2988 ["Blockquote" markdown-insert-blockquote]
2989 ["Preformatted" markdown-insert-pre]
2990 ["Code" markdown-insert-code]
2991 "---"
2992 ["Insert inline link" markdown-insert-link]
2993 ["Insert reference link" markdown-insert-reference-link-dwim]
2994 ["Insert image" markdown-insert-image]
2995 ["Insert horizontal rule" markdown-insert-hr]
2996 "---"
2997 ("Footnotes"
2998 ["Insert footnote" markdown-footnote-new]
2999 ["Jump to footnote text" markdown-footnote-goto-text]
3000 ["Return from footnote" markdown-footnote-return])
3001 "---"
3002 ["Check references" markdown-check-refs]
3003 ["Clean up list numbering" markdown-cleanup-list-numbers]
3004 "---"
3005 ["Version" markdown-show-version]
3009 ;;; imenu =====================================================================
3011 (defun markdown-imenu-create-index ()
3012 "Create and return an imenu index alist for the current buffer.
3013 See `imenu-create-index-function' and `imenu--index-alist' for details."
3014 (let* ((root '(nil . nil))
3015 cur-alist
3016 (cur-level 0)
3017 (empty-heading "-")
3018 (self-heading ".")
3019 hashes pos level heading)
3020 (save-excursion
3021 (goto-char (point-min))
3022 (while (re-search-forward markdown-regex-header (point-max) t)
3023 (cond
3024 ((setq heading (match-string-no-properties 1))
3025 (setq pos (match-beginning 1)
3026 level 1))
3027 ((setq heading (match-string-no-properties 3))
3028 (setq pos (match-beginning 3)
3029 level 2))
3030 ((setq hashes (match-string-no-properties 5))
3031 (setq heading (match-string-no-properties 6)
3032 pos (match-beginning 5)
3033 level (length hashes))))
3034 (let ((alist (list (cons heading pos))))
3035 (cond
3036 ((= cur-level level) ; new sibling
3037 (setcdr cur-alist alist)
3038 (setq cur-alist alist))
3039 ((< cur-level level) ; first child
3040 (dotimes (i (- level cur-level 1))
3041 (setq alist (list (cons empty-heading alist))))
3042 (if cur-alist
3043 (let* ((parent (car cur-alist))
3044 (self-pos (cdr parent)))
3045 (setcdr parent (cons (cons self-heading self-pos) alist)))
3046 (setcdr root alist)) ; primogenitor
3047 (setq cur-alist alist)
3048 (setq cur-level level))
3049 (t ; new sibling of an ancestor
3050 (let ((sibling-alist (last (cdr root))))
3051 (dotimes (i (1- level))
3052 (setq sibling-alist (last (cdar sibling-alist))))
3053 (setcdr sibling-alist alist)
3054 (setq cur-alist alist))
3055 (setq cur-level level)))))
3056 (cdr root))))
3059 ;;; References ================================================================
3061 (defun markdown-insert-reference-definition (ref &optional buffer)
3062 "Add blank REF definition to the end of BUFFER.
3063 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3064 (or buffer (setq buffer (current-buffer)))
3065 (with-current-buffer buffer
3066 (goto-char (point-max))
3067 (indent-new-comment-line)
3068 (insert (concat ref ": "))))
3070 (defun markdown-reference-goto-definition ()
3071 "Jump to the definition of the reference at point or create it."
3072 (interactive)
3073 (when (thing-at-point-looking-at markdown-regex-link-reference)
3074 (let* ((text (match-string-no-properties 2))
3075 (reference (match-string-no-properties 4))
3076 (target (downcase (if (string= reference "[]") text reference)))
3077 (loc (cadr (markdown-reference-definition target))))
3078 (if loc
3079 (goto-char loc)
3080 (markdown-insert-reference-definition target (current-buffer))))))
3082 (defun markdown-reference-find-links (reference)
3083 "Return a list of all links for REFERENCE.
3084 REFERENCE should include the surrounding square brackets like [this].
3085 Elements of the list have the form (text start line), where
3086 text is the link text, start is the location at the beginning of
3087 the link, and line is the line number on which the link appears."
3088 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3089 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3090 ref-quote ref-quote))
3091 links)
3092 (save-excursion
3093 (goto-char (point-min))
3094 (while (re-search-forward regexp nil t)
3095 (let* ((text (or (match-string-no-properties 1)
3096 (match-string-no-properties 2)))
3097 (start (match-beginning 0))
3098 (line (markdown-line-number-at-pos)))
3099 (add-to-list 'links (list text start line)))))
3100 links))
3102 (defun markdown-get-undefined-refs ()
3103 "Return a list of undefined Markdown references.
3104 Result is an alist of pairs (reference . occurrences), where
3105 occurrences is itself another alist of pairs (label . line-number).
3106 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3107 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3108 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3109 (let ((missing))
3110 (save-excursion
3111 (goto-char (point-min))
3112 (while
3113 (re-search-forward markdown-regex-link-reference nil t)
3114 (let* ((text (match-string-no-properties 2))
3115 (reference (match-string-no-properties 4))
3116 (target (downcase (if (string= reference "[]") text reference))))
3117 (unless (markdown-reference-definition target)
3118 (let ((entry (assoc target missing)))
3119 (if (not entry)
3120 (add-to-list 'missing (cons target
3121 (list (cons text (markdown-line-number-at-pos)))) t)
3122 (setcdr entry
3123 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3124 missing)))
3126 (defconst markdown-reference-check-buffer
3127 "*Undefined references for %buffer%*"
3128 "Pattern for name of buffer for listing undefined references.
3129 The string %buffer% will be replaced by the corresponding
3130 `markdown-mode' buffer name.")
3132 (defun markdown-reference-check-buffer (&optional buffer-name)
3133 "Name and return buffer for reference checking."
3134 (or buffer-name (setq buffer-name (buffer-name)))
3135 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3136 "%buffer%" buffer-name
3137 markdown-reference-check-buffer))))
3138 (with-current-buffer refbuf
3139 (when view-mode
3140 (View-exit-and-edit))
3141 (use-local-map button-buffer-map)
3142 (erase-buffer))
3143 refbuf))
3145 (defconst markdown-reference-links-buffer
3146 "*Reference links for %buffer%*"
3147 "Pattern for name of buffer for listing references.
3148 The string %buffer% will be replaced by the corresponding buffer name.")
3150 (defun markdown-reference-links-buffer (&optional buffer-name)
3151 "Name, setup, and return a buffer for listing links."
3152 (or buffer-name (setq buffer-name (buffer-name)))
3153 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3154 "%buffer%" buffer-name
3155 markdown-reference-links-buffer))))
3156 (with-current-buffer linkbuf
3157 (when view-mode
3158 (View-exit-and-edit))
3159 (use-local-map button-buffer-map)
3160 (erase-buffer))
3161 linkbuf))
3163 (when (markdown-use-buttons-p)
3164 ;; Add an empty Markdown reference definition to the end of buffer
3165 ;; specified in the 'target-buffer property. The reference name is
3166 ;; the button's label.
3167 (define-button-type 'markdown-undefined-reference-button
3168 'help-echo "mouse-1, RET: create definition for undefined reference"
3169 'follow-link t
3170 'face 'bold
3171 'action (lambda (b)
3172 (let ((buffer (button-get b 'target-buffer)))
3173 (markdown-insert-reference-definition (button-label b) buffer)
3174 (switch-to-buffer-other-window buffer)
3175 (goto-char (point-max))
3176 (markdown-check-refs t))))
3178 ;; Jump to line in buffer specified by 'target-buffer property.
3179 ;; Line number is button's 'line property.
3180 (define-button-type 'markdown-goto-line-button
3181 'help-echo "mouse-1, RET: go to line"
3182 'follow-link t
3183 'face 'italic
3184 'action (lambda (b)
3185 (message (button-get b 'buffer))
3186 (switch-to-buffer-other-window (button-get b 'target-buffer))
3187 ;; use call-interactively to silence compiler
3188 (let ((current-prefix-arg (button-get b 'target-line)))
3189 (call-interactively 'goto-line))))
3191 ;; Jumps to a particular link at location given by 'target-char
3192 ;; property in buffer given by 'target-buffer property.
3193 (define-button-type 'markdown-link-button
3194 'help-echo "mouse-1, RET: jump to location of link"
3195 'follow-link t
3196 'face 'bold
3197 'action (lambda (b)
3198 (let ((target (button-get b 'target-buffer))
3199 (loc (button-get b 'target-char)))
3200 (kill-buffer-and-window)
3201 (switch-to-buffer target)
3202 (goto-char loc)))))
3204 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3205 "Insert a button for creating REFERENCE in buffer OLDBUF.
3206 REFERENCE should be a list of the form (reference . occurrences),
3207 as by `markdown-get-undefined-refs'."
3208 (let ((label (car reference)))
3209 (if (markdown-use-buttons-p)
3210 ;; Create a reference button in Emacs 22
3211 (insert-button label
3212 :type 'markdown-undefined-reference-button
3213 'target-buffer oldbuf)
3214 ;; Insert reference as text in Emacs < 22
3215 (insert label))
3216 (insert " (")
3217 (dolist (occurrence (cdr reference))
3218 (let ((line (cdr occurrence)))
3219 (if (markdown-use-buttons-p)
3220 ;; Create a line number button in Emacs 22
3221 (insert-button (number-to-string line)
3222 :type 'markdown-goto-line-button
3223 'target-buffer oldbuf
3224 'target-line line)
3225 ;; Insert line number as text in Emacs < 22
3226 (insert (number-to-string line)))
3227 (insert " ")))
3228 (delete-char -1)
3229 (insert ")")
3230 (newline)))
3232 (defun markdown-insert-link-button (link oldbuf)
3233 "Insert a button for jumping to LINK in buffer OLDBUF.
3234 LINK should be a list of the form (text char line) containing
3235 the link text, location, and line number."
3236 (let ((label (first link))
3237 (char (second link))
3238 (line (third link)))
3239 (if (markdown-use-buttons-p)
3240 ;; Create a reference button in Emacs 22
3241 (insert-button label
3242 :type 'markdown-link-button
3243 'target-buffer oldbuf
3244 'target-char char)
3245 ;; Insert reference as text in Emacs < 22
3246 (insert label))
3247 (insert (format " (line %d)\n" line))))
3249 (defun markdown-reference-goto-link (&optional reference)
3250 "Jump to the location of the first use of reference."
3251 (interactive)
3252 (unless reference
3253 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3254 (setq reference (match-string-no-properties 1))
3255 (error "No reference definition at point.")))
3256 (let ((links (markdown-reference-find-links reference)))
3257 (cond ((= (length links) 1)
3258 (goto-char (cadr (car links))))
3259 ((> (length links) 1)
3260 (let ((oldbuf (current-buffer))
3261 (linkbuf (markdown-reference-links-buffer)))
3262 (with-current-buffer linkbuf
3263 (insert "Links using reference " reference ":\n\n")
3264 (dolist (link (reverse links))
3265 (markdown-insert-link-button link oldbuf)))
3266 (view-buffer-other-window linkbuf)
3267 (goto-char (point-min))
3268 (forward-line 2)))
3270 (error "No links for reference %s" reference)))))
3272 (defun markdown-check-refs (&optional silent)
3273 "Show all undefined Markdown references in current `markdown-mode' buffer.
3274 If SILENT is non-nil, do not message anything when no undefined
3275 references found.
3276 Links which have empty reference definitions are considered to be
3277 defined."
3278 (interactive "P")
3279 (when (not (eq major-mode 'markdown-mode))
3280 (error "Not available in current mode"))
3281 (let ((oldbuf (current-buffer))
3282 (refs (markdown-get-undefined-refs))
3283 (refbuf (markdown-reference-check-buffer)))
3284 (if (null refs)
3285 (progn
3286 (when (not silent)
3287 (message "No undefined references found"))
3288 (kill-buffer refbuf))
3289 (with-current-buffer refbuf
3290 (insert "The following references are undefined:\n\n")
3291 (dolist (ref refs)
3292 (markdown-insert-undefined-reference-button ref oldbuf))
3293 (view-buffer-other-window refbuf)
3294 (goto-char (point-min))
3295 (forward-line 2)))))
3298 ;;; Lists =====================================================================
3300 (defun markdown-insert-list-item (&optional arg)
3301 "Insert a new list item.
3302 If the point is inside unordered list, insert a bullet mark. If
3303 the point is inside ordered list, insert the next number followed
3304 by a period. Use the previous list item to determine the amount
3305 of whitespace to place before and after list markers.
3307 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3308 decrease the indentation by one level.
3310 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3311 increase the indentation by one level."
3312 (interactive "p")
3313 (let (bounds item-indent marker indent new-indent new-loc)
3314 (save-match-data
3315 ;; Look for a list item on current or previous non-blank line
3316 (save-excursion
3317 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3318 (not (bobp))
3319 (markdown-cur-line-blank-p))
3320 (forward-line -1)))
3321 (when bounds
3322 (cond ((save-excursion
3323 (skip-chars-backward " \t")
3324 (looking-at markdown-regex-list))
3325 (beginning-of-line)
3326 (insert "\n")
3327 (forward-line -1))
3328 ((not (markdown-cur-line-blank-p))
3329 (newline)))
3330 (setq new-loc (point)))
3331 ;; Look ahead for a list item on next non-blank line
3332 (unless bounds
3333 (save-excursion
3334 (while (and (null bounds)
3335 (not (eobp))
3336 (markdown-cur-line-blank-p))
3337 (forward-line)
3338 (setq bounds (markdown-cur-list-item-bounds))))
3339 (when bounds
3340 (setq new-loc (point))
3341 (unless (markdown-cur-line-blank-p)
3342 (newline))))
3343 (if (not bounds)
3344 ;; When not in a list, start a new unordered one
3345 (progn
3346 (unless (markdown-cur-line-blank-p)
3347 (insert "\n"))
3348 (insert "* "))
3349 ;; Compute indentation for a new list item
3350 (setq item-indent (nth 2 bounds))
3351 (setq marker (nth 4 bounds))
3352 (setq indent (cond
3353 ((= arg 4) (max (- item-indent 4) 0))
3354 ((= arg 16) (+ item-indent 4))
3355 (t item-indent)))
3356 (setq new-indent (make-string indent 32))
3357 (goto-char new-loc)
3358 (cond
3359 ;; Ordered list
3360 ((string-match "[0-9]" marker)
3361 (if (= arg 16) ;; starting a new column indented one more level
3362 (insert (concat new-indent "1. "))
3363 ;; travel up to the last item and pick the correct number. If
3364 ;; the argument was nil, "new-indent = item-indent" is the same,
3365 ;; so we don't need special treatment. Neat.
3366 (save-excursion
3367 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3368 (forward-line -1)))
3369 (insert (concat new-indent
3370 (int-to-string (1+ (string-to-number (match-string 1))))
3371 ". "))))
3372 ;; Unordered list
3373 ((string-match "[\\*\\+-]" marker)
3374 (insert new-indent marker)))))))
3376 (defun markdown-move-list-item-up ()
3377 "Move the current list item up in the list when possible."
3378 (interactive)
3379 (let (cur prev old)
3380 (when (setq cur (markdown-cur-list-item-bounds))
3381 (setq old (point))
3382 (goto-char (nth 0 cur))
3383 (if (markdown-prev-list-item (nth 3 cur))
3384 (progn
3385 (setq prev (markdown-cur-list-item-bounds))
3386 (condition-case nil
3387 (progn
3388 (transpose-regions (nth 0 prev) (nth 1 prev)
3389 (nth 0 cur) (nth 1 cur) t)
3390 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3391 ;; Catch error in case regions overlap.
3392 (error (goto-char old))))
3393 (goto-char old)))))
3395 (defun markdown-move-list-item-down ()
3396 "Move the current list item down in the list when possible."
3397 (interactive)
3398 (let (cur next old)
3399 (when (setq cur (markdown-cur-list-item-bounds))
3400 (setq old (point))
3401 (if (markdown-next-list-item (nth 3 cur))
3402 (progn
3403 (setq next (markdown-cur-list-item-bounds))
3404 (condition-case nil
3405 (progn
3406 (transpose-regions (nth 0 cur) (nth 1 cur)
3407 (nth 0 next) (nth 1 next) nil)
3408 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3409 ;; Catch error in case regions overlap.
3410 (error (goto-char old))))
3411 (goto-char old)))))
3413 (defun markdown-demote-list-item (&optional bounds)
3414 "Indent (or demote) the current list item.
3415 Optionally, BOUNDS of the current list item may be provided if available."
3416 (interactive)
3417 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3418 (save-excursion
3419 (save-match-data
3420 (let* ((end-marker (make-marker))
3421 (end-marker (set-marker end-marker (nth 1 bounds))))
3422 (goto-char (nth 0 bounds))
3423 (while (< (point) end-marker)
3424 (unless (markdown-cur-line-blank-p)
3425 (insert " "))
3426 (forward-line)))))))
3428 (defun markdown-promote-list-item (&optional bounds)
3429 "Unindent (or promote) the current list item.
3430 Optionally, BOUNDS of the current list item may be provided if available."
3431 (interactive)
3432 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3433 (save-excursion
3434 (save-match-data
3435 (let* ((end-marker (make-marker))
3436 (end-marker (set-marker end-marker (nth 1 bounds)))
3437 num regexp)
3438 (goto-char (nth 0 bounds))
3439 (when (looking-at "^[ ]\\{1,4\\}")
3440 (setq num (- (match-end 0) (match-beginning 0)))
3441 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3442 (while (and (< (point) end-marker)
3443 (re-search-forward regexp end-marker t))
3444 (replace-match "" nil nil)
3445 (forward-line))))))))
3447 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3448 "Update the numbering for level PFX (as a string of spaces).
3450 Assume that the previously found match was for a numbered item in
3451 a list."
3452 (let ((cpfx pfx)
3453 (idx 0)
3454 (continue t)
3455 (step t)
3456 (sep nil))
3457 (while (and continue (not (eobp)))
3458 (setq step t)
3459 (cond
3460 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3461 (setq cpfx (match-string-no-properties 1))
3462 (cond
3463 ((string= cpfx pfx)
3464 (replace-match
3465 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3466 (setq sep nil))
3467 ;; indented a level
3468 ((string< pfx cpfx)
3469 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3470 (setq step nil))
3471 ;; exit the loop
3473 (setq step nil)
3474 (setq continue nil))))
3476 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3477 (setq cpfx (match-string-no-properties 1))
3478 (cond
3479 ;; reset if separated before
3480 ((string= cpfx pfx) (when sep (setq idx 0)))
3481 ((string< cpfx pfx)
3482 (setq step nil)
3483 (setq continue nil))))
3484 (t (setq sep t)))
3486 (when step
3487 (beginning-of-line)
3488 (setq continue (= (forward-line) 0))))
3489 sep))
3491 (defun markdown-cleanup-list-numbers ()
3492 "Update the numbering of ordered lists."
3493 (interactive)
3494 (save-excursion
3495 (goto-char (point-min))
3496 (markdown--cleanup-list-numbers-level "")))
3499 ;;; Outline ===================================================================
3501 (defvar markdown-cycle-global-status 1)
3502 (defvar markdown-cycle-subtree-status nil)
3504 (defun markdown-end-of-subtree (&optional invisible-OK)
3505 "Move to the end of the current subtree.
3506 Only visible heading lines are considered, unless INVISIBLE-OK is
3507 non-nil.
3508 Derived from `org-end-of-subtree'."
3509 (outline-back-to-heading invisible-OK)
3510 (let ((first t)
3511 (level (funcall outline-level)))
3512 (while (and (not (eobp))
3513 (or first (> (funcall outline-level) level)))
3514 (setq first nil)
3515 (outline-next-heading))
3516 (if (memq (preceding-char) '(?\n ?\^M))
3517 (progn
3518 ;; Go to end of line before heading
3519 (forward-char -1)
3520 (if (memq (preceding-char) '(?\n ?\^M))
3521 ;; leave blank line before heading
3522 (forward-char -1)))))
3523 (point))
3525 (defun markdown-cycle (&optional arg)
3526 "Visibility cycling for Markdown mode.
3527 If ARG is t, perform global visibility cycling. If the point is
3528 at an atx-style header, cycle visibility of the corresponding
3529 subtree. Otherwise, insert a tab using `indent-relative'.
3530 Derived from `org-cycle'."
3531 (interactive "P")
3532 (cond
3533 ((eq arg t) ;; Global cycling
3534 (cond
3535 ((and (eq last-command this-command)
3536 (eq markdown-cycle-global-status 2))
3537 ;; Move from overview to contents
3538 (hide-sublevels 1)
3539 (message "CONTENTS")
3540 (setq markdown-cycle-global-status 3))
3542 ((and (eq last-command this-command)
3543 (eq markdown-cycle-global-status 3))
3544 ;; Move from contents to all
3545 (show-all)
3546 (message "SHOW ALL")
3547 (setq markdown-cycle-global-status 1))
3550 ;; Defaults to overview
3551 (hide-body)
3552 (message "OVERVIEW")
3553 (setq markdown-cycle-global-status 2))))
3555 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3556 ;; At a heading: rotate between three different views
3557 (outline-back-to-heading)
3558 (let ((goal-column 0) eoh eol eos)
3559 ;; Determine boundaries
3560 (save-excursion
3561 (outline-back-to-heading)
3562 (save-excursion
3563 (beginning-of-line 2)
3564 (while (and (not (eobp)) ;; this is like `next-line'
3565 (get-char-property (1- (point)) 'invisible))
3566 (beginning-of-line 2)) (setq eol (point)))
3567 (outline-end-of-heading) (setq eoh (point))
3568 (markdown-end-of-subtree t)
3569 (skip-chars-forward " \t\n")
3570 (beginning-of-line 1) ; in case this is an item
3571 (setq eos (1- (point))))
3572 ;; Find out what to do next and set `this-command'
3573 (cond
3574 ((= eos eoh)
3575 ;; Nothing is hidden behind this heading
3576 (message "EMPTY ENTRY")
3577 (setq markdown-cycle-subtree-status nil))
3578 ((>= eol eos)
3579 ;; Entire subtree is hidden in one line: open it
3580 (show-entry)
3581 (show-children)
3582 (message "CHILDREN")
3583 (setq markdown-cycle-subtree-status 'children))
3584 ((and (eq last-command this-command)
3585 (eq markdown-cycle-subtree-status 'children))
3586 ;; We just showed the children, now show everything.
3587 (show-subtree)
3588 (message "SUBTREE")
3589 (setq markdown-cycle-subtree-status 'subtree))
3591 ;; Default action: hide the subtree.
3592 (hide-subtree)
3593 (message "FOLDED")
3594 (setq markdown-cycle-subtree-status 'folded)))))
3597 (indent-for-tab-command))))
3599 (defun markdown-shifttab ()
3600 "Global visibility cycling.
3601 Calls `markdown-cycle' with argument t."
3602 (interactive)
3603 (markdown-cycle t))
3605 (defun markdown-outline-level ()
3606 "Return the depth to which a statement is nested in the outline."
3607 (cond
3608 ((match-end 1) 1)
3609 ((match-end 3) 2)
3610 ((- (match-end 5) (match-beginning 5)))))
3613 ;;; Movement ==================================================================
3615 (defun markdown-beginning-of-defun (&optional arg)
3616 "`beginning-of-defun-function' for Markdown.
3617 Move backward to the beginning of the current or previous section."
3618 (interactive "P")
3619 (or arg (setq arg 1))
3620 (or (re-search-backward markdown-regex-header nil t arg)
3621 (goto-char (point-min))))
3623 (defun markdown-end-of-defun (&optional arg)
3624 "`end-of-defun-function' for Markdown.
3625 Move forward to the end of the current or following section."
3626 (interactive "P")
3627 (or arg (setq arg 1))
3628 (when (looking-at markdown-regex-header)
3629 (goto-char (match-beginning 0))
3630 (forward-char 1))
3631 (if (re-search-forward markdown-regex-header nil t arg)
3632 (goto-char (match-beginning 0))
3633 (goto-char (point-max)))
3634 (skip-syntax-backward "-"))
3636 (defun markdown-beginning-of-block ()
3637 "Move the point to the start of the previous text block."
3638 (interactive)
3639 (if (re-search-backward markdown-regex-block-separator nil t)
3640 (goto-char (or (match-end 2) (match-end 0)))
3641 (goto-char (point-min))))
3643 (defun markdown-end-of-block ()
3644 "Move the point to the start of the next text block."
3645 (interactive)
3646 (beginning-of-line)
3647 (skip-syntax-forward "-")
3648 (when (= (point) (point-min))
3649 (forward-char))
3650 (if (re-search-forward markdown-regex-block-separator nil t)
3651 (goto-char (or (match-end 2) (match-end 0)))
3652 (goto-char (point-max)))
3653 (skip-syntax-backward "-")
3654 (forward-line))
3656 (defun markdown-end-of-block-element ()
3657 "Move the point to the start of the next block unit.
3658 Stops at blank lines, list items, headers, and horizontal rules."
3659 (interactive)
3660 (forward-line)
3661 (while (and (or (not (markdown-prev-line-blank-p))
3662 (markdown-cur-line-blank-p))
3663 (not (or (looking-at markdown-regex-list)
3664 (looking-at markdown-regex-header)
3665 (looking-at markdown-regex-hr)))
3666 (not (eobp)))
3667 (forward-line)))
3669 (defun markdown-next-link ()
3670 "Jump to next inline, reference, or wiki link.
3671 If successful, return point. Otherwise, return nil.
3672 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3673 (interactive)
3674 (let ((opoint (point)))
3675 (when (or (markdown-link-p) (markdown-wiki-link-p))
3676 ;; At a link already, move past it.
3677 (goto-char (+ (match-end 0) 1)))
3678 ;; Search for the next wiki link and move to the beginning.
3679 (if (re-search-forward markdown-regex-link-generic nil t)
3680 ;; Group 1 will move past non-escape character in wiki link regexp.
3681 ;; Go to beginning of group zero for all other link types.
3682 (goto-char (or (match-beginning 1) (match-beginning 0)))
3683 (goto-char opoint)
3684 nil)))
3686 (defun markdown-previous-link ()
3687 "Jump to previous wiki link.
3688 If successful, return point. Otherwise, return nil.
3689 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3690 (interactive)
3691 (if (re-search-backward markdown-regex-link-generic nil t)
3692 (goto-char (or (match-beginning 1) (match-beginning 0)))
3693 nil))
3696 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3698 (defun markdown-move-up ()
3699 "Move list item up.
3700 Calls `markdown-move-list-item-up'."
3701 (interactive)
3702 (markdown-move-list-item-up))
3704 (defun markdown-move-down ()
3705 "Move list item down.
3706 Calls `markdown-move-list-item-down'."
3707 (interactive)
3708 (markdown-move-list-item-down))
3710 (defun markdown-promote ()
3711 "Either promote header or list item at point or cycle markup.
3712 See `markdown-cycle-atx', `markdown-cycle-setext', and
3713 `markdown-demote-list-item'."
3714 (interactive)
3715 (let (bounds)
3716 (cond
3717 ;; Promote atx header
3718 ((thing-at-point-looking-at markdown-regex-header-atx)
3719 (markdown-cycle-atx -1 t))
3720 ;; Promote setext header
3721 ((thing-at-point-looking-at markdown-regex-header-setext)
3722 (markdown-cycle-setext -1 t))
3723 ;; Promote horizonal rule
3724 ((thing-at-point-looking-at markdown-regex-hr)
3725 (markdown-cycle-hr -1 t))
3726 ;; Promote list item
3727 ((setq bounds (markdown-cur-list-item-bounds))
3728 (markdown-promote-list-item)))))
3730 (defun markdown-demote ()
3731 "Either demote header or list item at point or cycle or remove markup.
3732 See `markdown-cycle-atx', `markdown-cycle-setext', and
3733 `markdown-demote-list-item'."
3734 (interactive)
3735 (let (bounds)
3736 (cond
3737 ;; Demote atx header
3738 ((thing-at-point-looking-at markdown-regex-header-atx)
3739 (markdown-cycle-atx 1 t))
3740 ;; Demote setext header
3741 ((thing-at-point-looking-at markdown-regex-header-setext)
3742 (markdown-cycle-setext 1 t))
3743 ;; Demote horizonal rule
3744 ((thing-at-point-looking-at markdown-regex-hr)
3745 (markdown-cycle-hr 1 t))
3746 ;; Promote list item
3747 ((setq bounds (markdown-cur-list-item-bounds))
3748 (markdown-demote-list-item))
3749 ;; Create a new level one ATX header
3751 (markdown-insert-header-atx-1)))))
3753 (defun markdown-complete-or-cycle (arg)
3754 "Complete or cycle markup of object at point or complete objects in region.
3755 If there is an active region, complete markup in region.
3756 Otherwise, complete or cycle markup of object near point.
3757 When ARG is non-nil, cycle backwards when cycling."
3758 (interactive "*P")
3759 (if (markdown-use-region-p)
3760 ;; Complete markup in region
3761 (markdown-complete-region (region-beginning) (region-end))
3762 ;; Complete or cycle markup at point
3763 (let ((dir (if arg -1 1))
3764 bounds)
3765 (cond
3766 ;; atx header
3767 ((thing-at-point-looking-at markdown-regex-header-atx)
3768 (if (markdown-incomplete-atx-p)
3769 (markdown-complete-atx)
3770 (markdown-cycle-atx dir)))
3771 ;; setext header
3772 ((thing-at-point-looking-at markdown-regex-header-setext)
3773 (if (markdown-incomplete-setext-p)
3774 (markdown-complete-setext)
3775 (markdown-cycle-setext dir)))
3776 ;; horizonal rule
3777 ((thing-at-point-looking-at markdown-regex-hr)
3778 (if (markdown-incomplete-hr-p)
3779 (markdown-complete-hr)
3780 (markdown-cycle-hr dir)))
3781 ;; bold
3782 ((thing-at-point-looking-at markdown-regex-bold)
3783 (markdown-cycle-bold))
3784 ;; italic
3785 ((thing-at-point-looking-at markdown-regex-italic)
3786 (markdown-cycle-italic))))))
3789 ;;; Commands ==================================================================
3791 (defun markdown (&optional output-buffer-name)
3792 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3793 The output buffer name defaults to `markdown-output-buffer-name'.
3794 Return the name of the output buffer used."
3795 (interactive)
3796 (save-window-excursion
3797 (let ((begin-region)
3798 (end-region))
3799 (if (markdown-use-region-p)
3800 (setq begin-region (region-beginning)
3801 end-region (region-end))
3802 (setq begin-region (point-min)
3803 end-region (point-max)))
3805 (unless output-buffer-name
3806 (setq output-buffer-name markdown-output-buffer-name))
3808 (cond
3809 ;; Handle case when `markdown-command' does not read from stdin
3810 (markdown-command-needs-filename
3811 (if (not buffer-file-name)
3812 (error "Must be visiting a file")
3813 (shell-command (concat markdown-command " "
3814 (shell-quote-argument buffer-file-name))
3815 output-buffer-name)))
3816 ;; Pass region to `markdown-command' via stdin
3818 (shell-command-on-region begin-region end-region markdown-command
3819 output-buffer-name))))
3820 output-buffer-name))
3822 (defun markdown-standalone (&optional output-buffer-name)
3823 "Special function to provide standalone HTML output.
3824 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3825 (interactive)
3826 (setq output-buffer-name (markdown output-buffer-name))
3827 (with-current-buffer output-buffer-name
3828 (set-buffer output-buffer-name)
3829 (goto-char (point-min))
3830 (unless (markdown-output-standalone-p)
3831 (markdown-add-xhtml-header-and-footer output-buffer-name))
3832 (html-mode))
3833 output-buffer-name)
3835 (defun markdown-other-window (&optional output-buffer-name)
3836 "Run `markdown-command' on current buffer and display in other window.
3837 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3838 that name."
3839 (interactive)
3840 (display-buffer (markdown-standalone output-buffer-name)))
3842 (defun markdown-output-standalone-p ()
3843 "Determine whether `markdown-command' output is standalone XHTML.
3844 Standalone XHTML output is identified by an occurrence of
3845 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3846 (re-search-forward
3847 markdown-xhtml-standalone-regexp
3848 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3851 (defun markdown-add-xhtml-header-and-footer (title)
3852 "Wrap XHTML header and footer with given TITLE around current buffer."
3853 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3854 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3855 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3856 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3857 "<head>\n<title>")
3858 (insert title)
3859 (insert "</title>\n")
3860 (when (> (length markdown-content-type) 0)
3861 (insert
3862 (format
3863 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3864 markdown-content-type
3865 (or (and markdown-coding-system
3866 (fboundp 'coding-system-get)
3867 (coding-system-get markdown-coding-system
3868 'mime-charset))
3869 (and (fboundp 'coding-system-get)
3870 (coding-system-get buffer-file-coding-system
3871 'mime-charset))
3872 "iso-8859-1"))))
3873 (if (> (length markdown-css-path) 0)
3874 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3875 markdown-css-path
3876 "\" />\n"))
3877 (when (> (length markdown-xhtml-header-content) 0)
3878 (insert markdown-xhtml-header-content))
3879 (insert "\n</head>\n\n"
3880 "<body>\n\n")
3881 (goto-char (point-max))
3882 (insert "\n"
3883 "</body>\n"
3884 "</html>\n"))
3886 (defun markdown-preview (&optional output-buffer-name)
3887 "Run `markdown-command' on the current buffer and view output in browser.
3888 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3889 that name."
3890 (interactive)
3891 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3893 (defun markdown-export-file-name (&optional extension)
3894 "Attempt to generate a filename for Markdown output.
3895 The file extension will be EXTENSION if given, or .html by default.
3896 If the current buffer is visiting a file, we construct a new
3897 output filename based on that filename. Otherwise, return nil."
3898 (when (buffer-file-name)
3899 (unless extension
3900 (setq extension ".html"))
3901 (concat
3902 (cond
3903 ((buffer-file-name)
3904 (file-name-sans-extension (buffer-file-name)))
3905 (t (buffer-name)))
3906 extension)))
3908 (defun markdown-export (&optional output-file)
3909 "Run Markdown on the current buffer, save to file, and return the filename.
3910 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3911 generated by `markdown-export-file-name', which will be constructed using the
3912 current filename, but with the extension removed and replaced with .html."
3913 (interactive)
3914 (unless output-file
3915 (setq output-file (markdown-export-file-name ".html")))
3916 (when output-file
3917 (let ((output-buffer-name))
3918 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
3919 (run-hook-with-args 'markdown-before-export-hooks output-file)
3920 (markdown-standalone output-buffer-name)
3921 (with-current-buffer output-buffer-name
3922 (save-buffer))
3923 (run-hook-with-args 'markdown-after-export-hooks output-file)
3924 output-file)))
3926 (defun markdown-export-and-preview ()
3927 "Export to XHTML using `markdown-export' and browse the resulting file."
3928 (interactive)
3929 (browse-url (markdown-export)))
3931 (defun markdown-open ()
3932 "Open file for the current buffer with `markdown-open-command'."
3933 (interactive)
3934 (if (not markdown-open-command)
3935 (error "Variable `markdown-open-command' must be set")
3936 (if (not buffer-file-name)
3937 (error "Must be visiting a file")
3938 (call-process markdown-open-command
3939 nil nil nil buffer-file-name))))
3941 (defun markdown-kill-ring-save ()
3942 "Run Markdown on file and store output in the kill ring."
3943 (interactive)
3944 (save-window-excursion
3945 (markdown)
3946 (with-current-buffer markdown-output-buffer-name
3947 (kill-ring-save (point-min) (point-max)))))
3950 ;;; Links =====================================================================
3952 (require 'thingatpt)
3954 (defun markdown-link-p ()
3955 "Return non-nil when `point' is at a non-wiki link.
3956 See `markdown-wiki-link-p' for more information."
3957 (let ((case-fold-search nil))
3958 (and (not (markdown-wiki-link-p))
3959 (or (thing-at-point-looking-at markdown-regex-link-inline)
3960 (thing-at-point-looking-at markdown-regex-link-reference)
3961 (thing-at-point-looking-at markdown-regex-uri)
3962 (thing-at-point-looking-at markdown-regex-angle-uri)))))
3964 (defun markdown-link-link ()
3965 "Return the link part of the regular (non-wiki) link at point.
3966 Works with both inline and reference style links. If point is
3967 not at a link or the link reference is not defined returns nil."
3968 (cond
3969 ((thing-at-point-looking-at markdown-regex-link-inline)
3970 (match-string-no-properties 5))
3971 ((thing-at-point-looking-at markdown-regex-link-reference)
3972 (let* ((text (match-string-no-properties 2))
3973 (reference (match-string-no-properties 4))
3974 (target (downcase (if (string= reference "[]") text reference))))
3975 (car (markdown-reference-definition target))))
3976 ((thing-at-point-looking-at markdown-regex-uri)
3977 (match-string-no-properties 0))
3978 ((thing-at-point-looking-at markdown-regex-angle-uri)
3979 (match-string-no-properties 2))
3980 (t nil)))
3982 (defun markdown-follow-link-at-point ()
3983 "Open the current non-wiki link in a browser."
3984 (interactive)
3985 (if (markdown-link-p) (browse-url (markdown-link-link))
3986 (error "Point is not at a Markdown link or URI")))
3989 ;;; WikiLink Following/Markup =================================================
3991 (defun markdown-wiki-link-p ()
3992 "Return non-nil when `point' is at a true wiki link.
3993 A true wiki link name matches `markdown-regex-wiki-link' but does not
3994 match the current file name after conversion. This modifies the data
3995 returned by `match-data'. Note that the potential wiki link name must
3996 be available via `match-string'."
3997 (let ((case-fold-search nil))
3998 (and (thing-at-point-looking-at markdown-regex-wiki-link)
3999 (or (not buffer-file-name)
4000 (not (string-equal (buffer-file-name)
4001 (markdown-convert-wiki-link-to-filename
4002 (markdown-wiki-link-link)))))
4003 (not (save-match-data
4004 (save-excursion))))))
4006 (defun markdown-wiki-link-link ()
4007 "Return the link part of the wiki link using current match data.
4008 The location of the link component depends on the value of
4009 `markdown-wiki-link-alias-first'."
4010 (if markdown-wiki-link-alias-first
4011 (or (match-string-no-properties 4) (match-string-no-properties 2))
4012 (match-string-no-properties 2)))
4014 (defun markdown-convert-wiki-link-to-filename (name)
4015 "Generate a filename from the wiki link NAME.
4016 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4017 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4018 and [[test test]] both map to Test-test.ext."
4019 (let ((basename (markdown-replace-regexp-in-string
4020 "[[:space:]\n]" markdown-link-space-sub-char name)))
4021 (when (eq major-mode 'gfm-mode)
4022 (setq basename (concat (upcase (substring basename 0 1))
4023 (downcase (substring basename 1 nil)))))
4024 (concat basename
4025 (if (buffer-file-name)
4026 (concat "."
4027 (file-name-extension (buffer-file-name)))))))
4029 (defun markdown-follow-wiki-link (name &optional other)
4030 "Follow the wiki link NAME.
4031 Convert the name to a file name and call `find-file'. Ensure that
4032 the new buffer remains in `markdown-mode'. Open the link in another
4033 window when OTHER is non-nil."
4034 (let ((filename (markdown-convert-wiki-link-to-filename name))
4035 (wp (file-name-directory buffer-file-name)))
4036 (when other (other-window 1))
4037 (find-file (concat wp filename)))
4038 (when (not (eq major-mode 'markdown-mode))
4039 (markdown-mode)))
4041 (defun markdown-follow-wiki-link-at-point (&optional arg)
4042 "Find Wiki Link at point.
4043 With prefix argument ARG, open the file in other window.
4044 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4045 (interactive "P")
4046 (if (markdown-wiki-link-p)
4047 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4048 (error "Point is not at a Wiki Link")))
4050 (defun markdown-highlight-wiki-link (from to face)
4051 "Highlight the wiki link in the region between FROM and TO using FACE."
4052 (put-text-property from to 'font-lock-face face))
4054 (defun markdown-unfontify-region-wiki-links (from to)
4055 "Remove wiki link faces from the region specified by FROM and TO."
4056 (interactive "nfrom: \nnto: ")
4057 (remove-text-properties from to '(font-lock-face markdown-link-face))
4058 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4060 (defun markdown-fontify-region-wiki-links (from to)
4061 "Search region given by FROM and TO for wiki links and fontify them.
4062 If a wiki link is found check to see if the backing file exists
4063 and highlight accordingly."
4064 (goto-char from)
4065 (save-match-data
4066 (while (re-search-forward markdown-regex-wiki-link to t)
4067 (let ((highlight-beginning (match-beginning 1))
4068 (highlight-end (match-end 1))
4069 (file-name
4070 (markdown-convert-wiki-link-to-filename
4071 (markdown-wiki-link-link))))
4072 (if (file-exists-p file-name)
4073 (markdown-highlight-wiki-link
4074 highlight-beginning highlight-end markdown-link-face)
4075 (markdown-highlight-wiki-link
4076 highlight-beginning highlight-end markdown-link-face)
4077 (markdown-highlight-wiki-link
4078 highlight-beginning highlight-end markdown-missing-link-face))))))
4080 (defun markdown-extend-changed-region (from to)
4081 "Extend region given by FROM and TO so that we can fontify all links.
4082 The region is extended to the first newline before and the first
4083 newline after."
4084 ;; start looking for the first new line before 'from
4085 (goto-char from)
4086 (re-search-backward "\n" nil t)
4087 (let ((new-from (point-min))
4088 (new-to (point-max)))
4089 (if (not (= (point) from))
4090 (setq new-from (point)))
4091 ;; do the same thing for the first new line after 'to
4092 (goto-char to)
4093 (re-search-forward "\n" nil t)
4094 (if (not (= (point) to))
4095 (setq new-to (point)))
4096 (values new-from new-to)))
4098 (defun markdown-check-change-for-wiki-link (from to change)
4099 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4100 Designed to be used with the `after-change-functions' hook.
4101 CHANGE is the number of bytes of pre-change text replaced by the
4102 given range."
4103 (interactive "nfrom: \nnto: \nnchange: ")
4104 (let* ((modified (buffer-modified-p))
4105 (buffer-undo-list t)
4106 (inhibit-read-only t)
4107 (inhibit-point-motion-hooks t)
4108 deactivate-mark
4109 buffer-file-truename)
4110 (unwind-protect
4111 (save-excursion
4112 (save-match-data
4113 (save-restriction
4114 ;; Extend the region to fontify so that it starts
4115 ;; and ends at safe places.
4116 (multiple-value-bind (new-from new-to)
4117 (markdown-extend-changed-region from to)
4118 ;; Unfontify existing fontification (start from scratch)
4119 (markdown-unfontify-region-wiki-links new-from new-to)
4120 ;; Now do the fontification.
4121 (markdown-fontify-region-wiki-links new-from new-to)))))
4122 (and (not modified)
4123 (buffer-modified-p)
4124 (set-buffer-modified-p nil)))))
4126 (defun markdown-fontify-buffer-wiki-links ()
4127 "Refontify all wiki links in the buffer."
4128 (interactive)
4129 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4132 ;;; Following and Jumping =====================================================
4134 (defun markdown-follow-thing-at-point (arg)
4135 "Follow thing at point if possible, such as a reference link or wiki link.
4136 Opens inline and reference links in a browser. Opens wiki links
4137 to other files in the current window, or the another window if
4138 ARG is non-nil.
4139 See `markdown-follow-link-at-point' and
4140 `markdown-follow-wiki-link-at-point'."
4141 (interactive "P")
4142 (cond ((markdown-link-p)
4143 (markdown-follow-link-at-point))
4144 ((markdown-wiki-link-p)
4145 (markdown-follow-wiki-link-at-point arg))
4147 (error "Nothing to follow at point."))))
4149 (defun markdown-jump ()
4150 "Jump to another location based on context at point.
4151 Jumps between reference links and definitions; between footnote
4152 markers and footnote text."
4153 (interactive)
4154 (cond ((markdown-footnote-text-positions)
4155 (markdown-footnote-return))
4156 ((markdown-footnote-marker-positions)
4157 (markdown-footnote-goto-text))
4158 ((thing-at-point-looking-at markdown-regex-link-reference)
4159 (markdown-reference-goto-definition))
4160 ((thing-at-point-looking-at markdown-regex-reference-definition)
4161 (markdown-reference-goto-link (match-string-no-properties 1)))
4163 (error "Nothing to jump to from context at point."))))
4166 ;;; Miscellaneous =============================================================
4168 (defun markdown-compress-whitespace-string (str)
4169 "Compress whitespace in STR and return result.
4170 Leading and trailing whitespace is removed. Sequences of multiple
4171 spaces, tabs, and newlines are replaced with single spaces."
4172 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4173 (replace-regexp-in-string "[ \t\n]+" " " str)))
4175 (defun markdown-line-number-at-pos (&optional pos)
4176 "Return (narrowed) buffer line number at position POS.
4177 If POS is nil, use current buffer location.
4178 This is an exact copy of `line-number-at-pos' for use in emacs21."
4179 (let ((opoint (or pos (point))) start)
4180 (save-excursion
4181 (goto-char (point-min))
4182 (setq start (point))
4183 (goto-char opoint)
4184 (forward-line 0)
4185 (1+ (count-lines start (point))))))
4187 (defun markdown-nobreak-p ()
4188 "Return nil if it is acceptable to break the current line at the point."
4189 ;; inside in square brackets (e.g., link anchor text)
4190 (looking-back "\\[[^]]*"))
4192 (defun markdown-adaptive-fill-function ()
4193 "Return prefix for filling paragraph or nil if not determined."
4194 (cond
4195 ;; List item inside blockquote
4196 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4197 (replace-regexp-in-string
4198 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4199 ;; Blockquote
4200 ((looking-at "^[ \t]*>[ \t]*")
4201 (match-string-no-properties 0))
4202 ;; List items
4203 ((looking-at markdown-regex-list)
4204 (match-string-no-properties 0))
4205 ;; No match
4206 (t nil)))
4209 ;;; Mode Definition ==========================================================
4211 (defun markdown-show-version ()
4212 "Show the version number in the minibuffer."
4213 (interactive)
4214 (message "markdown-mode, version %s" markdown-mode-version))
4216 ;;;###autoload
4217 (define-derived-mode markdown-mode text-mode "Markdown"
4218 "Major mode for editing Markdown files."
4219 ;; Natural Markdown tab width
4220 (setq tab-width 4)
4221 ;; Comments
4222 (make-local-variable 'comment-start)
4223 (setq comment-start "<!-- ")
4224 (make-local-variable 'comment-end)
4225 (setq comment-end " -->")
4226 (make-local-variable 'comment-start-skip)
4227 (setq comment-start-skip "<!--[ \t]*")
4228 (make-local-variable 'comment-column)
4229 (setq comment-column 0)
4230 ;; Font lock.
4231 (set (make-local-variable 'font-lock-defaults)
4232 '(markdown-mode-font-lock-keywords))
4233 (set (make-local-variable 'font-lock-multiline) t)
4234 ;; For imenu support
4235 (setq imenu-create-index-function 'markdown-imenu-create-index)
4236 ;; For menu support in XEmacs
4237 (easy-menu-add markdown-mode-menu markdown-mode-map)
4238 ;; Defun movement
4239 (set (make-local-variable 'beginning-of-defun-function)
4240 'markdown-beginning-of-defun)
4241 (set (make-local-variable 'end-of-defun-function)
4242 'markdown-end-of-defun)
4243 ;; Paragraph filling
4244 (set (make-local-variable 'paragraph-start)
4245 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4246 (set (make-local-variable 'paragraph-separate)
4247 "\\(?:[ \t\f]\\|.* \\)*$")
4248 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4249 "\\`[ \t]*>[ \t]*?\\'")
4250 (set (make-local-variable 'adaptive-fill-function)
4251 'markdown-adaptive-fill-function)
4252 ;; Outline mode
4253 (make-local-variable 'outline-regexp)
4254 (setq outline-regexp markdown-regex-header)
4255 (make-local-variable 'outline-level)
4256 (setq outline-level 'markdown-outline-level)
4257 ;; Cause use of ellipses for invisible text.
4258 (add-to-invisibility-spec '(outline . t))
4259 ;; Indentation and filling
4260 (make-local-variable 'fill-nobreak-predicate)
4261 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4262 (setq indent-line-function markdown-indent-function)
4264 ;; Prepare hooks for XEmacs compatibility
4265 (when (featurep 'xemacs)
4266 (make-local-hook 'after-change-functions)
4267 (make-local-hook 'font-lock-extend-region-functions)
4268 (make-local-hook 'window-configuration-change-hook))
4270 ;; Multiline font lock
4271 (add-hook 'font-lock-extend-region-functions
4272 'markdown-font-lock-extend-region)
4274 ;; Anytime text changes make sure it gets fontified correctly
4275 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4277 ;; If we left the buffer there is a really good chance we were
4278 ;; creating one of the wiki link documents. Make sure we get
4279 ;; refontified when we come back.
4280 (add-hook 'window-configuration-change-hook
4281 'markdown-fontify-buffer-wiki-links t t)
4283 ;; do the initial link fontification
4284 (markdown-fontify-buffer-wiki-links))
4286 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4289 ;;; GitHub Flavored Markdown Mode ============================================
4291 (defvar gfm-font-lock-keywords
4292 (append
4293 ;; GFM features to match first
4294 (list
4295 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4296 (2 markdown-language-keyword-face)
4297 (3 markdown-pre-face)
4298 (4 markdown-pre-face))))
4299 ;; Basic Markdown features (excluding possibly overridden ones)
4300 markdown-mode-font-lock-keywords-basic
4301 ;; GFM features to match last
4302 (list
4303 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4304 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4306 ;;;###autoload
4307 (define-derived-mode gfm-mode markdown-mode "GFM"
4308 "Major mode for editing GitHub Flavored Markdown files."
4309 (setq markdown-link-space-sub-char "-")
4310 (set (make-local-variable 'font-lock-defaults)
4311 '(gfm-font-lock-keywords))
4312 (auto-fill-mode 0)
4313 ;; Use visual-line-mode if available, fall back to longlines-mode:
4314 (if (fboundp 'visual-line-mode)
4315 (visual-line-mode 1)
4316 (longlines-mode 1))
4317 ;; do the initial link fontification
4318 (markdown-fontify-buffer-wiki-links))
4321 (provide 'markdown-mode)
4323 ;;; markdown-mode.el ends here