Protect markdown-block-region from getting stuck at end of buffer
[markdown-mode.git] / markdown-mode.el
blob84690f712dd800f5080a718b394e323851b19c2b
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 (dedention)
547 ;; un-indentation function.
548 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
549 ;; and GFM code block insertion.
550 ;; * Peter Jones <pjones@pmade.com> for link following functions.
551 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
552 ;; externally modified files.
553 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
554 ;; related to orgtbl-mode.
555 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
556 ;; export hooks and unit test improvements.
557 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
559 ;;; Bugs:
561 ;; Although markdown-mode is developed and tested primarily using
562 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
563 ;; priority.
565 ;; If you find any bugs in markdown-mode, please construct a test case
566 ;; or a patch and email me at <jrblevin@sdf.org>.
568 ;;; History:
570 ;; markdown-mode was written and is maintained by Jason Blevins. The
571 ;; first version was released on May 24, 2007.
573 ;; * 2007-05-24: Version 1.1
574 ;; * 2007-05-25: Version 1.2
575 ;; * 2007-06-05: [Version 1.3][]
576 ;; * 2007-06-29: Version 1.4
577 ;; * 2008-05-24: [Version 1.5][]
578 ;; * 2008-06-04: [Version 1.6][]
579 ;; * 2009-10-01: [Version 1.7][]
580 ;; * 2011-08-12: [Version 1.8][]
581 ;; * 2011-08-15: [Version 1.8.1][]
582 ;; * 2013-01-25: [Version 1.9][]
584 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
585 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
586 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
587 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
588 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
589 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
590 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
593 ;;; Code:
595 (require 'easymenu)
596 (require 'outline)
597 (eval-when-compile (require 'cl))
600 ;;; Constants =================================================================
602 (defconst markdown-mode-version "1.9"
603 "Markdown mode version number.")
605 (defconst markdown-output-buffer-name "*markdown-output*"
606 "Name of temporary buffer for markdown command output.")
609 ;;; Customizable Variables ====================================================
611 (defvar markdown-mode-hook nil
612 "Hook run when entering Markdown mode.")
614 (defvar markdown-before-export-hooks nil
615 "Hook run before output XHTML.
616 This hook is abnormal and registered functions are given an argument that is output filename.")
618 (defvar markdown-after-export-hooks nil
619 "Hook run after output XHTML.
620 This hook is abnormal and registered functions are given an argument that is output filename.")
622 (defgroup markdown nil
623 "Major mode for editing text files in Markdown format."
624 :prefix "markdown-"
625 :group 'wp
626 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
628 (defcustom markdown-command "markdown"
629 "Command to run markdown."
630 :group 'markdown
631 :type 'string)
633 (defcustom markdown-command-needs-filename nil
634 "Set to non-nil if `markdown-command' does not accept input from stdin.
635 Instead, it will be passed a filename as the final command line
636 option. As a result, you will only be able to run Markdown from
637 buffers which are visiting a file."
638 :group 'markdown
639 :type 'boolean)
641 (defcustom markdown-open-command nil
642 "Command used for opening Markdown files directly.
643 For example, a standalone Markdown previewer. This command will
644 be called with a single argument: the filename of the current
645 buffer."
646 :group 'markdown
647 :type 'string)
649 (defcustom markdown-hr-strings
650 '("* * * * *"
651 "---------"
652 "* * * * * * * * * * * * * * * * * * * *"
653 "---------------------------------------"
654 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
655 "-------------------------------------------------------------------------------")
656 "Strings to use when inserting horizontal rules.
657 The first string in the list will be the default when inserting a
658 horizontal rule. Strings should be listed in increasing order of
659 prominence for use with promotion and demotion functions."
660 :group 'markdown
661 :type 'list)
663 (defcustom markdown-bold-underscore nil
664 "Use two underscores for bold instead of two asterisks."
665 :group 'markdown
666 :type 'boolean)
668 (defcustom markdown-italic-underscore nil
669 "Use underscores for italic instead of asterisks."
670 :group 'markdown
671 :type 'boolean)
673 (defcustom markdown-indent-function 'markdown-indent-line
674 "Function to use to indent."
675 :group 'markdown
676 :type 'function)
678 (defcustom markdown-indent-on-enter t
679 "Automatically indent new lines when enter key is pressed."
680 :group 'markdown
681 :type 'boolean)
683 (defcustom markdown-follow-wiki-link-on-enter t
684 "Follow wiki link at point (if any) when the enter key is pressed."
685 :group 'markdown
686 :type 'boolean)
688 (defcustom markdown-wiki-link-alias-first t
689 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
690 Otherwise, they will be treated as [[PageName|alias text]]."
691 :group 'markdown
692 :type 'boolean)
694 (defcustom markdown-uri-types
695 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
696 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
697 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
698 "Link types for syntax highlighting of URIs."
699 :group 'markdown
700 :type 'list)
702 (defcustom markdown-enable-math nil
703 "Syntax highlighting for inline LaTeX expressions.
704 This will not take effect until Emacs is restarted."
705 :group 'markdown
706 :type 'boolean)
708 (defcustom markdown-css-path ""
709 "URL of CSS file to link to in the output XHTML."
710 :group 'markdown
711 :type 'string)
713 (defcustom markdown-content-type ""
714 "Content type string for the http-equiv header in XHTML output.
715 When set to a non-empty string, insert the http-equiv attribute.
716 Otherwise, this attribute is omitted."
717 :group 'markdown
718 :type 'string)
720 (defcustom markdown-coding-system nil
721 "Character set string for the http-equiv header in XHTML output.
722 Defaults to `buffer-file-coding-system' (and falling back to
723 `iso-8859-1' when not available). Common settings are `utf-8'
724 and `iso-latin-1'. Use `list-coding-systems' for more choices."
725 :group 'markdown
726 :type 'coding-system)
728 (defcustom markdown-xhtml-header-content ""
729 "Additional content to include in the XHTML <head> block."
730 :group 'markdown
731 :type 'string)
733 (defcustom markdown-xhtml-standalone-regexp
734 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
735 "Regexp indicating whether `markdown-command' output is standalone XHTML."
736 :group 'markdown
737 :type 'regexp)
739 (defcustom markdown-link-space-sub-char
741 "Character to use instead of spaces when mapping wiki links to filenames."
742 :group 'markdown
743 :type 'string)
745 (defcustom markdown-footnote-location 'end
746 "Position where new footnotes are inserted in the document."
747 :group 'markdown
748 :type '(choice (const :tag "At the end of the document" end)
749 (const :tag "Immediately after the paragraph" immediately)
750 (const :tag "Before next header" header)))
753 ;;; Font Lock =================================================================
755 (require 'font-lock)
757 (defvar markdown-italic-face 'markdown-italic-face
758 "Face name to use for italic text.")
760 (defvar markdown-bold-face 'markdown-bold-face
761 "Face name to use for bold text.")
763 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
764 "Face name to use as a base for header delimiters.")
766 (defvar markdown-header-rule-face 'markdown-header-rule-face
767 "Face name to use as a base for header rules.")
769 (defvar markdown-header-face 'markdown-header-face
770 "Face name to use as a base for headers.")
772 (defvar markdown-header-face-1 'markdown-header-face-1
773 "Face name to use for level-1 headers.")
775 (defvar markdown-header-face-2 'markdown-header-face-2
776 "Face name to use for level-2 headers.")
778 (defvar markdown-header-face-3 'markdown-header-face-3
779 "Face name to use for level-3 headers.")
781 (defvar markdown-header-face-4 'markdown-header-face-4
782 "Face name to use for level-4 headers.")
784 (defvar markdown-header-face-5 'markdown-header-face-5
785 "Face name to use for level-5 headers.")
787 (defvar markdown-header-face-6 'markdown-header-face-6
788 "Face name to use for level-6 headers.")
790 (defvar markdown-inline-code-face 'markdown-inline-code-face
791 "Face name to use for inline code.")
793 (defvar markdown-list-face 'markdown-list-face
794 "Face name to use for list markers.")
796 (defvar markdown-blockquote-face 'markdown-blockquote-face
797 "Face name to use for blockquote.")
799 (defvar markdown-pre-face 'markdown-pre-face
800 "Face name to use for preformatted text.")
802 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
803 "Face name to use for programming language identifiers.")
805 (defvar markdown-link-face 'markdown-link-face
806 "Face name to use for links.")
808 (defvar markdown-missing-link-face 'markdown-missing-link-face
809 "Face name to use for links where the linked file does not exist.")
811 (defvar markdown-reference-face 'markdown-reference-face
812 "Face name to use for reference.")
814 (defvar markdown-footnote-face 'markdown-footnote-face
815 "Face name to use for footnote identifiers.")
817 (defvar markdown-url-face 'markdown-url-face
818 "Face name to use for URLs.")
820 (defvar markdown-link-title-face 'markdown-link-title-face
821 "Face name to use for reference link titles.")
823 (defvar markdown-comment-face 'markdown-comment-face
824 "Face name to use for HTML comments.")
826 (defvar markdown-math-face 'markdown-math-face
827 "Face name to use for LaTeX expressions.")
829 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
830 "Face name to use for metadata keys.")
832 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
833 "Face name to use for metadata values.")
835 (defgroup markdown-faces nil
836 "Faces used in Markdown Mode"
837 :group 'markdown
838 :group 'faces)
840 (defface markdown-italic-face
841 '((t (:inherit font-lock-variable-name-face :slant italic)))
842 "Face for italic text."
843 :group 'markdown-faces)
845 (defface markdown-bold-face
846 '((t (:inherit font-lock-variable-name-face :weight bold)))
847 "Face for bold text."
848 :group 'markdown-faces)
850 (defface markdown-header-rule-face
851 '((t (:inherit font-lock-function-name-face :weight bold)))
852 "Base face for headers rules."
853 :group 'markdown-faces)
855 (defface markdown-header-delimiter-face
856 '((t (:inherit font-lock-function-name-face :weight bold)))
857 "Base face for headers hash delimiter."
858 :group 'markdown-faces)
860 (defface markdown-header-face
861 '((t (:inherit font-lock-function-name-face :weight bold)))
862 "Base face for headers."
863 :group 'markdown-faces)
865 (defface markdown-header-face-1
866 '((t (:inherit markdown-header-face)))
867 "Face for level-1 headers."
868 :group 'markdown-faces)
870 (defface markdown-header-face-2
871 '((t (:inherit markdown-header-face)))
872 "Face for level-2 headers."
873 :group 'markdown-faces)
875 (defface markdown-header-face-3
876 '((t (:inherit markdown-header-face)))
877 "Face for level-3 headers."
878 :group 'markdown-faces)
880 (defface markdown-header-face-4
881 '((t (:inherit markdown-header-face)))
882 "Face for level-4 headers."
883 :group 'markdown-faces)
885 (defface markdown-header-face-5
886 '((t (:inherit markdown-header-face)))
887 "Face for level-5 headers."
888 :group 'markdown-faces)
890 (defface markdown-header-face-6
891 '((t (:inherit markdown-header-face)))
892 "Face for level-6 headers."
893 :group 'markdown-faces)
895 (defface markdown-inline-code-face
896 '((t (:inherit font-lock-constant-face)))
897 "Face for inline code."
898 :group 'markdown-faces)
900 (defface markdown-list-face
901 '((t (:inherit font-lock-builtin-face)))
902 "Face for list item markers."
903 :group 'markdown-faces)
905 (defface markdown-blockquote-face
906 '((t (:inherit font-lock-doc-face)))
907 "Face for blockquote sections."
908 :group 'markdown-faces)
910 (defface markdown-pre-face
911 '((t (:inherit font-lock-constant-face)))
912 "Face for preformatted text."
913 :group 'markdown-faces)
915 (defface markdown-language-keyword-face
916 '((t (:inherit font-lock-type-face)))
917 "Face for programming language identifiers."
918 :group 'markdown-faces)
920 (defface markdown-link-face
921 '((t (:inherit font-lock-keyword-face)))
922 "Face for links."
923 :group 'markdown-faces)
925 (defface markdown-missing-link-face
926 '((t (:inherit font-lock-warning-face)))
927 "Face for missing links."
928 :group 'markdown-faces)
930 (defface markdown-reference-face
931 '((t (:inherit font-lock-type-face)))
932 "Face for link references."
933 :group 'markdown-faces)
935 (defface markdown-footnote-face
936 '((t (:inherit font-lock-keyword-face)))
937 "Face for footnote markers."
938 :group 'markdown-faces)
940 (defface markdown-url-face
941 '((t (:inherit font-lock-string-face)))
942 "Face for URLs."
943 :group 'markdown-faces)
945 (defface markdown-link-title-face
946 '((t (:inherit font-lock-comment-face)))
947 "Face for reference link titles."
948 :group 'markdown-faces)
950 (defface markdown-comment-face
951 '((t (:inherit font-lock-comment-face)))
952 "Face for HTML comments."
953 :group 'markdown-faces)
955 (defface markdown-math-face
956 '((t (:inherit font-lock-string-face)))
957 "Face for LaTeX expressions."
958 :group 'markdown-faces)
960 (defface markdown-metadata-key-face
961 '((t (:inherit font-lock-variable-name-face)))
962 "Face for metadata keys."
963 :group 'markdown-faces)
965 (defface markdown-metadata-value-face
966 '((t (:inherit font-lock-string-face)))
967 "Face for metadata values."
968 :group 'markdown-faces)
970 (defconst markdown-regex-link-inline
971 "\\(!?\\[\\([^]]*?\\)\\]\\)\\((\\([^\\)]*\\))\\)"
972 "Regular expression for a [text](file) or an image link ![text](file).")
974 (defconst markdown-regex-link-reference
975 "\\(!?\\[\\([^]]+?\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
976 "Regular expression for a reference link [text][id].")
978 (defconst markdown-regex-reference-definition
979 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
980 "Regular expression for a link definition [id]: ...")
982 (defconst markdown-regex-footnote
983 "\\(\\[\\^.+?\\]\\)"
984 "Regular expression for a footnote marker [^fn].")
986 (defconst markdown-regex-header
987 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
988 "Regexp identifying Markdown headers.")
990 (defconst markdown-regex-header-1-atx
991 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
992 "Regular expression for level 1 atx-style (hash mark) headers.")
994 (defconst markdown-regex-header-2-atx
995 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
996 "Regular expression for level 2 atx-style (hash mark) headers.")
998 (defconst markdown-regex-header-3-atx
999 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
1000 "Regular expression for level 3 atx-style (hash mark) headers.")
1002 (defconst markdown-regex-header-4-atx
1003 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
1004 "Regular expression for level 4 atx-style (hash mark) headers.")
1006 (defconst markdown-regex-header-5-atx
1007 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
1008 "Regular expression for level 5 atx-style (hash mark) headers.")
1010 (defconst markdown-regex-header-6-atx
1011 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
1012 "Regular expression for level 6 atx-style (hash mark) headers.")
1014 (defconst markdown-regex-header-1-setext
1015 "^\\(.*\\)\n\\(=+\\)$"
1016 "Regular expression for level 1 setext-style (underline) headers.")
1018 (defconst markdown-regex-header-2-setext
1019 "^\\(.*\\)\n\\(-+\\)$"
1020 "Regular expression for level 2 setext-style (underline) headers.")
1022 (defconst markdown-regex-header-setext
1023 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1024 "Regular expression for generic setext-style (underline) headers.")
1026 (defconst markdown-regex-header-atx
1027 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1028 "Regular expression for generic atx-style (hash mark) headers.")
1030 (defconst markdown-regex-hr
1031 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1032 "Regular expression for matching Markdown horizontal rules.")
1034 (defconst markdown-regex-code
1035 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1036 "Regular expression for matching inline code fragments.
1038 The first group ensures that the leading backquote character
1039 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1040 character, including newlines, but not two newlines in a row.
1041 The final group requires that the character following the code
1042 fragment is not a backquote.")
1044 (defconst markdown-regex-pre
1045 "^\\( \\|\t\\).*$"
1046 "Regular expression for matching preformatted text sections.")
1048 (defconst markdown-regex-list
1049 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1050 "Regular expression for matching list items.")
1052 (defconst markdown-regex-bold
1053 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1054 "Regular expression for matching bold text.
1055 Group 1 matches the character before the opening asterisk or
1056 underscore, if any, ensuring that it is not a backslash escape.
1057 Group 2 matches the entire expression, including delimiters.
1058 Groups 3 and 5 matches the opening and closing delimiters.
1059 Group 4 matches the text inside the delimiters.")
1061 (defconst markdown-regex-italic
1062 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1063 "Regular expression for matching italic text.
1064 Group 1 matches the character before the opening asterisk or
1065 underscore, if any, ensuring that it is not a backslash escape.
1066 Group 2 matches the entire expression, including delimiters.
1067 Groups 3 and 5 matches the opening and closing delimiters.
1068 Group 4 matches the text inside the delimiters.")
1070 (defconst markdown-regex-gfm-italic
1071 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1072 "Regular expression for matching italic text in GitHub-flavored Markdown.
1073 Underscores in words are not treated as special.")
1075 (defconst markdown-regex-blockquote
1076 "^[ \t]*\\(>\\).*$"
1077 "Regular expression for matching blockquote lines.")
1079 (defconst markdown-regex-line-break
1080 " $"
1081 "Regular expression for matching line breaks.")
1083 (defconst markdown-regex-wiki-link
1084 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1085 "Regular expression for matching wiki links.
1086 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1087 wiki links of the form [[PageName|link text]]. In this regular
1088 expression, #1 matches the page name and #3 matches the link
1089 text.")
1091 (defconst markdown-regex-uri
1092 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1093 "Regular expression for matching inline URIs.")
1095 (defconst markdown-regex-angle-uri
1096 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1097 "Regular expression for matching inline URIs in angle brackets.")
1099 (defconst markdown-regex-email
1100 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1101 "Regular expression for matching inline email addresses.")
1103 (defconst markdown-regex-link-generic
1104 (concat "\\(?:" markdown-regex-wiki-link
1105 "\\|" markdown-regex-link-inline
1106 "\\|" markdown-regex-link-reference
1107 "\\|" markdown-regex-angle-uri "\\)")
1108 "Regular expression for matching any recognized link.")
1110 (defconst markdown-regex-block-separator
1111 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1112 "Regular expression for matching block boundaries.")
1114 (defconst markdown-regex-latex-expression
1115 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1116 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1118 (defconst markdown-regex-latex-display
1119 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1120 "Regular expression for itex \[..\] display mode expressions.")
1122 (defconst markdown-regex-multimarkdown-metadata
1123 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1124 "Regular expression for matching MultiMarkdown metadata.")
1126 (defconst markdown-regex-pandoc-metadata
1127 "^\\(%\\)[ \t]*\\(.*\\)$"
1128 "Regular expression for matching Pandoc metadata.")
1130 (defvar markdown-mode-font-lock-keywords-basic
1131 (list
1132 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1133 (2 markdown-metadata-value-face)))
1134 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1135 (2 markdown-metadata-value-face)))
1136 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1137 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1138 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1139 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1140 (2 markdown-header-rule-face)))
1141 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1142 (2 markdown-header-rule-face)))
1143 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1144 (2 markdown-header-face-1)
1145 (3 markdown-header-delimiter-face)))
1146 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1147 (2 markdown-header-face-2)
1148 (3 markdown-header-delimiter-face)))
1149 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1150 (2 markdown-header-face-3)
1151 (3 markdown-header-delimiter-face)))
1152 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1153 (2 markdown-header-face-4)
1154 (3 markdown-header-delimiter-face)))
1155 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1156 (2 markdown-header-face-5)
1157 (3 markdown-header-delimiter-face)))
1158 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1159 (2 markdown-header-face-6)
1160 (3 markdown-header-delimiter-face)))
1161 (cons markdown-regex-hr 'markdown-header-face)
1162 (cons 'markdown-match-comments '((0 markdown-comment-face t t)))
1163 (cons 'markdown-match-code '((0 markdown-inline-code-face)))
1164 (cons markdown-regex-angle-uri 'markdown-link-face)
1165 (cons markdown-regex-uri 'markdown-link-face)
1166 (cons markdown-regex-email 'markdown-link-face)
1167 (cons markdown-regex-list '(2 markdown-list-face))
1168 (cons markdown-regex-link-inline '((1 markdown-link-face t)
1169 (3 markdown-url-face t)))
1170 (cons markdown-regex-link-reference '((1 markdown-link-face t)
1171 (3 markdown-reference-face t)))
1172 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1173 (2 markdown-url-face t)
1174 (3 markdown-link-title-face t)))
1175 (cons markdown-regex-footnote 'markdown-footnote-face)
1176 (cons markdown-regex-bold '(2 markdown-bold-face))
1178 "Syntax highlighting for Markdown files.")
1180 (defvar markdown-mode-font-lock-keywords-core
1181 (list
1182 (cons markdown-regex-italic '(2 markdown-italic-face))
1184 "Additional syntax highlighting for Markdown files.
1185 Includes features which are overridden by some variants.")
1187 (defconst markdown-mode-font-lock-keywords-latex
1188 (list
1189 ;; Math mode $..$ or $$..$$
1190 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1191 ;; Display mode equations with brackets: \[ \]
1192 (cons markdown-regex-latex-display 'markdown-math-face)
1193 ;; Equation reference (eq:foo)
1194 (cons "(eq:\\w+)" 'markdown-reference-face)
1195 ;; Equation reference \eqref{foo}
1196 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1197 "Syntax highlighting for LaTeX fragments.")
1199 (defvar markdown-mode-font-lock-keywords
1200 (append
1201 (if markdown-enable-math
1202 markdown-mode-font-lock-keywords-latex)
1203 markdown-mode-font-lock-keywords-basic
1204 markdown-mode-font-lock-keywords-core)
1205 "Default highlighting expressions for Markdown mode.")
1207 ;; Footnotes
1208 (defvar markdown-footnote-counter 0
1209 "Counter for footnote numbers.")
1210 (make-variable-buffer-local 'markdown-footnote-counter)
1212 (defconst markdown-footnote-chars
1213 "[[:alnum:]-]"
1214 "Regular expression maching any character that is allowed in a footnote identifier.")
1217 ;;; Compatibility =============================================================
1219 (defun markdown-replace-regexp-in-string (regexp rep string)
1220 "Replace all matches for REGEXP with REP in STRING.
1221 This is a compatibility wrapper to provide `replace-regexp-in-string'
1222 in XEmacs 21."
1223 (if (featurep 'xemacs)
1224 (replace-in-string string regexp rep)
1225 (replace-regexp-in-string regexp rep string)))
1227 ;; `markdown-use-region-p' is a compatibility function which checks
1228 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1229 (eval-and-compile
1230 (cond
1231 ;; Emacs 23 and newer
1232 ((fboundp 'use-region-p)
1233 (defalias 'markdown-use-region-p 'use-region-p))
1234 ;; Older Emacsen
1235 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1236 (defun markdown-use-region-p ()
1237 "Compatibility wrapper to provide `use-region-p'."
1238 (and transient-mark-mode mark-active)))
1239 ;; XEmacs
1240 ((fboundp 'region-active-p)
1241 (defalias 'markdown-use-region-p 'region-active-p))))
1243 (defun markdown-use-buttons-p ()
1244 "Determine whether this Emacs supports buttons."
1245 (or (featurep 'button) (locate-library "button")))
1248 ;;; Markdown Parsing Functions ================================================
1250 (defun markdown-cur-line-blank-p ()
1251 "Return t if the current line is blank and nil otherwise."
1252 (save-excursion
1253 (beginning-of-line)
1254 (re-search-forward "^\\s *$" (line-end-position) t)))
1256 (defun markdown-prev-line-blank-p ()
1257 "Return t if the previous line is blank and nil otherwise.
1258 If we are at the first line, then consider the previous line to be blank."
1259 (or (= (line-beginning-position) (point-min))
1260 (save-excursion
1261 (forward-line -1)
1262 (markdown-cur-line-blank-p))))
1264 (defun markdown-next-line-blank-p ()
1265 "Return t if the next line is blank and nil otherwise.
1266 If we are at the last line, then consider the next line to be blank."
1267 (or (= (line-end-position) (point-max))
1268 (save-excursion
1269 (forward-line 1)
1270 (markdown-cur-line-blank-p))))
1272 (defun markdown-prev-line-indent-p ()
1273 "Return t if the previous line is indented and nil otherwise."
1274 (save-excursion
1275 (forward-line -1)
1276 (goto-char (line-beginning-position))
1277 (if (re-search-forward "^\\s " (line-end-position) t) t)))
1279 (defun markdown-cur-line-indent ()
1280 "Return the number of leading whitespace characters in the current line."
1281 (save-match-data
1282 (save-excursion
1283 (goto-char (line-beginning-position))
1284 (re-search-forward "^[ \t]+" (line-end-position) t)
1285 (current-column))))
1287 (defun markdown-prev-line-indent ()
1288 "Return the number of leading whitespace characters in the previous line."
1289 (save-excursion
1290 (forward-line -1)
1291 (markdown-cur-line-indent)))
1293 (defun markdown-next-line-indent ()
1294 "Return the number of leading whitespace characters in the next line."
1295 (save-excursion
1296 (forward-line 1)
1297 (markdown-cur-line-indent)))
1299 (defun markdown-cur-non-list-indent ()
1300 "Return beginning position of list item text (not including the list marker).
1301 Return nil if the current line is not the beginning of a list item."
1302 (save-match-data
1303 (save-excursion
1304 (beginning-of-line)
1305 (when (re-search-forward markdown-regex-list (line-end-position) t)
1306 (current-column)))))
1308 (defun markdown-prev-non-list-indent ()
1309 "Return position of the first non-list-marker on the previous line."
1310 (save-excursion
1311 (forward-line -1)
1312 (markdown-cur-non-list-indent)))
1314 (defun markdown-new-baseline-p ()
1315 "Determine if the current line begins a new baseline level."
1316 (save-excursion
1317 (beginning-of-line)
1318 (save-match-data
1319 (or (looking-at markdown-regex-header)
1320 (looking-at markdown-regex-hr)
1321 (and (null (markdown-cur-non-list-indent))
1322 (= (markdown-cur-line-indent) 0)
1323 (markdown-prev-line-blank-p))))))
1325 (defun markdown-search-backward-baseline ()
1326 "Search backward baseline point with no indentation and not a list item."
1327 (end-of-line)
1328 (let (stop)
1329 (while (not (or stop (bobp)))
1330 (re-search-backward markdown-regex-block-separator nil t)
1331 (when (match-end 2)
1332 (goto-char (match-end 2))
1333 (cond
1334 ((markdown-new-baseline-p)
1335 (setq stop t))
1336 ((looking-at markdown-regex-list)
1337 (setq stop nil))
1338 (t (setq stop t)))))))
1340 (defun markdown-update-list-levels (marker indent levels)
1341 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1342 Here, MARKER is a string representing the type of list, INDENT is an integer
1343 giving the indentation, in spaces, of the current block, and LEVELS is a
1344 list of the indentation levels of parent list items. When LEVELS is nil,
1345 it means we are at baseline (not inside of a nested list)."
1346 (cond
1347 ;; New list item at baseline.
1348 ((and marker (null levels))
1349 (setq levels (list indent)))
1350 ;; List item with greater indentation (four or more spaces).
1351 ;; Increase list level.
1352 ((and marker (>= indent (+ (car levels) 4)))
1353 (setq levels (cons indent levels)))
1354 ;; List item with greater or equal indentation (less than four spaces).
1355 ;; Do not increase list level.
1356 ((and marker (>= indent (car levels)))
1357 levels)
1358 ;; Lesser indentation level.
1359 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1360 ;; indentation could move back more than one list level). Note
1361 ;; that this block need not be the beginning of list item.
1362 ((< indent (car levels))
1363 (while (and (> (length levels) 1)
1364 (< indent (+ (cadr levels) 4)))
1365 (setq levels (cdr levels)))
1366 levels)
1367 ;; Otherwise, do nothing.
1368 (t levels)))
1370 (defun markdown-calculate-list-levels ()
1371 "Calculate list levels at point.
1372 Return a list of the form (n1 n2 n3 ...) where n1 is the
1373 indentation of the deepest nested list item in the branch of
1374 the list at the point, n2 is the indentation of the parent
1375 list item, and so on. The depth of the list item is therefore
1376 the length of the returned list. If the point is not at or
1377 immediately after a list item, return nil."
1378 (save-excursion
1379 (let ((first (point)) levels indent pre-regexp)
1380 ;; Find a baseline point with zero list indentation
1381 (markdown-search-backward-baseline)
1382 ;; Search for all list items between baseline and LOC
1383 (while (and (< (point) first)
1384 (re-search-forward markdown-regex-list first t))
1385 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1386 (beginning-of-line)
1387 (cond
1388 ;; Make sure this is not a header or hr
1389 ((markdown-new-baseline-p) (setq levels nil))
1390 ;; Make sure this is not a line from a pre block
1391 ((looking-at pre-regexp))
1392 ;; If not, then update levels
1394 (setq indent (markdown-cur-line-indent))
1395 (setq levels (markdown-update-list-levels (match-string 2)
1396 indent levels))))
1397 (end-of-line))
1398 levels)))
1400 (defun markdown-prev-list-item (level)
1401 "Search backward from point for a list item with indentation LEVEL.
1402 Set point to the beginning of the item, and return point, or nil
1403 upon failure."
1404 (let (bounds indent prev)
1405 (setq prev (point))
1406 (forward-line -1)
1407 (setq indent (markdown-cur-line-indent))
1408 (while
1409 (cond
1410 ;; Stop at beginning of buffer
1411 ((bobp) (setq prev nil))
1412 ;; Continue if current line is blank
1413 ((markdown-cur-line-blank-p) t)
1414 ;; List item
1415 ((and (looking-at markdown-regex-list)
1416 (setq bounds (markdown-cur-list-item-bounds)))
1417 (cond
1418 ;; Continue at item with greater indentation
1419 ((> (nth 3 bounds) level) t)
1420 ;; Stop and return point at item of equal indentation
1421 ((= (nth 3 bounds) level)
1422 (setq prev (point))
1423 nil)
1424 ;; Stop and return nil at item with lesser indentation
1425 ((< (nth 3 bounds) level)
1426 (setq prev nil)
1427 nil)))
1428 ;; Continue while indentation is the same or greater
1429 ((>= indent level) t)
1430 ;; Stop if current indentation is less than list item
1431 ;; and the next is blank
1432 ((and (< indent level)
1433 (markdown-next-line-blank-p))
1434 (setq prev nil))
1435 ;; Stop at a header
1436 ((looking-at markdown-regex-header) (setq prev nil))
1437 ;; Stop at a horizontal rule
1438 ((looking-at markdown-regex-hr) (setq prev nil))
1439 ;; Otherwise, continue.
1440 (t t))
1441 (forward-line -1)
1442 (setq indent (markdown-cur-line-indent)))
1443 prev))
1445 (defun markdown-next-list-item (level)
1446 "Search forward from point for the next list item with indentation LEVEL.
1447 Set point to the beginning of the item, and return point, or nil
1448 upon failure."
1449 (let (bounds indent prev next)
1450 (setq next (point))
1451 (forward-line)
1452 (setq indent (markdown-cur-line-indent))
1453 (while
1454 (cond
1455 ;; Stop at end of the buffer.
1456 ((eobp) (setq prev nil))
1457 ;; Continue if the current line is blank
1458 ((markdown-cur-line-blank-p) t)
1459 ;; List item
1460 ((and (looking-at markdown-regex-list)
1461 (setq bounds (markdown-cur-list-item-bounds)))
1462 (cond
1463 ;; Continue at item with greater indentation
1464 ((> (nth 3 bounds) level) t)
1465 ;; Stop and return point at item of equal indentation
1466 ((= (nth 3 bounds) level)
1467 (setq next (point))
1468 nil)
1469 ;; Stop and return nil at item with lesser indentation
1470 ((< (nth 3 bounds) level)
1471 (setq next nil)
1472 nil)))
1473 ;; Continue while indentation is the same or greater
1474 ((>= indent level) t)
1475 ;; Stop if current indentation is less than list item
1476 ;; and the previous line was blank.
1477 ((and (< indent level)
1478 (markdown-prev-line-blank-p))
1479 (setq next nil))
1480 ;; Stop at a header
1481 ((looking-at markdown-regex-header) (setq next nil))
1482 ;; Stop at a horizontal rule
1483 ((looking-at markdown-regex-hr) (setq next nil))
1484 ;; Otherwise, continue.
1485 (t t))
1486 (forward-line)
1487 (setq indent (markdown-cur-line-indent)))
1488 next))
1490 (defun markdown-cur-list-item-end (level)
1491 "Move to the end of the current list item with nonlist indentation LEVEL.
1492 If the point is not in a list item, do nothing."
1493 (let (indent)
1494 (forward-line)
1495 (setq indent (markdown-cur-line-indent))
1496 (while
1497 (cond
1498 ;; Stop at end of the buffer.
1499 ((eobp) nil)
1500 ;; Continue if the current line is blank
1501 ((markdown-cur-line-blank-p) t)
1502 ;; Continue while indentation is the same or greater
1503 ((>= indent level) t)
1504 ;; Stop if current indentation is less than list item
1505 ;; and the previous line was blank.
1506 ((and (< indent level)
1507 (markdown-prev-line-blank-p))
1508 nil)
1509 ;; Stop at a new list item of the same or lesser indentation
1510 ((looking-at markdown-regex-list) nil)
1511 ;; Stop at a header
1512 ((looking-at markdown-regex-header) nil)
1513 ;; Stop at a horizontal rule
1514 ((looking-at markdown-regex-hr) nil)
1515 ;; Otherwise, continue.
1516 (t t))
1517 (forward-line)
1518 (setq indent (markdown-cur-line-indent)))
1519 ;; Don't skip over whitespace for empty list items (marker and
1520 ;; whitespace only), just move to end of whitespace.
1521 (if (looking-back (concat markdown-regex-list "\\s-*"))
1522 (goto-char (match-end 3))
1523 (skip-syntax-backward "-"))))
1525 (defun markdown-cur-list-item-bounds ()
1526 "Return bounds and indentation of the current list item.
1527 Return a list of the form (begin end indent nonlist-indent).
1528 If the point is not inside a list item, return nil.
1529 Leave match data intact for `markdown-regex-list'."
1530 (let (cur prev-begin prev-end indent nonlist-indent)
1531 ;; Store current location
1532 (setq cur (point))
1533 ;; Verify that cur is between beginning and end of item
1534 (save-excursion
1535 (end-of-line)
1536 (when (re-search-backward markdown-regex-list nil t)
1537 (setq prev-begin (match-beginning 0))
1538 (setq indent (length (match-string 1)))
1539 (setq nonlist-indent (length (match-string 0)))
1540 (save-match-data
1541 (markdown-cur-list-item-end nonlist-indent)
1542 (setq prev-end (point)))
1543 (when (and (>= cur prev-begin)
1544 (<= cur prev-end)
1545 nonlist-indent)
1546 (list prev-begin prev-end indent nonlist-indent))))))
1548 (defun markdown-bounds-of-thing-at-point (thing)
1549 "Calls `bounds-of-thing-at-point' for THING with slight modifications.
1550 Does not include trailing newlines when THING is 'line. Handles the
1551 end of buffer case by setting both endpoints equal to the value of
1552 `point-max', since an empty region will trigger empty markup insertion.
1553 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1554 (let* ((bounds (bounds-of-thing-at-point thing))
1555 (a (car bounds))
1556 (b (cdr bounds)))
1557 (when bounds
1558 (when (eq thing 'line)
1559 (cond ((and (eobp) (markdown-cur-line-blank-p))
1560 (setq a b))
1561 ((char-equal (char-before b) ?\^J)
1562 (setq b (1- b)))))
1563 (cons a b))))
1565 (defun markdown-reference-definition (reference)
1566 "Find out whether Markdown REFERENCE is defined.
1567 REFERENCE should include the square brackets, like [this].
1568 When REFERENCE is defined, return a list of the form (text start end)
1569 containing the definition text itself followed by the start and end
1570 locations of the text. Otherwise, return nil.
1571 Leave match data for `markdown-regex-reference-definition'
1572 intact additional processing."
1573 (let ((reference (downcase reference)))
1574 (save-excursion
1575 (goto-char (point-min))
1576 (catch 'found
1577 (while (re-search-forward markdown-regex-reference-definition nil t)
1578 (when (string= reference (downcase (match-string-no-properties 1)))
1579 (throw 'found
1580 (list (match-string-no-properties 2)
1581 (match-beginning 2) (match-end 2)))))))))
1584 ;;; Markdown Font Lock Matching Functions =====================================
1586 (defun markdown-match-comments (last)
1587 "Match HTML comments from the point to LAST."
1588 (cond ((search-forward "<!--" last t)
1589 (backward-char 4)
1590 (let ((beg (point)))
1591 (cond ((search-forward-regexp "--[ \t]*>" last t)
1592 (set-match-data (list beg (point)))
1594 (t nil))))
1595 (t nil)))
1597 (defun markdown-match-code (last)
1598 "Match inline code from the point to LAST."
1599 (unless (bobp)
1600 (backward-char 1))
1601 (cond ((re-search-forward markdown-regex-code last t)
1602 (set-match-data (list (match-beginning 2) (match-end 2)))
1603 (goto-char (match-end 0))
1605 (t (forward-char 2) nil)))
1607 (defun markdown-match-pre-blocks (last)
1608 "Match Markdown pre blocks from point to LAST."
1609 (let ((levels (markdown-calculate-list-levels))
1610 indent pre-regexp end-regexp begin end stop)
1611 (while (and (< (point) last) (not end))
1612 ;; Search for a region with sufficient indentation
1613 (if (null levels)
1614 (setq indent 1)
1615 (setq indent (1+ (length levels))))
1616 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1617 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1619 (cond
1620 ;; If not at the beginning of a line, move forward
1621 ((not (bolp)) (forward-line))
1622 ;; Move past blank lines
1623 ((markdown-cur-line-blank-p) (forward-line))
1624 ;; At headers and horizontal rules, reset levels
1625 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1626 ;; If the current line has sufficient indentation, mark out pre block
1627 ((looking-at pre-regexp)
1628 (setq begin (match-beginning 0))
1629 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1630 (not (eobp)))
1631 (forward-line))
1632 (setq end (point)))
1633 ;; If current line has a list marker, update levels, move to end of block
1634 ((looking-at markdown-regex-list)
1635 (setq levels (markdown-update-list-levels
1636 (match-string 2) (markdown-cur-line-indent) levels))
1637 (markdown-end-of-block-element))
1638 ;; If this is the end of the indentation level, adjust levels accordingly.
1639 ;; Only match end of indentation level if levels is not the empty list.
1640 ((and (car levels) (looking-at end-regexp))
1641 (setq levels (markdown-update-list-levels
1642 nil (markdown-cur-line-indent) levels))
1643 (markdown-end-of-block-element))
1644 (t (markdown-end-of-block-element))))
1646 (if (not (and begin end))
1647 ;; Return nil if no pre block was found
1649 ;; Set match data and return t upon success
1650 (set-match-data (list begin end))
1651 t)))
1653 (defun markdown-match-fenced-code-blocks (last)
1654 "Match fenced code blocks from the point to LAST."
1655 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1656 (beginning-of-line)
1657 (let ((beg (point)))
1658 (forward-line)
1659 (cond ((search-forward-regexp
1660 (concat "^" (match-string 1) "~*") last t)
1661 (set-match-data (list beg (point)))
1663 (t nil))))
1664 (t nil)))
1666 (defun markdown-match-gfm-code-blocks (last)
1667 "Match GFM quoted code blocks from point to LAST."
1668 (let (open lang body close all)
1669 (cond ((and (eq major-mode 'gfm-mode)
1670 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1671 (beginning-of-line)
1672 (setq open (list (match-beginning 1) (match-end 1))
1673 lang (list (match-beginning 2) (match-end 2)))
1674 (forward-line)
1675 (setq body (list (point)))
1676 (cond ((search-forward-regexp "^```$" last t)
1677 (setq body (reverse (cons (1- (match-beginning 0)) body))
1678 close (list (match-beginning 0) (match-end 0))
1679 all (list (car open) (match-end 0)))
1680 (set-match-data (append all open lang body close))
1682 (t nil)))
1683 (t nil))))
1685 (defun markdown-match-generic-metadata (regexp last)
1686 "Match generic metadata specified by REGEXP from the point to LAST."
1687 (let ((header-end (save-excursion
1688 (goto-char (point-min))
1689 (if (re-search-forward "\n\n" (point-max) t)
1690 (match-beginning 0)
1691 (point-max)))))
1692 (cond ((>= (point) header-end)
1693 ;; Don't match anything outside of the header.
1694 nil)
1695 ((re-search-forward regexp (min last header-end) t)
1696 ;; If a metadata item is found, it may span several lines.
1697 (let ((key-beginning (match-beginning 1))
1698 (key-end (match-end 1))
1699 (value-beginning (match-beginning 2)))
1700 (while (and (not (looking-at regexp))
1701 (not (> (point) (min last header-end)))
1702 (not (eobp)))
1703 (forward-line))
1704 (unless (eobp)
1705 (forward-line -1)
1706 (end-of-line))
1707 (set-match-data (list key-beginning (point) ; complete metadata
1708 key-beginning key-end ; key
1709 value-beginning (point))) ; value
1711 (t nil))))
1713 (defun markdown-match-multimarkdown-metadata (last)
1714 "Match MultiMarkdown metadata from the point to LAST."
1715 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1717 (defun markdown-match-pandoc-metadata (last)
1718 "Match Pandoc metadata from the point to LAST."
1719 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1721 (defun markdown-font-lock-extend-region ()
1722 "Extend the search region to include an entire block of text.
1723 This helps improve font locking for block constructs such as pre blocks."
1724 ;; Avoid compiler warnings about these global variables from font-lock.el.
1725 ;; See the documentation for variable `font-lock-extend-region-functions'.
1726 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1727 (save-excursion
1728 (goto-char font-lock-beg)
1729 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1730 (goto-char font-lock-end)
1731 (when (re-search-forward "\n\n" nil t)
1732 (beginning-of-line)
1733 (setq font-lock-end (point)))
1734 (setq font-lock-beg found))))
1737 ;;; Syntax Table ==============================================================
1739 (defvar markdown-mode-syntax-table
1740 (let ((tab (make-syntax-table text-mode-syntax-table)))
1741 (modify-syntax-entry ?\" "." tab)
1742 tab)
1743 "Syntax table for `markdown-mode'.")
1746 ;;; Element Insertion =========================================================
1748 (defun markdown-ensure-blank-line-before ()
1749 "If previous line is not already blank, insert a blank line before point."
1750 (unless (bolp) (insert "\n"))
1751 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1753 (defun markdown-ensure-blank-line-after ()
1754 "If following line is not already blank, insert a blank line after point.
1755 Return the point where it was originally."
1756 (save-excursion
1757 (unless (eolp) (insert "\n"))
1758 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1760 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1761 "Insert the strings S1 and S2, wrapping around region or THING.
1762 If a region is specified by the optional BEG and END arguments,
1763 wrap the strings S1 and S2 around that region.
1764 If there is an active region, wrap the strings S1 and S2 around
1765 the region. If there is not an active region but the point is at
1766 THING, wrap that thing (which defaults to word). Otherwise, just
1767 insert S1 and S2 and place the cursor in between. Return the
1768 bounds of the entire wrapped string, or nil if nothing was wrapped
1769 and S1 and S2 were only inserted."
1770 (let (a b bounds new-point)
1771 (cond
1772 ;; Given region
1773 ((and beg end)
1774 (setq a beg
1775 b end
1776 new-point (+ (point) (length s1))))
1777 ;; Active region
1778 ((markdown-use-region-p)
1779 (setq a (region-beginning)
1780 b (region-end)
1781 new-point (+ (point) (length s1))))
1782 ;; Thing (word) at point
1783 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1784 (setq a (car bounds)
1785 b (cdr bounds)
1786 new-point (+ (point) (length s1))))
1787 ;; No active region and no word
1789 (setq a (point)
1790 b (point))))
1791 (goto-char b)
1792 (insert s2)
1793 (goto-char a)
1794 (insert s1)
1795 (when new-point (goto-char new-point))
1796 (if (= a b)
1798 (setq b (+ b (length s1) (length s2)))
1799 (cons a b))))
1801 (defun markdown-point-after-unwrap (cur prefix suffix)
1802 "Return desired position of point after an unwrapping operation.
1803 Two cons cells must be provided. PREFIX gives the bounds of the
1804 prefix string and SUFFIX gives the bounds of the suffix string."
1805 (cond ((< cur (cdr prefix)) (car prefix))
1806 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1807 ((<= cur (cdr suffix))
1808 (- cur (+ (- (cdr prefix) (car prefix))
1809 (- cur (car suffix)))))
1810 (t cur)))
1812 (defun markdown-unwrap-thing-at-point (regexp all text)
1813 "Remove prefix and suffix of thing at point and reposition the point.
1814 When the thing at point matches REGEXP, replace the subexpression
1815 ALL with the string in subexpression TEXT. Reposition the point
1816 in an appropriate location accounting for the removal of prefix
1817 and suffix strings. Return new bounds of string from group TEXT.
1818 When REGEXP is nil, assumes match data is already set."
1819 (when (or (null regexp)
1820 (thing-at-point-looking-at regexp))
1821 (let ((cur (point))
1822 (prefix (cons (match-beginning all) (match-beginning text)))
1823 (suffix (cons (match-end text) (match-end all)))
1824 (bounds (cons (match-beginning text) (match-end text))))
1825 ;; Replace the thing at point
1826 (replace-match (match-string text) t t nil all)
1827 ;; Reposition the point
1828 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1829 ;; Adjust bounds
1830 (setq bounds (cons (car prefix)
1831 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1833 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1834 "Remove prefix and suffix of all things in region.
1835 When a thing in the region matches REGEXP, replace the
1836 subexpression ALL with the string in subexpression TEXT.
1837 Return a cons cell containing updated bounds for the region."
1838 (save-excursion
1839 (goto-char beg)
1840 (let ((removed 0) len-all len-text)
1841 (while (re-search-forward regexp (- end removed) t)
1842 (setq len-all (length (match-string-no-properties all)))
1843 (setq len-text (length (match-string-no-properties text)))
1844 (setq removed (+ removed (- len-all len-text)))
1845 (replace-match (match-string text) t t nil all))
1846 (cons beg (- end removed)))))
1848 (defun markdown-insert-hr (arg)
1849 "Insert or replace a horizonal rule.
1850 By default, use the first element of `markdown-hr-strings'. When
1851 prefixed with C-u, use the last element of `markdown-hr-strings'
1852 instead. When prefixed with an integer from 1 to the length of
1853 `markdown-hr-strings', use the element in that position instead."
1854 (interactive "*P")
1855 (when (thing-at-point-looking-at markdown-regex-hr)
1856 (delete-region (match-beginning 0) (match-end 0)))
1857 (markdown-ensure-blank-line-before)
1858 (cond ((equal arg '(4))
1859 (insert (car (reverse markdown-hr-strings))))
1860 ((and (integerp arg) (> arg 0)
1861 (<= arg (length markdown-hr-strings)))
1862 (insert (nth (1- arg) markdown-hr-strings)))
1864 (insert (car markdown-hr-strings))))
1865 (markdown-ensure-blank-line-after))
1867 (defun markdown-insert-bold ()
1868 "Insert markup to make a region or word bold.
1869 If there is an active region, make the region bold. If the point
1870 is at a non-bold word, make the word bold. If the point is at a
1871 bold word or phrase, remove the bold markup. Otherwise, simply
1872 insert bold delimiters and place the cursor in between them."
1873 (interactive)
1874 (let ((delim (if markdown-bold-underscore "__" "**")))
1875 (if (markdown-use-region-p)
1876 ;; Active region
1877 (let ((bounds (markdown-unwrap-things-in-region
1878 (region-beginning) (region-end)
1879 markdown-regex-bold 2 4)))
1880 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1881 ;; Bold markup removal, bold word at point, or empty markup insertion
1882 (if (thing-at-point-looking-at markdown-regex-bold)
1883 (markdown-unwrap-thing-at-point nil 2 4)
1884 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1886 (defun markdown-insert-italic ()
1887 "Insert markup to make a region or word italic.
1888 If there is an active region, make the region italic. If the point
1889 is at a non-italic word, make the word italic. If the point is at an
1890 italic word or phrase, remove the italic markup. Otherwise, simply
1891 insert italic delimiters and place the cursor in between them."
1892 (interactive)
1893 (let ((delim (if markdown-italic-underscore "_" "*")))
1894 (if (markdown-use-region-p)
1895 ;; Active region
1896 (let ((bounds (markdown-unwrap-things-in-region
1897 (region-beginning) (region-end)
1898 markdown-regex-italic 2 4)))
1899 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1900 ;; Italic markup removal, italic word at point, or empty markup insertion
1901 (if (thing-at-point-looking-at markdown-regex-italic)
1902 (markdown-unwrap-thing-at-point nil 2 4)
1903 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1905 (defun markdown-insert-code ()
1906 "Insert markup to make a region or word an inline code fragment.
1907 If there is an active region, make the region an inline code
1908 fragment. If the point is at a word, make the word an inline
1909 code fragment. Otherwise, simply insert code delimiters and
1910 place the cursor in between them."
1911 (interactive)
1912 (if (markdown-use-region-p)
1913 ;; Active region
1914 (let ((bounds (markdown-unwrap-things-in-region
1915 (region-beginning) (region-end)
1916 markdown-regex-code 2 4)))
1917 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
1918 ;; Code markup removal, code markup for word, or empty markup insertion
1919 (if (thing-at-point-looking-at markdown-regex-code)
1920 (markdown-unwrap-thing-at-point nil 2 4)
1921 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
1923 (defun markdown-insert-link ()
1924 "Insert an inline link, using region or word as link text if possible.
1925 If there is an active region, use the region as the link text. If the
1926 point is at a word, use the word as the link text. In these cases, the
1927 point will be left at the position for inserting a URL. If there is no
1928 active region and the point is not at word, simply insert link markup and
1929 place the point in the position to enter link text."
1930 (interactive)
1931 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
1932 (when bounds
1933 (goto-char (- (cdr bounds) 1)))))
1935 (defun markdown-insert-reference-link-dwim ()
1936 "Insert a reference link of the form [text][label] at point.
1937 If Transient Mark mode is on and a region is active, the region
1938 is used as the link text. Otherwise, the link text will be read
1939 from the minibuffer. The link URL, label, and title will be read
1940 from the minibuffer. The link label definition is placed at the
1941 end of the current paragraph."
1942 (interactive)
1943 (if (markdown-use-region-p)
1944 (call-interactively 'markdown-insert-reference-link-region)
1945 (call-interactively 'markdown-insert-reference-link)))
1947 (defun markdown-insert-reference-link-region (url label title)
1948 "Insert a reference link at point using the region as the link text.
1949 The link will point to URL, will be referenced as LABEL, and will have the
1950 optional title text given by TITLE."
1951 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1952 (let ((text (delete-and-extract-region (region-beginning) (region-end))))
1953 (markdown-insert-reference-link text url label title)))
1955 (defun markdown-insert-reference-link (text url label title)
1956 "Insert a reference link at point.
1957 The link TEXT will point to the given URL and may be referenced using
1958 LABEL. The link TITLE is optional and will be used to populate the
1959 title attribute when converted to XHTML."
1960 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1961 (let (end)
1962 (insert (concat "[" text "][" label "]"))
1963 (setq end (point))
1964 (forward-paragraph)
1965 (insert "\n[")
1966 (if (> (length label) 0)
1967 (insert label)
1968 (insert text))
1969 (insert (concat "]: " url))
1970 (unless (> (length url) 0)
1971 (setq end (point)))
1972 (when (> (length title) 0)
1973 (insert (concat " \"" title "\"")))
1974 (insert "\n")
1975 (unless (looking-at "\n")
1976 (insert "\n"))
1977 (goto-char end)))
1979 (defun markdown-insert-wiki-link ()
1980 "Insert a wiki link of the form [[WikiLink]].
1981 If Transient Mark mode is on and a region is active, it is used
1982 as the link text."
1983 (interactive)
1984 (markdown-wrap-or-insert "[[" "]]")
1985 (backward-char 2))
1987 (defun markdown-insert-image (&optional arg)
1988 "Insert image markup using region or word as alt text if possible.
1989 If there is an active region, use the region as the alt text. If the
1990 point is at a word, use the word as the alt text. In these cases, the
1991 point will be left at the position for inserting a URL. If there is no
1992 active region and the point is not at word, simply insert image markup and
1993 place the point in the position to enter alt text. If ARG is nil, insert
1994 inline image markup. Otherwise, insert reference image markup."
1995 (interactive "*P")
1996 (let ((bounds (if arg
1997 (markdown-wrap-or-insert "![" "][]")
1998 (markdown-wrap-or-insert "![" "]()"))))
1999 (when bounds
2000 (goto-char (- (cdr bounds) 1)))))
2002 (defun markdown-remove-header ()
2003 "Remove header markup if point is at a header.
2004 Return bounds of remaining header text if a header was removed
2005 and nil otherwise."
2006 (interactive "*")
2007 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2008 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2010 (defun markdown-insert-header (&optional level text setext)
2011 "Insert or replace header markup.
2012 The level of the header is specified by LEVEL and header text is
2013 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2014 default value is 1.
2015 When TEXT is nil, the header text is obtained as follows.
2016 If there is an active region, it is used as the header text.
2017 Otherwise, the current line will be used as the header text.
2018 If there is not an active region and the point is at a header,
2019 remove the header markup and replace with level N header.
2020 Otherwise, insert empty header markup and place the cursor in
2021 between.
2022 The style of the header will be atx (hash marks) unless
2023 SETEXT is non-nil, in which case a setext-style (underlined)
2024 header will be inserted."
2025 (interactive "p\nsHeader text: ")
2026 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2027 ;; Determine header text if not given
2028 (when (null text)
2029 (if (markdown-use-region-p)
2030 ;; Active region
2031 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2032 ;; No active region
2033 (markdown-remove-header)
2034 (setq text (delete-and-extract-region
2035 (line-beginning-position) (line-end-position)))
2036 (when (and setext (string-match "^[ \t]*$" text))
2037 (setq text (read-string "Header text: "))))
2038 (setq text (markdown-compress-whitespace-string text)))
2039 ;; Insertion with given text
2040 (markdown-ensure-blank-line-before)
2041 (let (hdr)
2042 (cond (setext
2043 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2044 (insert text "\n" hdr))
2046 (setq hdr (make-string level ?#))
2047 (insert hdr " " text " " hdr))))
2048 (markdown-ensure-blank-line-after)
2049 ;; Leave point at end of text
2050 (if setext
2051 (backward-char (1+ (length text)))
2052 (backward-char (1+ level))))
2054 (defun markdown-insert-header-dwim (&optional arg setext)
2055 "Insert or replace header markup.
2056 The level and type of the header are determined automatically by
2057 the type and level of the previous header, unless a prefix
2058 argument is given.
2059 With a numeric prefix valued 1 to 6, insert a header of the given
2060 level, with the type being determined automatically (note that
2061 only level 1 or 2 setext headers are possible).
2062 With C-u, insert a level-one setext header.
2063 With C-u C-u, insert a level two setext header.
2065 When there is an active region, use it for the header text. When
2066 the point is at an existing header, change the type and level
2067 according to the rules above.
2068 Otherwise, if the line is not empty, create a header using the
2069 text on the current line as the header text.
2070 Finally, if the point is on a blank line, insert empty header
2071 markup (atx) or prompt for text (setext).
2072 See `markdown-insert-header' for more details about how the
2073 header text is determined."
2074 (interactive "*P")
2075 (let (level)
2076 (cond ((equal arg '(4)) ; level-one setext with C-u
2077 (setq setext t)
2078 (setq level 1))
2079 ((equal arg '(16)) ; level-two setext with C-u C-u
2080 (setq setext t)
2081 (setq level 2))
2082 (t ; automatic with numeric override
2083 (save-excursion
2084 (when (re-search-backward markdown-regex-header nil t)
2085 ;; level of previous header
2086 (setq level (markdown-outline-level))
2087 ;; match groups 1 and 2 indicate setext headers
2088 (setq setext (or setext (match-end 1) (match-end 3)))))
2089 ;; use prefix if given, or level of previous header
2090 (setq level (if arg (prefix-numeric-value arg) level))
2091 ;; setext headers must be level one or two
2092 (and level (setq setext (and setext (<= level 2))))))
2093 (markdown-insert-header level nil setext)))
2095 (defun markdown-insert-header-setext-dwim (&optional arg)
2096 "Insert or replace header markup, with preference for setext.
2097 See `markdown-insert-header-dwim' for details."
2098 (interactive "*P")
2099 (markdown-insert-header-dwim arg t))
2101 (defun markdown-insert-header-atx-1 ()
2102 "Insert a first level atx-style (hash mark) header.
2103 See `markdown-insert-header'."
2104 (interactive "*")
2105 (markdown-insert-header 1 nil nil))
2107 (defun markdown-insert-header-atx-2 ()
2108 "Insert a level two atx-style (hash mark) header.
2109 See `markdown-insert-header'."
2110 (interactive "*")
2111 (markdown-insert-header 2 nil nil))
2113 (defun markdown-insert-header-atx-3 ()
2114 "Insert a level three atx-style (hash mark) header.
2115 See `markdown-insert-header'."
2116 (interactive "*")
2117 (markdown-insert-header 3 nil nil))
2119 (defun markdown-insert-header-atx-4 ()
2120 "Insert a level four atx-style (hash mark) header.
2121 See `markdown-insert-header'."
2122 (interactive "*")
2123 (markdown-insert-header 4 nil nil))
2125 (defun markdown-insert-header-atx-5 ()
2126 "Insert a level five atx-style (hash mark) header.
2127 See `markdown-insert-header'."
2128 (interactive "*")
2129 (markdown-insert-header 5 nil nil))
2131 (defun markdown-insert-header-atx-6 ()
2132 "Insert a sixth level atx-style (hash mark) header.
2133 See `markdown-insert-header'."
2134 (interactive "*")
2135 (markdown-insert-header 6 nil nil))
2137 (defun markdown-insert-header-setext-1 ()
2138 "Insert a setext-style (underlined) first-level header.
2139 See `markdown-insert-header'."
2140 (interactive "*")
2141 (markdown-insert-header 1 nil t))
2143 (defun markdown-insert-header-setext-2 ()
2144 "Insert a setext-style (underlined) second-level header.
2145 See `markdown-insert-header'."
2146 (interactive "*")
2147 (markdown-insert-header 2 nil t))
2149 (defun markdown-blockquote-indentation (loc)
2150 "Return string containing necessary indentation for a blockquote at LOC.
2151 Also see `markdown-pre-indentation'."
2152 (save-excursion
2153 (goto-char loc)
2154 (let* ((list-level (length (markdown-calculate-list-levels)))
2155 (indent ""))
2156 (dotimes (count list-level indent)
2157 (setq indent (concat indent " "))))))
2159 (defun markdown-insert-blockquote ()
2160 "Start a blockquote section (or blockquote the region).
2161 If Transient Mark mode is on and a region is active, it is used as
2162 the blockquote text."
2163 (interactive)
2164 (if (markdown-use-region-p)
2165 (markdown-blockquote-region (region-beginning) (region-end))
2166 (markdown-ensure-blank-line-before)
2167 (insert (markdown-blockquote-indentation (point)) "> ")
2168 (markdown-ensure-blank-line-after)))
2170 (defun markdown-block-region (beg end prefix)
2171 "Format the region using a block prefix.
2172 Arguments BEG and END specify the beginning and end of the
2173 region. The characters PREFIX will appear at the beginning
2174 of each line."
2175 (save-excursion
2176 (let* ((end-marker (make-marker))
2177 (beg-marker (make-marker)))
2178 ;; Ensure blank line after and remove extra whitespace
2179 (goto-char end)
2180 (skip-syntax-backward "-")
2181 (set-marker end-marker (point))
2182 (delete-horizontal-space)
2183 (markdown-ensure-blank-line-after)
2184 ;; Ensure blank line before and remove extra whitespace
2185 (goto-char beg)
2186 (skip-syntax-forward "-")
2187 (delete-horizontal-space)
2188 (markdown-ensure-blank-line-before)
2189 (set-marker beg-marker (point))
2190 ;; Insert PREFIX before each line
2191 (goto-char beg-marker)
2192 (while (and (< (line-beginning-position) end-marker)
2193 (not (eobp)))
2194 (insert prefix)
2195 (forward-line)))))
2197 (defun markdown-blockquote-region (beg end)
2198 "Blockquote the region.
2199 Arguments BEG and END specify the beginning and end of the region."
2200 (interactive "*r")
2201 (markdown-block-region
2202 beg end (concat (markdown-blockquote-indentation
2203 (max (point-min) (1- beg))) "> ")))
2205 (defun markdown-pre-indentation (loc)
2206 "Return string containing necessary whitespace for a pre block at LOC.
2207 Also see `markdown-blockquote-indentation'."
2208 (save-excursion
2209 (goto-char loc)
2210 (let* ((list-level (length (markdown-calculate-list-levels)))
2211 indent)
2212 (dotimes (count (1+ list-level) indent)
2213 (setq indent (concat indent " "))))))
2215 (defun markdown-insert-pre ()
2216 "Start a preformatted section (or apply to the region).
2217 If Transient Mark mode is on and a region is active, it is marked
2218 as preformatted text."
2219 (interactive)
2220 (if (markdown-use-region-p)
2221 (markdown-pre-region (region-beginning) (region-end))
2222 (markdown-ensure-blank-line-before)
2223 (insert (markdown-pre-indentation (point)))
2224 (markdown-ensure-blank-line-after)))
2226 (defun markdown-pre-region (beg end)
2227 "Format the region as preformatted text.
2228 Arguments BEG and END specify the beginning and end of the region."
2229 (interactive "*r")
2230 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2231 (markdown-block-region beg end indent)))
2233 (defun markdown-insert-gfm-code-block (&optional lang)
2234 "Insert GFM code block for language LANG.
2235 If LANG is nil, the language will be queried from user. If a
2236 region is active, wrap this region with the markup instead. If
2237 the region boundaries are not on empty lines, these are added
2238 automatically in order to have the correct markup."
2239 (interactive "sProgramming language: ")
2240 (if (markdown-use-region-p)
2241 (let ((b (region-beginning)) (e (region-end)))
2242 (goto-char b)
2243 ;; if we're on a blank line, insert the quotes here, otherwise
2244 ;; add a new line first
2245 (unless (looking-at "\n")
2246 (newline)
2247 (forward-line -1)
2248 (setq e (1+ e)))
2249 (insert "```" lang)
2250 (goto-char (+ e 3 (length lang)))
2251 ;; if we're on a blank line, don't newline, otherwise the ```
2252 ;; should go on its own line
2253 (unless (looking-back "\n")
2254 (newline))
2255 (insert "```"))
2256 (insert "```" lang)
2257 (newline 2)
2258 (insert "```")
2259 (forward-line -1)))
2262 ;;; Footnotes ======================================================================
2264 (defun markdown-footnote-counter-inc ()
2265 "Increment `markdown-footnote-counter' and return the new value."
2266 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2267 (save-excursion
2268 (goto-char (point-min))
2269 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2270 (point-max) t)
2271 (let ((fn (string-to-number (match-string 1))))
2272 (when (> fn markdown-footnote-counter)
2273 (setq markdown-footnote-counter fn))))))
2274 (incf markdown-footnote-counter))
2276 (defun markdown-footnote-new ()
2277 "Insert footnote with a new number and move point to footnote definition."
2278 (interactive)
2279 (let ((fn (markdown-footnote-counter-inc)))
2280 (insert (format "[^%d]" fn))
2281 (markdown-footnote-text-find-new-location)
2282 (markdown-ensure-blank-line-before)
2283 (unless (markdown-cur-line-blank-p)
2284 (insert "\n"))
2285 (insert (format "[^%d]: " fn))
2286 (markdown-ensure-blank-line-after)))
2288 (defun markdown-footnote-text-find-new-location ()
2289 "Position the cursor at the proper location for a new footnote text."
2290 (cond
2291 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2292 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
2293 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2295 (defun markdown-footnote-kill ()
2296 "Kill the footnote at point.
2297 The footnote text is killed (and added to the kill ring), the
2298 footnote marker is deleted. Point has to be either at the
2299 footnote marker or in the footnote text."
2300 (interactive)
2301 (let (return-pos)
2302 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2303 (markdown-footnote-return) ; we first move to the marker
2304 (setq return-pos 'text)) ; and remember our return position
2305 (let ((marker (markdown-footnote-delete-marker)))
2306 (unless marker
2307 (error "Not at a footnote"))
2308 (let ((text-pos (markdown-footnote-find-text (car marker))))
2309 (unless text-pos
2310 (error "No text for footnote `%s'" (car marker)))
2311 (goto-char text-pos)
2312 (let ((pos (markdown-footnote-kill-text)))
2313 (setq return-pos
2314 (if (and pos (eq return-pos 'text))
2316 (cadr marker))))))
2317 (goto-char return-pos)))
2319 (defun markdown-footnote-delete-marker ()
2320 "Delete a footnote marker at point.
2321 Returns a list (ID START) containing the footnote ID and the
2322 start position of the marker before deletion. If no footnote
2323 marker was deleted, this function returns NIL."
2324 (let ((marker (markdown-footnote-marker-positions)))
2325 (when marker
2326 (delete-region (second marker) (third marker))
2327 (butlast marker))))
2329 (defun markdown-footnote-kill-text ()
2330 "Kill footnote text at point.
2331 Returns the start position of the footnote text before deletion,
2332 or NIL if point was not inside a footnote text.
2334 The killed text is placed in the kill ring (without the footnote
2335 number)."
2336 (let ((fn (markdown-footnote-text-positions)))
2337 (when fn
2338 (let ((text (delete-and-extract-region (second fn) (third fn))))
2339 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2340 (kill-new (match-string 1 text))
2341 (when (and (markdown-cur-line-blank-p)
2342 (markdown-prev-line-blank-p))
2343 (delete-region (1- (point)) (point)))
2344 (second fn)))))
2346 (defun markdown-footnote-goto-text ()
2347 "Jump to the text of the footnote at point."
2348 (interactive)
2349 (let ((fn (car (markdown-footnote-marker-positions))))
2350 (unless fn
2351 (error "Not at a footnote marker"))
2352 (let ((new-pos (markdown-footnote-find-text fn)))
2353 (unless new-pos
2354 (error "No definition found for footnote `%s'" fn))
2355 (goto-char new-pos))))
2357 (defun markdown-footnote-return ()
2358 "Return from a footnote to its footnote number in the main text."
2359 (interactive)
2360 (let ((fn (save-excursion
2361 (car (markdown-footnote-text-positions)))))
2362 (unless fn
2363 (error "Not in a footnote"))
2364 (let ((new-pos (markdown-footnote-find-marker fn)))
2365 (unless new-pos
2366 (error "Footnote marker `%s' not found" fn))
2367 (goto-char new-pos))))
2369 (defun markdown-footnote-find-marker (id)
2370 "Find the location of the footnote marker with ID.
2371 The actual buffer position returned is the position directly
2372 following the marker's closing bracket. If no marker is found,
2373 NIL is returned."
2374 (save-excursion
2375 (goto-char (point-min))
2376 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2377 (skip-chars-backward "^]")
2378 (point))))
2380 (defun markdown-footnote-find-text (id)
2381 "Find the location of the text of footnote ID.
2382 The actual buffer position returned is the position of the first
2383 character of the text, after the footnote's identifier. If no
2384 footnote text is found, NIL is returned."
2385 (save-excursion
2386 (goto-char (point-min))
2387 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2388 (skip-chars-forward "[ \t]")
2389 (point))))
2391 (defun markdown-footnote-marker-positions ()
2392 "Return the position and ID of the footnote marker point is on.
2393 The return value is a list (ID START END). If point is not on a
2394 footnote, NIL is returned."
2395 ;; first make sure we're at a footnote marker
2396 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2397 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2398 (save-excursion
2399 ;; move point between [ and ^:
2400 (if (looking-at "\\[")
2401 (forward-char 1)
2402 (skip-chars-backward "^["))
2403 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2404 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2406 (defun markdown-footnote-text-positions ()
2407 "Return the start and end positions of the footnote text point is in.
2408 The exact return value is a list of three elements: (ID START END).
2409 The start position is the position of the opening bracket
2410 of the footnote id. The end position is directly after the
2411 newline that ends the footnote. If point is not in a footnote,
2412 NIL is returned instead."
2413 (save-excursion
2414 (let ((fn (progn
2415 (backward-paragraph)
2416 ;; if we're in a multiparagraph footnote, we need to back up further
2417 (while (>= (markdown-next-line-indent) 4)
2418 (backward-paragraph))
2419 (forward-line)
2420 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2421 (list (match-string 1) (point))))))
2422 (when fn
2423 (while (progn
2424 (forward-paragraph)
2425 (>= (markdown-next-line-indent) 4)))
2426 (append fn (list (point)))))))
2429 ;;; Element Removal ===========================================================
2431 (defun markdown-kill-thing-at-point ()
2432 "Kill thing at point and add important text, without markup, to kill ring.
2433 Possible things to kill include (roughly in order of precedence):
2434 inline code, headers, horizonal rules, links (add link text to
2435 kill ring), images (add alt text to kill ring), angle uri, email
2436 addresses, bold, italics, reference definition (add URI to kill
2437 ring), footnote markers and text (kill both marker and text, add
2438 text to kill ring), and list items."
2439 (interactive "*")
2440 (let (val tmp)
2441 (cond
2442 ;; Inline code
2443 ((thing-at-point-looking-at markdown-regex-code)
2444 (kill-new (match-string 4))
2445 (delete-region (match-beginning 2) (match-end 2)))
2446 ;; ATX header
2447 ((thing-at-point-looking-at markdown-regex-header-atx)
2448 (kill-new (match-string 2))
2449 (delete-region (match-beginning 0) (match-end 0)))
2450 ;; Setext header
2451 ((thing-at-point-looking-at markdown-regex-header-setext)
2452 (kill-new (match-string 1))
2453 (delete-region (match-beginning 0) (match-end 0)))
2454 ;; Horizonal rule
2455 ((thing-at-point-looking-at markdown-regex-hr)
2456 (kill-new (match-string 0))
2457 (delete-region (match-beginning 0) (match-end 0)))
2458 ;; Inline link or image (add link or alt text to kill ring)
2459 ((thing-at-point-looking-at markdown-regex-link-inline)
2460 (kill-new (match-string 2))
2461 (delete-region (match-beginning 0) (match-end 0)))
2462 ;; Reference link or image (add link or alt text to kill ring)
2463 ((thing-at-point-looking-at markdown-regex-link-reference)
2464 (kill-new (match-string 2))
2465 (delete-region (match-beginning 0) (match-end 0)))
2466 ;; Angle URI (add URL to kill ring)
2467 ((thing-at-point-looking-at markdown-regex-angle-uri)
2468 (kill-new (match-string 2))
2469 (delete-region (match-beginning 0) (match-end 0)))
2470 ;; Email address in angle brackets (add email address to kill ring)
2471 ((thing-at-point-looking-at markdown-regex-email)
2472 (kill-new (match-string 1))
2473 (delete-region (match-beginning 0) (match-end 0)))
2474 ;; Wiki link (add alias text to kill ring)
2475 ((thing-at-point-looking-at markdown-regex-wiki-link)
2476 (kill-new (if markdown-wiki-link-alias-first
2477 (match-string-no-properties 2)
2478 (or (match-string-no-properties 2) (match-string-no-properties 4))))
2479 (delete-region (match-beginning 1) (match-end 1)))
2480 ;; Bold
2481 ((thing-at-point-looking-at markdown-regex-bold)
2482 (kill-new (match-string 4))
2483 (delete-region (match-beginning 2) (match-end 2)))
2484 ;; Italics
2485 ((thing-at-point-looking-at markdown-regex-italic)
2486 (kill-new (match-string 4))
2487 (delete-region (match-beginning 2) (match-end 2)))
2488 ;; Reference definition (add URL to kill ring)
2489 ((thing-at-point-looking-at markdown-regex-reference-definition)
2490 (kill-new (match-string 2))
2491 (delete-region (match-beginning 0) (match-end 0)))
2492 ;; Footnote marker (add footnote text to kill ring)
2493 ((thing-at-point-looking-at markdown-regex-footnote)
2494 (markdown-footnote-kill))
2495 ;; Footnote text (add footnote text to kill ring)
2496 ((setq val (markdown-footnote-text-positions))
2497 (markdown-footnote-kill))
2498 ;; List item
2499 ((setq val (markdown-cur-list-item-bounds))
2500 (kill-new (delete-and-extract-region (first val) (second val))))
2502 (error "Nothing found at point to kill")))))
2505 ;;; Indentation ====================================================================
2507 (defun markdown-indent-find-next-position (cur-pos positions)
2508 "Return the position after the index of CUR-POS in POSITIONS.
2509 Positions are calculated by `markdown-calc-indents'."
2510 (while (and positions
2511 (not (equal cur-pos (car positions))))
2512 (setq positions (cdr positions)))
2513 (or (cadr positions) 0))
2515 (defun markdown-indent-line ()
2516 "Indent the current line using some heuristics.
2517 If the _previous_ command was either `markdown-enter-key' or
2518 `markdown-cycle', then we should cycle to the next
2519 reasonable indentation position. Otherwise, we could have been
2520 called directly by `markdown-enter-key', by an initial call of
2521 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2522 these cases, indent to the default position.
2523 Positions are calculated by `markdown-calc-indents'."
2524 (interactive)
2525 (let ((positions (markdown-calc-indents))
2526 (cur-pos (current-column)))
2527 (if (not (equal this-command 'markdown-cycle))
2528 (indent-line-to (car positions))
2529 (setq positions (sort (delete-dups positions) '<))
2530 (indent-line-to
2531 (markdown-indent-find-next-position cur-pos positions)))))
2533 (defun markdown-calc-indents ()
2534 "Return a list of indentation columns to cycle through.
2535 The first element in the returned list should be considered the
2536 default indentation level. This function does not worry about
2537 duplicate positions, which are handled up by calling functions."
2538 (let (pos prev-line-pos positions)
2540 ;; Indentation of previous line
2541 (setq prev-line-pos (markdown-prev-line-indent))
2542 (setq positions (cons prev-line-pos positions))
2544 ;; Indentation of previous non-list-marker text
2545 (when (setq pos (markdown-prev-non-list-indent))
2546 (setq positions (cons pos positions)))
2548 ;; Indentation required for a pre block in current context
2549 (setq pos (length (markdown-pre-indentation (point))))
2550 (setq positions (cons pos positions))
2552 ;; Indentation of the previous line + tab-width
2553 (if prev-line-pos
2554 (setq positions (cons (+ prev-line-pos tab-width) positions))
2555 (setq positions (cons tab-width positions)))
2557 ;; Indentation of the previous line - tab-width
2558 (if (and prev-line-pos (> prev-line-pos tab-width))
2559 (setq positions (cons (- prev-line-pos tab-width) positions)))
2561 ;; Indentation of all preceeding list markers (when in a list)
2562 (when (setq pos (markdown-calculate-list-levels))
2563 (setq positions (append pos positions)))
2565 ;; First column
2566 (setq positions (cons 0 positions))
2568 ;; Return reversed list
2569 (reverse positions)))
2571 (defun markdown-do-normal-return ()
2572 "Insert a newline and optionally indent the next line."
2573 (newline)
2574 (if markdown-indent-on-enter
2575 (funcall indent-line-function)))
2577 (defun markdown-enter-key ()
2578 "Handle RET according to context.
2579 If there is a wiki link at the point, follow it unless
2580 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2581 it in the usual way."
2582 (interactive)
2583 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2584 (markdown-follow-wiki-link-at-point)
2585 (markdown-do-normal-return)))
2587 (defun markdown-dedent-or-delete (arg)
2588 "Handle BACKSPACE by cycling through indentation points.
2589 When BACKSPACE is pressed, if there is only whitespace
2590 before the current point, then dedent the line one level.
2591 Otherwise, do normal delete by repeating
2592 `backward-delete-char-untabify' ARG times."
2593 (interactive "*p")
2594 (let ((cur-pos (current-column))
2595 (start-of-indention (save-excursion
2596 (back-to-indentation)
2597 (current-column))))
2598 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2599 (let ((result 0))
2600 (dolist (i (markdown-calc-indents))
2601 (when (< i cur-pos)
2602 (setq result (max result i))))
2603 (indent-line-to result))
2604 (backward-delete-char-untabify arg))))
2607 ;;; Markup Completion =========================================================
2609 (defconst markdown-complete-alist
2610 '((markdown-regex-header-atx . markdown-complete-atx)
2611 (markdown-regex-header-setext . markdown-complete-setext)
2612 (markdown-regex-hr . markdown-complete-hr))
2613 "Association list of form (regexp . function) for markup completion.")
2615 (defun markdown-incomplete-atx-p ()
2616 "Return t if ATX header markup is incomplete and nil otherwise.
2617 Assumes match data is available for `markdown-regex-header-atx'.
2618 Checks that the number of trailing hash marks equals the number of leading
2619 hash marks, that there is only a single space before and after the text,
2620 and that there is no extraneous whitespace in the text."
2621 (save-match-data
2622 (or (not (= (length (match-string 1)) (length (match-string 3))))
2623 (not (= (match-beginning 2) (1+ (match-end 1))))
2624 (not (= (match-beginning 3) (1+ (match-end 2))))
2625 (string-match "[ \t\n]\\{2\\}" (match-string 2)))))
2627 (defun markdown-complete-atx ()
2628 "Complete and normalize ATX headers.
2629 Add or remove hash marks to the end of the header to match the
2630 beginning. Ensure that there is only a single space between hash
2631 marks and header text. Removes extraneous whitespace from header text.
2632 Assumes match data is available for `markdown-regex-header-atx'."
2633 (when (markdown-incomplete-atx-p)
2634 (let* ((new-marker (make-marker))
2635 (new-marker (set-marker new-marker (match-end 2))))
2636 ;; Hash marks and spacing at end
2637 (goto-char (match-end 2))
2638 (delete-region (match-end 2) (match-end 3))
2639 (insert " " (match-string 1))
2640 ;; Remove extraneous whitespace from title
2641 (replace-match (markdown-compress-whitespace-string (match-string 2))
2642 t t nil 2)
2643 ;; Spacing at beginning
2644 (goto-char (match-end 1))
2645 (delete-region (match-end 1) (match-beginning 2))
2646 (insert " ")
2647 ;; Leave point at end of text
2648 (goto-char new-marker))))
2650 (defun markdown-incomplete-setext-p ()
2651 "Return t if setext header markup is incomplete and nil otherwise.
2652 Assumes match data is available for `markdown-regex-header-setext'.
2653 Checks that length of underline matches text and that there is no
2654 extraneous whitespace in the text."
2655 (save-match-data
2656 (or (not (= (length (match-string 1)) (length (match-string 2))))
2657 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2659 (defun markdown-complete-setext ()
2660 "Complete and normalize setext headers.
2661 Add or remove underline characters to match length of header
2662 text. Removes extraneous whitespace from header text. Assumes
2663 match data is available for `markdown-regex-header-setext'."
2664 (when (markdown-incomplete-setext-p)
2665 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2666 (char (char-after (match-beginning 2)))
2667 (level (if (char-equal char ?-) 2 1)))
2668 (goto-char (match-beginning 0))
2669 (delete-region (match-beginning 0) (match-end 0))
2670 (markdown-insert-header level text t))))
2672 (defun markdown-incomplete-hr-p ()
2673 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2674 Assumes match data is available for `markdown-regex-hr'."
2675 (not (member (match-string 0) markdown-hr-strings)))
2677 (defun markdown-complete-hr ()
2678 "Complete horizontal rules.
2679 If horizontal rule string is a member of `markdown-hr-strings',
2680 do nothing. Otherwise, replace with the car of
2681 `markdown-hr-strings'.
2682 Assumes match data is available for `markdown-regex-hr'."
2683 (replace-match (car markdown-hr-strings)))
2685 (defun markdown-complete ()
2686 "Complete markup of object near point or in region when active.
2687 Handle all objects in `markdown-complete-alist', in order.
2688 See `markdown-complete-at-point' and `markdown-complete-region'."
2689 (interactive "*")
2690 (if (markdown-use-region-p)
2691 (markdown-complete-region (region-beginning) (region-end))
2692 (markdown-complete-at-point)))
2694 (defun markdown-complete-at-point ()
2695 "Complete markup of object near point.
2696 Handle all objects in `markdown-complete-alist', in
2697 order."
2698 (interactive "*")
2699 (loop for (regexp . function) in markdown-complete-alist
2700 until (thing-at-point-looking-at (eval regexp))
2701 finally (funcall function)))
2703 (defun markdown-complete-region (beg end)
2704 "Complete markup of object near point.
2705 Handle all objects in `markdown-complete-alist', in
2706 order."
2707 (interactive "*r")
2708 (let* ((end-marker (make-marker))
2709 (end-marker (set-marker end-marker end)))
2710 (loop for (regexp . function) in markdown-complete-alist
2711 do (save-excursion
2712 (goto-char beg)
2713 (while (re-search-forward (eval regexp) end-marker t)
2714 (funcall function))))))
2716 (defun markdown-complete-buffer ()
2717 "Complete markup for all objects in the current buffer."
2718 (interactive "*")
2719 (markdown-complete-region (point-min) (point-max)))
2722 ;;; Markup Cycling ============================================================
2724 (defun markdown-cycle-atx (arg &optional remove)
2725 "Cycle ATX header markup.
2726 Promote header (decrease level) when ARG is 1 and demote
2727 header (increase level) if arg is -1. When REMOVE is non-nil,
2728 remove the header when the level reaches zero and stop cycling
2729 when it reaches six. Otherwise, perform a proper cycling through
2730 levels one through six. Assumes match data is available for
2731 `markdown-regex-header-atx'."
2732 (let* ((old-level (length (match-string 1)))
2733 (new-level (+ old-level arg))
2734 (text (match-string 2)))
2735 (when (not remove)
2736 (setq new-level (% new-level 6))
2737 (setq new-level (cond ((= new-level 0) 6)
2738 ((< new-level 0) (+ new-level 6))
2739 (t new-level))))
2740 (cond
2741 ((= new-level 0)
2742 (markdown-unwrap-thing-at-point nil 0 2))
2743 ((<= new-level 6)
2744 (goto-char (match-beginning 0))
2745 (delete-region (match-beginning 0) (match-end 0))
2746 (markdown-insert-header new-level text nil)))))
2748 (defun markdown-cycle-setext (arg &optional remove)
2749 "Cycle setext header markup.
2750 Promote header (increase level) when ARG is 1 and demote
2751 header (decrease level or remove) if arg is -1. When demoting a
2752 level-two setext header, replace with a level-three atx header.
2753 When REMOVE is non-nil, remove the header when the level reaches
2754 zero. Otherwise, cycle back to a level six atx header. Assumes
2755 match data is available for `markdown-regex-header-setext'."
2756 (let* ((char (char-after (match-beginning 2)))
2757 (old-level (if (char-equal char ?=) 1 2))
2758 (new-level (+ old-level arg))
2759 (text (match-string 1)))
2760 (when (and (not remove) (= new-level 0))
2761 (setq new-level 6))
2762 (cond
2763 ((= new-level 0)
2764 (markdown-unwrap-thing-at-point nil 0 1))
2765 ((<= new-level 2)
2766 (markdown-insert-header new-level nil t))
2767 ((<= new-level 6)
2768 (markdown-insert-header new-level nil nil)))))
2770 (defun markdown-cycle-hr (arg &optional remove)
2771 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2772 When ARG is 1, cycle forward (promote), and when ARG is -1, cycle
2773 backwards (demote). When REMOVE is non-nil, remove the hr instead
2774 of cycling when the end of the list is reached.
2775 Assumes match data is available for `markdown-regex-hr'."
2776 (let* ((strings (if (= arg 1)
2777 (reverse markdown-hr-strings)
2778 markdown-hr-strings))
2779 (tail (member (match-string 0) strings))
2780 (new (or (cadr tail)
2781 (if remove
2782 (if (= arg 1)
2784 (car tail))
2785 (car strings)))))
2786 (replace-match new)))
2788 (defun markdown-cycle-bold ()
2789 "Cycle bold markup between underscores and asterisks.
2790 Assumes match data is available for `markdown-regex-bold'."
2791 (save-excursion
2792 (let* ((old-delim (match-string 3))
2793 (new-delim (if (string-equal old-delim "**") "__" "**")))
2794 (replace-match new-delim t t nil 3)
2795 (replace-match new-delim t t nil 5))))
2797 (defun markdown-cycle-italic ()
2798 "Cycle italic markup between underscores and asterisks.
2799 Assumes match data is available for `markdown-regex-italic'."
2800 (save-excursion
2801 (let* ((old-delim (match-string 3))
2802 (new-delim (if (string-equal old-delim "*") "_" "*")))
2803 (replace-match new-delim t t nil 3)
2804 (replace-match new-delim t t nil 5))))
2807 ;;; Keymap ====================================================================
2809 (defvar markdown-mode-map
2810 (let ((map (make-keymap)))
2811 ;; Element insertion
2812 (define-key map "\C-c\C-al" 'markdown-insert-link)
2813 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
2814 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
2815 (define-key map "\C-c\C-ii" 'markdown-insert-image)
2816 (define-key map "\C-c\C-t0" 'markdown-remove-header)
2817 (define-key map "\C-c\C-t1" 'markdown-insert-header-atx-1)
2818 (define-key map "\C-c\C-t2" 'markdown-insert-header-atx-2)
2819 (define-key map "\C-c\C-t3" 'markdown-insert-header-atx-3)
2820 (define-key map "\C-c\C-t4" 'markdown-insert-header-atx-4)
2821 (define-key map "\C-c\C-t5" 'markdown-insert-header-atx-5)
2822 (define-key map "\C-c\C-t6" 'markdown-insert-header-atx-6)
2823 (define-key map "\C-c\C-th" 'markdown-insert-header-dwim)
2824 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
2825 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
2826 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
2827 (define-key map "\C-c\C-se" 'markdown-insert-italic)
2828 (define-key map "\C-c\C-pf" 'markdown-insert-code)
2829 (define-key map "\C-c\C-sc" 'markdown-insert-code)
2830 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
2831 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
2832 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
2833 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
2834 (define-key map "\C-c-" 'markdown-insert-hr)
2835 (define-key map "\C-c\C-tt" 'markdown-insert-header-setext-1)
2836 (define-key map "\C-c\C-ts" 'markdown-insert-header-setext-2)
2837 ;; Element removal
2838 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
2839 ;; Footnotes
2840 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
2841 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
2842 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
2843 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
2844 ;; Promotion, Demotion, Completion, and Cycling
2845 (define-key map (kbd "M-<left>") 'markdown-promote)
2846 (define-key map (kbd "M-<right>") 'markdown-demote)
2847 (define-key map (kbd "C-c C-l") 'markdown-promote)
2848 (define-key map (kbd "C-c C-r") 'markdown-demote)
2849 (define-key map (kbd "C-c C-=") 'markdown-complete-or-cycle)
2850 (define-key map (kbd "C-c C-c =") 'markdown-complete-buffer)
2851 ;; Following and Jumping
2852 (define-key map "\C-c\C-o" 'markdown-follow-thing-at-point)
2853 (define-key map "\C-c\C-j" 'markdown-jump)
2854 ;; Indentation
2855 (define-key map "\C-m" 'markdown-enter-key)
2856 (define-key map (kbd "<backspace>") 'markdown-dedent-or-delete)
2857 ;; Visibility cycling
2858 (define-key map (kbd "<tab>") 'markdown-cycle)
2859 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
2860 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
2861 (define-key map (kbd "<backtab>") 'markdown-shifttab)
2862 ;; Header navigation
2863 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
2864 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
2865 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
2866 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
2867 (define-key map (kbd "C-M-u") 'outline-up-heading)
2868 ;; Markdown functions
2869 (define-key map "\C-c\C-cm" 'markdown-other-window)
2870 (define-key map "\C-c\C-cp" 'markdown-preview)
2871 (define-key map "\C-c\C-ce" 'markdown-export)
2872 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
2873 (define-key map "\C-c\C-co" 'markdown-open)
2874 (define-key map "\C-c\C-cw" 'markdown-kill-ring-save)
2875 ;; References
2876 (define-key map "\C-c\C-cc" 'markdown-check-refs)
2877 ;; Lists
2878 (define-key map "\C-c\C-cn" 'markdown-cleanup-list-numbers)
2879 (define-key map (kbd "M-<up>") 'markdown-move-up)
2880 (define-key map (kbd "M-<down>") 'markdown-move-down)
2881 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
2882 ;; Movement
2883 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
2884 (define-key map (kbd "M-]") 'markdown-end-of-block)
2885 (define-key map (kbd "M-n") 'markdown-next-link)
2886 (define-key map (kbd "M-p") 'markdown-previous-link)
2887 map)
2888 "Keymap for Markdown major mode.")
2890 (defvar gfm-mode-map
2891 (let ((map (make-sparse-keymap)))
2892 (set-keymap-parent map markdown-mode-map)
2893 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
2894 map)
2895 "Keymap for `gfm-mode'.
2896 See also `markdown-mode-map'.")
2899 ;;; Menu ==================================================================
2901 (easy-menu-define markdown-mode-menu markdown-mode-map
2902 "Menu for Markdown mode"
2903 '("Markdown"
2904 ("Show/Hide"
2905 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
2906 ["Cycle global visibility" markdown-shifttab])
2907 "---"
2908 ["Compile" markdown-other-window]
2909 ["Preview" markdown-preview]
2910 ["Export" markdown-export]
2911 ["Export & View" markdown-export-and-preview]
2912 ["Open" markdown-open]
2913 ["Kill ring save" markdown-kill-ring-save]
2914 "---"
2915 ("Headers (setext)"
2916 ["First level" markdown-insert-setext-header-1]
2917 ["Second level" markdown-insert-setext-header-2])
2918 ("Headers (atx)"
2919 ["First level" markdown-insert-header-atx-1]
2920 ["Second level" markdown-insert-header-atx-2]
2921 ["Third level" markdown-insert-header-atx-3]
2922 ["Fourth level" markdown-insert-header-atx-4]
2923 ["Fifth level" markdown-insert-header-atx-5]
2924 ["Sixth level" markdown-insert-header-atx-6])
2925 "---"
2926 ["Bold" markdown-insert-bold]
2927 ["Italic" markdown-insert-italic]
2928 ["Blockquote" markdown-insert-blockquote]
2929 ["Preformatted" markdown-insert-pre]
2930 ["Code" markdown-insert-code]
2931 "---"
2932 ["Insert inline link" markdown-insert-link]
2933 ["Insert reference link" markdown-insert-reference-link-dwim]
2934 ["Insert image" markdown-insert-image]
2935 ["Insert horizontal rule" markdown-insert-hr]
2936 "---"
2937 ("Footnotes"
2938 ["Insert footnote" markdown-footnote-new]
2939 ["Jump to footnote text" markdown-footnote-goto-text]
2940 ["Return from footnote" markdown-footnote-return])
2941 "---"
2942 ["Check references" markdown-check-refs]
2943 ["Clean up list numbering" markdown-cleanup-list-numbers]
2944 "---"
2945 ["Version" markdown-show-version]
2949 ;;; imenu =====================================================================
2951 (defun markdown-imenu-create-index ()
2952 "Create and return an imenu index alist for the current buffer.
2953 See `imenu-create-index-function' and `imenu--index-alist' for details."
2954 (let* ((root '(nil . nil))
2955 cur-alist
2956 (cur-level 0)
2957 (empty-heading "-")
2958 (self-heading ".")
2959 hashes pos level heading)
2960 (save-excursion
2961 (goto-char (point-min))
2962 (while (re-search-forward markdown-regex-header (point-max) t)
2963 (cond
2964 ((setq heading (match-string-no-properties 1))
2965 (setq pos (match-beginning 1)
2966 level 1))
2967 ((setq heading (match-string-no-properties 3))
2968 (setq pos (match-beginning 3)
2969 level 2))
2970 ((setq hashes (match-string-no-properties 5))
2971 (setq heading (match-string-no-properties 6)
2972 pos (match-beginning 5)
2973 level (length hashes))))
2974 (let ((alist (list (cons heading pos))))
2975 (cond
2976 ((= cur-level level) ; new sibling
2977 (setcdr cur-alist alist)
2978 (setq cur-alist alist))
2979 ((< cur-level level) ; first child
2980 (dotimes (i (- level cur-level 1))
2981 (setq alist (list (cons empty-heading alist))))
2982 (if cur-alist
2983 (let* ((parent (car cur-alist))
2984 (self-pos (cdr parent)))
2985 (setcdr parent (cons (cons self-heading self-pos) alist)))
2986 (setcdr root alist)) ; primogenitor
2987 (setq cur-alist alist)
2988 (setq cur-level level))
2989 (t ; new sibling of an ancestor
2990 (let ((sibling-alist (last (cdr root))))
2991 (dotimes (i (1- level))
2992 (setq sibling-alist (last (cdar sibling-alist))))
2993 (setcdr sibling-alist alist)
2994 (setq cur-alist alist))
2995 (setq cur-level level)))))
2996 (cdr root))))
2999 ;;; References ================================================================
3001 (defun markdown-insert-reference-definition (ref &optional buffer)
3002 "Add blank REF definition to the end of BUFFER.
3003 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3004 (or buffer (setq buffer (current-buffer)))
3005 (with-current-buffer buffer
3006 (goto-char (point-max))
3007 (indent-new-comment-line)
3008 (insert (concat ref ": "))))
3010 (defun markdown-reference-goto-definition ()
3011 "Jump to the definition of the reference at point or create it."
3012 (interactive)
3013 (when (thing-at-point-looking-at markdown-regex-link-reference)
3014 (let* ((label (match-string-no-properties 1))
3015 (reference (match-string-no-properties 3))
3016 (target (downcase (if (string= reference "[]") label reference)))
3017 (loc (cadr (markdown-reference-definition target))))
3018 (if loc
3019 (goto-char loc)
3020 (markdown-insert-reference-definition reference (current-buffer))))))
3022 (defun markdown-reference-find-links (reference)
3023 "Return a list of all links for REFERENCE.
3024 REFERENCE should include the surrounding square brackets like [this].
3025 Elements of the list have the form (text start line), where
3026 text is the link text, start is the location at the beginning of
3027 the link, and line is the line number on which the link appears."
3028 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3029 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3030 ref-quote ref-quote))
3031 links)
3032 (save-excursion
3033 (goto-char (point-min))
3034 (while (re-search-forward regexp nil t)
3035 (let* ((text (or (match-string-no-properties 1)
3036 (match-string-no-properties 2)))
3037 (start (match-beginning 0))
3038 (line (markdown-line-number-at-pos)))
3039 (add-to-list 'links (list text start line)))))
3040 links))
3042 (defun markdown-get-undefined-refs ()
3043 "Return a list of undefined Markdown references.
3044 Result is an alist of pairs (reference . occurrences), where
3045 occurrences is itself another alist of pairs (label . line-number).
3046 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3047 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3048 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3049 (let ((missing))
3050 (save-excursion
3051 (goto-char (point-min))
3052 (while
3053 (re-search-forward markdown-regex-link-reference nil t)
3054 (let* ((label (match-string-no-properties 1))
3055 (reference (match-string-no-properties 3))
3056 (target (downcase (if (string= reference "[]") label reference))))
3057 (unless (markdown-reference-definition target)
3058 (let ((entry (assoc target missing)))
3059 (if (not entry)
3060 (add-to-list 'missing (cons target
3061 (list (cons label (markdown-line-number-at-pos)))) t)
3062 (setcdr entry
3063 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
3064 missing)))
3066 (defconst markdown-reference-check-buffer
3067 "*Undefined references for %buffer%*"
3068 "Pattern for name of buffer for listing undefined references.
3069 The string %buffer% will be replaced by the corresponding
3070 `markdown-mode' buffer name.")
3072 (defun markdown-reference-check-buffer (&optional buffer-name)
3073 "Name and return buffer for reference checking."
3074 (or buffer-name (setq buffer-name (buffer-name)))
3075 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3076 "%buffer%" buffer-name
3077 markdown-reference-check-buffer))))
3078 (with-current-buffer refbuf
3079 (when view-mode
3080 (View-exit-and-edit))
3081 (use-local-map button-buffer-map)
3082 (erase-buffer))
3083 refbuf))
3085 (defconst markdown-reference-links-buffer
3086 "*Reference links for %buffer%*"
3087 "Pattern for name of buffer for listing references.
3088 The string %buffer% will be replaced by the corresponding buffer name.")
3090 (defun markdown-reference-links-buffer (&optional buffer-name)
3091 "Name, setup, and return a buffer for listing links."
3092 (or buffer-name (setq buffer-name (buffer-name)))
3093 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3094 "%buffer%" buffer-name
3095 markdown-reference-links-buffer))))
3096 (with-current-buffer linkbuf
3097 (when view-mode
3098 (View-exit-and-edit))
3099 (use-local-map button-buffer-map)
3100 (erase-buffer))
3101 linkbuf))
3103 (when (markdown-use-buttons-p)
3104 ;; Add an empty Markdown reference definition to the end of buffer
3105 ;; specified in the 'target-buffer property. The reference name is
3106 ;; the button's label.
3107 (define-button-type 'markdown-undefined-reference-button
3108 'help-echo "mouse-1, RET: create definition for undefined reference"
3109 'follow-link t
3110 'face 'bold
3111 'action (lambda (b)
3112 (let ((buffer (button-get b 'target-buffer)))
3113 (markdown-insert-reference-definition (button-label b) buffer)
3114 (switch-to-buffer-other-window buffer)
3115 (goto-char (point-max))
3116 (markdown-check-refs t))))
3118 ;; Jump to line in buffer specified by 'target-buffer property.
3119 ;; Line number is button's 'line property.
3120 (define-button-type 'markdown-goto-line-button
3121 'help-echo "mouse-1, RET: go to line"
3122 'follow-link t
3123 'face 'italic
3124 'action (lambda (b)
3125 (message (button-get b 'buffer))
3126 (switch-to-buffer-other-window (button-get b 'target-buffer))
3127 ;; use call-interactively to silence compiler
3128 (let ((current-prefix-arg (button-get b 'target-line)))
3129 (call-interactively 'goto-line))))
3131 ;; Jumps to a particular link at location given by 'target-char
3132 ;; property in buffer given by 'target-buffer property.
3133 (define-button-type 'markdown-link-button
3134 'help-echo "mouse-1, RET: jump to location of link"
3135 'follow-link t
3136 'face 'bold
3137 'action (lambda (b)
3138 (let ((target (button-get b 'target-buffer))
3139 (loc (button-get b 'target-char)))
3140 (kill-buffer-and-window)
3141 (switch-to-buffer target)
3142 (goto-char loc)))))
3144 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3145 "Insert a button for creating REFERENCE in buffer OLDBUF.
3146 REFERENCE should be a list of the form (reference . occurrences),
3147 as by `markdown-get-undefined-refs'."
3148 (let ((label (car reference)))
3149 (if (markdown-use-buttons-p)
3150 ;; Create a reference button in Emacs 22
3151 (insert-button label
3152 :type 'markdown-undefined-reference-button
3153 'target-buffer oldbuf)
3154 ;; Insert reference as text in Emacs < 22
3155 (insert label))
3156 (insert " (")
3157 (dolist (occurrence (cdr reference))
3158 (let ((line (cdr occurrence)))
3159 (if (markdown-use-buttons-p)
3160 ;; Create a line number button in Emacs 22
3161 (insert-button (number-to-string line)
3162 :type 'markdown-goto-line-button
3163 'target-buffer oldbuf
3164 'target-line line)
3165 ;; Insert line number as text in Emacs < 22
3166 (insert (number-to-string line)))
3167 (insert " ")))
3168 (delete-char -1)
3169 (insert ")")
3170 (newline)))
3172 (defun markdown-insert-link-button (link oldbuf)
3173 "Insert a button for jumping to LINK in buffer OLDBUF.
3174 LINK should be a list of the form (text char line) containing
3175 the link text, location, and line number."
3176 (let ((label (first link))
3177 (char (second link))
3178 (line (third link)))
3179 (if (markdown-use-buttons-p)
3180 ;; Create a reference button in Emacs 22
3181 (insert-button label
3182 :type 'markdown-link-button
3183 'target-buffer oldbuf
3184 'target-char char)
3185 ;; Insert reference as text in Emacs < 22
3186 (insert label))
3187 (insert (format " (line %d)\n" line))))
3189 (defun markdown-reference-goto-link (&optional reference)
3190 "Jump to the location of the first use of reference."
3191 (interactive)
3192 (unless reference
3193 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3194 (setq reference (match-string-no-properties 1))
3195 (error "No reference definition at point.")))
3196 (let ((links (markdown-reference-find-links reference)))
3197 (cond ((= (length links) 1)
3198 (goto-char (cadr (car links))))
3199 ((> (length links) 1)
3200 (let ((oldbuf (current-buffer))
3201 (linkbuf (markdown-reference-links-buffer)))
3202 (with-current-buffer linkbuf
3203 (insert "Links using reference " reference ":\n\n")
3204 (dolist (link (reverse links))
3205 (markdown-insert-link-button link oldbuf)))
3206 (view-buffer-other-window linkbuf)
3207 (goto-char (point-min))
3208 (forward-line 2)))
3210 (error "No links for reference %s" reference)))))
3212 (defun markdown-check-refs (&optional silent)
3213 "Show all undefined Markdown references in current `markdown-mode' buffer.
3214 If SILENT is non-nil, do not message anything when no undefined
3215 references found.
3216 Links which have empty reference definitions are considered to be
3217 defined."
3218 (interactive "P")
3219 (when (not (eq major-mode 'markdown-mode))
3220 (error "Not available in current mode"))
3221 (let ((oldbuf (current-buffer))
3222 (refs (markdown-get-undefined-refs))
3223 (refbuf (markdown-reference-check-buffer)))
3224 (if (null refs)
3225 (progn
3226 (when (not silent)
3227 (message "No undefined references found"))
3228 (kill-buffer refbuf))
3229 (with-current-buffer refbuf
3230 (insert "The following references are undefined:\n\n")
3231 (dolist (ref refs)
3232 (markdown-insert-undefined-reference-button ref oldbuf))
3233 (view-buffer-other-window refbuf)
3234 (goto-char (point-min))
3235 (forward-line 2)))))
3238 ;;; Lists =====================================================================
3240 (defun markdown-insert-list-item (&optional arg)
3241 "Insert a new list item.
3242 If the point is inside unordered list, insert a bullet mark. If
3243 the point is inside ordered list, insert the next number followed
3244 by a period. Use the previous list item to determine the amount
3245 of whitespace to place before and after list markers.
3247 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3248 decrease the indentation by one level.
3250 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3251 increase the indentation by one level."
3252 (interactive "p")
3253 (let (bounds item-indent marker indent new-indent end)
3254 (save-match-data
3255 (setq bounds (markdown-cur-list-item-bounds))
3256 (if (not bounds)
3257 ;; When not in a list, start a new unordered one
3258 (progn
3259 (unless (markdown-cur-line-blank-p)
3260 (insert "\n"))
3261 (insert "* "))
3262 ;; Compute indentation for a new list item
3263 (setq item-indent (nth 2 bounds))
3264 (setq marker (concat (match-string 2) (match-string 3)))
3265 (setq indent (cond
3266 ((= arg 4) (max (- item-indent 4) 0))
3267 ((= arg 16) (+ item-indent 4))
3268 (t item-indent)))
3269 (setq new-indent (make-string indent 32))
3270 (goto-char (nth 1 bounds))
3271 (newline)
3272 (cond
3273 ;; Ordered list
3274 ((string-match "[0-9]" marker)
3275 (if (= arg 16) ;; starting a new column indented one more level
3276 (insert (concat new-indent "1. "))
3277 ;; travel up to the last item and pick the correct number. If
3278 ;; the argument was nil, "new-indent = item-indent" is the same,
3279 ;; so we don't need special treatment. Neat.
3280 (save-excursion
3281 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3282 (forward-line -1)))
3283 (insert (concat new-indent
3284 (int-to-string (1+ (string-to-number (match-string 1))))
3285 ". "))))
3286 ;; Unordered list
3287 ((string-match "[\\*\\+-]" marker)
3288 (insert (concat new-indent marker))))))))
3290 (defun markdown-move-list-item-up ()
3291 "Move the current list item up in the list when possible."
3292 (interactive)
3293 (let (cur prev old)
3294 (when (setq cur (markdown-cur-list-item-bounds))
3295 (setq old (point))
3296 (goto-char (nth 0 cur))
3297 (if (markdown-prev-list-item (nth 3 cur))
3298 (progn
3299 (setq prev (markdown-cur-list-item-bounds))
3300 (condition-case nil
3301 (progn
3302 (transpose-regions (nth 0 prev) (nth 1 prev)
3303 (nth 0 cur) (nth 1 cur) t)
3304 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3305 ;; Catch error in case regions overlap.
3306 (error (goto-char old))))
3307 (goto-char old)))))
3309 (defun markdown-move-list-item-down ()
3310 "Move the current list item down in the list when possible."
3311 (interactive)
3312 (let (cur next old)
3313 (when (setq cur (markdown-cur-list-item-bounds))
3314 (setq old (point))
3315 (if (markdown-next-list-item (nth 3 cur))
3316 (progn
3317 (setq next (markdown-cur-list-item-bounds))
3318 (condition-case nil
3319 (progn
3320 (transpose-regions (nth 0 cur) (nth 1 cur)
3321 (nth 0 next) (nth 1 next) nil)
3322 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3323 ;; Catch error in case regions overlap.
3324 (error (goto-char old))))
3325 (goto-char old)))))
3327 (defun markdown-demote-list-item (&optional bounds)
3328 "Indent (or demote) the current list item.
3329 Optionally, BOUNDS of the current list item may be provided if available."
3330 (interactive)
3331 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3332 (save-excursion
3333 (save-match-data
3334 (let* ((end-marker (make-marker))
3335 (end-marker (set-marker end-marker (nth 1 bounds))))
3336 (goto-char (nth 0 bounds))
3337 (while (< (point) end-marker)
3338 (unless (markdown-cur-line-blank-p)
3339 (insert " "))
3340 (forward-line)))))))
3342 (defun markdown-promote-list-item (&optional bounds)
3343 "Unindent (or promote) the current list item.
3344 Optionally, BOUNDS of the current list item may be provided if available."
3345 (interactive)
3346 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3347 (save-excursion
3348 (save-match-data
3349 (let* ((end-marker (make-marker))
3350 (end-marker (set-marker end-marker (nth 1 bounds)))
3351 num regexp)
3352 (goto-char (nth 0 bounds))
3353 (when (looking-at "^[ ]\\{1,4\\}")
3354 (setq num (- (match-end 0) (match-beginning 0)))
3355 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3356 (while (and (< (point) end-marker)
3357 (re-search-forward regexp end-marker t))
3358 (replace-match "" nil nil)
3359 (forward-line))))))))
3361 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3362 "Update the numbering for level PFX (as a string of spaces).
3364 Assume that the previously found match was for a numbered item in
3365 a list."
3366 (let ((cpfx pfx)
3367 (idx 0)
3368 (continue t)
3369 (step t)
3370 (sep nil))
3371 (while (and continue (not (eobp)))
3372 (setq step t)
3373 (cond
3374 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3375 (setq cpfx (match-string-no-properties 1))
3376 (cond
3377 ((string= cpfx pfx)
3378 (replace-match
3379 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3380 (setq sep nil))
3381 ;; indented a level
3382 ((string< pfx cpfx)
3383 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3384 (setq step nil))
3385 ;; exit the loop
3387 (setq step nil)
3388 (setq continue nil))))
3390 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3391 (setq cpfx (match-string-no-properties 1))
3392 (cond
3393 ;; reset if separated before
3394 ((string= cpfx pfx) (when sep (setq idx 0)))
3395 ((string< cpfx pfx)
3396 (setq step nil)
3397 (setq continue nil))))
3398 (t (setq sep t)))
3400 (when step
3401 (beginning-of-line)
3402 (setq continue (= (forward-line) 0))))
3403 sep))
3405 (defun markdown-cleanup-list-numbers ()
3406 "Update the numbering of ordered lists."
3407 (interactive)
3408 (save-excursion
3409 (goto-char (point-min))
3410 (markdown--cleanup-list-numbers-level "")))
3413 ;;; Outline ===================================================================
3415 (defvar markdown-cycle-global-status 1)
3416 (defvar markdown-cycle-subtree-status nil)
3418 (defun markdown-end-of-subtree (&optional invisible-OK)
3419 "Move to the end of the current subtree.
3420 Only visible heading lines are considered, unless INVISIBLE-OK is
3421 non-nil.
3422 Derived from `org-end-of-subtree'."
3423 (outline-back-to-heading invisible-OK)
3424 (let ((first t)
3425 (level (funcall outline-level)))
3426 (while (and (not (eobp))
3427 (or first (> (funcall outline-level) level)))
3428 (setq first nil)
3429 (outline-next-heading))
3430 (if (memq (preceding-char) '(?\n ?\^M))
3431 (progn
3432 ;; Go to end of line before heading
3433 (forward-char -1)
3434 (if (memq (preceding-char) '(?\n ?\^M))
3435 ;; leave blank line before heading
3436 (forward-char -1)))))
3437 (point))
3439 (defun markdown-cycle (&optional arg)
3440 "Visibility cycling for Markdown mode.
3441 If ARG is t, perform global visibility cycling. If the point is
3442 at an atx-style header, cycle visibility of the corresponding
3443 subtree. Otherwise, insert a tab using `indent-relative'.
3444 Derived from `org-cycle'."
3445 (interactive "P")
3446 (cond
3447 ((eq arg t) ;; Global cycling
3448 (cond
3449 ((and (eq last-command this-command)
3450 (eq markdown-cycle-global-status 2))
3451 ;; Move from overview to contents
3452 (hide-sublevels 1)
3453 (message "CONTENTS")
3454 (setq markdown-cycle-global-status 3))
3456 ((and (eq last-command this-command)
3457 (eq markdown-cycle-global-status 3))
3458 ;; Move from contents to all
3459 (show-all)
3460 (message "SHOW ALL")
3461 (setq markdown-cycle-global-status 1))
3464 ;; Defaults to overview
3465 (hide-body)
3466 (message "OVERVIEW")
3467 (setq markdown-cycle-global-status 2))))
3469 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3470 ;; At a heading: rotate between three different views
3471 (outline-back-to-heading)
3472 (let ((goal-column 0) eoh eol eos)
3473 ;; Determine boundaries
3474 (save-excursion
3475 (outline-back-to-heading)
3476 (save-excursion
3477 (beginning-of-line 2)
3478 (while (and (not (eobp)) ;; this is like `next-line'
3479 (get-char-property (1- (point)) 'invisible))
3480 (beginning-of-line 2)) (setq eol (point)))
3481 (outline-end-of-heading) (setq eoh (point))
3482 (markdown-end-of-subtree t)
3483 (skip-chars-forward " \t\n")
3484 (beginning-of-line 1) ; in case this is an item
3485 (setq eos (1- (point))))
3486 ;; Find out what to do next and set `this-command'
3487 (cond
3488 ((= eos eoh)
3489 ;; Nothing is hidden behind this heading
3490 (message "EMPTY ENTRY")
3491 (setq markdown-cycle-subtree-status nil))
3492 ((>= eol eos)
3493 ;; Entire subtree is hidden in one line: open it
3494 (show-entry)
3495 (show-children)
3496 (message "CHILDREN")
3497 (setq markdown-cycle-subtree-status 'children))
3498 ((and (eq last-command this-command)
3499 (eq markdown-cycle-subtree-status 'children))
3500 ;; We just showed the children, now show everything.
3501 (show-subtree)
3502 (message "SUBTREE")
3503 (setq markdown-cycle-subtree-status 'subtree))
3505 ;; Default action: hide the subtree.
3506 (hide-subtree)
3507 (message "FOLDED")
3508 (setq markdown-cycle-subtree-status 'folded)))))
3511 (indent-for-tab-command))))
3513 (defun markdown-shifttab ()
3514 "Global visibility cycling.
3515 Calls `markdown-cycle' with argument t."
3516 (interactive)
3517 (markdown-cycle t))
3519 (defun markdown-outline-level ()
3520 "Return the depth to which a statement is nested in the outline."
3521 (cond
3522 ((match-end 1) 1)
3523 ((match-end 3) 2)
3524 ((- (match-end 5) (match-beginning 5)))))
3527 ;;; Movement ==================================================================
3529 (defun markdown-beginning-of-defun (&optional arg)
3530 "`beginning-of-defun-function' for Markdown.
3531 Move backward to the beginning of the current or previous section."
3532 (interactive "P")
3533 (or arg (setq arg 1))
3534 (or (re-search-backward markdown-regex-header nil t arg)
3535 (goto-char (point-min))))
3537 (defun markdown-end-of-defun (&optional arg)
3538 "`end-of-defun-function' for Markdown.
3539 Move forward to the end of the current or following section."
3540 (interactive "P")
3541 (or arg (setq arg 1))
3542 (when (looking-at markdown-regex-header)
3543 (goto-char (match-beginning 0))
3544 (forward-char 1))
3545 (if (re-search-forward markdown-regex-header nil t arg)
3546 (goto-char (match-beginning 0))
3547 (goto-char (point-max)))
3548 (skip-syntax-backward "-"))
3550 (defun markdown-beginning-of-block ()
3551 "Move the point to the start of the previous text block."
3552 (interactive)
3553 (if (re-search-backward markdown-regex-block-separator nil t)
3554 (goto-char (or (match-end 2) (match-end 0)))
3555 (goto-char (point-min))))
3557 (defun markdown-end-of-block ()
3558 "Move the point to the start of the next text block."
3559 (interactive)
3560 (beginning-of-line)
3561 (skip-syntax-forward "-")
3562 (when (= (point) (point-min))
3563 (forward-char))
3564 (if (re-search-forward markdown-regex-block-separator nil t)
3565 (goto-char (or (match-end 2) (match-end 0)))
3566 (goto-char (point-max)))
3567 (skip-syntax-backward "-")
3568 (forward-line))
3570 (defun markdown-end-of-block-element ()
3571 "Move the point to the start of the next block unit.
3572 Stops at blank lines, list items, headers, and horizontal rules."
3573 (interactive)
3574 (forward-line)
3575 (while (and (or (not (markdown-prev-line-blank-p))
3576 (markdown-cur-line-blank-p))
3577 (not (or (looking-at markdown-regex-list)
3578 (looking-at markdown-regex-header)
3579 (looking-at markdown-regex-hr)))
3580 (not (eobp)))
3581 (forward-line)))
3583 (defun markdown-next-link ()
3584 "Jump to next inline, reference, or wiki link.
3585 If successful, return point. Otherwise, return nil.
3586 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3587 (interactive)
3588 (let ((opoint (point)))
3589 (when (or (markdown-link-p) (markdown-wiki-link-p))
3590 ;; At a link already, move past it.
3591 (goto-char (+ (match-end 0) 1)))
3592 ;; Search for the next wiki link and move to the beginning.
3593 (if (re-search-forward markdown-regex-link-generic nil t)
3594 ;; Group 1 will move past non-escape character in wiki link regexp.
3595 ;; Go to beginning of group zero for all other link types.
3596 (goto-char (or (match-beginning 1) (match-beginning 0)))
3597 (goto-char opoint)
3598 nil)))
3600 (defun markdown-previous-link ()
3601 "Jump to previous wiki link.
3602 If successful, return point. Otherwise, return nil.
3603 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3604 (interactive)
3605 (if (re-search-backward markdown-regex-link-generic nil t)
3606 (goto-char (or (match-beginning 1) (match-beginning 0)))
3607 nil))
3610 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3612 (defun markdown-move-up ()
3613 "Move list item up.
3614 Calls `markdown-move-list-item-up'."
3615 (interactive)
3616 (markdown-move-list-item-up))
3618 (defun markdown-move-down ()
3619 "Move list item down.
3620 Calls `markdown-move-list-item-down'."
3621 (interactive)
3622 (markdown-move-list-item-down))
3624 (defun markdown-promote ()
3625 "Either promote header or list item at point or cycle markup.
3626 See `markdown-cycle-atx', `markdown-cycle-setext', and
3627 `markdown-demote-list-item'."
3628 (interactive)
3629 (let (bounds)
3630 (cond
3631 ;; Promote atx header
3632 ((thing-at-point-looking-at markdown-regex-header-atx)
3633 (markdown-cycle-atx -1 t))
3634 ;; Promote setext header
3635 ((thing-at-point-looking-at markdown-regex-header-setext)
3636 (markdown-cycle-setext -1 t))
3637 ;; Promote horizonal rule
3638 ((thing-at-point-looking-at markdown-regex-hr)
3639 (markdown-cycle-hr -1 t))
3640 ;; Promote list item
3641 ((setq bounds (markdown-cur-list-item-bounds))
3642 (markdown-promote-list-item)))))
3644 (defun markdown-demote ()
3645 "Either demote header or list item at point or cycle or remove markup.
3646 See `markdown-cycle-atx', `markdown-cycle-setext', and
3647 `markdown-demote-list-item'."
3648 (interactive)
3649 (let (bounds)
3650 (cond
3651 ;; Demote atx header
3652 ((thing-at-point-looking-at markdown-regex-header-atx)
3653 (markdown-cycle-atx 1 t))
3654 ;; Demote setext header
3655 ((thing-at-point-looking-at markdown-regex-header-setext)
3656 (markdown-cycle-setext 1 t))
3657 ;; Demote horizonal rule
3658 ((thing-at-point-looking-at markdown-regex-hr)
3659 (markdown-cycle-hr 1 t))
3660 ;; Promote list item
3661 ((setq bounds (markdown-cur-list-item-bounds))
3662 (markdown-demote-list-item))
3663 ;; Create a new level one ATX header
3665 (markdown-insert-header-atx-1)))))
3667 (defun markdown-complete-or-cycle (arg)
3668 "Complete or cycle markup of object at point or complete objects in region.
3669 If there is an active region, complete markup in region.
3670 Otherwise, complete or cycle markup of object near point.
3671 When ARG is non-nil, cycle backwards when cycling."
3672 (interactive "*P")
3673 (if (markdown-use-region-p)
3674 ;; Complete markup in region
3675 (markdown-complete-region (region-beginning) (region-end))
3676 ;; Complete or cycle markup at point
3677 (let ((dir (if arg -1 1))
3678 bounds)
3679 (cond
3680 ;; atx header
3681 ((thing-at-point-looking-at markdown-regex-header-atx)
3682 (if (markdown-incomplete-atx-p)
3683 (markdown-complete-atx)
3684 (markdown-cycle-atx dir)))
3685 ;; setext header
3686 ((thing-at-point-looking-at markdown-regex-header-setext)
3687 (if (markdown-incomplete-setext-p)
3688 (markdown-complete-setext)
3689 (markdown-cycle-setext dir)))
3690 ;; horizonal rule
3691 ((thing-at-point-looking-at markdown-regex-hr)
3692 (if (markdown-incomplete-hr-p)
3693 (markdown-complete-hr)
3694 (markdown-cycle-hr dir)))
3695 ;; bold
3696 ((thing-at-point-looking-at markdown-regex-bold)
3697 (markdown-cycle-bold))
3698 ;; italic
3699 ((thing-at-point-looking-at markdown-regex-italic)
3700 (markdown-cycle-italic))))))
3703 ;;; Commands ==================================================================
3705 (defun markdown (&optional output-buffer-name)
3706 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3707 The output buffer name defaults to `markdown-output-buffer-name'.
3708 Return the name of the output buffer used."
3709 (interactive)
3710 (save-window-excursion
3711 (let ((begin-region)
3712 (end-region))
3713 (if (markdown-use-region-p)
3714 (setq begin-region (region-beginning)
3715 end-region (region-end))
3716 (setq begin-region (point-min)
3717 end-region (point-max)))
3719 (unless output-buffer-name
3720 (setq output-buffer-name markdown-output-buffer-name))
3722 (cond
3723 ;; Handle case when `markdown-command' does not read from stdin
3724 (markdown-command-needs-filename
3725 (if (not buffer-file-name)
3726 (error "Must be visiting a file")
3727 (shell-command (concat markdown-command " "
3728 (shell-quote-argument buffer-file-name))
3729 output-buffer-name)))
3730 ;; Pass region to `markdown-command' via stdin
3732 (shell-command-on-region begin-region end-region markdown-command
3733 output-buffer-name))))
3734 output-buffer-name))
3736 (defun markdown-standalone (&optional output-buffer-name)
3737 "Special function to provide standalone HTML output.
3738 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3739 (interactive)
3740 (setq output-buffer-name (markdown output-buffer-name))
3741 (with-current-buffer output-buffer-name
3742 (set-buffer output-buffer-name)
3743 (goto-char (point-min))
3744 (unless (markdown-output-standalone-p)
3745 (markdown-add-xhtml-header-and-footer output-buffer-name))
3746 (html-mode))
3747 output-buffer-name)
3749 (defun markdown-other-window (&optional output-buffer-name)
3750 "Run `markdown-command' on current buffer and display in other window.
3751 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3752 that name."
3753 (interactive)
3754 (display-buffer (markdown-standalone output-buffer-name)))
3756 (defun markdown-output-standalone-p ()
3757 "Determine whether `markdown-command' output is standalone XHTML.
3758 Standalone XHTML output is identified by an occurrence of
3759 `markdown-xhtml-standalone-regexp' in the first five lines of output."
3760 (re-search-forward
3761 markdown-xhtml-standalone-regexp
3762 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
3765 (defun markdown-add-xhtml-header-and-footer (title)
3766 "Wrap XHTML header and footer with given TITLE around current buffer."
3767 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
3768 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
3769 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
3770 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
3771 "<head>\n<title>")
3772 (insert title)
3773 (insert "</title>\n")
3774 (when (> (length markdown-content-type) 0)
3775 (insert
3776 (format
3777 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
3778 markdown-content-type
3779 (or (and markdown-coding-system
3780 (fboundp 'coding-system-get)
3781 (coding-system-get markdown-coding-system
3782 'mime-charset))
3783 (and (fboundp 'coding-system-get)
3784 (coding-system-get buffer-file-coding-system
3785 'mime-charset))
3786 "iso-8859-1"))))
3787 (if (> (length markdown-css-path) 0)
3788 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
3789 markdown-css-path
3790 "\" />\n"))
3791 (when (> (length markdown-xhtml-header-content) 0)
3792 (insert markdown-xhtml-header-content))
3793 (insert "\n</head>\n\n"
3794 "<body>\n\n")
3795 (goto-char (point-max))
3796 (insert "\n"
3797 "</body>\n"
3798 "</html>\n"))
3800 (defun markdown-preview (&optional output-buffer-name)
3801 "Run `markdown-command' on the current buffer and view output in browser.
3802 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3803 that name."
3804 (interactive)
3805 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
3807 (defun markdown-export-file-name (&optional extension)
3808 "Attempt to generate a filename for Markdown output.
3809 The file extension will be EXTENSION if given, or .html by default.
3810 If the current buffer is visiting a file, we construct a new
3811 output filename based on that filename. Otherwise, return nil."
3812 (when (buffer-file-name)
3813 (unless extension
3814 (setq extension ".html"))
3815 (concat
3816 (cond
3817 ((buffer-file-name)
3818 (file-name-sans-extension (buffer-file-name)))
3819 (t (buffer-name)))
3820 extension)))
3822 (defun markdown-export (&optional output-file)
3823 "Run Markdown on the current buffer, save to file, and return the filename.
3824 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
3825 generated by `markdown-export-file-name', which will be constructed using the
3826 current filename, but with the extension removed and replaced with .html."
3827 (interactive)
3828 (unless output-file
3829 (setq output-file (markdown-export-file-name ".html")))
3830 (when output-file
3831 (let ((output-buffer-name))
3832 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
3833 (run-hook-with-args 'markdown-before-export-hooks output-file)
3834 (markdown-standalone output-buffer-name)
3835 (with-current-buffer output-buffer-name
3836 (save-buffer))
3837 (run-hook-with-args 'markdown-after-export-hooks output-file)
3838 output-file)))
3840 (defun markdown-export-and-preview ()
3841 "Export to XHTML using `markdown-export' and browse the resulting file."
3842 (interactive)
3843 (browse-url (markdown-export)))
3845 (defun markdown-open ()
3846 "Open file for the current buffer with `markdown-open-command'."
3847 (interactive)
3848 (if (not markdown-open-command)
3849 (error "Variable `markdown-open-command' must be set")
3850 (if (not buffer-file-name)
3851 (error "Must be visiting a file")
3852 (call-process markdown-open-command
3853 nil nil nil buffer-file-name))))
3855 (defun markdown-kill-ring-save ()
3856 "Run Markdown on file and store output in the kill ring."
3857 (interactive)
3858 (save-window-excursion
3859 (markdown)
3860 (with-current-buffer markdown-output-buffer-name
3861 (kill-ring-save (point-min) (point-max)))))
3864 ;;; Links =====================================================================
3866 (require 'thingatpt)
3868 (defun markdown-link-p ()
3869 "Return non-nil when `point' is at a non-wiki link.
3870 See `markdown-wiki-link-p' for more information."
3871 (let ((case-fold-search nil))
3872 (and (not (markdown-wiki-link-p))
3873 (or (thing-at-point-looking-at markdown-regex-link-inline)
3874 (thing-at-point-looking-at markdown-regex-link-reference)
3875 (thing-at-point-looking-at markdown-regex-uri)
3876 (thing-at-point-looking-at markdown-regex-angle-uri)))))
3878 (defun markdown-link-link ()
3879 "Return the link part of the regular (non-wiki) link at point.
3880 Works with both inline and reference style links. If point is
3881 not at a link or the link reference is not defined returns nil."
3882 (cond
3883 ((thing-at-point-looking-at markdown-regex-link-inline)
3884 (match-string-no-properties 4))
3885 ((thing-at-point-looking-at markdown-regex-link-reference)
3886 (let* ((label (match-string-no-properties 1))
3887 (reference (match-string-no-properties 3))
3888 (target (downcase (if (string= reference "[]") label reference))))
3889 (car (markdown-reference-definition target))))
3890 ((thing-at-point-looking-at markdown-regex-uri)
3891 (match-string-no-properties 0))
3892 ((thing-at-point-looking-at markdown-regex-angle-uri)
3893 (match-string-no-properties 2))
3894 (t nil)))
3896 (defun markdown-follow-link-at-point ()
3897 "Open the current non-wiki link in a browser."
3898 (interactive)
3899 (if (markdown-link-p) (browse-url (markdown-link-link))
3900 (error "Point is not at a Markdown link or URI")))
3903 ;;; WikiLink Following/Markup =================================================
3905 (defun markdown-wiki-link-p ()
3906 "Return non-nil when `point' is at a true wiki link.
3907 A true wiki link name matches `markdown-regex-wiki-link' but does not
3908 match the current file name after conversion. This modifies the data
3909 returned by `match-data'. Note that the potential wiki link name must
3910 be available via `match-string'."
3911 (let ((case-fold-search nil))
3912 (and (thing-at-point-looking-at markdown-regex-wiki-link)
3913 (or (not buffer-file-name)
3914 (not (string-equal (buffer-file-name)
3915 (markdown-convert-wiki-link-to-filename
3916 (markdown-wiki-link-link)))))
3917 (not (save-match-data
3918 (save-excursion))))))
3920 (defun markdown-wiki-link-link ()
3921 "Return the link part of the wiki link using current match data.
3922 The location of the link component depends on the value of
3923 `markdown-wiki-link-alias-first'."
3924 (if markdown-wiki-link-alias-first
3925 (or (match-string-no-properties 4) (match-string-no-properties 2))
3926 (match-string-no-properties 2)))
3928 (defun markdown-convert-wiki-link-to-filename (name)
3929 "Generate a filename from the wiki link NAME.
3930 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
3931 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
3932 and [[test test]] both map to Test-test.ext."
3933 (let ((basename (markdown-replace-regexp-in-string
3934 "[[:space:]\n]" markdown-link-space-sub-char name)))
3935 (when (eq major-mode 'gfm-mode)
3936 (setq basename (concat (upcase (substring basename 0 1))
3937 (downcase (substring basename 1 nil)))))
3938 (concat basename
3939 (if (buffer-file-name)
3940 (concat "."
3941 (file-name-extension (buffer-file-name)))))))
3943 (defun markdown-follow-wiki-link (name &optional other)
3944 "Follow the wiki link NAME.
3945 Convert the name to a file name and call `find-file'. Ensure that
3946 the new buffer remains in `markdown-mode'. Open the link in another
3947 window when OTHER is non-nil."
3948 (let ((filename (markdown-convert-wiki-link-to-filename name))
3949 (wp (file-name-directory buffer-file-name)))
3950 (when other (other-window 1))
3951 (find-file (concat wp filename)))
3952 (when (not (eq major-mode 'markdown-mode))
3953 (markdown-mode)))
3955 (defun markdown-follow-wiki-link-at-point (&optional arg)
3956 "Find Wiki Link at point.
3957 With prefix argument ARG, open the file in other window.
3958 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
3959 (interactive "P")
3960 (if (markdown-wiki-link-p)
3961 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
3962 (error "Point is not at a Wiki Link")))
3964 (defun markdown-highlight-wiki-link (from to face)
3965 "Highlight the wiki link in the region between FROM and TO using FACE."
3966 (put-text-property from to 'font-lock-face face))
3968 (defun markdown-unfontify-region-wiki-links (from to)
3969 "Remove wiki link faces from the region specified by FROM and TO."
3970 (interactive "nfrom: \nnto: ")
3971 (remove-text-properties from to '(font-lock-face markdown-link-face))
3972 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
3974 (defun markdown-fontify-region-wiki-links (from to)
3975 "Search region given by FROM and TO for wiki links and fontify them.
3976 If a wiki link is found check to see if the backing file exists
3977 and highlight accordingly."
3978 (goto-char from)
3979 (save-match-data
3980 (while (re-search-forward markdown-regex-wiki-link to t)
3981 (let ((highlight-beginning (match-beginning 1))
3982 (highlight-end (match-end 1))
3983 (file-name
3984 (markdown-convert-wiki-link-to-filename
3985 (markdown-wiki-link-link))))
3986 (if (file-exists-p file-name)
3987 (markdown-highlight-wiki-link
3988 highlight-beginning highlight-end markdown-link-face)
3989 (markdown-highlight-wiki-link
3990 highlight-beginning highlight-end markdown-link-face)
3991 (markdown-highlight-wiki-link
3992 highlight-beginning highlight-end markdown-missing-link-face))))))
3994 (defun markdown-extend-changed-region (from to)
3995 "Extend region given by FROM and TO so that we can fontify all links.
3996 The region is extended to the first newline before and the first
3997 newline after."
3998 ;; start looking for the first new line before 'from
3999 (goto-char from)
4000 (re-search-backward "\n" nil t)
4001 (let ((new-from (point-min))
4002 (new-to (point-max)))
4003 (if (not (= (point) from))
4004 (setq new-from (point)))
4005 ;; do the same thing for the first new line after 'to
4006 (goto-char to)
4007 (re-search-forward "\n" nil t)
4008 (if (not (= (point) to))
4009 (setq new-to (point)))
4010 (values new-from new-to)))
4012 (defun markdown-check-change-for-wiki-link (from to change)
4013 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4014 Designed to be used with the `after-change-functions' hook.
4015 CHANGE is the number of bytes of pre-change text replaced by the
4016 given range."
4017 (interactive "nfrom: \nnto: \nnchange: ")
4018 (let* ((modified (buffer-modified-p))
4019 (buffer-undo-list t)
4020 (inhibit-read-only t)
4021 (inhibit-point-motion-hooks t)
4022 deactivate-mark
4023 buffer-file-truename)
4024 (unwind-protect
4025 (save-excursion
4026 (save-match-data
4027 (save-restriction
4028 ;; Extend the region to fontify so that it starts
4029 ;; and ends at safe places.
4030 (multiple-value-bind (new-from new-to)
4031 (markdown-extend-changed-region from to)
4032 ;; Unfontify existing fontification (start from scratch)
4033 (markdown-unfontify-region-wiki-links new-from new-to)
4034 ;; Now do the fontification.
4035 (markdown-fontify-region-wiki-links new-from new-to)))))
4036 (and (not modified)
4037 (buffer-modified-p)
4038 (set-buffer-modified-p nil)))))
4040 (defun markdown-fontify-buffer-wiki-links ()
4041 "Refontify all wiki links in the buffer."
4042 (interactive)
4043 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4046 ;;; Following and Jumping =====================================================
4048 (defun markdown-follow-thing-at-point (arg)
4049 "Follow thing at point if possible, such as a reference link or wiki link.
4050 Opens inline and reference links in a browser. Opens wiki links
4051 to other files in the current window, or the another window if
4052 ARG is non-nil.
4053 See `markdown-follow-link-at-point' and
4054 `markdown-follow-wiki-link-at-point'."
4055 (interactive "P")
4056 (cond ((markdown-link-p)
4057 (markdown-follow-link-at-point))
4058 ((markdown-wiki-link-p)
4059 (markdown-follow-wiki-link-at-point arg))
4061 (error "Nothing to follow at point."))))
4063 (defun markdown-jump ()
4064 "Jump to another location based on context at point.
4065 Jumps between reference links and definitions; between footnote
4066 markers and footnote text."
4067 (interactive)
4068 (cond ((markdown-footnote-text-positions)
4069 (markdown-footnote-return))
4070 ((markdown-footnote-marker-positions)
4071 (markdown-footnote-goto-text))
4072 ((thing-at-point-looking-at markdown-regex-link-reference)
4073 (markdown-reference-goto-definition))
4074 ((thing-at-point-looking-at markdown-regex-reference-definition)
4075 (markdown-reference-goto-link (match-string-no-properties 1)))
4077 (error "Nothing to jump to from context at point."))))
4080 ;;; Miscellaneous =============================================================
4082 (defun markdown-compress-whitespace-string (str)
4083 "Compress whitespace in STR and return result.
4084 Leading and trailing whitespace is removed. Sequences of multiple
4085 spaces, tabs, and newlines are replaced with single spaces."
4086 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4087 (replace-regexp-in-string "[ \t\n]+" " " str)))
4089 (defun markdown-line-number-at-pos (&optional pos)
4090 "Return (narrowed) buffer line number at position POS.
4091 If POS is nil, use current buffer location.
4092 This is an exact copy of `line-number-at-pos' for use in emacs21."
4093 (let ((opoint (or pos (point))) start)
4094 (save-excursion
4095 (goto-char (point-min))
4096 (setq start (point))
4097 (goto-char opoint)
4098 (forward-line 0)
4099 (1+ (count-lines start (point))))))
4101 (defun markdown-nobreak-p ()
4102 "Return nil if it is acceptable to break the current line at the point."
4103 ;; inside in square brackets (e.g., link anchor text)
4104 (looking-back "\\[[^]]*"))
4106 (defun markdown-adaptive-fill-function ()
4107 "Return prefix for filling paragraph or nil if not determined."
4108 (cond
4109 ;; List item inside blockquote
4110 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4111 (replace-regexp-in-string
4112 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4113 ;; Blockquote
4114 ((looking-at "^[ \t]*>[ \t]*")
4115 (match-string-no-properties 0))
4116 ;; List items
4117 ((looking-at markdown-regex-list)
4118 (match-string-no-properties 0))
4119 ;; No match
4120 (t nil)))
4123 ;;; Mode Definition ==========================================================
4125 (defun markdown-show-version ()
4126 "Show the version number in the minibuffer."
4127 (interactive)
4128 (message "markdown-mode, version %s" markdown-mode-version))
4130 ;;;###autoload
4131 (define-derived-mode markdown-mode text-mode "Markdown"
4132 "Major mode for editing Markdown files."
4133 ;; Natural Markdown tab width
4134 (setq tab-width 4)
4135 ;; Comments
4136 (make-local-variable 'comment-start)
4137 (setq comment-start "<!-- ")
4138 (make-local-variable 'comment-end)
4139 (setq comment-end " -->")
4140 (make-local-variable 'comment-start-skip)
4141 (setq comment-start-skip "<!--[ \t]*")
4142 (make-local-variable 'comment-column)
4143 (setq comment-column 0)
4144 ;; Font lock.
4145 (set (make-local-variable 'font-lock-defaults)
4146 '(markdown-mode-font-lock-keywords))
4147 (set (make-local-variable 'font-lock-multiline) t)
4148 ;; For imenu support
4149 (setq imenu-create-index-function 'markdown-imenu-create-index)
4150 ;; For menu support in XEmacs
4151 (easy-menu-add markdown-mode-menu markdown-mode-map)
4152 ;; Defun movement
4153 (set (make-local-variable 'beginning-of-defun-function)
4154 'markdown-beginning-of-defun)
4155 (set (make-local-variable 'end-of-defun-function)
4156 'markdown-end-of-defun)
4157 ;; Paragraph filling
4158 (set (make-local-variable 'paragraph-start)
4159 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4160 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4161 "\\`[ \t]*>[ \t]*?\\'")
4162 (set (make-local-variable 'adaptive-fill-function)
4163 'markdown-adaptive-fill-function)
4164 ;; Outline mode
4165 (make-local-variable 'outline-regexp)
4166 (setq outline-regexp markdown-regex-header)
4167 (make-local-variable 'outline-level)
4168 (setq outline-level 'markdown-outline-level)
4169 ;; Cause use of ellipses for invisible text.
4170 (add-to-invisibility-spec '(outline . t))
4171 ;; Indentation and filling
4172 (make-local-variable 'fill-nobreak-predicate)
4173 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4174 (setq indent-line-function markdown-indent-function)
4176 ;; Prepare hooks for XEmacs compatibility
4177 (when (featurep 'xemacs)
4178 (make-local-hook 'after-change-functions)
4179 (make-local-hook 'font-lock-extend-region-functions)
4180 (make-local-hook 'window-configuration-change-hook))
4182 ;; Multiline font lock
4183 (add-hook 'font-lock-extend-region-functions
4184 'markdown-font-lock-extend-region)
4186 ;; Anytime text changes make sure it gets fontified correctly
4187 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4189 ;; If we left the buffer there is a really good chance we were
4190 ;; creating one of the wiki link documents. Make sure we get
4191 ;; refontified when we come back.
4192 (add-hook 'window-configuration-change-hook
4193 'markdown-fontify-buffer-wiki-links t t)
4195 ;; do the initial link fontification
4196 (markdown-fontify-buffer-wiki-links))
4198 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4201 ;;; GitHub Flavored Markdown Mode ============================================
4203 (defvar gfm-font-lock-keywords
4204 (append
4205 ;; GFM features to match first
4206 (list
4207 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4208 (2 markdown-language-keyword-face)
4209 (3 markdown-pre-face)
4210 (4 markdown-pre-face))))
4211 ;; Basic Markdown features (excluding possibly overridden ones)
4212 markdown-mode-font-lock-keywords-basic
4213 ;; GFM features to match last
4214 (list
4215 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4216 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4218 ;;;###autoload
4219 (define-derived-mode gfm-mode markdown-mode "GFM"
4220 "Major mode for editing GitHub Flavored Markdown files."
4221 (setq markdown-link-space-sub-char "-")
4222 (set (make-local-variable 'font-lock-defaults)
4223 '(gfm-font-lock-keywords))
4224 (auto-fill-mode 0)
4225 ;; Use visual-line-mode if available, fall back to longlines-mode:
4226 (if (fboundp 'visual-line-mode)
4227 (visual-line-mode 1)
4228 (longlines-mode 1))
4229 ;; do the initial link fontification
4230 (markdown-fontify-buffer-wiki-links))
4233 (provide 'markdown-mode)
4235 ;;; markdown-mode.el ends here