Reverse cycle command should be declated interactive
[markdown-mode.git] / markdown-mode.el
blobb561a174f52f129360568c89b150d960be9a5654
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.
128 ;; * `markdown-command-needs-filename' - by default, `markdown-mode'
129 ;; will pass the Markdown content to `markdown-command' using
130 ;; standard input (`stdin`). If `markdown-command' does not
131 ;; accept standard input, then `markdown-command-needs-filename'
132 ;; should be set to non-nil, which instructs `markdown-mode' to
133 ;; pass the name of the file as the final command-line argument.
134 ;; Note that with this option, you will only be able to run
135 ;; `markdown-command' from buffers which are visiting a file.
137 ;; * `markdown-open-command' - the command used for calling a standalone
138 ;; Markdown previewer which is capable of opening Markdown source files
139 ;; directly (default: `nil'). This command will be called
140 ;; with a single argument, the filename of the current buffer.
141 ;; A representative program is the Mac app [Marked][], a
142 ;; live-updating MultiMarkdown previewer which has a command line
143 ;; utility at `/usr/local/bin/mark`.
145 ;; * `markdown-hr-strings' - list of strings to use when inserting
146 ;; horizontal rules. Different strings will not be distinguished
147 ;; when converted to HTML--they will all be converted to
148 ;; `<hr/>`--but they may add visual distinction and style to plain
149 ;; text documents. To maintain some notion of promotion and
150 ;; demotion, keep these sorted from largest to smallest.
152 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
153 ;; underscores for bold instead of two asterisks (default: `nil').
155 ;; * `markdown-italic-underscore' - set to a non-nil value to use
156 ;; underscores for italic instead of asterisks (default: `nil').
158 ;; * `markdown-indent-function' - the function to use for automatic
159 ;; indentation (default: `markdown-indent-line').
161 ;; * `markdown-indent-on-enter' - set to a non-nil value to
162 ;; automatically indent new lines when the enter key is pressed
163 ;; (default: `t')
165 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
166 ;; to automatically open a linked document in a new buffer if the
167 ;; cursor is an wiki link
168 ;; (default: `t')
170 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
171 ;; treat aliased wiki links like `[[link text|PageName]]`.
172 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
174 ;; * `markdown-uri-types' - a list of protocols for URIs that
175 ;; `markdown-mode' should highlight.
177 ;; * `markdown-enable-math' - syntax highlighting for
178 ;; LaTeX fragments (default: `nil').
180 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
182 ;; * `markdown-content-type' - when set to a nonempty string, an
183 ;; `http-equiv` attribute will be included in the XHTML `<head>`
184 ;; block. If needed, the suggested values are
185 ;; `application/xhtml+xml` or `text/html`.
187 ;; * `markdown-coding-system' - used for specifying the character
188 ;; set identifier in the `http-equiv` attribute (see
189 ;; `markdown-content-type'). When set to `nil',
190 ;; `buffer-file-coding-system' will be used (and falling back to
191 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
192 ;; and `iso-latin-1'.
194 ;; * `markdown-xhtml-header-content' - additional content to include
195 ;; in the XHTML `<head>` block.
197 ;; * `markdown-command-needs-filename' - set to non-nil if
198 ;; `markdown-command' does not accept input from stdin (default: nil).
199 ;; Instead, it will be passed a filename as the final command-line
200 ;; argument. As a result, you will only be able to run Markdown
201 ;; from buffers which are visiting a file.
203 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
204 ;; `markdown-mode' uses to determine whether the output of
205 ;; `markdown-command' is a standalone XHTML document or an XHTML
206 ;; fragment (default: `"^\\(\<\\?xml\\|\<!DOCTYPE\\|\<html\\)"`). If
207 ;; this regular expression not matched in the first five lines of
208 ;; output, `markdown-mode' assumes the output is a fragment and
209 ;; adds a header and footer.
211 ;; * `markdown-link-space-sub-char' - a character to replace spaces
212 ;; when mapping wiki links to filenames (default: `_`).
213 ;; For example, use an underscore for compatibility with the
214 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
215 ;; with GitHub wiki links.
217 ;; Additionally, the faces used for syntax highlighting can be modified to
218 ;; your liking by issuing `M-x customize-group RET markdown-faces`
219 ;; or by using the "Markdown Faces" link at the bottom of the mode
220 ;; customization screen.
222 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
224 ;;; Usage:
226 ;; Keybindings are grouped by prefixes based on their function. For
227 ;; example, commands dealing with headers begin with `C-c C-t`. The
228 ;; primary commands in each group will are described below. You can
229 ;; obtain a list of all keybindings by pressing `C-c C-h`.
231 ;; * Anchors: `C-c C-a`
233 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
234 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
235 ;; The label definition will be placed at the end of the current
236 ;; block. `C-c C-a w` acts similarly for wiki links of the form
237 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
238 ;; text in the region is used as the link text.
240 ;; * Commands: `C-c C-c`
242 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
243 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
244 ;; runs Markdown on the current buffer and previews, stores the
245 ;; output in a temporary file, and displays the file in a browser.
246 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
247 ;; and save the result in the file `basename.html`, where
248 ;; `basename` is the name of the Markdown file with the extension
249 ;; removed. *Export and View:* press `C-c C-c v` to export the
250 ;; file and view it in a browser. **For both export commands, the
251 ;; output file will be overwritten without notice.**
252 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
253 ;; using `markdown-open-command'.
255 ;; To summarize:
257 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
258 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
259 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
260 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
261 ;; - `C-c C-c w`: `markdown-command' > kill ring.
262 ;; - `C-c C-c o`: `markdown-open-command'.
264 ;; `C-c C-c c` will check for undefined references. If there are
265 ;; any, a small buffer will open with a list of undefined
266 ;; references and the line numbers on which they appear. In Emacs
267 ;; 22 and greater, selecting a reference from this list and
268 ;; pressing `RET` will insert an empty reference definition at the
269 ;; end of the buffer. Similarly, selecting the line number will
270 ;; jump to the corresponding line.
272 ;; `C-c C-c n` will clean up the numbering of ordered lists.
274 ;; * Images: `C-c C-i`
276 ;; `C-c C-i i` inserts markup for an inline image, using the
277 ;; active region (if any) or the word at point as the alt text.
278 ;; To insert reference-style image markup, provide a `C-u` prefix.
280 ;; * Physical styles: `C-c C-p`
282 ;; These commands all act on text in the active region, if any,
283 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
284 ;; the selected text bold, `C-c C-p f` formats the region as
285 ;; fixed-width text, and `C-c C-p i` is used for italic text.
287 ;; * Logical styles: `C-c C-s`
289 ;; These commands all act on text in the active region, if any,
290 ;; and insert empty markup fragments otherwise. Logical styles
291 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
292 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
293 ;; (`C-c C-s s`).
295 ;; * Headers: `C-c C-t`
297 ;; All header commands use text in the active region, if any, as
298 ;; the header text. Otherwise, if the current line is not blank,
299 ;; use the text on the current line. Finally, prompt for header
300 ;; text if there is no active region and the current line is
301 ;; blank. To insert an atx or hash style level-n
302 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
303 ;; top-level setext or underline style header press `C-c C-t t`
304 ;; (mnemonic: title) and for a second-level underline-style header
305 ;; press `C-c C-t s` (mnemonic: section).
307 ;; If the point is at a header, these commands will replace the
308 ;; existing markup in order to update the level and/or type of the
309 ;; header. To remove the markup of the header at the point, press
310 ;; `C-c C-t 0`.
312 ;; * Footnotes: `C-c C-f`
314 ;; To create a new footnote at the point, press `C-c C-f n`.
315 ;; Press `C-c C-f g` with the point at a footnote to jump to the
316 ;; location where the footnote text is defined. Then, press
317 ;; `C-c C-f b` to return to the footnote marker in the main text.
318 ;; When the point is at a footnote marker or in the body of a
319 ;; footnote, press `C-c C-f k` to kill the footnote and add the
320 ;; text to the kill ring.
322 ;; * Other elements:
324 ;; `C-c -` inserts a horizontal rule. By default, insert the
325 ;; first string in the list `markdown-hr-strings' (the most
326 ;; prominent rule). With a `C-u` prefix, insert the last string.
327 ;; With a numeric prefix `N`, insert the string in position `N`
328 ;; (counting from 1).
330 ;; * Following Links:
332 ;; Press `C-c C-o` when the point is on an inline or reference
333 ;; link to open the URL in a browser. When the point is at a
334 ;; wiki link, open it in another buffer (in the current window,
335 ;; or in the other window with the `C-u` prefix).
336 ;; To move between links, use `M-p` and `M-n` to quickly jump
337 ;; to the previous or next link of any type.
339 ;; * Jumping:
341 ;; Use `C-c C-j` to jump from the object at point to its counterpart
342 ;; elsewhere in the text, when possible. Jumps between reference
343 ;; links and definitions; between footnote markers and footnote
344 ;; text. If more than one link uses the same reference name, a
345 ;; new buffer will be created containing clickable buttons for jumping
346 ;; to each link. You may press `TAB` or `S-TAB` to jump between
347 ;; buttons in this window.
349 ;; * Killing Elements:
351 ;; Press `C-c C-k` to kill the thing at point and add important
352 ;; text, without markup, to the kill ring. Possible things to
353 ;; kill include (roughly in order of precedece): inline code,
354 ;; headers, horizonal rules, links (add link text to kill ring),
355 ;; images (add alt text to kill ring), angle URIs, email
356 ;; addresses, bold, italics, reference definitions (add URI to
357 ;; kill ring), footnote markers and text (kill both marker and
358 ;; text, add text to kill ring), and list items.
360 ;; * Outline Navigation:
362 ;; Navigation between headings is possible using `outline-mode'.
363 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
364 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
365 ;; next and previous visible headings at the same level as the one
366 ;; at the point. Finally, `C-M-u` will move up to a lower-level
367 ;; (more inclusive) visible heading.
369 ;; * Movement by Block:
371 ;; markdown-mode supports the usual Emacs paragraph movement with
372 ;; `M-{` and `M-}`. These commands treat list items as
373 ;; paragraphs, so they will stop at each line within a block of
374 ;; list items. Additionally, markdown-mode includes movement
375 ;; commands, `M-[` and `M-]` for jumping to the beginning or end
376 ;; of an entire block of text (with blocks being separated by at
377 ;; least one blank line).
379 ;; * Movement by Defun:
381 ;; The usual Emacs commands can be used to move by defuns
382 ;; (top-level major definitions). In markdown-mode, a defun
383 ;; is a section. As usual, `C-M-a` will move the point to
384 ;; the beginning of the current or preceding defun, `C-M-e`
385 ;; will move to the end of the current or following defun,
386 ;; and `C-M-h` will put the region around the entire defun.
388 ;; Many of the commands described above behave differently depending on
389 ;; whether Transient Mark mode is enabled or not. When it makes sense,
390 ;; if Transient Mark mode is on and a region is active, the command
391 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
392 ;; bold). For users who prefer to work outside of Transient Mark mode,
393 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
395 ;; When applicable, commands that specifically act on the region even
396 ;; outside of Transient Mark mode have the same keybinding as the with
397 ;; the exception of an additional `C-` prefix. For example,
398 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
399 ;; the region in Transient Mark mode while `markdown-blockquote-region'
400 ;; is bound to `C-c C-s C-b` and always applies to the region (when
401 ;; nonempty).
403 ;; Note that these region-specific functions are useful in many
404 ;; cases where it may not be obvious. For example, yanking text from
405 ;; the kill ring sets the mark at the beginning of the yanked text
406 ;; and moves the point to the end. Therefore, the (inactive) region
407 ;; contains the yanked text. So, `C-y` then `C-c C-s C-b` will yank
408 ;; text and make it a blockquote.
410 ;; markdown-mode attempts to be flexible in how it handles
411 ;; indentation. When you press `TAB` repeatedly, the point will cycle
412 ;; through several possible indentation levels corresponding to things
413 ;; you might have in mind when you press `RET` at the end of a line or
414 ;; `TAB`. For example, you may want to start a new list item,
415 ;; continue a list item with hanging indentation, indent for a nested
416 ;; pre block, and so on.
418 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
419 ;; visibility cycling for atx- or hash-style headers. There are two
420 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
421 ;; the table of contents view (headers only), outline view (top-level
422 ;; headers only), and the full document view. Pressing `TAB` while the
423 ;; point is at a header will cycle through levels of visibility for the
424 ;; subtree: completely folded, visible children, and fully visible.
425 ;; Note that mixing hash and underline style headers will give undesired
426 ;; results.
428 ;;; Extensions:
430 ;; Besides supporting the basic Markdown syntax, markdown-mode also
431 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
432 ;; links may be followed automatically by pressing the enter key when
433 ;; your curser is on a wiki link or by pressing `C-c C-o`. The
434 ;; auto-following on enter key may be controlled with the
435 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
436 ;; `M-n` to quickly jump to the previous and next wiki links,
437 ;; respectively. Aliased or piped wiki links of the form
438 ;; `[[link text|PageName]]` are also supported. Since some wikis
439 ;; reverse these components, set `markdown-wiki-link-alias-first'
440 ;; to nil to treat them as `[[PageName|link text]]`.
442 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
443 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
444 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
445 ;; You can do this either by using `M-x customize-group markdown`
446 ;; or by placing the following in your `.emacs` file:
448 ;; (defun markdown-custom ()
449 ;; "markdown-mode-hook"
450 ;; (setq markdown-command "markdown | smartypants"))
451 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
453 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
455 ;; Syntax highlighting for mathematical expressions written
456 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
457 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
458 ;; either via customize or by placing `(setq markdown-enable-math t)`
459 ;; in `.emacs`, and then restarting Emacs or calling
460 ;; `markdown-reload-extensions'.
462 ;;; GitHub Flavored Markdown:
464 ;; A [GitHub Flavored Markdown][GFM] (GFM) mode, `gfm-mode', is also
465 ;; available. The GitHub implementation of differs slightly from
466 ;; standard Markdown. The most important differences are that
467 ;; newlines are significant, triggering hard line breaks, and that
468 ;; underscores inside of words (e.g., variable names) need not be
469 ;; escaped. As such, `gfm-mode' turns off `auto-fill-mode' and turns
470 ;; on `visual-line-mode' (or `longlines-mode' if `visual-line-mode' is
471 ;; not available). Underscores inside of words (such as
472 ;; test_variable) will not trigger emphasis.
474 ;; Wiki links in this mode will be treated as on GitHub, with hyphens
475 ;; replacing spaces in filenames and where the first letter of the
476 ;; filename capitalized. For example, `[[wiki link]]' will map to a
477 ;; file named `Wiki-link` with the same extension as the current file.
479 ;; GFM code blocks, with optional programming language keywords, will
480 ;; be highlighted. They can be inserted with `C-c C-s l`. If there
481 ;; is an active region, the text in the region will be placed inside
482 ;; the code block. You will be prompted for the name of the language,
483 ;; but may press enter to continue without naming a language.
485 ;; For a more complete GitHub-flavored markdown experience, consider
486 ;; adding README.md to your `auto-mode-alist':
488 ;; (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))
490 ;; For GFM preview can be powered by setting `markdown-command' to
491 ;; use [Docter][]. This may also be configured to work with [Marked][]
492 ;; for `markdown-open-command'.
494 ;; [GFM]: http://github.github.com/github-flavored-markdown/
495 ;; [Docter]: https://github.com/alampros/Docter
497 ;;; Acknowledgments:
499 ;; markdown-mode has benefited greatly from the efforts of the
500 ;; following people:
502 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
503 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
504 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
505 ;; GitHub Flavored Markdown mode (`gfm-mode').
506 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
507 ;; `markdown' with an active region.
508 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
509 ;; * Peter S. Galbraith <psg@debian.org> for maintaining `emacs-goodies-el`.
510 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for undefined reference checking.
511 ;; * Carsten Dominik <carsten@orgmode.org> for `org-mode', from which the
512 ;; visibility cycling functionality was derived, and for a bug fix
513 ;; related to `orgtbl-mode'.
514 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
515 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
516 ;; * Ankit Solanki <ankit.solanki@gmail.com> for `longlines.el`
517 ;; compatibility and custom CSS.
518 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
519 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
520 ;; * Nelson Minar <nelson@santafe.edu> for `html-helper-mode', from which
521 ;; comment matching functions were derived.
522 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
523 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
524 ;; functions, bug reports regarding indentation, and
525 ;; fixes for byte-compilation warnings.
526 ;; * Peter Williams <pezra@barelyenough.org> for `fill-paragraph'
527 ;; enhancements.
528 ;; * George Ogata <george.ogata@gmail.com> for fixing several
529 ;; byte-compilation warnings.
530 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
531 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
532 ;; customizations and XHTML export.
533 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
534 ;; Markdown processors which do not accept input from stdin.
535 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
536 ;; regarding the `cl` dependency and `auto-fill-mode' and indentation.
537 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
538 ;; substitution character for mapping wiki links to filenames.
539 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
540 ;; escape shell commands.
541 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
542 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
543 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
544 ;; Emacs Lisp coding conventions.
545 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `fill-paragraph'
546 ;; regexp, refactoring the compilation and preview functions,
547 ;; heading font-lock generalizations, list renumbering,
548 ;; and kill ring save.
549 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
550 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
551 ;; for an autoload token for `gfm-mode'.
552 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
553 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
554 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
555 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggesting charset
556 ;; declaration in XHTML output.
557 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart exdention function.
558 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following
559 ;; and GFM code block insertion.
560 ;; * Peter Jones <pjones@pmade.com> for link following functions.
561 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
562 ;; externally modified files.
563 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> for a bug fix
564 ;; related to `orgtbl-mode'.
565 ;; * Makoto Motohashi <mkt.motohashi@gmail.com> for before- and after-
566 ;; export hooks and unit test improvements.
567 ;; * Michael Dwyer <mdwyer@ehtech.in> for `gfm-mode' underscore regexp.
568 ;; * Chris Lott <chris@chrislott.org> for suggesting reference label
569 ;; completion.
571 ;;; Bugs:
573 ;; Although markdown-mode is developed and tested primarily using
574 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
575 ;; priority.
577 ;; If you find any bugs in markdown-mode, please construct a test case
578 ;; or a patch and email me at <jrblevin@sdf.org>.
580 ;;; History:
582 ;; markdown-mode was written and is maintained by Jason Blevins. The
583 ;; first version was released on May 24, 2007.
585 ;; * 2007-05-24: Version 1.1
586 ;; * 2007-05-25: Version 1.2
587 ;; * 2007-06-05: [Version 1.3][]
588 ;; * 2007-06-29: Version 1.4
589 ;; * 2007-10-11: [Version 1.5][]
590 ;; * 2008-06-04: [Version 1.6][]
591 ;; * 2009-10-01: [Version 1.7][]
592 ;; * 2011-08-12: [Version 1.8][]
593 ;; * 2011-08-15: [Version 1.8.1][]
594 ;; * 2013-01-25: [Version 1.9][]
596 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
597 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
598 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
599 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
600 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
601 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
602 ;; [Version 1.9]: http://jblevins.org/projects/markdown-mode/rev-1-9
605 ;;; Code:
607 (require 'easymenu)
608 (require 'outline)
609 (eval-when-compile (require 'cl))
612 ;;; Constants =================================================================
614 (defconst markdown-mode-version "2.0-pre"
615 "Markdown mode version number.")
617 (defconst markdown-output-buffer-name "*markdown-output*"
618 "Name of temporary buffer for markdown command output.")
621 ;;; Global Variables ==========================================================
623 (defvar markdown-reference-label-history nil
624 "History of used reference labels.")
627 ;;; Customizable Variables ====================================================
629 (defvar markdown-mode-hook nil
630 "Hook run when entering Markdown mode.")
632 (defvar markdown-before-export-hooks nil
633 "Hook run before output XHTML.
634 This hook is abnormal and registered functions are given an argument that is output filename.")
636 (defvar markdown-after-export-hooks nil
637 "Hook run after output XHTML.
638 This hook is abnormal and registered functions are given an argument that is output filename.")
640 (defgroup markdown nil
641 "Major mode for editing text files in Markdown format."
642 :prefix "markdown-"
643 :group 'wp
644 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
646 (defcustom markdown-command "markdown"
647 "Command to run markdown."
648 :group 'markdown
649 :type 'string)
651 (defcustom markdown-command-needs-filename nil
652 "Set to non-nil if `markdown-command' does not accept input from stdin.
653 Instead, it will be passed a filename as the final command line
654 option. As a result, you will only be able to run Markdown from
655 buffers which are visiting a file."
656 :group 'markdown
657 :type 'boolean)
659 (defcustom markdown-open-command nil
660 "Command used for opening Markdown files directly.
661 For example, a standalone Markdown previewer. This command will
662 be called with a single argument: the filename of the current
663 buffer."
664 :group 'markdown
665 :type 'string)
667 (defcustom markdown-hr-strings
668 '("-------------------------------------------------------------------------------"
669 "* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *"
670 "---------------------------------------"
671 "* * * * * * * * * * * * * * * * * * * *"
672 "---------"
673 "* * * * *")
674 "Strings to use when inserting horizontal rules.
675 The first string in the list will be the default when inserting a
676 horizontal rule. Strings should be listed in decreasing order of
677 prominence (as in headers from level one to six) for use with
678 promotion and demotion functions."
679 :group 'markdown
680 :type 'list)
682 (defcustom markdown-bold-underscore nil
683 "Use two underscores for bold instead of two asterisks."
684 :group 'markdown
685 :type 'boolean)
687 (defcustom markdown-italic-underscore nil
688 "Use underscores for italic instead of asterisks."
689 :group 'markdown
690 :type 'boolean)
692 (defcustom markdown-indent-function 'markdown-indent-line
693 "Function to use to indent."
694 :group 'markdown
695 :type 'function)
697 (defcustom markdown-indent-on-enter t
698 "Automatically indent new lines when enter key is pressed."
699 :group 'markdown
700 :type 'boolean)
702 (defcustom markdown-follow-wiki-link-on-enter t
703 "Follow wiki link at point (if any) when the enter key is pressed."
704 :group 'markdown
705 :type 'boolean)
707 (defcustom markdown-wiki-link-alias-first t
708 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
709 Otherwise, they will be treated as [[PageName|alias text]]."
710 :group 'markdown
711 :type 'boolean)
713 (defcustom markdown-uri-types
714 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
715 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
716 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
717 "Link types for syntax highlighting of URIs."
718 :group 'markdown
719 :type 'list)
721 (defcustom markdown-enable-math nil
722 "Syntax highlighting for inline LaTeX and itex expressions.
723 Set this to a non-nil value to turn on math support by default.
724 Math support can be toggled later using `markdown-enable-math'
725 or \\[markdown-enable-math]."
726 :group 'markdown
727 :type 'boolean
728 :safe 'booleanp)
730 (defcustom markdown-css-path ""
731 "URL of CSS file to link to in the output XHTML."
732 :group 'markdown
733 :type 'string)
735 (defcustom markdown-content-type ""
736 "Content type string for the http-equiv header in XHTML output.
737 When set to a non-empty string, insert the http-equiv attribute.
738 Otherwise, this attribute is omitted."
739 :group 'markdown
740 :type 'string)
742 (defcustom markdown-coding-system nil
743 "Character set string for the http-equiv header in XHTML output.
744 Defaults to `buffer-file-coding-system' (and falling back to
745 `iso-8859-1' when not available). Common settings are `utf-8'
746 and `iso-latin-1'. Use `list-coding-systems' for more choices."
747 :group 'markdown
748 :type 'coding-system)
750 (defcustom markdown-xhtml-header-content ""
751 "Additional content to include in the XHTML <head> block."
752 :group 'markdown
753 :type 'string)
755 (defcustom markdown-xhtml-standalone-regexp
756 "^\\(<\\?xml\\|<!DOCTYPE\\|<html\\)"
757 "Regexp indicating whether `markdown-command' output is standalone XHTML."
758 :group 'markdown
759 :type 'regexp)
761 (defcustom markdown-link-space-sub-char
763 "Character to use instead of spaces when mapping wiki links to filenames."
764 :group 'markdown
765 :type 'string)
767 (defcustom markdown-reference-location 'header
768 "Position where new reference definitions are inserted in the document."
769 :group 'markdown
770 :type '(choice (const :tag "At the end of the document" end)
771 (const :tag "Immediately after the current block" immediately)
772 (const :tag "Before next header" header)))
774 (defcustom markdown-footnote-location 'end
775 "Position where new footnotes are inserted in the document."
776 :group 'markdown
777 :type '(choice (const :tag "At the end of the document" end)
778 (const :tag "Immediately after the current block" immediately)
779 (const :tag "Before next header" header)))
782 ;;; Font Lock =================================================================
784 (require 'font-lock)
786 (defvar markdown-italic-face 'markdown-italic-face
787 "Face name to use for italic text.")
789 (defvar markdown-bold-face 'markdown-bold-face
790 "Face name to use for bold text.")
792 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
793 "Face name to use as a base for header delimiters.")
795 (defvar markdown-header-rule-face 'markdown-header-rule-face
796 "Face name to use as a base for header rules.")
798 (defvar markdown-header-face 'markdown-header-face
799 "Face name to use as a base for headers.")
801 (defvar markdown-header-face-1 'markdown-header-face-1
802 "Face name to use for level-1 headers.")
804 (defvar markdown-header-face-2 'markdown-header-face-2
805 "Face name to use for level-2 headers.")
807 (defvar markdown-header-face-3 'markdown-header-face-3
808 "Face name to use for level-3 headers.")
810 (defvar markdown-header-face-4 'markdown-header-face-4
811 "Face name to use for level-4 headers.")
813 (defvar markdown-header-face-5 'markdown-header-face-5
814 "Face name to use for level-5 headers.")
816 (defvar markdown-header-face-6 'markdown-header-face-6
817 "Face name to use for level-6 headers.")
819 (defvar markdown-inline-code-face 'markdown-inline-code-face
820 "Face name to use for inline code.")
822 (defvar markdown-list-face 'markdown-list-face
823 "Face name to use for list markers.")
825 (defvar markdown-blockquote-face 'markdown-blockquote-face
826 "Face name to use for blockquote.")
828 (defvar markdown-pre-face 'markdown-pre-face
829 "Face name to use for preformatted text.")
831 (defvar markdown-language-keyword-face 'markdown-language-keyword-face
832 "Face name to use for programming language identifiers.")
834 (defvar markdown-link-face 'markdown-link-face
835 "Face name to use for links.")
837 (defvar markdown-missing-link-face 'markdown-missing-link-face
838 "Face name to use for links where the linked file does not exist.")
840 (defvar markdown-reference-face 'markdown-reference-face
841 "Face name to use for reference.")
843 (defvar markdown-footnote-face 'markdown-footnote-face
844 "Face name to use for footnote identifiers.")
846 (defvar markdown-url-face 'markdown-url-face
847 "Face name to use for URLs.")
849 (defvar markdown-link-title-face 'markdown-link-title-face
850 "Face name to use for reference link titles.")
852 (defvar markdown-line-break-face 'markdown-line-break-face
853 "Face name to use for hard line breaks.")
855 (defvar markdown-comment-face 'markdown-comment-face
856 "Face name to use for HTML comments.")
858 (defvar markdown-math-face 'markdown-math-face
859 "Face name to use for LaTeX expressions.")
861 (defvar markdown-metadata-key-face 'markdown-metadata-key-face
862 "Face name to use for metadata keys.")
864 (defvar markdown-metadata-value-face 'markdown-metadata-value-face
865 "Face name to use for metadata values.")
867 (defgroup markdown-faces nil
868 "Faces used in Markdown Mode"
869 :group 'markdown
870 :group 'faces)
872 (defface markdown-italic-face
873 '((t (:inherit font-lock-variable-name-face :slant italic)))
874 "Face for italic text."
875 :group 'markdown-faces)
877 (defface markdown-bold-face
878 '((t (:inherit font-lock-variable-name-face :weight bold)))
879 "Face for bold text."
880 :group 'markdown-faces)
882 (defface markdown-header-rule-face
883 '((t (:inherit font-lock-function-name-face :weight bold)))
884 "Base face for headers rules."
885 :group 'markdown-faces)
887 (defface markdown-header-delimiter-face
888 '((t (:inherit font-lock-function-name-face :weight bold)))
889 "Base face for headers hash delimiter."
890 :group 'markdown-faces)
892 (defface markdown-header-face
893 '((t (:inherit font-lock-function-name-face :weight bold)))
894 "Base face for headers."
895 :group 'markdown-faces)
897 (defface markdown-header-face-1
898 '((t (:inherit markdown-header-face)))
899 "Face for level-1 headers."
900 :group 'markdown-faces)
902 (defface markdown-header-face-2
903 '((t (:inherit markdown-header-face)))
904 "Face for level-2 headers."
905 :group 'markdown-faces)
907 (defface markdown-header-face-3
908 '((t (:inherit markdown-header-face)))
909 "Face for level-3 headers."
910 :group 'markdown-faces)
912 (defface markdown-header-face-4
913 '((t (:inherit markdown-header-face)))
914 "Face for level-4 headers."
915 :group 'markdown-faces)
917 (defface markdown-header-face-5
918 '((t (:inherit markdown-header-face)))
919 "Face for level-5 headers."
920 :group 'markdown-faces)
922 (defface markdown-header-face-6
923 '((t (:inherit markdown-header-face)))
924 "Face for level-6 headers."
925 :group 'markdown-faces)
927 (defface markdown-inline-code-face
928 '((t (:inherit font-lock-constant-face)))
929 "Face for inline code."
930 :group 'markdown-faces)
932 (defface markdown-list-face
933 '((t (:inherit font-lock-builtin-face)))
934 "Face for list item markers."
935 :group 'markdown-faces)
937 (defface markdown-blockquote-face
938 '((t (:inherit font-lock-doc-face)))
939 "Face for blockquote sections."
940 :group 'markdown-faces)
942 (defface markdown-pre-face
943 '((t (:inherit font-lock-constant-face)))
944 "Face for preformatted text."
945 :group 'markdown-faces)
947 (defface markdown-language-keyword-face
948 '((t (:inherit font-lock-type-face)))
949 "Face for programming language identifiers."
950 :group 'markdown-faces)
952 (defface markdown-link-face
953 '((t (:inherit font-lock-keyword-face)))
954 "Face for links."
955 :group 'markdown-faces)
957 (defface markdown-missing-link-face
958 '((t (:inherit font-lock-warning-face)))
959 "Face for missing links."
960 :group 'markdown-faces)
962 (defface markdown-reference-face
963 '((t (:inherit font-lock-type-face)))
964 "Face for link references."
965 :group 'markdown-faces)
967 (defface markdown-footnote-face
968 '((t (:inherit font-lock-keyword-face)))
969 "Face for footnote markers."
970 :group 'markdown-faces)
972 (defface markdown-url-face
973 '((t (:inherit font-lock-string-face)))
974 "Face for URLs."
975 :group 'markdown-faces)
977 (defface markdown-link-title-face
978 '((t (:inherit font-lock-comment-face)))
979 "Face for reference link titles."
980 :group 'markdown-faces)
982 (defface markdown-line-break-face
983 '((t (:inherit font-lock-constant-face :underline t)))
984 "Face for hard line breaks."
985 :group 'markdown-faces)
987 (defface markdown-comment-face
988 '((t (:inherit font-lock-comment-face)))
989 "Face for HTML comments."
990 :group 'markdown-faces)
992 (defface markdown-math-face
993 '((t (:inherit font-lock-string-face)))
994 "Face for LaTeX expressions."
995 :group 'markdown-faces)
997 (defface markdown-metadata-key-face
998 '((t (:inherit font-lock-variable-name-face)))
999 "Face for metadata keys."
1000 :group 'markdown-faces)
1002 (defface markdown-metadata-value-face
1003 '((t (:inherit font-lock-string-face)))
1004 "Face for metadata values."
1005 :group 'markdown-faces)
1007 (defconst markdown-regex-link-inline
1008 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)\\((\\([^)]*?\\)\\(?:\\s-+\\(\"[^\"]*\"\\)\\)?)\\)"
1009 "Regular expression for a [text](file) or an image link ![text](file).
1010 Group 1 matches the leading exclamation point, if any.
1011 Group 2 matchs the entire square bracket term, including the text.
1012 Group 3 matches the text inside the square brackets.
1013 Group 4 matches the entire parenthesis term, including the URL and title.
1014 Group 5 matches the URL.
1015 Group 6 matches (optional) title.")
1017 (defconst markdown-regex-link-reference
1018 "\\(!\\)?\\(\\[\\([^]^][^]]*\\|\\)\\]\\)[ ]?\\(\\[\\([^]]*?\\)\\]\\)"
1019 "Regular expression for a reference link [text][id].
1020 Group 1 matches the leading exclamation point, if any.
1021 Group 2 matchs the entire first square bracket term, including the text.
1022 Group 3 matches the text inside the square brackets.
1023 Group 4 matches the entire second square bracket term.
1024 Group 5 matches the reference label.")
1026 (defconst markdown-regex-reference-definition
1027 "^ \\{0,3\\}\\(\\[[^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
1028 "Regular expression for a link definition [id]: ...")
1030 (defconst markdown-regex-footnote
1031 "\\(\\[\\^.+?\\]\\)"
1032 "Regular expression for a footnote marker [^fn].")
1034 (defconst markdown-regex-header
1035 "^\\(?:\\(.+\\)\n\\(=+\\)\\|\\(.+\\)\n\\(-+\\)\\|\\(#+\\)\\s-*\\(.*?\\)\\s-*?\\(#*\\)\\)$"
1036 "Regexp identifying Markdown headers.")
1038 (defconst markdown-regex-header-1-atx
1039 "^\\(#\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1040 "Regular expression for level 1 atx-style (hash mark) headers.")
1042 (defconst markdown-regex-header-2-atx
1043 "^\\(##\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1044 "Regular expression for level 2 atx-style (hash mark) headers.")
1046 (defconst markdown-regex-header-3-atx
1047 "^\\(###\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1048 "Regular expression for level 3 atx-style (hash mark) headers.")
1050 (defconst markdown-regex-header-4-atx
1051 "^\\(####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1052 "Regular expression for level 4 atx-style (hash mark) headers.")
1054 (defconst markdown-regex-header-5-atx
1055 "^\\(#####\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1056 "Regular expression for level 5 atx-style (hash mark) headers.")
1058 (defconst markdown-regex-header-6-atx
1059 "^\\(######\\)[ \t]*\\(.+?\\)[ \t]*\\(#*\\)$"
1060 "Regular expression for level 6 atx-style (hash mark) headers.")
1062 (defconst markdown-regex-header-1-setext
1063 "^\\(.*\\)\n\\(=+\\)$"
1064 "Regular expression for level 1 setext-style (underline) headers.")
1066 (defconst markdown-regex-header-2-setext
1067 "^\\(.*\\)\n\\(-+\\)$"
1068 "Regular expression for level 2 setext-style (underline) headers.")
1070 (defconst markdown-regex-header-setext
1071 "^\\(.+\\)\n\\(\\(?:=\\|-\\)+\\)$"
1072 "Regular expression for generic setext-style (underline) headers.")
1074 (defconst markdown-regex-header-atx
1075 "^\\(#+\\)[ \t]*\\(.*?\\)[ \t]*\\(#*\\)$"
1076 "Regular expression for generic atx-style (hash mark) headers.")
1078 (defconst markdown-regex-hr
1079 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
1080 "Regular expression for matching Markdown horizontal rules.")
1082 (defconst markdown-regex-code
1083 "\\(\\`\\|[^\\]\\)\\(\\(`+\\)\\(\\(.\\|\n[^\n]\\)*?[^`]\\)\\3\\)\\([^`]\\|\\'\\)"
1084 "Regular expression for matching inline code fragments.
1086 The first group ensures that the leading backquote character
1087 is not escaped. The group \\(.\\|\n[^\n]\\) matches any
1088 character, including newlines, but not two newlines in a row.
1089 The final group requires that the character following the code
1090 fragment is not a backquote.")
1092 (defconst markdown-regex-pre
1093 "^\\( \\|\t\\).*$"
1094 "Regular expression for matching preformatted text sections.")
1096 (defconst markdown-regex-list
1097 "^\\([ \t]*\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\([ \t]+\\)"
1098 "Regular expression for matching list items.")
1100 (defconst markdown-regex-bold
1101 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1102 "Regular expression for matching bold text.
1103 Group 1 matches the character before the opening asterisk or
1104 underscore, if any, ensuring that it is not a backslash escape.
1105 Group 2 matches the entire expression, including delimiters.
1106 Groups 3 and 5 matches the opening and closing delimiters.
1107 Group 4 matches the text inside the delimiters.")
1109 (defconst markdown-regex-italic
1110 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \n\t\\]\\|[^ \n\t]\\(?:.\\|\n[^\n]\\)*?[^\\ ]\\)\\(\\3\\)\\)"
1111 "Regular expression for matching italic text.
1112 Group 1 matches the character before the opening asterisk or
1113 underscore, if any, ensuring that it is not a backslash escape.
1114 Group 2 matches the entire expression, including delimiters.
1115 Groups 3 and 5 matches the opening and closing delimiters.
1116 Group 4 matches the text inside the delimiters.")
1118 (defconst markdown-regex-gfm-italic
1119 "\\(^\\|\\s-\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
1120 "Regular expression for matching italic text in GitHub-flavored Markdown.
1121 Underscores in words are not treated as special.")
1123 (defconst markdown-regex-blockquote
1124 "^[ \t]*\\(>\\).*$"
1125 "Regular expression for matching blockquote lines.")
1127 (defconst markdown-regex-line-break
1128 "[^ \n\t][ \t]*\\( \\)$"
1129 "Regular expression for matching line breaks.")
1131 (defconst markdown-regex-wiki-link
1132 "\\(?:^\\|[^\\]\\)\\(\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]\\)"
1133 "Regular expression for matching wiki links.
1134 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
1135 wiki links of the form [[PageName|link text]]. In this regular
1136 expression, group 1 matches the entire link, including square
1137 brackets, group 2 matches the first component of the wiki link
1138 and group 4 matches the second component, after the pipe, when
1139 present. The meanings of the first and second components depend
1140 on the value of `markdown-wiki-link-alias-first'.")
1142 (defconst markdown-regex-uri
1143 (concat (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;() ]+")
1144 "Regular expression for matching inline URIs.")
1146 (defconst markdown-regex-angle-uri
1147 (concat "\\(<\\)\\(" (regexp-opt markdown-uri-types) ":[^]\t\n\r<>,;()]+\\)\\(>\\)")
1148 "Regular expression for matching inline URIs in angle brackets.")
1150 (defconst markdown-regex-email
1151 "<\\(\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+\\)>"
1152 "Regular expression for matching inline email addresses.")
1154 (defconst markdown-regex-link-generic
1155 (concat "\\(?:" markdown-regex-wiki-link
1156 "\\|" markdown-regex-link-inline
1157 "\\|" markdown-regex-link-reference
1158 "\\|" markdown-regex-angle-uri "\\)")
1159 "Regular expression for matching any recognized link.")
1161 (defconst markdown-regex-block-separator
1162 "\\(\\`\\|\\(\n[ \t]*\n\\)[^\n \t]\\)"
1163 "Regular expression for matching block boundaries.")
1165 (defconst markdown-regex-math-inline
1166 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
1167 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
1169 (defconst markdown-regex-math-display
1170 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
1171 "Regular expression for itex \[..\] display mode expressions.")
1173 (defconst markdown-regex-multimarkdown-metadata
1174 "^\\([[:alpha:]][[:alpha:] _-]*?\\):[ \t]*\\(.*\\)$"
1175 "Regular expression for matching MultiMarkdown metadata.")
1177 (defconst markdown-regex-pandoc-metadata
1178 "^\\(%\\)[ \t]*\\(.*\\)$"
1179 "Regular expression for matching Pandoc metadata.")
1181 (defvar markdown-mode-font-lock-keywords-basic
1182 (list
1183 (cons 'markdown-match-pre-blocks '((0 markdown-pre-face)))
1184 (cons 'markdown-match-fenced-code-blocks '((0 markdown-pre-face)))
1185 (cons markdown-regex-blockquote 'markdown-blockquote-face)
1186 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
1187 (2 markdown-header-rule-face)))
1188 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
1189 (2 markdown-header-rule-face)))
1190 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
1191 (2 markdown-header-face-6)
1192 (3 markdown-header-delimiter-face)))
1193 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
1194 (2 markdown-header-face-5)
1195 (3 markdown-header-delimiter-face)))
1196 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
1197 (2 markdown-header-face-4)
1198 (3 markdown-header-delimiter-face)))
1199 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
1200 (2 markdown-header-face-3)
1201 (3 markdown-header-delimiter-face)))
1202 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
1203 (2 markdown-header-face-2)
1204 (3 markdown-header-delimiter-face)))
1205 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
1206 (2 markdown-header-face-1)
1207 (3 markdown-header-delimiter-face)))
1208 (cons 'markdown-match-multimarkdown-metadata '((1 markdown-metadata-key-face)
1209 (2 markdown-metadata-value-face)))
1210 (cons 'markdown-match-pandoc-metadata '((1 markdown-comment-face)
1211 (2 markdown-metadata-value-face)))
1212 (cons markdown-regex-hr 'markdown-header-face)
1213 (cons 'markdown-match-comments '((0 markdown-comment-face)))
1214 (cons 'markdown-match-code '((0 markdown-inline-code-face)))
1215 (cons markdown-regex-angle-uri 'markdown-link-face)
1216 (cons markdown-regex-uri 'markdown-link-face)
1217 (cons markdown-regex-email 'markdown-link-face)
1218 (cons markdown-regex-list '(2 markdown-list-face))
1219 (cons markdown-regex-footnote 'markdown-footnote-face)
1220 (cons markdown-regex-link-inline '((1 markdown-link-face t t)
1221 (2 markdown-link-face t)
1222 (4 markdown-url-face t)
1223 (6 markdown-link-title-face t t)))
1224 (cons markdown-regex-link-reference '((1 markdown-link-face t t)
1225 (2 markdown-link-face t)
1226 (4 markdown-reference-face t)))
1227 (cons markdown-regex-reference-definition '((1 markdown-reference-face t)
1228 (2 markdown-url-face t)
1229 (3 markdown-link-title-face t)))
1230 (cons markdown-regex-bold '(2 markdown-bold-face))
1231 (cons markdown-regex-line-break '(1 markdown-line-break-face prepend))
1233 "Syntax highlighting for Markdown files.")
1235 (defvar markdown-mode-font-lock-keywords-core
1236 (list
1237 (cons markdown-regex-italic '(2 markdown-italic-face))
1239 "Additional syntax highlighting for Markdown files.
1240 Includes features which are overridden by some variants.")
1242 (defconst markdown-mode-font-lock-keywords-math
1243 (list
1244 ;; Math mode $..$ or $$..$$
1245 (cons markdown-regex-math-inline '(2 markdown-math-face))
1246 ;; Display mode equations with brackets: \[ \]
1247 (cons markdown-regex-math-display 'markdown-math-face)
1248 ;; Equation reference (eq:foo)
1249 (cons "(eq:[[:alnum:]:_]+)" 'markdown-reference-face)
1250 ;; Equation reference \eqref{foo}
1251 (cons "\\\\eqref{[[:alnum:]:_]+}" 'markdown-reference-face))
1252 "Syntax highlighting for LaTeX and itex fragments.")
1254 (defvar markdown-mode-font-lock-keywords nil
1255 "Default highlighting expressions for Markdown mode.
1256 This variable is defined as a buffer-local variable for dynamic
1257 extension support.")
1259 ;; Footnotes
1260 (defvar markdown-footnote-counter 0
1261 "Counter for footnote numbers.")
1262 (make-variable-buffer-local 'markdown-footnote-counter)
1264 (defconst markdown-footnote-chars
1265 "[[:alnum:]-]"
1266 "Regular expression maching any character that is allowed in a footnote identifier.")
1269 ;;; Compatibility =============================================================
1271 (defun markdown-replace-regexp-in-string (regexp rep string)
1272 "Replace ocurrences of REGEXP with REP in STRING.
1273 This is a compatibility wrapper to provide `replace-regexp-in-string'
1274 in XEmacs 21."
1275 (if (featurep 'xemacs)
1276 (replace-in-string string regexp rep)
1277 (replace-regexp-in-string regexp rep string)))
1279 ;; `markdown-use-region-p' is a compatibility function which checks
1280 ;; for an active region, with fallbacks for older Emacsen and XEmacs.
1281 (eval-and-compile
1282 (cond
1283 ;; Emacs 23 and newer
1284 ((fboundp 'use-region-p)
1285 (defalias 'markdown-use-region-p 'use-region-p))
1286 ;; Older Emacsen
1287 ((and (boundp 'transient-mark-mode) (boundp 'mark-active))
1288 (defun markdown-use-region-p ()
1289 "Compatibility wrapper to provide `use-region-p'."
1290 (and transient-mark-mode mark-active)))
1291 ;; XEmacs
1292 ((fboundp 'region-active-p)
1293 (defalias 'markdown-use-region-p 'region-active-p))))
1295 (defun markdown-use-buttons-p ()
1296 "Determine whether this Emacs supports buttons."
1297 (or (featurep 'button) (locate-library "button")))
1300 ;;; Markdown Parsing Functions ================================================
1302 (defun markdown-cur-line-blank-p ()
1303 "Return t if the current line is blank and nil otherwise."
1304 (save-excursion
1305 (beginning-of-line)
1306 (re-search-forward "^\\s *$" (line-end-position) t)))
1308 (defun markdown-prev-line-blank-p ()
1309 "Return t if the previous line is blank and nil otherwise.
1310 If we are at the first line, then consider the previous line to be blank."
1311 (or (= (line-beginning-position) (point-min))
1312 (save-excursion
1313 (forward-line -1)
1314 (markdown-cur-line-blank-p))))
1316 (defun markdown-next-line-blank-p ()
1317 "Return t if the next line is blank and nil otherwise.
1318 If we are at the last line, then consider the next line to be blank."
1319 (or (= (line-end-position) (point-max))
1320 (save-excursion
1321 (forward-line 1)
1322 (markdown-cur-line-blank-p))))
1324 (defun markdown-prev-line-indent-p ()
1325 "Return t if the previous line is indented and nil otherwise."
1326 (save-excursion
1327 (forward-line -1)
1328 (goto-char (line-beginning-position))
1329 (if (re-search-forward "^\\s " (line-end-position) t) t)))
1331 (defun markdown-cur-line-indent ()
1332 "Return the number of leading whitespace characters in the current line."
1333 (save-match-data
1334 (save-excursion
1335 (goto-char (line-beginning-position))
1336 (re-search-forward "^[ \t]+" (line-end-position) t)
1337 (current-column))))
1339 (defun markdown-prev-line-indent ()
1340 "Return the number of leading whitespace characters in the previous line."
1341 (save-excursion
1342 (forward-line -1)
1343 (markdown-cur-line-indent)))
1345 (defun markdown-next-line-indent ()
1346 "Return the number of leading whitespace characters in the next line."
1347 (save-excursion
1348 (forward-line 1)
1349 (markdown-cur-line-indent)))
1351 (defun markdown-cur-non-list-indent ()
1352 "Return beginning position of list item text (not including the list marker).
1353 Return nil if the current line is not the beginning of a list item."
1354 (save-match-data
1355 (save-excursion
1356 (beginning-of-line)
1357 (when (re-search-forward markdown-regex-list (line-end-position) t)
1358 (current-column)))))
1360 (defun markdown-prev-non-list-indent ()
1361 "Return position of the first non-list-marker on the previous line."
1362 (save-excursion
1363 (forward-line -1)
1364 (markdown-cur-non-list-indent)))
1366 (defun markdown-new-baseline-p ()
1367 "Determine if the current line begins a new baseline level."
1368 (save-excursion
1369 (beginning-of-line)
1370 (save-match-data
1371 (or (looking-at markdown-regex-header)
1372 (looking-at markdown-regex-hr)
1373 (and (null (markdown-cur-non-list-indent))
1374 (= (markdown-cur-line-indent) 0)
1375 (markdown-prev-line-blank-p))))))
1377 (defun markdown-search-backward-baseline ()
1378 "Search backward baseline point with no indentation and not a list item."
1379 (end-of-line)
1380 (let (stop)
1381 (while (not (or stop (bobp)))
1382 (re-search-backward markdown-regex-block-separator nil t)
1383 (when (match-end 2)
1384 (goto-char (match-end 2))
1385 (cond
1386 ((markdown-new-baseline-p)
1387 (setq stop t))
1388 ((looking-at markdown-regex-list)
1389 (setq stop nil))
1390 (t (setq stop t)))))))
1392 (defun markdown-update-list-levels (marker indent levels)
1393 "Update list levels given list MARKER, block INDENT, and current LEVELS.
1394 Here, MARKER is a string representing the type of list, INDENT is an integer
1395 giving the indentation, in spaces, of the current block, and LEVELS is a
1396 list of the indentation levels of parent list items. When LEVELS is nil,
1397 it means we are at baseline (not inside of a nested list)."
1398 (cond
1399 ;; New list item at baseline.
1400 ((and marker (null levels))
1401 (setq levels (list indent)))
1402 ;; List item with greater indentation (four or more spaces).
1403 ;; Increase list level.
1404 ((and marker (>= indent (+ (car levels) 4)))
1405 (setq levels (cons indent levels)))
1406 ;; List item with greater or equal indentation (less than four spaces).
1407 ;; Do not increase list level.
1408 ((and marker (>= indent (car levels)))
1409 levels)
1410 ;; Lesser indentation level.
1411 ;; Pop appropriate number of elements off LEVELS list (e.g., lesser
1412 ;; indentation could move back more than one list level). Note
1413 ;; that this block need not be the beginning of list item.
1414 ((< indent (car levels))
1415 (while (and (> (length levels) 1)
1416 (< indent (+ (cadr levels) 4)))
1417 (setq levels (cdr levels)))
1418 levels)
1419 ;; Otherwise, do nothing.
1420 (t levels)))
1422 (defun markdown-calculate-list-levels ()
1423 "Calculate list levels at point.
1424 Return a list of the form (n1 n2 n3 ...) where n1 is the
1425 indentation of the deepest nested list item in the branch of
1426 the list at the point, n2 is the indentation of the parent
1427 list item, and so on. The depth of the list item is therefore
1428 the length of the returned list. If the point is not at or
1429 immediately after a list item, return nil."
1430 (save-excursion
1431 (let ((first (point)) levels indent pre-regexp)
1432 ;; Find a baseline point with zero list indentation
1433 (markdown-search-backward-baseline)
1434 ;; Search for all list items between baseline and LOC
1435 (while (and (< (point) first)
1436 (re-search-forward markdown-regex-list first t))
1437 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" (1+ (length levels))))
1438 (beginning-of-line)
1439 (cond
1440 ;; Make sure this is not a header or hr
1441 ((markdown-new-baseline-p) (setq levels nil))
1442 ;; Make sure this is not a line from a pre block
1443 ((looking-at pre-regexp))
1444 ;; If not, then update levels
1446 (setq indent (markdown-cur-line-indent))
1447 (setq levels (markdown-update-list-levels (match-string 2)
1448 indent levels))))
1449 (end-of-line))
1450 levels)))
1452 (defun markdown-prev-list-item (level)
1453 "Search backward from point for a list item with indentation LEVEL.
1454 Set point to the beginning of the item, and return point, or nil
1455 upon failure."
1456 (let (bounds indent prev)
1457 (setq prev (point))
1458 (forward-line -1)
1459 (setq indent (markdown-cur-line-indent))
1460 (while
1461 (cond
1462 ;; Stop at beginning of buffer
1463 ((bobp) (setq prev nil))
1464 ;; Continue if current line is blank
1465 ((markdown-cur-line-blank-p) t)
1466 ;; List item
1467 ((and (looking-at markdown-regex-list)
1468 (setq bounds (markdown-cur-list-item-bounds)))
1469 (cond
1470 ;; Continue at item with greater indentation
1471 ((> (nth 3 bounds) level) t)
1472 ;; Stop and return point at item of equal indentation
1473 ((= (nth 3 bounds) level)
1474 (setq prev (point))
1475 nil)
1476 ;; Stop and return nil at item with lesser indentation
1477 ((< (nth 3 bounds) level)
1478 (setq prev nil)
1479 nil)))
1480 ;; Continue while indentation is the same or greater
1481 ((>= indent level) t)
1482 ;; Stop if current indentation is less than list item
1483 ;; and the next is blank
1484 ((and (< indent level)
1485 (markdown-next-line-blank-p))
1486 (setq prev nil))
1487 ;; Stop at a header
1488 ((looking-at markdown-regex-header) (setq prev nil))
1489 ;; Stop at a horizontal rule
1490 ((looking-at markdown-regex-hr) (setq prev nil))
1491 ;; Otherwise, continue.
1492 (t t))
1493 (forward-line -1)
1494 (setq indent (markdown-cur-line-indent)))
1495 prev))
1497 (defun markdown-next-list-item (level)
1498 "Search forward from point for the next list item with indentation LEVEL.
1499 Set point to the beginning of the item, and return point, or nil
1500 upon failure."
1501 (let (bounds indent prev next)
1502 (setq next (point))
1503 (forward-line)
1504 (setq indent (markdown-cur-line-indent))
1505 (while
1506 (cond
1507 ;; Stop at end of the buffer.
1508 ((eobp) (setq prev nil))
1509 ;; Continue if the current line is blank
1510 ((markdown-cur-line-blank-p) t)
1511 ;; List item
1512 ((and (looking-at markdown-regex-list)
1513 (setq bounds (markdown-cur-list-item-bounds)))
1514 (cond
1515 ;; Continue at item with greater indentation
1516 ((> (nth 3 bounds) level) t)
1517 ;; Stop and return point at item of equal indentation
1518 ((= (nth 3 bounds) level)
1519 (setq next (point))
1520 nil)
1521 ;; Stop and return nil at item with lesser indentation
1522 ((< (nth 3 bounds) level)
1523 (setq next nil)
1524 nil)))
1525 ;; Continue while indentation is the same or greater
1526 ((>= indent level) t)
1527 ;; Stop if current indentation is less than list item
1528 ;; and the previous line was blank.
1529 ((and (< indent level)
1530 (markdown-prev-line-blank-p))
1531 (setq next nil))
1532 ;; Stop at a header
1533 ((looking-at markdown-regex-header) (setq next nil))
1534 ;; Stop at a horizontal rule
1535 ((looking-at markdown-regex-hr) (setq next nil))
1536 ;; Otherwise, continue.
1537 (t t))
1538 (forward-line)
1539 (setq indent (markdown-cur-line-indent)))
1540 next))
1542 (defun markdown-cur-list-item-end (level)
1543 "Move to the end of the current list item with nonlist indentation LEVEL.
1544 If the point is not in a list item, do nothing."
1545 (let (indent)
1546 (forward-line)
1547 (setq indent (markdown-cur-line-indent))
1548 (while
1549 (cond
1550 ;; Stop at end of the buffer.
1551 ((eobp) nil)
1552 ;; Continue if the current line is blank
1553 ((markdown-cur-line-blank-p) t)
1554 ;; Continue while indentation is the same or greater
1555 ((>= indent level) t)
1556 ;; Stop if current indentation is less than list item
1557 ;; and the previous line was blank.
1558 ((and (< indent level)
1559 (markdown-prev-line-blank-p))
1560 nil)
1561 ;; Stop at a new list item of the same or lesser indentation
1562 ((looking-at markdown-regex-list) nil)
1563 ;; Stop at a header
1564 ((looking-at markdown-regex-header) nil)
1565 ;; Stop at a horizontal rule
1566 ((looking-at markdown-regex-hr) nil)
1567 ;; Otherwise, continue.
1568 (t t))
1569 (forward-line)
1570 (setq indent (markdown-cur-line-indent)))
1571 ;; Don't skip over whitespace for empty list items (marker and
1572 ;; whitespace only), just move to end of whitespace.
1573 (if (looking-back (concat markdown-regex-list "\\s-*"))
1574 (goto-char (match-end 3))
1575 (skip-syntax-backward "-"))))
1577 (defun markdown-cur-list-item-bounds ()
1578 "Return bounds and indentation of the current list item.
1579 Return a list of the form (begin end indent nonlist-indent marker).
1580 If the point is not inside a list item, return nil.
1581 Leave match data intact for `markdown-regex-list'."
1582 (let (cur prev-begin prev-end indent nonlist-indent marker)
1583 ;; Store current location
1584 (setq cur (point))
1585 ;; Verify that cur is between beginning and end of item
1586 (save-excursion
1587 (end-of-line)
1588 (when (re-search-backward markdown-regex-list nil t)
1589 (setq prev-begin (match-beginning 0))
1590 (setq indent (length (match-string 1)))
1591 (setq nonlist-indent (length (match-string 0)))
1592 (setq marker (concat (match-string 2) (match-string 3)))
1593 (save-match-data
1594 (markdown-cur-list-item-end nonlist-indent)
1595 (setq prev-end (point)))
1596 (when (and (>= cur prev-begin)
1597 (<= cur prev-end)
1598 nonlist-indent)
1599 (list prev-begin prev-end indent nonlist-indent marker))))))
1601 (defun markdown-bounds-of-thing-at-point (thing)
1602 "Call `bounds-of-thing-at-point' for THING with slight modifications.
1603 Does not include trailing newlines when THING is 'line. Handles the
1604 end of buffer case by setting both endpoints equal to the value of
1605 `point-max', since an empty region will trigger empty markup insertion.
1606 Return bounds of form (beg . end) if THING is found, or nil otherwise."
1607 (let* ((bounds (bounds-of-thing-at-point thing))
1608 (a (car bounds))
1609 (b (cdr bounds)))
1610 (when bounds
1611 (when (eq thing 'line)
1612 (cond ((and (eobp) (markdown-cur-line-blank-p))
1613 (setq a b))
1614 ((char-equal (char-before b) ?\^J)
1615 (setq b (1- b)))))
1616 (cons a b))))
1618 (defun markdown-reference-definition (reference)
1619 "Find out whether Markdown REFERENCE is defined.
1620 REFERENCE should include the square brackets, like [this].
1621 When REFERENCE is defined, return a list of the form (text start end)
1622 containing the definition text itself followed by the start and end
1623 locations of the text. Otherwise, return nil.
1624 Leave match data for `markdown-regex-reference-definition'
1625 intact additional processing."
1626 (let ((reference (downcase reference)))
1627 (save-excursion
1628 (goto-char (point-min))
1629 (catch 'found
1630 (while (re-search-forward markdown-regex-reference-definition nil t)
1631 (when (string= reference (downcase (match-string-no-properties 1)))
1632 (throw 'found
1633 (list (match-string-no-properties 2)
1634 (match-beginning 2) (match-end 2)))))))))
1636 (defun markdown-get-defined-references ()
1637 "Return a list of all defined reference labels (including square brackets)."
1638 (save-excursion
1639 (goto-char (point-min))
1640 (let (refs)
1641 (while (re-search-forward markdown-regex-reference-definition nil t)
1642 (let ((target (match-string-no-properties 1)))
1643 (add-to-list 'refs target t)))
1644 refs)))
1646 (defun markdown-code-at-point-p ()
1647 "Return non-nil if the point is at an inline code fragment.
1648 Return nil otherwise. Set match data according to
1649 `markdown-match-code' upon success.
1650 This function searches the block for a code fragment that
1651 contains the point using `markdown-match-code'. We do this
1652 because `thing-at-point-looking-at' does not work reliably with
1653 `markdown-regex-code'."
1654 (interactive)
1655 (save-excursion
1656 (let ((old-point (point))
1657 (end-of-block (progn (markdown-end-of-block) (point))))
1658 (markdown-beginning-of-block)
1659 (while (and (markdown-match-code end-of-block)
1660 (< (match-end 0) old-point)))
1661 (and (match-beginning 0) ; matched something
1662 (<= (match-beginning 0) old-point) ; match contains old-point
1663 (>= (match-end 0) old-point)))))
1666 ;;; Markdown Font Lock Matching Functions =====================================
1668 (defun markdown-match-comments (last)
1669 "Match HTML comments from the point to LAST."
1670 (cond ((search-forward "<!--" last t)
1671 (backward-char 4)
1672 (let ((beg (point)))
1673 (cond ((search-forward-regexp "--[ \t]*>" last t)
1674 (set-match-data (list beg (point)))
1676 (t nil))))
1677 (t nil)))
1679 (defun markdown-match-code (last)
1680 "Match inline code from the point to LAST."
1681 (unless (bobp)
1682 (backward-char 1))
1683 (cond ((re-search-forward markdown-regex-code last t)
1684 (set-match-data (list (match-beginning 2) (match-end 2)
1685 (match-beginning 4) (match-end 4)))
1686 (goto-char (match-end 0))
1688 (t (forward-char 2) nil)))
1690 (defun markdown-match-pre-blocks (last)
1691 "Match Markdown pre blocks from point to LAST."
1692 (let ((levels (markdown-calculate-list-levels))
1693 indent pre-regexp end-regexp begin end stop)
1694 (while (and (< (point) last) (not end))
1695 ;; Search for a region with sufficient indentation
1696 (if (null levels)
1697 (setq indent 1)
1698 (setq indent (1+ (length levels))))
1699 (setq pre-regexp (format "^\\( \\|\t\\)\\{%d\\}" indent))
1700 (setq end-regexp (format "^\\( \\|\t\\)\\{0,%d\\}\\([^ \t]\\)" (1- indent)))
1702 (cond
1703 ;; If not at the beginning of a line, move forward
1704 ((not (bolp)) (forward-line))
1705 ;; Move past blank lines
1706 ((markdown-cur-line-blank-p) (forward-line))
1707 ;; At headers and horizontal rules, reset levels
1708 ((markdown-new-baseline-p) (forward-line) (setq levels nil))
1709 ;; If the current line has sufficient indentation, mark out pre block
1710 ((looking-at pre-regexp)
1711 (setq begin (match-beginning 0))
1712 (while (and (or (looking-at pre-regexp) (markdown-cur-line-blank-p))
1713 (not (eobp)))
1714 (forward-line))
1715 (setq end (point)))
1716 ;; If current line has a list marker, update levels, move to end of block
1717 ((looking-at markdown-regex-list)
1718 (setq levels (markdown-update-list-levels
1719 (match-string 2) (markdown-cur-line-indent) levels))
1720 (markdown-end-of-block-element))
1721 ;; If this is the end of the indentation level, adjust levels accordingly.
1722 ;; Only match end of indentation level if levels is not the empty list.
1723 ((and (car levels) (looking-at end-regexp))
1724 (setq levels (markdown-update-list-levels
1725 nil (markdown-cur-line-indent) levels))
1726 (markdown-end-of-block-element))
1727 (t (markdown-end-of-block-element))))
1729 (if (not (and begin end))
1730 ;; Return nil if no pre block was found
1732 ;; Set match data and return t upon success
1733 (set-match-data (list begin end))
1734 t)))
1736 (defun markdown-match-fenced-code-blocks (last)
1737 "Match fenced code blocks from the point to LAST."
1738 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1739 (beginning-of-line)
1740 (let ((beg (point)))
1741 (forward-line)
1742 (cond ((search-forward-regexp
1743 (concat "^" (match-string 1) "~*") last t)
1744 (set-match-data (list beg (point)))
1746 (t nil))))
1747 (t nil)))
1749 (defun markdown-match-gfm-code-blocks (last)
1750 "Match GFM quoted code blocks from point to LAST."
1751 (let (open lang body close all)
1752 (cond ((and (eq major-mode 'gfm-mode)
1753 (search-forward-regexp "^\\(```\\)\\(\\w+\\)?$" last t))
1754 (beginning-of-line)
1755 (setq open (list (match-beginning 1) (match-end 1))
1756 lang (list (match-beginning 2) (match-end 2)))
1757 (forward-line)
1758 (setq body (list (point)))
1759 (cond ((search-forward-regexp "^```$" last t)
1760 (setq body (reverse (cons (1- (match-beginning 0)) body))
1761 close (list (match-beginning 0) (match-end 0))
1762 all (list (car open) (match-end 0)))
1763 (set-match-data (append all open lang body close))
1765 (t nil)))
1766 (t nil))))
1768 (defun markdown-match-generic-metadata (regexp last)
1769 "Match generic metadata specified by REGEXP from the point to LAST."
1770 (let ((header-end (save-excursion
1771 (goto-char (point-min))
1772 (if (re-search-forward "\n\n" (point-max) t)
1773 (match-beginning 0)
1774 (point-max)))))
1775 (cond ((>= (point) header-end)
1776 ;; Don't match anything outside of the header.
1777 nil)
1778 ((re-search-forward regexp (min last header-end) t)
1779 ;; If a metadata item is found, it may span several lines.
1780 (let ((key-beginning (match-beginning 1))
1781 (key-end (match-end 1))
1782 (value-beginning (match-beginning 2)))
1783 (while (and (not (looking-at regexp))
1784 (not (> (point) (min last header-end)))
1785 (not (eobp)))
1786 (forward-line))
1787 (unless (eobp)
1788 (forward-line -1)
1789 (end-of-line))
1790 (set-match-data (list key-beginning (point) ; complete metadata
1791 key-beginning key-end ; key
1792 value-beginning (point))) ; value
1794 (t nil))))
1796 (defun markdown-match-multimarkdown-metadata (last)
1797 "Match MultiMarkdown metadata from the point to LAST."
1798 (markdown-match-generic-metadata markdown-regex-multimarkdown-metadata last))
1800 (defun markdown-match-pandoc-metadata (last)
1801 "Match Pandoc metadata from the point to LAST."
1802 (markdown-match-generic-metadata markdown-regex-pandoc-metadata last))
1804 (defun markdown-font-lock-extend-region ()
1805 "Extend the search region to include an entire block of text.
1806 This helps improve font locking for block constructs such as pre blocks."
1807 ;; Avoid compiler warnings about these global variables from font-lock.el.
1808 ;; See the documentation for variable `font-lock-extend-region-functions'.
1809 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1810 (save-excursion
1811 (goto-char font-lock-beg)
1812 (let ((found (or (re-search-backward "\n\n" nil t) (point-min))))
1813 (goto-char font-lock-end)
1814 (when (re-search-forward "\n\n" nil t)
1815 (beginning-of-line)
1816 (setq font-lock-end (point)))
1817 (setq font-lock-beg found))))
1820 ;;; Syntax Table ==============================================================
1822 (defvar markdown-mode-syntax-table
1823 (let ((tab (make-syntax-table text-mode-syntax-table)))
1824 (modify-syntax-entry ?\" "." tab)
1825 tab)
1826 "Syntax table for `markdown-mode'.")
1829 ;;; Element Insertion =========================================================
1831 (defun markdown-ensure-blank-line-before ()
1832 "If previous line is not already blank, insert a blank line before point."
1833 (unless (bolp) (insert "\n"))
1834 (unless (or (bobp) (looking-back "\n\\s-*\n")) (insert "\n")))
1836 (defun markdown-ensure-blank-line-after ()
1837 "If following line is not already blank, insert a blank line after point.
1838 Return the point where it was originally."
1839 (save-excursion
1840 (unless (eolp) (insert "\n"))
1841 (unless (or (eobp) (looking-at "\n\\s-*\n")) (insert "\n"))))
1843 (defun markdown-wrap-or-insert (s1 s2 &optional thing beg end)
1844 "Insert the strings S1 and S2, wrapping around region or THING.
1845 If a region is specified by the optional BEG and END arguments,
1846 wrap the strings S1 and S2 around that region.
1847 If there is an active region, wrap the strings S1 and S2 around
1848 the region. If there is not an active region but the point is at
1849 THING, wrap that thing (which defaults to word). Otherwise, just
1850 insert S1 and S2 and place the cursor in between. Return the
1851 bounds of the entire wrapped string, or nil if nothing was wrapped
1852 and S1 and S2 were only inserted."
1853 (let (a b bounds new-point)
1854 (cond
1855 ;; Given region
1856 ((and beg end)
1857 (setq a beg
1858 b end
1859 new-point (+ (point) (length s1))))
1860 ;; Active region
1861 ((markdown-use-region-p)
1862 (setq a (region-beginning)
1863 b (region-end)
1864 new-point (+ (point) (length s1))))
1865 ;; Thing (word) at point
1866 ((setq bounds (markdown-bounds-of-thing-at-point (or thing 'word)))
1867 (setq a (car bounds)
1868 b (cdr bounds)
1869 new-point (+ (point) (length s1))))
1870 ;; No active region and no word
1872 (setq a (point)
1873 b (point))))
1874 (goto-char b)
1875 (insert s2)
1876 (goto-char a)
1877 (insert s1)
1878 (when new-point (goto-char new-point))
1879 (if (= a b)
1881 (setq b (+ b (length s1) (length s2)))
1882 (cons a b))))
1884 (defun markdown-point-after-unwrap (cur prefix suffix)
1885 "Return desired position of point after an unwrapping operation.
1886 CUR gives the position of the point before the operation.
1887 Additionally, two cons cells must be provided. PREFIX gives the
1888 bounds of the prefix string and SUFFIX gives the bounds of the
1889 suffix string."
1890 (cond ((< cur (cdr prefix)) (car prefix))
1891 ((< cur (car suffix)) (- cur (- (cdr prefix) (car prefix))))
1892 ((<= cur (cdr suffix))
1893 (- cur (+ (- (cdr prefix) (car prefix))
1894 (- cur (car suffix)))))
1895 (t cur)))
1897 (defun markdown-unwrap-thing-at-point (regexp all text)
1898 "Remove prefix and suffix of thing at point and reposition the point.
1899 When the thing at point matches REGEXP, replace the subexpression
1900 ALL with the string in subexpression TEXT. Reposition the point
1901 in an appropriate location accounting for the removal of prefix
1902 and suffix strings. Return new bounds of string from group TEXT.
1903 When REGEXP is nil, assumes match data is already set."
1904 (when (or (null regexp)
1905 (thing-at-point-looking-at regexp))
1906 (let ((cur (point))
1907 (prefix (cons (match-beginning all) (match-beginning text)))
1908 (suffix (cons (match-end text) (match-end all)))
1909 (bounds (cons (match-beginning text) (match-end text))))
1910 ;; Replace the thing at point
1911 (replace-match (match-string text) t t nil all)
1912 ;; Reposition the point
1913 (goto-char (markdown-point-after-unwrap cur prefix suffix))
1914 ;; Adjust bounds
1915 (setq bounds (cons (car prefix)
1916 (- (cdr bounds) (- (cdr prefix) (car prefix))))))))
1918 (defun markdown-unwrap-things-in-region (beg end regexp all text)
1919 "Remove prefix and suffix of all things in region from BEG to END.
1920 When a thing in the region matches REGEXP, replace the
1921 subexpression ALL with the string in subexpression TEXT.
1922 Return a cons cell containing updated bounds for the region."
1923 (save-excursion
1924 (goto-char beg)
1925 (let ((removed 0) len-all len-text)
1926 (while (re-search-forward regexp (- end removed) t)
1927 (setq len-all (length (match-string-no-properties all)))
1928 (setq len-text (length (match-string-no-properties text)))
1929 (setq removed (+ removed (- len-all len-text)))
1930 (replace-match (match-string text) t t nil all))
1931 (cons beg (- end removed)))))
1933 (defun markdown-insert-hr (arg)
1934 "Insert or replace a horizonal rule.
1935 By default, use the first element of `markdown-hr-strings'. When
1936 ARG is non-nil, as when given a prefix, select a different
1937 element as follows. When prefixed with \\[universal-argument],
1938 use the last element of `markdown-hr-strings' instead. When
1939 prefixed with an integer from 1 to the length of
1940 `markdown-hr-strings', use the element in that position instead."
1941 (interactive "*P")
1942 (when (thing-at-point-looking-at markdown-regex-hr)
1943 (delete-region (match-beginning 0) (match-end 0)))
1944 (markdown-ensure-blank-line-before)
1945 (cond ((equal arg '(4))
1946 (insert (car (reverse markdown-hr-strings))))
1947 ((and (integerp arg) (> arg 0)
1948 (<= arg (length markdown-hr-strings)))
1949 (insert (nth (1- arg) markdown-hr-strings)))
1951 (insert (car markdown-hr-strings))))
1952 (markdown-ensure-blank-line-after))
1954 (defun markdown-insert-bold ()
1955 "Insert markup to make a region or word bold.
1956 If there is an active region, make the region bold. If the point
1957 is at a non-bold word, make the word bold. If the point is at a
1958 bold word or phrase, remove the bold markup. Otherwise, simply
1959 insert bold delimiters and place the cursor in between them."
1960 (interactive)
1961 (let ((delim (if markdown-bold-underscore "__" "**")))
1962 (if (markdown-use-region-p)
1963 ;; Active region
1964 (let ((bounds (markdown-unwrap-things-in-region
1965 (region-beginning) (region-end)
1966 markdown-regex-bold 2 4)))
1967 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1968 ;; Bold markup removal, bold word at point, or empty markup insertion
1969 (if (thing-at-point-looking-at markdown-regex-bold)
1970 (markdown-unwrap-thing-at-point nil 2 4)
1971 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1973 (defun markdown-insert-italic ()
1974 "Insert markup to make a region or word italic.
1975 If there is an active region, make the region italic. If the point
1976 is at a non-italic word, make the word italic. If the point is at an
1977 italic word or phrase, remove the italic markup. Otherwise, simply
1978 insert italic delimiters and place the cursor in between them."
1979 (interactive)
1980 (let ((delim (if markdown-italic-underscore "_" "*")))
1981 (if (markdown-use-region-p)
1982 ;; Active region
1983 (let ((bounds (markdown-unwrap-things-in-region
1984 (region-beginning) (region-end)
1985 markdown-regex-italic 2 4)))
1986 (markdown-wrap-or-insert delim delim nil (car bounds) (cdr bounds)))
1987 ;; Italic markup removal, italic word at point, or empty markup insertion
1988 (if (thing-at-point-looking-at markdown-regex-italic)
1989 (markdown-unwrap-thing-at-point nil 2 4)
1990 (markdown-wrap-or-insert delim delim 'word nil nil)))))
1992 (defun markdown-insert-code ()
1993 "Insert markup to make a region or word an inline code fragment.
1994 If there is an active region, make the region an inline code
1995 fragment. If the point is at a word, make the word an inline
1996 code fragment. Otherwise, simply insert code delimiters and
1997 place the cursor in between them."
1998 (interactive)
1999 (if (markdown-use-region-p)
2000 ;; Active region
2001 (let ((bounds (markdown-unwrap-things-in-region
2002 (region-beginning) (region-end)
2003 markdown-regex-code 2 4)))
2004 (markdown-wrap-or-insert "`" "`" nil (car bounds) (cdr bounds)))
2005 ;; Code markup removal, code markup for word, or empty markup insertion
2006 (if (markdown-code-at-point-p)
2007 (markdown-unwrap-thing-at-point nil 0 1)
2008 (markdown-wrap-or-insert "`" "`" 'word nil nil))))
2010 (defun markdown-insert-link ()
2011 "Insert an inline link, using region or word as link text if possible.
2012 If there is an active region, use the region as the link text. If the
2013 point is at a word, use the word as the link text. In these cases, the
2014 point will be left at the position for inserting a URL. If there is no
2015 active region and the point is not at word, simply insert link markup and
2016 place the point in the position to enter link text."
2017 (interactive)
2018 (let ((bounds (markdown-wrap-or-insert "[" "]()")))
2019 (when bounds
2020 (goto-char (- (cdr bounds) 1)))))
2022 (defun markdown-insert-reference-link (text label &optional url title)
2023 "Insert a reference link and, optionally, a reference definition.
2024 The link TEXT will be inserted followed by the optional LABEL.
2025 If a URL is given, also insert a definition for the reference
2026 LABEL after the end of the paragraph. If a TITLE is given, it
2027 will be added to the end of the reference definition and will be
2028 used to populate the title attribute when converted to XHTML. If
2029 URL is nil, insert only the link portion (for example, when a
2030 reference label is already defined)."
2031 (insert (concat "[" text "][" label "]"))
2032 (when url
2033 (let ((end (point))
2034 (label (if (> (length label) 0) label text)))
2035 (cond
2036 ((eq markdown-reference-location 'end) (goto-char (point-max)))
2037 ((eq markdown-reference-location 'immediately) (markdown-end-of-block))
2038 ((eq markdown-reference-location 'header) (markdown-end-of-defun)))
2039 (unless (markdown-cur-line-blank-p) (insert "\n"))
2040 (insert "\n[" label "]: " url)
2041 (unless (> (length url) 0)
2042 (setq end (point)))
2043 (when (> (length title) 0)
2044 (insert " \"" title "\""))
2045 (insert "\n")
2046 (unless (or (eobp) (looking-at "\n"))
2047 (insert "\n"))
2048 (goto-char end)
2049 (when (> (length url) 0)
2050 (message
2051 (substitute-command-keys
2052 "Defined reference [%s], press \\[markdown-jump] to jump there")
2053 (or label text))))))
2055 (defun markdown-insert-reference-link-dwim ()
2056 "Insert a reference link of the form [text][label] at point.
2057 If there is an active region, the text in the region will be used
2058 as the link text. If the point is at a word, it will be used as
2059 the link text. Otherwise, the link text will be read from the
2060 minibuffer. The link label will be read from the minibuffer in
2061 both cases, with completion from the set of currently defined
2062 references. To create an implicit reference link, press RET to
2063 accept the default, an empty label. If the entered referenced
2064 label is not defined, additionally prompt for the URL
2065 and (optional) title. The reference definition is placed at the
2066 end of the current paragraph."
2067 (interactive)
2068 (let* ((defined-labels (mapcar (lambda (x) (substring x 1 -1))
2069 (markdown-get-defined-references)))
2070 (bounds (or (and (markdown-use-region-p)
2071 (cons (region-beginning) (region-end)))
2072 (markdown-bounds-of-thing-at-point 'word)))
2073 (text (if bounds
2074 (buffer-substring (car bounds) (cdr bounds))
2075 (read-string "Link Text: ")))
2076 (label (completing-read
2077 "Link Label (default: none): " defined-labels
2078 nil nil nil 'markdown-reference-label-history nil))
2079 (ref (markdown-reference-definition
2080 (concat "[" (if (> (length label) 0) label text) "]")))
2081 (url (unless ref (read-string "Link URL: ")))
2082 (title (when (> (length url) 0)
2083 (read-string "Link Title (optional): "))))
2084 (when bounds (delete-region (car bounds) (cdr bounds)))
2085 (markdown-insert-reference-link text label url title)))
2087 (defun markdown-insert-uri ()
2088 "Insert markup for an inline URI.
2089 If there is an active region, use it as the URI. If the point is
2090 at a URI, wrap it with angle brackets. If the point is at an
2091 inline URI, remove the angle brackets. Otherwise, simply insert
2092 angle brackets place the point between them."
2093 (interactive)
2094 (if (markdown-use-region-p)
2095 ;; Active region
2096 (let ((bounds (markdown-unwrap-things-in-region
2097 (region-beginning) (region-end)
2098 markdown-regex-angle-uri 0 2)))
2099 (markdown-wrap-or-insert "<" ">" nil (car bounds) (cdr bounds)))
2100 ;; Markup removal, URI at point, or empty markup insertion
2101 (if (thing-at-point-looking-at markdown-regex-angle-uri)
2102 (markdown-unwrap-thing-at-point nil 0 2)
2103 (markdown-wrap-or-insert "<" ">" 'url nil nil))))
2105 (defun markdown-insert-wiki-link ()
2106 "Insert a wiki link of the form [[WikiLink]].
2107 If Transient Mark mode is on and a region is active, it is used
2108 as the link text."
2109 (interactive)
2110 (if (markdown-use-region-p)
2111 ;; Active region
2112 (markdown-wrap-or-insert "[[" "]]" nil (region-beginning) (region-end))
2113 ;; Markup removal, wiki link at at point, or empty markup insertion
2114 (if (thing-at-point-looking-at markdown-regex-wiki-link)
2115 (if (or markdown-wiki-link-alias-first
2116 (null (match-string 4)))
2117 (markdown-unwrap-thing-at-point nil 1 2)
2118 (markdown-unwrap-thing-at-point nil 1 4))
2119 (markdown-wrap-or-insert "[[" "]]"))))
2121 (defun markdown-insert-image (&optional arg)
2122 "Insert image markup using region or word as alt text if possible.
2123 If there is an active region, use the region as the alt text. If the
2124 point is at a word, use the word as the alt text. In these cases, the
2125 point will be left at the position for inserting a URL. If there is no
2126 active region and the point is not at word, simply insert image markup and
2127 place the point in the position to enter alt text. If ARG is nil, insert
2128 inline image markup. Otherwise, insert reference image markup."
2129 (interactive "*P")
2130 (let ((bounds (if arg
2131 (markdown-wrap-or-insert "![" "][]")
2132 (markdown-wrap-or-insert "![" "]()"))))
2133 (when bounds
2134 (goto-char (- (cdr bounds) 1)))))
2136 (defun markdown-insert-reference-image ()
2137 "Insert reference-style image markup using region or word as alt text.
2138 Calls `markdown-insert-image' with prefix argument."
2139 (interactive)
2140 (markdown-insert-image t))
2142 (defun markdown-remove-header ()
2143 "Remove header markup if point is at a header.
2144 Return bounds of remaining header text if a header was removed
2145 and nil otherwise."
2146 (interactive "*")
2147 (or (markdown-unwrap-thing-at-point markdown-regex-header-atx 0 2)
2148 (markdown-unwrap-thing-at-point markdown-regex-header-setext 0 1)))
2150 (defun markdown-insert-header (&optional level text setext)
2151 "Insert or replace header markup.
2152 The level of the header is specified by LEVEL and header text is
2153 given by TEXT. LEVEL must be an integer from 1 and 6, and the
2154 default value is 1.
2155 When TEXT is nil, the header text is obtained as follows.
2156 If there is an active region, it is used as the header text.
2157 Otherwise, the current line will be used as the header text.
2158 If there is not an active region and the point is at a header,
2159 remove the header markup and replace with level N header.
2160 Otherwise, insert empty header markup and place the cursor in
2161 between.
2162 The style of the header will be atx (hash marks) unless
2163 SETEXT is non-nil, in which case a setext-style (underlined)
2164 header will be inserted."
2165 (interactive "p\nsHeader text: ")
2166 (setq level (min (max (or level 1) 1) (if setext 2 6)))
2167 ;; Determine header text if not given
2168 (when (null text)
2169 (if (markdown-use-region-p)
2170 ;; Active region
2171 (setq text (delete-and-extract-region (region-beginning) (region-end)))
2172 ;; No active region
2173 (markdown-remove-header)
2174 (setq text (delete-and-extract-region
2175 (line-beginning-position) (line-end-position)))
2176 (when (and setext (string-match "^[ \t]*$" text))
2177 (setq text (read-string "Header text: "))))
2178 (setq text (markdown-compress-whitespace-string text)))
2179 ;; Insertion with given text
2180 (markdown-ensure-blank-line-before)
2181 (let (hdr)
2182 (cond (setext
2183 (setq hdr (make-string (length text) (if (= level 2) ?- ?=)))
2184 (insert text "\n" hdr))
2186 (setq hdr (make-string level ?#))
2187 (insert hdr " " text " " hdr))))
2188 (markdown-ensure-blank-line-after)
2189 ;; Leave point at end of text
2190 (if setext
2191 (backward-char (1+ (length text)))
2192 (backward-char (1+ level))))
2194 (defun markdown-insert-header-dwim (&optional arg setext)
2195 "Insert or replace header markup.
2196 The level and type of the header are determined automatically by
2197 the type and level of the previous header, unless a prefix
2198 argument is given via ARG.
2199 With a numeric prefix valued 1 to 6, insert a header of the given
2200 level, with the type being determined automatically (note that
2201 only level 1 or 2 setext headers are possible).
2202 With \\[universal-argument], insert a level-one setext header.
2203 With \\[universal-argument] \\[universal-argument], insert a
2204 level two setext header.
2205 When SETEXT is non-nil, prefer setext-style headers when
2206 possible (levels one and two).
2208 When there is an active region, use it for the header text. When
2209 the point is at an existing header, change the type and level
2210 according to the rules above.
2211 Otherwise, if the line is not empty, create a header using the
2212 text on the current line as the header text.
2213 Finally, if the point is on a blank line, insert empty header
2214 markup (atx) or prompt for text (setext).
2215 See `markdown-insert-header' for more details about how the
2216 header text is determined."
2217 (interactive "*P")
2218 (let (level)
2219 (cond ((equal arg '(4)) ; level-one setext with C-u
2220 (setq setext t)
2221 (setq level 1))
2222 ((equal arg '(16)) ; level-two setext with C-u C-u
2223 (setq setext t)
2224 (setq level 2))
2225 (t ; automatic with numeric override
2226 (save-excursion
2227 (when (re-search-backward markdown-regex-header nil t)
2228 ;; level of previous header
2229 (setq level (markdown-outline-level))
2230 ;; match groups 1 and 2 indicate setext headers
2231 (setq setext (or setext (match-end 1) (match-end 3)))))
2232 ;; use prefix if given, or level of previous header
2233 (setq level (if arg (prefix-numeric-value arg) level))
2234 ;; setext headers must be level one or two
2235 (and level (setq setext (and setext (<= level 2))))))
2236 (markdown-insert-header level nil setext)))
2238 (defun markdown-insert-header-setext-dwim (&optional arg)
2239 "Insert or replace header markup, with preference for setext.
2240 See `markdown-insert-header-dwim' for details, including how ARG is handled."
2241 (interactive "*P")
2242 (markdown-insert-header-dwim arg t))
2244 (defun markdown-insert-header-atx-1 ()
2245 "Insert a first level atx-style (hash mark) header.
2246 See `markdown-insert-header'."
2247 (interactive "*")
2248 (markdown-insert-header 1 nil nil))
2250 (defun markdown-insert-header-atx-2 ()
2251 "Insert a level two atx-style (hash mark) header.
2252 See `markdown-insert-header'."
2253 (interactive "*")
2254 (markdown-insert-header 2 nil nil))
2256 (defun markdown-insert-header-atx-3 ()
2257 "Insert a level three atx-style (hash mark) header.
2258 See `markdown-insert-header'."
2259 (interactive "*")
2260 (markdown-insert-header 3 nil nil))
2262 (defun markdown-insert-header-atx-4 ()
2263 "Insert a level four atx-style (hash mark) header.
2264 See `markdown-insert-header'."
2265 (interactive "*")
2266 (markdown-insert-header 4 nil nil))
2268 (defun markdown-insert-header-atx-5 ()
2269 "Insert a level five atx-style (hash mark) header.
2270 See `markdown-insert-header'."
2271 (interactive "*")
2272 (markdown-insert-header 5 nil nil))
2274 (defun markdown-insert-header-atx-6 ()
2275 "Insert a sixth level atx-style (hash mark) header.
2276 See `markdown-insert-header'."
2277 (interactive "*")
2278 (markdown-insert-header 6 nil nil))
2280 (defun markdown-insert-header-setext-1 ()
2281 "Insert a setext-style (underlined) first-level header.
2282 See `markdown-insert-header'."
2283 (interactive "*")
2284 (markdown-insert-header 1 nil t))
2286 (defun markdown-insert-header-setext-2 ()
2287 "Insert a setext-style (underlined) second-level header.
2288 See `markdown-insert-header'."
2289 (interactive "*")
2290 (markdown-insert-header 2 nil t))
2292 (defun markdown-blockquote-indentation (loc)
2293 "Return string containing necessary indentation for a blockquote at LOC.
2294 Also see `markdown-pre-indentation'."
2295 (save-excursion
2296 (goto-char loc)
2297 (let* ((list-level (length (markdown-calculate-list-levels)))
2298 (indent ""))
2299 (dotimes (count list-level indent)
2300 (setq indent (concat indent " "))))))
2302 (defun markdown-insert-blockquote ()
2303 "Start a blockquote section (or blockquote the region).
2304 If Transient Mark mode is on and a region is active, it is used as
2305 the blockquote text."
2306 (interactive)
2307 (if (markdown-use-region-p)
2308 (markdown-blockquote-region (region-beginning) (region-end))
2309 (markdown-ensure-blank-line-before)
2310 (insert (markdown-blockquote-indentation (point)) "> ")
2311 (markdown-ensure-blank-line-after)))
2313 (defun markdown-block-region (beg end prefix)
2314 "Format the region using a block prefix.
2315 Arguments BEG and END specify the beginning and end of the
2316 region. The characters PREFIX will appear at the beginning
2317 of each line."
2318 (save-excursion
2319 (let* ((end-marker (make-marker))
2320 (beg-marker (make-marker)))
2321 ;; Ensure blank line after and remove extra whitespace
2322 (goto-char end)
2323 (skip-syntax-backward "-")
2324 (set-marker end-marker (point))
2325 (delete-horizontal-space)
2326 (markdown-ensure-blank-line-after)
2327 ;; Ensure blank line before and remove extra whitespace
2328 (goto-char beg)
2329 (skip-syntax-forward "-")
2330 (delete-horizontal-space)
2331 (markdown-ensure-blank-line-before)
2332 (set-marker beg-marker (point))
2333 ;; Insert PREFIX before each line
2334 (goto-char beg-marker)
2335 (while (and (< (line-beginning-position) end-marker)
2336 (not (eobp)))
2337 (insert prefix)
2338 (forward-line)))))
2340 (defun markdown-blockquote-region (beg end)
2341 "Blockquote the region.
2342 Arguments BEG and END specify the beginning and end of the region."
2343 (interactive "*r")
2344 (markdown-block-region
2345 beg end (concat (markdown-blockquote-indentation
2346 (max (point-min) (1- beg))) "> ")))
2348 (defun markdown-pre-indentation (loc)
2349 "Return string containing necessary whitespace for a pre block at LOC.
2350 Also see `markdown-blockquote-indentation'."
2351 (save-excursion
2352 (goto-char loc)
2353 (let* ((list-level (length (markdown-calculate-list-levels)))
2354 indent)
2355 (dotimes (count (1+ list-level) indent)
2356 (setq indent (concat indent " "))))))
2358 (defun markdown-insert-pre ()
2359 "Start a preformatted section (or apply to the region).
2360 If Transient Mark mode is on and a region is active, it is marked
2361 as preformatted text."
2362 (interactive)
2363 (if (markdown-use-region-p)
2364 (markdown-pre-region (region-beginning) (region-end))
2365 (markdown-ensure-blank-line-before)
2366 (insert (markdown-pre-indentation (point)))
2367 (markdown-ensure-blank-line-after)))
2369 (defun markdown-pre-region (beg end)
2370 "Format the region as preformatted text.
2371 Arguments BEG and END specify the beginning and end of the region."
2372 (interactive "*r")
2373 (let ((indent (markdown-pre-indentation (max (point-min) (1- beg)))))
2374 (markdown-block-region beg end indent)))
2376 (defun markdown-insert-gfm-code-block (&optional lang)
2377 "Insert GFM code block for language LANG.
2378 If LANG is nil, the language will be queried from user. If a
2379 region is active, wrap this region with the markup instead. If
2380 the region boundaries are not on empty lines, these are added
2381 automatically in order to have the correct markup."
2382 (interactive "sProgramming language: ")
2383 (if (markdown-use-region-p)
2384 (let ((b (region-beginning)) (e (region-end)))
2385 (goto-char b)
2386 ;; if we're on a blank line, insert the quotes here, otherwise
2387 ;; add a new line first
2388 (unless (looking-at "\n")
2389 (newline)
2390 (forward-line -1)
2391 (setq e (1+ e)))
2392 (insert "```" lang)
2393 (goto-char (+ e 3 (length lang)))
2394 ;; if we're on a blank line, don't newline, otherwise the ```
2395 ;; should go on its own line
2396 (unless (looking-back "\n")
2397 (newline))
2398 (insert "```"))
2399 (insert "```" lang)
2400 (newline 2)
2401 (insert "```")
2402 (forward-line -1)))
2405 ;;; Footnotes ======================================================================
2407 (defun markdown-footnote-counter-inc ()
2408 "Increment `markdown-footnote-counter' and return the new value."
2409 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
2410 (save-excursion
2411 (goto-char (point-min))
2412 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
2413 (point-max) t)
2414 (let ((fn (string-to-number (match-string 1))))
2415 (when (> fn markdown-footnote-counter)
2416 (setq markdown-footnote-counter fn))))))
2417 (incf markdown-footnote-counter))
2419 (defun markdown-footnote-new ()
2420 "Insert footnote with a new number and move point to footnote definition."
2421 (interactive)
2422 (let ((fn (markdown-footnote-counter-inc)))
2423 (insert (format "[^%d]" fn))
2424 (markdown-footnote-text-find-new-location)
2425 (markdown-ensure-blank-line-before)
2426 (unless (markdown-cur-line-blank-p)
2427 (insert "\n"))
2428 (insert (format "[^%d]: " fn))
2429 (markdown-ensure-blank-line-after)))
2431 (defun markdown-footnote-text-find-new-location ()
2432 "Position the cursor at the proper location for a new footnote text."
2433 (cond
2434 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
2435 ((eq markdown-footnote-location 'immediately) (markdown-end-of-block))
2436 ((eq markdown-footnote-location 'header) (markdown-end-of-defun))))
2438 (defun markdown-footnote-kill ()
2439 "Kill the footnote at point.
2440 The footnote text is killed (and added to the kill ring), the
2441 footnote marker is deleted. Point has to be either at the
2442 footnote marker or in the footnote text."
2443 (interactive)
2444 (let (return-pos)
2445 (when (markdown-footnote-text-positions) ; if we're in a footnote text
2446 (markdown-footnote-return) ; we first move to the marker
2447 (setq return-pos 'text)) ; and remember our return position
2448 (let ((marker (markdown-footnote-delete-marker)))
2449 (unless marker
2450 (error "Not at a footnote"))
2451 (let ((text-pos (markdown-footnote-find-text (car marker))))
2452 (unless text-pos
2453 (error "No text for footnote `%s'" (car marker)))
2454 (goto-char text-pos)
2455 (let ((pos (markdown-footnote-kill-text)))
2456 (setq return-pos
2457 (if (and pos (eq return-pos 'text))
2459 (cadr marker))))))
2460 (goto-char return-pos)))
2462 (defun markdown-footnote-delete-marker ()
2463 "Delete a footnote marker at point.
2464 Returns a list (ID START) containing the footnote ID and the
2465 start position of the marker before deletion. If no footnote
2466 marker was deleted, this function returns NIL."
2467 (let ((marker (markdown-footnote-marker-positions)))
2468 (when marker
2469 (delete-region (second marker) (third marker))
2470 (butlast marker))))
2472 (defun markdown-footnote-kill-text ()
2473 "Kill footnote text at point.
2474 Returns the start position of the footnote text before deletion,
2475 or NIL if point was not inside a footnote text.
2477 The killed text is placed in the kill ring (without the footnote
2478 number)."
2479 (let ((fn (markdown-footnote-text-positions)))
2480 (when fn
2481 (let ((text (delete-and-extract-region (second fn) (third fn))))
2482 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
2483 (kill-new (match-string 1 text))
2484 (when (and (markdown-cur-line-blank-p)
2485 (markdown-prev-line-blank-p))
2486 (delete-region (1- (point)) (point)))
2487 (second fn)))))
2489 (defun markdown-footnote-goto-text ()
2490 "Jump to the text of the footnote at point."
2491 (interactive)
2492 (let ((fn (car (markdown-footnote-marker-positions))))
2493 (unless fn
2494 (error "Not at a footnote marker"))
2495 (let ((new-pos (markdown-footnote-find-text fn)))
2496 (unless new-pos
2497 (error "No definition found for footnote `%s'" fn))
2498 (goto-char new-pos))))
2500 (defun markdown-footnote-return ()
2501 "Return from a footnote to its footnote number in the main text."
2502 (interactive)
2503 (let ((fn (save-excursion
2504 (car (markdown-footnote-text-positions)))))
2505 (unless fn
2506 (error "Not in a footnote"))
2507 (let ((new-pos (markdown-footnote-find-marker fn)))
2508 (unless new-pos
2509 (error "Footnote marker `%s' not found" fn))
2510 (goto-char new-pos))))
2512 (defun markdown-footnote-find-marker (id)
2513 "Find the location of the footnote marker with ID.
2514 The actual buffer position returned is the position directly
2515 following the marker's closing bracket. If no marker is found,
2516 NIL is returned."
2517 (save-excursion
2518 (goto-char (point-min))
2519 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
2520 (skip-chars-backward "^]")
2521 (point))))
2523 (defun markdown-footnote-find-text (id)
2524 "Find the location of the text of footnote ID.
2525 The actual buffer position returned is the position of the first
2526 character of the text, after the footnote's identifier. If no
2527 footnote text is found, NIL is returned."
2528 (save-excursion
2529 (goto-char (point-min))
2530 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
2531 (skip-chars-forward "[ \t]")
2532 (point))))
2534 (defun markdown-footnote-marker-positions ()
2535 "Return the position and ID of the footnote marker point is on.
2536 The return value is a list (ID START END). If point is not on a
2537 footnote, NIL is returned."
2538 ;; first make sure we're at a footnote marker
2539 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (line-beginning-position))
2540 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
2541 (save-excursion
2542 ;; move point between [ and ^:
2543 (if (looking-at "\\[")
2544 (forward-char 1)
2545 (skip-chars-backward "^["))
2546 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
2547 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
2549 (defun markdown-footnote-text-positions ()
2550 "Return the start and end positions of the footnote text point is in.
2551 The exact return value is a list of three elements: (ID START END).
2552 The start position is the position of the opening bracket
2553 of the footnote id. The end position is directly after the
2554 newline that ends the footnote. If point is not in a footnote,
2555 NIL is returned instead."
2556 (save-excursion
2557 (let ((fn (progn
2558 (backward-paragraph)
2559 ;; if we're in a multiparagraph footnote, we need to back up further
2560 (while (>= (markdown-next-line-indent) 4)
2561 (backward-paragraph))
2562 (forward-line)
2563 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
2564 (list (match-string 1) (point))))))
2565 (when fn
2566 (while (progn
2567 (forward-paragraph)
2568 (>= (markdown-next-line-indent) 4)))
2569 (append fn (list (point)))))))
2572 ;;; Element Removal ===========================================================
2574 (defun markdown-kill-thing-at-point ()
2575 "Kill thing at point and add important text, without markup, to kill ring.
2576 Possible things to kill include (roughly in order of precedence):
2577 inline code, headers, horizonal rules, links (add link text to
2578 kill ring), images (add alt text to kill ring), angle uri, email
2579 addresses, bold, italics, reference definition (add URI to kill
2580 ring), footnote markers and text (kill both marker and text, add
2581 text to kill ring), and list items."
2582 (interactive "*")
2583 (let (val tmp)
2584 (cond
2585 ;; Inline code
2586 ((markdown-code-at-point-p)
2587 (kill-new (match-string 1))
2588 (delete-region (match-beginning 0) (match-end 0)))
2589 ;; ATX header
2590 ((thing-at-point-looking-at markdown-regex-header-atx)
2591 (kill-new (match-string 2))
2592 (delete-region (match-beginning 0) (match-end 0)))
2593 ;; Setext header
2594 ((thing-at-point-looking-at markdown-regex-header-setext)
2595 (kill-new (match-string 1))
2596 (delete-region (match-beginning 0) (match-end 0)))
2597 ;; Horizonal rule
2598 ((thing-at-point-looking-at markdown-regex-hr)
2599 (kill-new (match-string 0))
2600 (delete-region (match-beginning 0) (match-end 0)))
2601 ;; Inline link or image (add link or alt text to kill ring)
2602 ((thing-at-point-looking-at markdown-regex-link-inline)
2603 (kill-new (match-string 3))
2604 (delete-region (match-beginning 0) (match-end 0)))
2605 ;; Reference link or image (add link or alt text to kill ring)
2606 ((thing-at-point-looking-at markdown-regex-link-reference)
2607 (kill-new (match-string 3))
2608 (delete-region (match-beginning 0) (match-end 0)))
2609 ;; Angle URI (add URL to kill ring)
2610 ((thing-at-point-looking-at markdown-regex-angle-uri)
2611 (kill-new (match-string 2))
2612 (delete-region (match-beginning 0) (match-end 0)))
2613 ;; Email address in angle brackets (add email address to kill ring)
2614 ((thing-at-point-looking-at markdown-regex-email)
2615 (kill-new (match-string 1))
2616 (delete-region (match-beginning 0) (match-end 0)))
2617 ;; Wiki link (add alias text to kill ring)
2618 ((thing-at-point-looking-at markdown-regex-wiki-link)
2619 (kill-new (markdown-wiki-link-alias))
2620 (delete-region (match-beginning 1) (match-end 1)))
2621 ;; Bold
2622 ((thing-at-point-looking-at markdown-regex-bold)
2623 (kill-new (match-string 4))
2624 (delete-region (match-beginning 2) (match-end 2)))
2625 ;; Italics
2626 ((thing-at-point-looking-at markdown-regex-italic)
2627 (kill-new (match-string 4))
2628 (delete-region (match-beginning 2) (match-end 2)))
2629 ;; Footnote marker (add footnote text to kill ring)
2630 ((thing-at-point-looking-at markdown-regex-footnote)
2631 (markdown-footnote-kill))
2632 ;; Footnote text (add footnote text to kill ring)
2633 ((setq val (markdown-footnote-text-positions))
2634 (markdown-footnote-kill))
2635 ;; Reference definition (add URL to kill ring)
2636 ((thing-at-point-looking-at markdown-regex-reference-definition)
2637 (kill-new (match-string 2))
2638 (delete-region (match-beginning 0) (match-end 0)))
2639 ;; List item
2640 ((setq val (markdown-cur-list-item-bounds))
2641 (kill-new (delete-and-extract-region (first val) (second val))))
2643 (error "Nothing found at point to kill")))))
2646 ;;; Indentation ====================================================================
2648 (defun markdown-indent-find-next-position (cur-pos positions)
2649 "Return the position after the index of CUR-POS in POSITIONS.
2650 Positions are calculated by `markdown-calc-indents'."
2651 (while (and positions
2652 (not (equal cur-pos (car positions))))
2653 (setq positions (cdr positions)))
2654 (or (cadr positions) 0))
2656 (defun markdown-exdent-find-next-position (cur-pos positions)
2657 "Return the maximal element that precedes CUR-POS from POSITIONS.
2658 Positions are calculated by `markdown-calc-indents'."
2659 (let ((result 0))
2660 (dolist (i positions)
2661 (when (< i cur-pos)
2662 (setq result (max result i))))
2663 result))
2665 (defun markdown-indent-line ()
2666 "Indent the current line using some heuristics.
2667 If the _previous_ command was either `markdown-enter-key' or
2668 `markdown-cycle', then we should cycle to the next
2669 reasonable indentation position. Otherwise, we could have been
2670 called directly by `markdown-enter-key', by an initial call of
2671 `markdown-cycle', or indirectly by `auto-fill-mode'. In
2672 these cases, indent to the default position.
2673 Positions are calculated by `markdown-calc-indents'."
2674 (interactive)
2675 (let ((positions (markdown-calc-indents))
2676 (cur-pos (current-column)))
2677 (if (not (equal this-command 'markdown-cycle))
2678 (indent-line-to (car positions))
2679 (setq positions (sort (delete-dups positions) '<))
2680 (indent-line-to
2681 (markdown-indent-find-next-position cur-pos positions)))))
2683 (defun markdown-calc-indents ()
2684 "Return a list of indentation columns to cycle through.
2685 The first element in the returned list should be considered the
2686 default indentation level. This function does not worry about
2687 duplicate positions, which are handled up by calling functions."
2688 (let (pos prev-line-pos positions)
2690 ;; Indentation of previous line
2691 (setq prev-line-pos (markdown-prev-line-indent))
2692 (setq positions (cons prev-line-pos positions))
2694 ;; Indentation of previous non-list-marker text
2695 (when (setq pos (markdown-prev-non-list-indent))
2696 (setq positions (cons pos positions)))
2698 ;; Indentation required for a pre block in current context
2699 (setq pos (length (markdown-pre-indentation (point))))
2700 (setq positions (cons pos positions))
2702 ;; Indentation of the previous line + tab-width
2703 (if prev-line-pos
2704 (setq positions (cons (+ prev-line-pos tab-width) positions))
2705 (setq positions (cons tab-width positions)))
2707 ;; Indentation of the previous line - tab-width
2708 (if (and prev-line-pos (> prev-line-pos tab-width))
2709 (setq positions (cons (- prev-line-pos tab-width) positions)))
2711 ;; Indentation of all preceeding list markers (when in a list)
2712 (when (setq pos (markdown-calculate-list-levels))
2713 (setq positions (append pos positions)))
2715 ;; First column
2716 (setq positions (cons 0 positions))
2718 ;; Return reversed list
2719 (reverse positions)))
2721 (defun markdown-do-normal-return ()
2722 "Insert a newline and optionally indent the next line."
2723 (newline)
2724 (if markdown-indent-on-enter
2725 (funcall indent-line-function)))
2727 (defun markdown-enter-key ()
2728 "Handle RET according to context.
2729 If there is a wiki link at the point, follow it unless
2730 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
2731 it in the usual way."
2732 (interactive)
2733 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
2734 (markdown-follow-wiki-link-at-point)
2735 (markdown-do-normal-return)))
2737 (defun markdown-exdent-or-delete (arg)
2738 "Handle BACKSPACE by cycling through indentation points.
2739 When BACKSPACE is pressed, if there is only whitespace
2740 before the current point, then exdent the line one level.
2741 Otherwise, do normal delete by repeating
2742 `backward-delete-char-untabify' ARG times."
2743 (interactive "*p")
2744 (let ((cur-pos (current-column))
2745 (start-of-indention (save-excursion
2746 (back-to-indentation)
2747 (current-column)))
2748 (positions (markdown-calc-indents)))
2749 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
2750 (indent-line-to (markdown-exdent-find-next-position cur-pos positions))
2751 (backward-delete-char-untabify arg))))
2753 (defun markdown-find-leftmost-column (beg end)
2754 "Find the leftmost column in the region from BEG to END."
2755 (let ((mincol 1000))
2756 (save-excursion
2757 (goto-char beg)
2758 (while (< (point) end)
2759 (back-to-indentation)
2760 (unless (looking-at "[ \t]*$")
2761 (setq mincol (min mincol (current-column))))
2762 (forward-line 1)
2764 mincol))
2766 (defun markdown-indent-region (beg end arg)
2767 "Indent the region from BEG to END using some heuristics.
2768 When ARG is non-nil, exdent the region instead.
2769 See `markdown-indent-line' and `markdown-indent-line'."
2770 (interactive "*r\nP")
2771 (let* ((positions (sort (delete-dups (markdown-calc-indents)) '<))
2772 (leftmostcol (markdown-find-leftmost-column beg end))
2773 (next-pos (if arg
2774 (markdown-exdent-find-next-position leftmostcol positions)
2775 (markdown-indent-find-next-position leftmostcol positions))))
2776 (indent-rigidly beg end (- next-pos leftmostcol))
2777 (setq deactivate-mark nil)))
2779 (defun markdown-exdent-region (beg end)
2780 "Call `markdown-indent-region' on region from BEG to END with prefix."
2781 (interactive "*r")
2782 (markdown-indent-region (region-beginning) (region-end) t))
2785 ;;; Markup Completion =========================================================
2787 (defconst markdown-complete-alist
2788 '((markdown-regex-header-atx . markdown-complete-atx)
2789 (markdown-regex-header-setext . markdown-complete-setext)
2790 (markdown-regex-hr . markdown-complete-hr))
2791 "Association list of form (regexp . function) for markup completion.")
2793 (defun markdown-incomplete-atx-p ()
2794 "Return t if ATX header markup is incomplete and nil otherwise.
2795 Assumes match data is available for `markdown-regex-header-atx'.
2796 Checks that the number of trailing hash marks equals the number of leading
2797 hash marks, that there is only a single space before and after the text,
2798 and that there is no extraneous whitespace in the text."
2799 (save-match-data
2801 ;; Number of starting and ending hash marks differs
2802 (not (= (length (match-string 1)) (length (match-string 3))))
2803 ;; When the header text is not empty...
2804 (and (> (length (match-string 2)) 0)
2805 ;; ...if there are extra leading, trailing, or interior spaces
2806 (or (not (= (match-beginning 2) (1+ (match-end 1))))
2807 (not (= (match-beginning 3) (1+ (match-end 2))))
2808 (string-match "[ \t\n]\\{2\\}" (match-string 2))))
2809 ;; When the header text is empty...
2810 (and (= (length (match-string 2)) 0)
2811 ;; ...if there are too many or too few spaces
2812 (not (= (match-beginning 3) (+ (match-end 1) 2)))))))
2814 (defun markdown-complete-atx ()
2815 "Complete and normalize ATX headers.
2816 Add or remove hash marks to the end of the header to match the
2817 beginning. Ensure that there is only a single space between hash
2818 marks and header text. Removes extraneous whitespace from header text.
2819 Assumes match data is available for `markdown-regex-header-atx'."
2820 (when (markdown-incomplete-atx-p)
2821 (let* ((new-marker (make-marker))
2822 (new-marker (set-marker new-marker (match-end 2))))
2823 ;; Hash marks and spacing at end
2824 (goto-char (match-end 2))
2825 (delete-region (match-end 2) (match-end 3))
2826 (insert " " (match-string 1))
2827 ;; Remove extraneous whitespace from title
2828 (replace-match (markdown-compress-whitespace-string (match-string 2))
2829 t t nil 2)
2830 ;; Spacing at beginning
2831 (goto-char (match-end 1))
2832 (delete-region (match-end 1) (match-beginning 2))
2833 (insert " ")
2834 ;; Leave point at end of text
2835 (goto-char new-marker))))
2837 (defun markdown-incomplete-setext-p ()
2838 "Return t if setext header markup is incomplete and nil otherwise.
2839 Assumes match data is available for `markdown-regex-header-setext'.
2840 Checks that length of underline matches text and that there is no
2841 extraneous whitespace in the text."
2842 (save-match-data
2843 (or (not (= (length (match-string 1)) (length (match-string 2))))
2844 (string-match "[ \t\n]\\{2\\}" (match-string 1)))))
2846 (defun markdown-complete-setext ()
2847 "Complete and normalize setext headers.
2848 Add or remove underline characters to match length of header
2849 text. Removes extraneous whitespace from header text. Assumes
2850 match data is available for `markdown-regex-header-setext'."
2851 (when (markdown-incomplete-setext-p)
2852 (let* ((text (markdown-compress-whitespace-string (match-string 1)))
2853 (char (char-after (match-beginning 2)))
2854 (level (if (char-equal char ?-) 2 1)))
2855 (goto-char (match-beginning 0))
2856 (delete-region (match-beginning 0) (match-end 0))
2857 (markdown-insert-header level text t))))
2859 (defun markdown-incomplete-hr-p ()
2860 "Return non-nil if hr is not in `markdown-hr-strings' and nil otherwise.
2861 Assumes match data is available for `markdown-regex-hr'."
2862 (not (member (match-string 0) markdown-hr-strings)))
2864 (defun markdown-complete-hr ()
2865 "Complete horizontal rules.
2866 If horizontal rule string is a member of `markdown-hr-strings',
2867 do nothing. Otherwise, replace with the car of
2868 `markdown-hr-strings'.
2869 Assumes match data is available for `markdown-regex-hr'."
2870 (replace-match (car markdown-hr-strings)))
2872 (defun markdown-complete ()
2873 "Complete markup of object near point or in region when active.
2874 Handle all objects in `markdown-complete-alist', in order.
2875 See `markdown-complete-at-point' and `markdown-complete-region'."
2876 (interactive "*")
2877 (if (markdown-use-region-p)
2878 (markdown-complete-region (region-beginning) (region-end))
2879 (markdown-complete-at-point)))
2881 (defun markdown-complete-at-point ()
2882 "Complete markup of object near point.
2883 Handle all objects in `markdown-complete-alist', in
2884 order."
2885 (interactive "*")
2886 (loop for (regexp . function) in markdown-complete-alist
2887 until (thing-at-point-looking-at (eval regexp))
2888 finally (funcall function)))
2890 (defun markdown-complete-region (beg end)
2891 "Complete markup of objects in region from BEG to END.
2892 Handle all objects in `markdown-complete-alist', in
2893 order."
2894 (interactive "*r")
2895 (let* ((end-marker (make-marker))
2896 (end-marker (set-marker end-marker end)))
2897 (loop for (regexp . function) in markdown-complete-alist
2898 do (save-excursion
2899 (goto-char beg)
2900 (while (re-search-forward (eval regexp) end-marker t)
2901 (funcall function))))))
2903 (defun markdown-complete-buffer ()
2904 "Complete markup for all objects in the current buffer."
2905 (interactive "*")
2906 (markdown-complete-region (point-min) (point-max)))
2909 ;;; Markup Cycling ============================================================
2911 (defun markdown-cycle-atx (arg &optional remove)
2912 "Cycle ATX header markup.
2913 Promote header (decrease level) when ARG is 1 and demote
2914 header (increase level) if arg is -1. When REMOVE is non-nil,
2915 remove the header when the level reaches zero and stop cycling
2916 when it reaches six. Otherwise, perform a proper cycling through
2917 levels one through six. Assumes match data is available for
2918 `markdown-regex-header-atx'."
2919 (let* ((old-level (length (match-string 1)))
2920 (new-level (+ old-level arg))
2921 (text (match-string 2)))
2922 (when (not remove)
2923 (setq new-level (% new-level 6))
2924 (setq new-level (cond ((= new-level 0) 6)
2925 ((< new-level 0) (+ new-level 6))
2926 (t new-level))))
2927 (cond
2928 ((= new-level 0)
2929 (markdown-unwrap-thing-at-point nil 0 2))
2930 ((<= new-level 6)
2931 (goto-char (match-beginning 0))
2932 (delete-region (match-beginning 0) (match-end 0))
2933 (markdown-insert-header new-level text nil)))))
2935 (defun markdown-cycle-setext (arg &optional remove)
2936 "Cycle setext header markup.
2937 Promote header (increase level) when ARG is 1 and demote
2938 header (decrease level or remove) if arg is -1. When demoting a
2939 level-two setext header, replace with a level-three atx header.
2940 When REMOVE is non-nil, remove the header when the level reaches
2941 zero. Otherwise, cycle back to a level six atx header. Assumes
2942 match data is available for `markdown-regex-header-setext'."
2943 (let* ((char (char-after (match-beginning 2)))
2944 (old-level (if (char-equal char ?=) 1 2))
2945 (new-level (+ old-level arg))
2946 (text (match-string 1)))
2947 (when (and (not remove) (= new-level 0))
2948 (setq new-level 6))
2949 (cond
2950 ((= new-level 0)
2951 (markdown-unwrap-thing-at-point nil 0 1))
2952 ((<= new-level 2)
2953 (markdown-insert-header new-level nil t))
2954 ((<= new-level 6)
2955 (markdown-insert-header new-level nil nil)))))
2957 (defun markdown-cycle-hr (arg &optional remove)
2958 "Cycle string used for horizontal rule from `markdown-hr-strings'.
2959 When ARG is 1, cycle forward (demote), and when ARG is -1, cycle
2960 backwards (promote). When REMOVE is non-nil, remove the hr instead
2961 of cycling when the end of the list is reached.
2962 Assumes match data is available for `markdown-regex-hr'."
2963 (let* ((strings (if (= arg -1)
2964 (reverse markdown-hr-strings)
2965 markdown-hr-strings))
2966 (tail (member (match-string 0) strings))
2967 (new (or (cadr tail)
2968 (if remove
2969 (if (= arg 1)
2971 (car tail))
2972 (car strings)))))
2973 (replace-match new)))
2975 (defun markdown-cycle-bold ()
2976 "Cycle bold markup between underscores and asterisks.
2977 Assumes match data is available for `markdown-regex-bold'."
2978 (save-excursion
2979 (let* ((old-delim (match-string 3))
2980 (new-delim (if (string-equal old-delim "**") "__" "**")))
2981 (replace-match new-delim t t nil 3)
2982 (replace-match new-delim t t nil 5))))
2984 (defun markdown-cycle-italic ()
2985 "Cycle italic markup between underscores and asterisks.
2986 Assumes match data is available for `markdown-regex-italic'."
2987 (save-excursion
2988 (let* ((old-delim (match-string 3))
2989 (new-delim (if (string-equal old-delim "*") "_" "*")))
2990 (replace-match new-delim t t nil 3)
2991 (replace-match new-delim t t nil 5))))
2994 ;;; Keymap ====================================================================
2996 (defvar markdown-mode-map
2997 (let ((map (make-keymap)))
2998 ;; Element insertion
2999 (define-key map (kbd "C-c l") 'markdown-insert-link)
3000 (define-key map (kbd "C-c L") 'markdown-insert-reference-link-dwim)
3001 (define-key map (kbd "C-c u") 'markdown-insert-uri)
3002 (define-key map (kbd "C-c w") 'markdown-insert-wiki-link)
3003 (define-key map (kbd "C-c i") 'markdown-insert-image)
3004 (define-key map (kbd "C-c I") 'markdown-insert-reference-image)
3005 (define-key map (kbd "C-c 1") 'markdown-insert-header-atx-1)
3006 (define-key map (kbd "C-c 2") 'markdown-insert-header-atx-2)
3007 (define-key map (kbd "C-c 3") 'markdown-insert-header-atx-3)
3008 (define-key map (kbd "C-c 4") 'markdown-insert-header-atx-4)
3009 (define-key map (kbd "C-c 5") 'markdown-insert-header-atx-5)
3010 (define-key map (kbd "C-c 6") 'markdown-insert-header-atx-6)
3011 (define-key map (kbd "C-c !") 'markdown-insert-header-setext-1)
3012 (define-key map (kbd "C-c @") 'markdown-insert-header-setext-2)
3013 (define-key map (kbd "C-c h") 'markdown-insert-header-dwim)
3014 (define-key map (kbd "C-c H") 'markdown-insert-header-setext-dwim)
3015 (define-key map (kbd "C-c s") 'markdown-insert-bold)
3016 (define-key map (kbd "C-c e") 'markdown-insert-italic)
3017 (define-key map (kbd "C-c c") 'markdown-insert-code)
3018 (define-key map (kbd "C-c b") 'markdown-insert-blockquote)
3019 (define-key map (kbd "C-c B") 'markdown-blockquote-region)
3020 (define-key map (kbd "C-c p") 'markdown-insert-pre)
3021 (define-key map (kbd "C-c P") 'markdown-pre-region)
3022 (define-key map (kbd "C-c -") 'markdown-insert-hr)
3023 (define-key map (kbd "C-c f") 'markdown-footnote-new)
3024 ;; Element removal
3025 (define-key map (kbd "C-c C-k") 'markdown-kill-thing-at-point)
3026 ;; Promotion, Demotion, Completion, and Cycling
3027 (define-key map (kbd "C-c C--") 'markdown-promote)
3028 (define-key map (kbd "C-c C-=") 'markdown-demote)
3029 (define-key map (kbd "M-<left>") 'markdown-promote)
3030 (define-key map (kbd "M-<right>") 'markdown-demote)
3031 (define-key map (kbd "C-c C-]") 'markdown-complete-or-cycle)
3032 (define-key map (kbd "C-c C-[") 'markdown-complete-or-reverse-cycle)
3033 ;; Following and Jumping
3034 (define-key map (kbd "C-c C-o") 'markdown-follow-thing-at-point)
3035 (define-key map (kbd "C-c C-j") 'markdown-jump)
3036 ;; Indentation
3037 (define-key map (kbd "C-m") 'markdown-enter-key)
3038 (define-key map (kbd "<backspace>") 'markdown-exdent-or-delete)
3039 (define-key map (kbd "C-c >") 'markdown-indent-region)
3040 (define-key map (kbd "C-c <") 'markdown-exdent-region)
3041 ;; Visibility cycling
3042 (define-key map (kbd "<tab>") 'markdown-cycle)
3043 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
3044 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
3045 (define-key map (kbd "<backtab>") 'markdown-shifttab)
3046 ;; Header navigation
3047 (define-key map (kbd "C-c C-n") 'outline-next-visible-heading)
3048 (define-key map (kbd "C-c C-p") 'outline-previous-visible-heading)
3049 (define-key map (kbd "C-c C-f") 'outline-forward-same-level)
3050 (define-key map (kbd "C-c C-b") 'outline-backward-same-level)
3051 (define-key map (kbd "C-c C-u") 'outline-up-heading)
3052 ;; Buffer-wide commands
3053 (define-key map (kbd "C-c C-c m") 'markdown-other-window)
3054 (define-key map (kbd "C-c C-c p") 'markdown-preview)
3055 (define-key map (kbd "C-c C-c e") 'markdown-export)
3056 (define-key map (kbd "C-c C-c v") 'markdown-export-and-preview)
3057 (define-key map (kbd "C-c C-c o") 'markdown-open)
3058 (define-key map (kbd "C-c C-c w") 'markdown-kill-ring-save)
3059 (define-key map (kbd "C-c C-c c") 'markdown-check-refs)
3060 (define-key map (kbd "C-c C-c n") 'markdown-cleanup-list-numbers)
3061 (define-key map (kbd "C-c C-c ]") 'markdown-complete-buffer)
3062 ;; List editing
3063 (define-key map (kbd "M-<up>") 'markdown-move-up)
3064 (define-key map (kbd "M-<down>") 'markdown-move-down)
3065 (define-key map (kbd "M-<return>") 'markdown-insert-list-item)
3066 ;; Movement
3067 (define-key map (kbd "M-[") 'markdown-beginning-of-block)
3068 (define-key map (kbd "M-]") 'markdown-end-of-block)
3069 (define-key map (kbd "M-n") 'markdown-next-link)
3070 (define-key map (kbd "M-p") 'markdown-previous-link)
3071 map)
3072 "Keymap for Markdown major mode.")
3074 (defvar gfm-mode-map
3075 (let ((map (make-sparse-keymap)))
3076 (set-keymap-parent map markdown-mode-map)
3077 (define-key map "\C-c\C-sl" 'markdown-insert-gfm-code-block)
3078 map)
3079 "Keymap for `gfm-mode'.
3080 See also `markdown-mode-map'.")
3083 ;;; Menu ==================================================================
3085 (easy-menu-define markdown-mode-menu markdown-mode-map
3086 "Menu for Markdown mode"
3087 '("Markdown"
3088 ("Show/Hide"
3089 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
3090 ["Cycle global visibility" markdown-shifttab])
3091 "---"
3092 ["Compile" markdown-other-window]
3093 ["Preview" markdown-preview]
3094 ["Export" markdown-export]
3095 ["Export & View" markdown-export-and-preview]
3096 ["Open" markdown-open]
3097 ["Kill ring save" markdown-kill-ring-save]
3098 "---"
3099 ("Headings"
3100 ["Automatic" markdown-insert-header-dwim]
3101 ["Automatic (prefer setext)" markdown-insert-header-setext-dwim]
3102 "---"
3103 ["First level setext" markdown-insert-header-setext-1]
3104 ["Second level setext" markdown-insert-header-setext-2]
3105 "---"
3106 ["First level atx" markdown-insert-header-atx-1]
3107 ["Second level atx" markdown-insert-header-atx-2]
3108 ["Third level atx" markdown-insert-header-atx-3]
3109 ["Fourth level atx" markdown-insert-header-atx-4]
3110 ["Fifth level atx" markdown-insert-header-atx-5]
3111 ["Sixth level atx" markdown-insert-header-atx-6])
3112 "---"
3113 ["Bold" markdown-insert-bold]
3114 ["Italic" markdown-insert-italic]
3115 ["Blockquote" markdown-insert-blockquote]
3116 ["Preformatted" markdown-insert-pre]
3117 ["Code" markdown-insert-code]
3118 "---"
3119 ["Insert inline link" markdown-insert-link]
3120 ["Insert reference link" markdown-insert-reference-link-dwim]
3121 ["Insert URL" markdown-insert-uri]
3122 ["Insert inline image" markdown-insert-image]
3123 ["Insert reference image" markdown-insert-reference-image]
3124 ["Insert list item" markdown-insert-list-item]
3125 ["Insert horizontal rule" markdown-insert-hr]
3126 ["Insert footnote" markdown-footnote-new]
3127 ["Kill element" markdown-kill-thing-at-point]
3128 "---"
3129 ["Jump" markdown-jump]
3130 ["Follow link" markdown-follow-thing-at-point]
3131 ("Outline"
3132 ["Next visible heading" outline-next-visible-heading]
3133 ["Previous visible heading" outline-previous-visible-heading]
3134 ["Forward same level" outline-forward-same-level]
3135 ["Backward same level" outline-backward-same-level]
3136 ["Up to parent heading" outline-up-heading])
3137 "---"
3138 ("Completion and Cycling"
3139 ["Complete or cycle" markdown-complete-or-cycle]
3140 ["Complete or reverse cycle" markdown-complete-or-reverse-cycle]
3141 ["Promote" markdown-promote]
3142 ["Demote" markdown-demote])
3143 ("List editing"
3144 ["Indent list item" markdown-demote]
3145 ["Exdent list item" markdown-promote])
3146 ("Region shifting"
3147 ["Indent region" markdown-indent-region]
3148 ["Exdent region" markdown-exdent-region])
3149 "---"
3150 ["Check references" markdown-check-refs]
3151 ["Clean up list numbering" markdown-cleanup-list-numbers]
3152 ["Complete markup" markdown-complete-buffer]
3153 "---"
3154 ["Version" markdown-show-version]
3158 ;;; imenu =====================================================================
3160 (defun markdown-imenu-create-index ()
3161 "Create and return an imenu index alist for the current buffer.
3162 See `imenu-create-index-function' and `imenu--index-alist' for details."
3163 (let* ((root '(nil . nil))
3164 cur-alist
3165 (cur-level 0)
3166 (empty-heading "-")
3167 (self-heading ".")
3168 hashes pos level heading)
3169 (save-excursion
3170 (goto-char (point-min))
3171 (while (re-search-forward markdown-regex-header (point-max) t)
3172 (cond
3173 ((setq heading (match-string-no-properties 1))
3174 (setq pos (match-beginning 1)
3175 level 1))
3176 ((setq heading (match-string-no-properties 3))
3177 (setq pos (match-beginning 3)
3178 level 2))
3179 ((setq hashes (match-string-no-properties 5))
3180 (setq heading (match-string-no-properties 6)
3181 pos (match-beginning 5)
3182 level (length hashes))))
3183 (let ((alist (list (cons heading pos))))
3184 (cond
3185 ((= cur-level level) ; new sibling
3186 (setcdr cur-alist alist)
3187 (setq cur-alist alist))
3188 ((< cur-level level) ; first child
3189 (dotimes (i (- level cur-level 1))
3190 (setq alist (list (cons empty-heading alist))))
3191 (if cur-alist
3192 (let* ((parent (car cur-alist))
3193 (self-pos (cdr parent)))
3194 (setcdr parent (cons (cons self-heading self-pos) alist)))
3195 (setcdr root alist)) ; primogenitor
3196 (setq cur-alist alist)
3197 (setq cur-level level))
3198 (t ; new sibling of an ancestor
3199 (let ((sibling-alist (last (cdr root))))
3200 (dotimes (i (1- level))
3201 (setq sibling-alist (last (cdar sibling-alist))))
3202 (setcdr sibling-alist alist)
3203 (setq cur-alist alist))
3204 (setq cur-level level)))))
3205 (cdr root))))
3208 ;;; References ================================================================
3210 (defun markdown-insert-reference-definition (ref &optional buffer)
3211 "Add blank REF definition to the end of BUFFER.
3212 REF is a Markdown reference in square brackets, like \"[lisp-history]\"."
3213 (or buffer (setq buffer (current-buffer)))
3214 (with-current-buffer buffer
3215 (goto-char (point-max))
3216 (indent-new-comment-line)
3217 (insert (concat ref ": "))))
3219 (defun markdown-reference-goto-definition ()
3220 "Jump to the definition of the reference at point or create it."
3221 (interactive)
3222 (when (thing-at-point-looking-at markdown-regex-link-reference)
3223 (let* ((text (match-string-no-properties 2))
3224 (reference (match-string-no-properties 4))
3225 (target (downcase (if (string= reference "[]") text reference)))
3226 (loc (cadr (markdown-reference-definition target))))
3227 (if loc
3228 (goto-char loc)
3229 (markdown-insert-reference-definition target (current-buffer))))))
3231 (defun markdown-reference-find-links (reference)
3232 "Return a list of all links for REFERENCE.
3233 REFERENCE should include the surrounding square brackets like [this].
3234 Elements of the list have the form (text start line), where
3235 text is the link text, start is the location at the beginning of
3236 the link, and line is the line number on which the link appears."
3237 (let* ((ref-quote (regexp-quote (substring reference 1 -1)))
3238 (regexp (format "!?\\(?:\\[\\(%s\\)\\][ ]?\\[\\]\\|\\[\\([^]]+?\\)\\][ ]?\\[%s\\]\\)"
3239 ref-quote ref-quote))
3240 links)
3241 (save-excursion
3242 (goto-char (point-min))
3243 (while (re-search-forward regexp nil t)
3244 (let* ((text (or (match-string-no-properties 1)
3245 (match-string-no-properties 2)))
3246 (start (match-beginning 0))
3247 (line (markdown-line-number-at-pos)))
3248 (add-to-list 'links (list text start line)))))
3249 links))
3251 (defun markdown-get-undefined-refs ()
3252 "Return a list of undefined Markdown references.
3253 Result is an alist of pairs (reference . occurrences), where
3254 occurrences is itself another alist of pairs (label . line-number).
3255 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
3256 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
3257 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
3258 (let ((missing))
3259 (save-excursion
3260 (goto-char (point-min))
3261 (while
3262 (re-search-forward markdown-regex-link-reference nil t)
3263 (let* ((text (match-string-no-properties 2))
3264 (reference (match-string-no-properties 4))
3265 (target (downcase (if (string= reference "[]") text reference))))
3266 (unless (markdown-reference-definition target)
3267 (let ((entry (assoc target missing)))
3268 (if (not entry)
3269 (add-to-list 'missing (cons target
3270 (list (cons text (markdown-line-number-at-pos)))) t)
3271 (setcdr entry
3272 (append (cdr entry) (list (cons text (markdown-line-number-at-pos))))))))))
3273 missing)))
3275 (defconst markdown-reference-check-buffer
3276 "*Undefined references for %buffer%*"
3277 "Pattern for name of buffer for listing undefined references.
3278 The string %buffer% will be replaced by the corresponding
3279 `markdown-mode' buffer name.")
3281 (defun markdown-reference-check-buffer (&optional buffer-name)
3282 "Name and return buffer for reference checking.
3283 BUFFER-NAME is the name of the main buffer being visited."
3284 (or buffer-name (setq buffer-name (buffer-name)))
3285 (let ((refbuf (get-buffer-create (markdown-replace-regexp-in-string
3286 "%buffer%" buffer-name
3287 markdown-reference-check-buffer))))
3288 (with-current-buffer refbuf
3289 (when view-mode
3290 (View-exit-and-edit))
3291 (use-local-map button-buffer-map)
3292 (erase-buffer))
3293 refbuf))
3295 (defconst markdown-reference-links-buffer
3296 "*Reference links for %buffer%*"
3297 "Pattern for name of buffer for listing references.
3298 The string %buffer% will be replaced by the corresponding buffer name.")
3300 (defun markdown-reference-links-buffer (&optional buffer-name)
3301 "Name, setup, and return a buffer for listing links.
3302 BUFFER-NAME is the name of the main buffer being visited."
3303 (or buffer-name (setq buffer-name (buffer-name)))
3304 (let ((linkbuf (get-buffer-create (markdown-replace-regexp-in-string
3305 "%buffer%" buffer-name
3306 markdown-reference-links-buffer))))
3307 (with-current-buffer linkbuf
3308 (when view-mode
3309 (View-exit-and-edit))
3310 (use-local-map button-buffer-map)
3311 (erase-buffer))
3312 linkbuf))
3314 (when (markdown-use-buttons-p)
3315 ;; Add an empty Markdown reference definition to the end of buffer
3316 ;; specified in the 'target-buffer property. The reference name is
3317 ;; the button's label.
3318 (define-button-type 'markdown-undefined-reference-button
3319 'help-echo "mouse-1, RET: create definition for undefined reference"
3320 'follow-link t
3321 'face 'bold
3322 'action (lambda (b)
3323 (let ((buffer (button-get b 'target-buffer)))
3324 (markdown-insert-reference-definition (button-label b) buffer)
3325 (switch-to-buffer-other-window buffer)
3326 (goto-char (point-max))
3327 (markdown-check-refs t))))
3329 ;; Jump to line in buffer specified by 'target-buffer property.
3330 ;; Line number is button's 'line property.
3331 (define-button-type 'markdown-goto-line-button
3332 'help-echo "mouse-1, RET: go to line"
3333 'follow-link t
3334 'face 'italic
3335 'action (lambda (b)
3336 (message (button-get b 'buffer))
3337 (switch-to-buffer-other-window (button-get b 'target-buffer))
3338 ;; use call-interactively to silence compiler
3339 (let ((current-prefix-arg (button-get b 'target-line)))
3340 (call-interactively 'goto-line))))
3342 ;; Jumps to a particular link at location given by 'target-char
3343 ;; property in buffer given by 'target-buffer property.
3344 (define-button-type 'markdown-link-button
3345 'help-echo "mouse-1, RET: jump to location of link"
3346 'follow-link t
3347 'face 'bold
3348 'action (lambda (b)
3349 (let ((target (button-get b 'target-buffer))
3350 (loc (button-get b 'target-char)))
3351 (kill-buffer-and-window)
3352 (switch-to-buffer target)
3353 (goto-char loc)))))
3355 (defun markdown-insert-undefined-reference-button (reference oldbuf)
3356 "Insert a button for creating REFERENCE in buffer OLDBUF.
3357 REFERENCE should be a list of the form (reference . occurrences),
3358 as by `markdown-get-undefined-refs'."
3359 (let ((label (car reference)))
3360 (if (markdown-use-buttons-p)
3361 ;; Create a reference button in Emacs 22
3362 (insert-button label
3363 :type 'markdown-undefined-reference-button
3364 'target-buffer oldbuf)
3365 ;; Insert reference as text in Emacs < 22
3366 (insert label))
3367 (insert " (")
3368 (dolist (occurrence (cdr reference))
3369 (let ((line (cdr occurrence)))
3370 (if (markdown-use-buttons-p)
3371 ;; Create a line number button in Emacs 22
3372 (insert-button (number-to-string line)
3373 :type 'markdown-goto-line-button
3374 'target-buffer oldbuf
3375 'target-line line)
3376 ;; Insert line number as text in Emacs < 22
3377 (insert (number-to-string line)))
3378 (insert " ")))
3379 (delete-char -1)
3380 (insert ")")
3381 (newline)))
3383 (defun markdown-insert-link-button (link oldbuf)
3384 "Insert a button for jumping to LINK in buffer OLDBUF.
3385 LINK should be a list of the form (text char line) containing
3386 the link text, location, and line number."
3387 (let ((label (first link))
3388 (char (second link))
3389 (line (third link)))
3390 (if (markdown-use-buttons-p)
3391 ;; Create a reference button in Emacs 22
3392 (insert-button label
3393 :type 'markdown-link-button
3394 'target-buffer oldbuf
3395 'target-char char)
3396 ;; Insert reference as text in Emacs < 22
3397 (insert label))
3398 (insert (format " (line %d)\n" line))))
3400 (defun markdown-reference-goto-link (&optional reference)
3401 "Jump to the location of the first use of REFERENCE."
3402 (interactive)
3403 (unless reference
3404 (if (thing-at-point-looking-at markdown-regex-reference-definition)
3405 (setq reference (match-string-no-properties 1))
3406 (error "No reference definition at point")))
3407 (let ((links (markdown-reference-find-links reference)))
3408 (cond ((= (length links) 1)
3409 (goto-char (cadr (car links))))
3410 ((> (length links) 1)
3411 (let ((oldbuf (current-buffer))
3412 (linkbuf (markdown-reference-links-buffer)))
3413 (with-current-buffer linkbuf
3414 (insert "Links using reference " reference ":\n\n")
3415 (dolist (link (reverse links))
3416 (markdown-insert-link-button link oldbuf)))
3417 (view-buffer-other-window linkbuf)
3418 (goto-char (point-min))
3419 (forward-line 2)))
3421 (error "No links for reference %s" reference)))))
3423 (defun markdown-check-refs (&optional silent)
3424 "Show all undefined Markdown references in current `markdown-mode' buffer.
3425 If SILENT is non-nil, do not message anything when no undefined
3426 references found.
3427 Links which have empty reference definitions are considered to be
3428 defined."
3429 (interactive "P")
3430 (when (not (eq major-mode 'markdown-mode))
3431 (error "Not available in current mode"))
3432 (let ((oldbuf (current-buffer))
3433 (refs (markdown-get-undefined-refs))
3434 (refbuf (markdown-reference-check-buffer)))
3435 (if (null refs)
3436 (progn
3437 (when (not silent)
3438 (message "No undefined references found"))
3439 (kill-buffer refbuf))
3440 (with-current-buffer refbuf
3441 (insert "The following references are undefined:\n\n")
3442 (dolist (ref refs)
3443 (markdown-insert-undefined-reference-button ref oldbuf))
3444 (view-buffer-other-window refbuf)
3445 (goto-char (point-min))
3446 (forward-line 2)))))
3449 ;;; Lists =====================================================================
3451 (defun markdown-insert-list-item (&optional arg)
3452 "Insert a new list item.
3453 If the point is inside unordered list, insert a bullet mark. If
3454 the point is inside ordered list, insert the next number followed
3455 by a period. Use the previous list item to determine the amount
3456 of whitespace to place before and after list markers.
3458 With a \\[universal-argument] prefix (i.e., when ARG is 4),
3459 decrease the indentation by one level.
3461 With two \\[universal-argument] prefixes (i.e., when ARG is 16),
3462 increase the indentation by one level."
3463 (interactive "p")
3464 (let (bounds item-indent marker indent new-indent new-loc)
3465 (save-match-data
3466 ;; Look for a list item on current or previous non-blank line
3467 (save-excursion
3468 (while (and (not (setq bounds (markdown-cur-list-item-bounds)))
3469 (not (bobp))
3470 (markdown-cur-line-blank-p))
3471 (forward-line -1)))
3472 (when bounds
3473 (cond ((save-excursion
3474 (skip-chars-backward " \t")
3475 (looking-at markdown-regex-list))
3476 (beginning-of-line)
3477 (insert "\n")
3478 (forward-line -1))
3479 ((not (markdown-cur-line-blank-p))
3480 (newline)))
3481 (setq new-loc (point)))
3482 ;; Look ahead for a list item on next non-blank line
3483 (unless bounds
3484 (save-excursion
3485 (while (and (null bounds)
3486 (not (eobp))
3487 (markdown-cur-line-blank-p))
3488 (forward-line)
3489 (setq bounds (markdown-cur-list-item-bounds))))
3490 (when bounds
3491 (setq new-loc (point))
3492 (unless (markdown-cur-line-blank-p)
3493 (newline))))
3494 (if (not bounds)
3495 ;; When not in a list, start a new unordered one
3496 (progn
3497 (unless (markdown-cur-line-blank-p)
3498 (insert "\n"))
3499 (insert "* "))
3500 ;; Compute indentation for a new list item
3501 (setq item-indent (nth 2 bounds))
3502 (setq marker (nth 4 bounds))
3503 (setq indent (cond
3504 ((= arg 4) (max (- item-indent 4) 0))
3505 ((= arg 16) (+ item-indent 4))
3506 (t item-indent)))
3507 (setq new-indent (make-string indent 32))
3508 (goto-char new-loc)
3509 (cond
3510 ;; Ordered list
3511 ((string-match "[0-9]" marker)
3512 (if (= arg 16) ;; starting a new column indented one more level
3513 (insert (concat new-indent "1. "))
3514 ;; travel up to the last item and pick the correct number. If
3515 ;; the argument was nil, "new-indent = item-indent" is the same,
3516 ;; so we don't need special treatment. Neat.
3517 (save-excursion
3518 (while (not (looking-at (concat new-indent "\\([0-9]+\\)\\.")))
3519 (forward-line -1)))
3520 (insert (concat new-indent
3521 (int-to-string (1+ (string-to-number (match-string 1))))
3522 ". "))))
3523 ;; Unordered list
3524 ((string-match "[\\*\\+-]" marker)
3525 (insert new-indent marker)))))))
3527 (defun markdown-move-list-item-up ()
3528 "Move the current list item up in the list when possible."
3529 (interactive)
3530 (let (cur prev old)
3531 (when (setq cur (markdown-cur-list-item-bounds))
3532 (setq old (point))
3533 (goto-char (nth 0 cur))
3534 (if (markdown-prev-list-item (nth 3 cur))
3535 (progn
3536 (setq prev (markdown-cur-list-item-bounds))
3537 (condition-case nil
3538 (progn
3539 (transpose-regions (nth 0 prev) (nth 1 prev)
3540 (nth 0 cur) (nth 1 cur) t)
3541 (goto-char (+ (nth 0 prev) (- old (nth 0 cur)))))
3542 ;; Catch error in case regions overlap.
3543 (error (goto-char old))))
3544 (goto-char old)))))
3546 (defun markdown-move-list-item-down ()
3547 "Move the current list item down in the list when possible."
3548 (interactive)
3549 (let (cur next old)
3550 (when (setq cur (markdown-cur-list-item-bounds))
3551 (setq old (point))
3552 (if (markdown-next-list-item (nth 3 cur))
3553 (progn
3554 (setq next (markdown-cur-list-item-bounds))
3555 (condition-case nil
3556 (progn
3557 (transpose-regions (nth 0 cur) (nth 1 cur)
3558 (nth 0 next) (nth 1 next) nil)
3559 (goto-char (+ old (- (nth 1 next) (nth 1 cur)))))
3560 ;; Catch error in case regions overlap.
3561 (error (goto-char old))))
3562 (goto-char old)))))
3564 (defun markdown-demote-list-item (&optional bounds)
3565 "Indent (or demote) the current list item.
3566 Optionally, BOUNDS of the current list item may be provided if available."
3567 (interactive)
3568 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3569 (save-excursion
3570 (save-match-data
3571 (let* ((end-marker (make-marker))
3572 (end-marker (set-marker end-marker (nth 1 bounds))))
3573 (goto-char (nth 0 bounds))
3574 (while (< (point) end-marker)
3575 (unless (markdown-cur-line-blank-p)
3576 (insert " "))
3577 (forward-line)))))))
3579 (defun markdown-promote-list-item (&optional bounds)
3580 "Unindent (or promote) the current list item.
3581 Optionally, BOUNDS of the current list item may be provided if available."
3582 (interactive)
3583 (when (or bounds (setq bounds (markdown-cur-list-item-bounds)))
3584 (save-excursion
3585 (save-match-data
3586 (let* ((end-marker (make-marker))
3587 (end-marker (set-marker end-marker (nth 1 bounds)))
3588 num regexp)
3589 (goto-char (nth 0 bounds))
3590 (when (looking-at "^[ ]\\{1,4\\}")
3591 (setq num (- (match-end 0) (match-beginning 0)))
3592 (setq regexp (format "^[ ]\\{1,%d\\}" num))
3593 (while (and (< (point) end-marker)
3594 (re-search-forward regexp end-marker t))
3595 (replace-match "" nil nil)
3596 (forward-line))))))))
3598 (defun markdown--cleanup-list-numbers-level (&optional pfx)
3599 "Update the numbering for level PFX (as a string of spaces).
3601 Assume that the previously found match was for a numbered item in
3602 a list."
3603 (let ((cpfx pfx)
3604 (idx 0)
3605 (continue t)
3606 (step t)
3607 (sep nil))
3608 (while (and continue (not (eobp)))
3609 (setq step t)
3610 (cond
3611 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
3612 (setq cpfx (match-string-no-properties 1))
3613 (cond
3614 ((string= cpfx pfx)
3615 (replace-match
3616 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
3617 (setq sep nil))
3618 ;; indented a level
3619 ((string< pfx cpfx)
3620 (setq sep (markdown--cleanup-list-numbers-level cpfx))
3621 (setq step nil))
3622 ;; exit the loop
3624 (setq step nil)
3625 (setq continue nil))))
3627 ((looking-at "^\\([\s-]*\\)[^ \t\n\r].*$")
3628 (setq cpfx (match-string-no-properties 1))
3629 (cond
3630 ;; reset if separated before
3631 ((string= cpfx pfx) (when sep (setq idx 0)))
3632 ((string< cpfx pfx)
3633 (setq step nil)
3634 (setq continue nil))))
3635 (t (setq sep t)))
3637 (when step
3638 (beginning-of-line)
3639 (setq continue (= (forward-line) 0))))
3640 sep))
3642 (defun markdown-cleanup-list-numbers ()
3643 "Update the numbering of ordered lists."
3644 (interactive)
3645 (save-excursion
3646 (goto-char (point-min))
3647 (markdown--cleanup-list-numbers-level "")))
3650 ;;; Outline ===================================================================
3652 (defvar markdown-cycle-global-status 1)
3653 (defvar markdown-cycle-subtree-status nil)
3655 (defun markdown-end-of-subtree (&optional invisible-OK)
3656 "Move to the end of the current subtree.
3657 Only visible heading lines are considered, unless INVISIBLE-OK is
3658 non-nil.
3659 Derived from `org-end-of-subtree'."
3660 (outline-back-to-heading invisible-OK)
3661 (let ((first t)
3662 (level (funcall outline-level)))
3663 (while (and (not (eobp))
3664 (or first (> (funcall outline-level) level)))
3665 (setq first nil)
3666 (outline-next-heading))
3667 (if (memq (preceding-char) '(?\n ?\^M))
3668 (progn
3669 ;; Go to end of line before heading
3670 (forward-char -1)
3671 (if (memq (preceding-char) '(?\n ?\^M))
3672 ;; leave blank line before heading
3673 (forward-char -1)))))
3674 (point))
3676 (defun markdown-cycle (&optional arg)
3677 "Visibility cycling for Markdown mode.
3678 If ARG is t, perform global visibility cycling. If the point is
3679 at an atx-style header, cycle visibility of the corresponding
3680 subtree. Otherwise, insert a tab using `indent-relative'.
3681 Derived from `org-cycle'."
3682 (interactive "P")
3683 (cond
3684 ((eq arg t) ;; Global cycling
3685 (cond
3686 ((and (eq last-command this-command)
3687 (eq markdown-cycle-global-status 2))
3688 ;; Move from overview to contents
3689 (hide-sublevels 1)
3690 (message "CONTENTS")
3691 (setq markdown-cycle-global-status 3))
3693 ((and (eq last-command this-command)
3694 (eq markdown-cycle-global-status 3))
3695 ;; Move from contents to all
3696 (show-all)
3697 (message "SHOW ALL")
3698 (setq markdown-cycle-global-status 1))
3701 ;; Defaults to overview
3702 (hide-body)
3703 (message "OVERVIEW")
3704 (setq markdown-cycle-global-status 2))))
3706 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3707 ;; At a heading: rotate between three different views
3708 (outline-back-to-heading)
3709 (let ((goal-column 0) eoh eol eos)
3710 ;; Determine boundaries
3711 (save-excursion
3712 (outline-back-to-heading)
3713 (save-excursion
3714 (beginning-of-line 2)
3715 (while (and (not (eobp)) ;; this is like `next-line'
3716 (get-char-property (1- (point)) 'invisible))
3717 (beginning-of-line 2)) (setq eol (point)))
3718 (outline-end-of-heading) (setq eoh (point))
3719 (markdown-end-of-subtree t)
3720 (skip-chars-forward " \t\n")
3721 (beginning-of-line 1) ; in case this is an item
3722 (setq eos (1- (point))))
3723 ;; Find out what to do next and set `this-command'
3724 (cond
3725 ((= eos eoh)
3726 ;; Nothing is hidden behind this heading
3727 (message "EMPTY ENTRY")
3728 (setq markdown-cycle-subtree-status nil))
3729 ((>= eol eos)
3730 ;; Entire subtree is hidden in one line: open it
3731 (show-entry)
3732 (show-children)
3733 (message "CHILDREN")
3734 (setq markdown-cycle-subtree-status 'children))
3735 ((and (eq last-command this-command)
3736 (eq markdown-cycle-subtree-status 'children))
3737 ;; We just showed the children, now show everything.
3738 (show-subtree)
3739 (message "SUBTREE")
3740 (setq markdown-cycle-subtree-status 'subtree))
3742 ;; Default action: hide the subtree.
3743 (hide-subtree)
3744 (message "FOLDED")
3745 (setq markdown-cycle-subtree-status 'folded)))))
3748 (indent-for-tab-command))))
3750 (defun markdown-shifttab ()
3751 "Global visibility cycling.
3752 Calls `markdown-cycle' with argument t."
3753 (interactive)
3754 (markdown-cycle t))
3756 (defun markdown-outline-level ()
3757 "Return the depth to which a statement is nested in the outline."
3758 (cond
3759 ((match-end 1) 1)
3760 ((match-end 3) 2)
3761 ((- (match-end 5) (match-beginning 5)))))
3764 ;;; Movement ==================================================================
3766 (defun markdown-beginning-of-defun (&optional arg)
3767 "`beginning-of-defun-function' for Markdown.
3768 Move backward to the beginning of the current or previous section.
3769 When ARG is non-nil, repeat that many times. When ARG is negative,
3770 move forward to the ARG-th following section."
3771 (interactive "P")
3772 (or arg (setq arg 1))
3773 (or (re-search-backward markdown-regex-header nil t arg)
3774 (goto-char (point-min))))
3776 (defun markdown-end-of-defun (&optional arg)
3777 "`end-of-defun-function' for Markdown.
3778 Move forward to the end of the current or following section.
3779 When ARG is non-nil, repeat that many times. When ARG is negative,
3780 move back to the ARG-th preceding section."
3781 (interactive "P")
3782 (or arg (setq arg 1))
3783 (when (looking-at markdown-regex-header)
3784 (goto-char (match-beginning 0))
3785 (forward-char 1))
3786 (if (re-search-forward markdown-regex-header nil t arg)
3787 (goto-char (match-beginning 0))
3788 (goto-char (point-max)))
3789 (skip-syntax-backward "-"))
3791 (defun markdown-beginning-of-block ()
3792 "Move the point to the start of the previous text block."
3793 (interactive)
3794 (if (re-search-backward markdown-regex-block-separator nil t)
3795 (goto-char (or (match-end 2) (match-end 0)))
3796 (goto-char (point-min))))
3798 (defun markdown-end-of-block ()
3799 "Move the point to the start of the next text block."
3800 (interactive)
3801 (beginning-of-line)
3802 (skip-syntax-forward "-")
3803 (when (= (point) (point-min))
3804 (forward-char))
3805 (if (re-search-forward markdown-regex-block-separator nil t)
3806 (goto-char (or (match-end 2) (match-end 0)))
3807 (goto-char (point-max)))
3808 (skip-syntax-backward "-")
3809 (forward-line))
3811 (defun markdown-end-of-block-element ()
3812 "Move the point to the start of the next block unit.
3813 Stops at blank lines, list items, headers, and horizontal rules."
3814 (interactive)
3815 (forward-line)
3816 (while (and (or (not (markdown-prev-line-blank-p))
3817 (markdown-cur-line-blank-p))
3818 (not (or (looking-at markdown-regex-list)
3819 (looking-at markdown-regex-header)
3820 (looking-at markdown-regex-hr)))
3821 (not (eobp)))
3822 (forward-line)))
3824 (defun markdown-next-link ()
3825 "Jump to next inline, reference, or wiki link.
3826 If successful, return point. Otherwise, return nil.
3827 See `markdown-wiki-link-p' and `markdown-previous-wiki-link'."
3828 (interactive)
3829 (let ((opoint (point)))
3830 (when (or (markdown-link-p) (markdown-wiki-link-p))
3831 ;; At a link already, move past it.
3832 (goto-char (+ (match-end 0) 1)))
3833 ;; Search for the next wiki link and move to the beginning.
3834 (if (re-search-forward markdown-regex-link-generic nil t)
3835 ;; Group 1 will move past non-escape character in wiki link regexp.
3836 ;; Go to beginning of group zero for all other link types.
3837 (goto-char (or (match-beginning 1) (match-beginning 0)))
3838 (goto-char opoint)
3839 nil)))
3841 (defun markdown-previous-link ()
3842 "Jump to previous wiki link.
3843 If successful, return point. Otherwise, return nil.
3844 See `markdown-wiki-link-p' and `markdown-next-wiki-link'."
3845 (interactive)
3846 (if (re-search-backward markdown-regex-link-generic nil t)
3847 (goto-char (or (match-beginning 1) (match-beginning 0)))
3848 nil))
3851 ;;; Generic Structure Editing, Completion, and Cycling Commands ===============
3853 (defun markdown-move-up ()
3854 "Move list item up.
3855 Calls `markdown-move-list-item-up'."
3856 (interactive)
3857 (markdown-move-list-item-up))
3859 (defun markdown-move-down ()
3860 "Move list item down.
3861 Calls `markdown-move-list-item-down'."
3862 (interactive)
3863 (markdown-move-list-item-down))
3865 (defun markdown-promote ()
3866 "Either promote header or list item at point or cycle markup.
3867 See `markdown-cycle-atx', `markdown-cycle-setext', and
3868 `markdown-demote-list-item'."
3869 (interactive)
3870 (let (bounds)
3871 (cond
3872 ;; Promote atx header
3873 ((thing-at-point-looking-at markdown-regex-header-atx)
3874 (markdown-cycle-atx -1 t))
3875 ;; Promote setext header
3876 ((thing-at-point-looking-at markdown-regex-header-setext)
3877 (markdown-cycle-setext -1 t))
3878 ;; Promote horizonal rule
3879 ((thing-at-point-looking-at markdown-regex-hr)
3880 (markdown-cycle-hr -1 t))
3881 ;; Promote list item
3882 ((setq bounds (markdown-cur-list-item-bounds))
3883 (markdown-promote-list-item)))))
3885 (defun markdown-demote ()
3886 "Either demote header or list item at point or cycle or remove markup.
3887 See `markdown-cycle-atx', `markdown-cycle-setext', and
3888 `markdown-demote-list-item'."
3889 (interactive)
3890 (let (bounds)
3891 (cond
3892 ;; Demote atx header
3893 ((thing-at-point-looking-at markdown-regex-header-atx)
3894 (markdown-cycle-atx 1 t))
3895 ;; Demote setext header
3896 ((thing-at-point-looking-at markdown-regex-header-setext)
3897 (markdown-cycle-setext 1 t))
3898 ;; Demote horizonal rule
3899 ((thing-at-point-looking-at markdown-regex-hr)
3900 (markdown-cycle-hr 1 t))
3901 ;; Promote list item
3902 ((setq bounds (markdown-cur-list-item-bounds))
3903 (markdown-demote-list-item))
3904 ;; Create a new level one ATX header
3906 (markdown-insert-header-atx-1)))))
3908 (defun markdown-complete-or-cycle (arg)
3909 "Complete or cycle markup of object at point or complete objects in region.
3910 If there is an active region, complete markup in region.
3911 Otherwise, complete or cycle markup of object near point.
3912 When ARG is non-nil, cycle backwards when cycling."
3913 (interactive "*P")
3914 (if (markdown-use-region-p)
3915 ;; Complete markup in region
3916 (markdown-complete-region (region-beginning) (region-end))
3917 ;; Complete or cycle markup at point
3918 (let ((dir (if arg -1 1))
3919 bounds)
3920 (cond
3921 ;; atx header
3922 ((thing-at-point-looking-at markdown-regex-header-atx)
3923 (if (markdown-incomplete-atx-p)
3924 (markdown-complete-atx)
3925 (markdown-cycle-atx dir)))
3926 ;; setext header
3927 ((thing-at-point-looking-at markdown-regex-header-setext)
3928 (if (markdown-incomplete-setext-p)
3929 (markdown-complete-setext)
3930 (markdown-cycle-setext dir)))
3931 ;; horizonal rule
3932 ((thing-at-point-looking-at markdown-regex-hr)
3933 (if (markdown-incomplete-hr-p)
3934 (markdown-complete-hr)
3935 (markdown-cycle-hr dir)))
3936 ;; bold
3937 ((thing-at-point-looking-at markdown-regex-bold)
3938 (markdown-cycle-bold))
3939 ;; italic
3940 ((thing-at-point-looking-at markdown-regex-italic)
3941 (markdown-cycle-italic))))))
3943 (defun markdown-complete-or-reverse-cycle ()
3944 "Complete or reverse cycle markup at point or complete objects in region.
3945 Call `markdown-complete-or-cycle' with prefix argument."
3946 (interactive)
3947 (markdown-complete-or-cycle t))
3950 ;;; Commands ==================================================================
3952 (defun markdown (&optional output-buffer-name)
3953 "Run `markdown-command' on buffer, sending output to OUTPUT-BUFFER-NAME.
3954 The output buffer name defaults to `markdown-output-buffer-name'.
3955 Return the name of the output buffer used."
3956 (interactive)
3957 (save-window-excursion
3958 (let ((begin-region)
3959 (end-region))
3960 (if (markdown-use-region-p)
3961 (setq begin-region (region-beginning)
3962 end-region (region-end))
3963 (setq begin-region (point-min)
3964 end-region (point-max)))
3966 (unless output-buffer-name
3967 (setq output-buffer-name markdown-output-buffer-name))
3969 (cond
3970 ;; Handle case when `markdown-command' does not read from stdin
3971 (markdown-command-needs-filename
3972 (if (not buffer-file-name)
3973 (error "Must be visiting a file")
3974 (shell-command (concat markdown-command " "
3975 (shell-quote-argument buffer-file-name))
3976 output-buffer-name)))
3977 ;; Pass region to `markdown-command' via stdin
3979 (shell-command-on-region begin-region end-region markdown-command
3980 output-buffer-name))))
3981 output-buffer-name))
3983 (defun markdown-standalone (&optional output-buffer-name)
3984 "Special function to provide standalone HTML output.
3985 Insert the output in the buffer named OUTPUT-BUFFER-NAME."
3986 (interactive)
3987 (setq output-buffer-name (markdown output-buffer-name))
3988 (with-current-buffer output-buffer-name
3989 (set-buffer output-buffer-name)
3990 (goto-char (point-min))
3991 (unless (markdown-output-standalone-p)
3992 (markdown-add-xhtml-header-and-footer output-buffer-name))
3993 (html-mode))
3994 output-buffer-name)
3996 (defun markdown-other-window (&optional output-buffer-name)
3997 "Run `markdown-command' on current buffer and display in other window.
3998 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
3999 that name."
4000 (interactive)
4001 (display-buffer (markdown-standalone output-buffer-name)))
4003 (defun markdown-output-standalone-p ()
4004 "Determine whether `markdown-command' output is standalone XHTML.
4005 Standalone XHTML output is identified by an occurrence of
4006 `markdown-xhtml-standalone-regexp' in the first five lines of output."
4007 (re-search-forward
4008 markdown-xhtml-standalone-regexp
4009 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
4012 (defun markdown-add-xhtml-header-and-footer (title)
4013 "Wrap XHTML header and footer with given TITLE around current buffer."
4014 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
4015 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
4016 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
4017 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
4018 "<head>\n<title>")
4019 (insert title)
4020 (insert "</title>\n")
4021 (when (> (length markdown-content-type) 0)
4022 (insert
4023 (format
4024 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
4025 markdown-content-type
4026 (or (and markdown-coding-system
4027 (fboundp 'coding-system-get)
4028 (coding-system-get markdown-coding-system
4029 'mime-charset))
4030 (and (fboundp 'coding-system-get)
4031 (coding-system-get buffer-file-coding-system
4032 'mime-charset))
4033 "iso-8859-1"))))
4034 (if (> (length markdown-css-path) 0)
4035 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
4036 markdown-css-path
4037 "\" />\n"))
4038 (when (> (length markdown-xhtml-header-content) 0)
4039 (insert markdown-xhtml-header-content))
4040 (insert "\n</head>\n\n"
4041 "<body>\n\n")
4042 (goto-char (point-max))
4043 (insert "\n"
4044 "</body>\n"
4045 "</html>\n"))
4047 (defun markdown-preview (&optional output-buffer-name)
4048 "Run `markdown-command' on the current buffer and view output in browser.
4049 When OUTPUT-BUFFER-NAME is given, insert the output in the buffer with
4050 that name."
4051 (interactive)
4052 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
4054 (defun markdown-export-file-name (&optional extension)
4055 "Attempt to generate a filename for Markdown output.
4056 The file extension will be EXTENSION if given, or .html by default.
4057 If the current buffer is visiting a file, we construct a new
4058 output filename based on that filename. Otherwise, return nil."
4059 (when (buffer-file-name)
4060 (unless extension
4061 (setq extension ".html"))
4062 (concat
4063 (cond
4064 ((buffer-file-name)
4065 (file-name-sans-extension (buffer-file-name)))
4066 (t (buffer-name)))
4067 extension)))
4069 (defun markdown-export (&optional output-file)
4070 "Run Markdown on the current buffer, save to file, and return the filename.
4071 If OUTPUT-FILE is given, use that as the filename. Otherwise, use the filename
4072 generated by `markdown-export-file-name', which will be constructed using the
4073 current filename, but with the extension removed and replaced with .html."
4074 (interactive)
4075 (unless output-file
4076 (setq output-file (markdown-export-file-name ".html")))
4077 (when output-file
4078 (let ((output-buffer-name))
4079 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
4080 (run-hook-with-args 'markdown-before-export-hooks output-file)
4081 (markdown-standalone output-buffer-name)
4082 (with-current-buffer output-buffer-name
4083 (save-buffer))
4084 (run-hook-with-args 'markdown-after-export-hooks output-file)
4085 output-file)))
4087 (defun markdown-export-and-preview ()
4088 "Export to XHTML using `markdown-export' and browse the resulting file."
4089 (interactive)
4090 (browse-url (markdown-export)))
4092 (defun markdown-open ()
4093 "Open file for the current buffer with `markdown-open-command'."
4094 (interactive)
4095 (if (not markdown-open-command)
4096 (error "Variable `markdown-open-command' must be set")
4097 (if (not buffer-file-name)
4098 (error "Must be visiting a file")
4099 (call-process markdown-open-command
4100 nil nil nil buffer-file-name))))
4102 (defun markdown-kill-ring-save ()
4103 "Run Markdown on file and store output in the kill ring."
4104 (interactive)
4105 (save-window-excursion
4106 (markdown)
4107 (with-current-buffer markdown-output-buffer-name
4108 (kill-ring-save (point-min) (point-max)))))
4111 ;;; Links =====================================================================
4113 (require 'thingatpt)
4115 (defun markdown-link-p ()
4116 "Return non-nil when `point' is at a non-wiki link.
4117 See `markdown-wiki-link-p' for more information."
4118 (let ((case-fold-search nil))
4119 (and (not (markdown-wiki-link-p))
4120 (or (thing-at-point-looking-at markdown-regex-link-inline)
4121 (thing-at-point-looking-at markdown-regex-link-reference)
4122 (thing-at-point-looking-at markdown-regex-uri)
4123 (thing-at-point-looking-at markdown-regex-angle-uri)))))
4125 (defun markdown-link-link ()
4126 "Return the link part of the regular (non-wiki) link at point.
4127 Works with both inline and reference style links. If point is
4128 not at a link or the link reference is not defined returns nil."
4129 (cond
4130 ((thing-at-point-looking-at markdown-regex-link-inline)
4131 (match-string-no-properties 5))
4132 ((thing-at-point-looking-at markdown-regex-link-reference)
4133 (let* ((text (match-string-no-properties 2))
4134 (reference (match-string-no-properties 4))
4135 (target (downcase (if (string= reference "[]") text reference))))
4136 (car (markdown-reference-definition target))))
4137 ((thing-at-point-looking-at markdown-regex-uri)
4138 (match-string-no-properties 0))
4139 ((thing-at-point-looking-at markdown-regex-angle-uri)
4140 (match-string-no-properties 2))
4141 (t nil)))
4143 (defun markdown-follow-link-at-point ()
4144 "Open the current non-wiki link in a browser."
4145 (interactive)
4146 (if (markdown-link-p) (browse-url (markdown-link-link))
4147 (error "Point is not at a Markdown link or URI")))
4150 ;;; WikiLink Following/Markup =================================================
4152 (defun markdown-wiki-link-p ()
4153 "Return non-nil when `point' is at a true wiki link.
4154 A true wiki link name matches `markdown-regex-wiki-link' but does not
4155 match the current file name after conversion. This modifies the data
4156 returned by `match-data'. Note that the potential wiki link name must
4157 be available via `match-string'."
4158 (let ((case-fold-search nil))
4159 (and (thing-at-point-looking-at markdown-regex-wiki-link)
4160 (or (not buffer-file-name)
4161 (not (string-equal (buffer-file-name)
4162 (markdown-convert-wiki-link-to-filename
4163 (markdown-wiki-link-link)))))
4164 (not (save-match-data
4165 (save-excursion))))))
4167 (defun markdown-wiki-link-link ()
4168 "Return the link part of the wiki link using current match data.
4169 The location of the link component depends on the value of
4170 `markdown-wiki-link-alias-first'."
4171 (if markdown-wiki-link-alias-first
4172 (or (match-string-no-properties 4) (match-string-no-properties 2))
4173 (match-string-no-properties 2)))
4175 (defun markdown-wiki-link-alias ()
4176 "Return the alias or text part of the wiki link using current match data.
4177 The location of the alias component depends on the value of
4178 `markdown-wiki-link-alias-first'."
4179 (if markdown-wiki-link-alias-first
4180 (match-string-no-properties 2)
4181 (or (match-string-no-properties 4) (match-string-no-properties 2))))
4183 (defun markdown-convert-wiki-link-to-filename (name)
4184 "Generate a filename from the wiki link NAME.
4185 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
4186 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
4187 and [[test test]] both map to Test-test.ext."
4188 (let ((basename (markdown-replace-regexp-in-string
4189 "[[:space:]\n]" markdown-link-space-sub-char name)))
4190 (when (eq major-mode 'gfm-mode)
4191 (setq basename (concat (upcase (substring basename 0 1))
4192 (downcase (substring basename 1 nil)))))
4193 (concat basename
4194 (if (buffer-file-name)
4195 (concat "."
4196 (file-name-extension (buffer-file-name)))))))
4198 (defun markdown-follow-wiki-link (name &optional other)
4199 "Follow the wiki link NAME.
4200 Convert the name to a file name and call `find-file'. Ensure that
4201 the new buffer remains in `markdown-mode'. Open the link in another
4202 window when OTHER is non-nil."
4203 (let ((filename (markdown-convert-wiki-link-to-filename name))
4204 (wp (file-name-directory buffer-file-name)))
4205 (when other (other-window 1))
4206 (find-file (concat wp filename)))
4207 (when (not (eq major-mode 'markdown-mode))
4208 (markdown-mode)))
4210 (defun markdown-follow-wiki-link-at-point (&optional arg)
4211 "Find Wiki Link at point.
4212 With prefix argument ARG, open the file in other window.
4213 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
4214 (interactive "P")
4215 (if (markdown-wiki-link-p)
4216 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
4217 (error "Point is not at a Wiki Link")))
4219 (defun markdown-highlight-wiki-link (from to face)
4220 "Highlight the wiki link in the region between FROM and TO using FACE."
4221 (put-text-property from to 'font-lock-face face))
4223 (defun markdown-unfontify-region-wiki-links (from to)
4224 "Remove wiki link faces from the region specified by FROM and TO."
4225 (interactive "nfrom: \nnto: ")
4226 (remove-text-properties from to '(font-lock-face markdown-link-face))
4227 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
4229 (defun markdown-fontify-region-wiki-links (from to)
4230 "Search region given by FROM and TO for wiki links and fontify them.
4231 If a wiki link is found check to see if the backing file exists
4232 and highlight accordingly."
4233 (goto-char from)
4234 (save-match-data
4235 (while (re-search-forward markdown-regex-wiki-link to t)
4236 (let ((highlight-beginning (match-beginning 1))
4237 (highlight-end (match-end 1))
4238 (file-name
4239 (markdown-convert-wiki-link-to-filename
4240 (markdown-wiki-link-link))))
4241 (if (file-exists-p file-name)
4242 (markdown-highlight-wiki-link
4243 highlight-beginning highlight-end markdown-link-face)
4244 (markdown-highlight-wiki-link
4245 highlight-beginning highlight-end markdown-link-face)
4246 (markdown-highlight-wiki-link
4247 highlight-beginning highlight-end markdown-missing-link-face))))))
4249 (defun markdown-extend-changed-region (from to)
4250 "Extend region given by FROM and TO so that we can fontify all links.
4251 The region is extended to the first newline before and the first
4252 newline after."
4253 ;; start looking for the first new line before 'from
4254 (goto-char from)
4255 (re-search-backward "\n" nil t)
4256 (let ((new-from (point-min))
4257 (new-to (point-max)))
4258 (if (not (= (point) from))
4259 (setq new-from (point)))
4260 ;; do the same thing for the first new line after 'to
4261 (goto-char to)
4262 (re-search-forward "\n" nil t)
4263 (if (not (= (point) to))
4264 (setq new-to (point)))
4265 (values new-from new-to)))
4267 (defun markdown-check-change-for-wiki-link (from to change)
4268 "Check region between FROM and TO for wiki links and re-fontfy as needed.
4269 Designed to be used with the `after-change-functions' hook.
4270 CHANGE is the number of bytes of pre-change text replaced by the
4271 given range."
4272 (interactive "nfrom: \nnto: \nnchange: ")
4273 (let* ((modified (buffer-modified-p))
4274 (buffer-undo-list t)
4275 (inhibit-read-only t)
4276 (inhibit-point-motion-hooks t)
4277 deactivate-mark
4278 buffer-file-truename)
4279 (unwind-protect
4280 (save-excursion
4281 (save-match-data
4282 (save-restriction
4283 ;; Extend the region to fontify so that it starts
4284 ;; and ends at safe places.
4285 (multiple-value-bind (new-from new-to)
4286 (markdown-extend-changed-region from to)
4287 ;; Unfontify existing fontification (start from scratch)
4288 (markdown-unfontify-region-wiki-links new-from new-to)
4289 ;; Now do the fontification.
4290 (markdown-fontify-region-wiki-links new-from new-to)))))
4291 (and (not modified)
4292 (buffer-modified-p)
4293 (set-buffer-modified-p nil)))))
4295 (defun markdown-fontify-buffer-wiki-links ()
4296 "Refontify all wiki links in the buffer."
4297 (interactive)
4298 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
4301 ;;; Following and Jumping =====================================================
4303 (defun markdown-follow-thing-at-point (arg)
4304 "Follow thing at point if possible, such as a reference link or wiki link.
4305 Opens inline and reference links in a browser. Opens wiki links
4306 to other files in the current window, or the another window if
4307 ARG is non-nil.
4308 See `markdown-follow-link-at-point' and
4309 `markdown-follow-wiki-link-at-point'."
4310 (interactive "P")
4311 (cond ((markdown-link-p)
4312 (markdown-follow-link-at-point))
4313 ((markdown-wiki-link-p)
4314 (markdown-follow-wiki-link-at-point arg))
4316 (error "Nothing to follow at point"))))
4318 (defun markdown-jump ()
4319 "Jump to another location based on context at point.
4320 Jumps between reference links and definitions; between footnote
4321 markers and footnote text."
4322 (interactive)
4323 (cond ((markdown-footnote-text-positions)
4324 (markdown-footnote-return))
4325 ((markdown-footnote-marker-positions)
4326 (markdown-footnote-goto-text))
4327 ((thing-at-point-looking-at markdown-regex-link-reference)
4328 (markdown-reference-goto-definition))
4329 ((thing-at-point-looking-at markdown-regex-reference-definition)
4330 (markdown-reference-goto-link (match-string-no-properties 1)))
4332 (error "Nothing to jump to from context at point"))))
4335 ;;; Miscellaneous =============================================================
4337 (defun markdown-compress-whitespace-string (str)
4338 "Compress whitespace in STR and return result.
4339 Leading and trailing whitespace is removed. Sequences of multiple
4340 spaces, tabs, and newlines are replaced with single spaces."
4341 (replace-regexp-in-string "\\(^[ \t\n]+\\|[ \t\n]+$\\)" ""
4342 (replace-regexp-in-string "[ \t\n]+" " " str)))
4344 (defun markdown-line-number-at-pos (&optional pos)
4345 "Return (narrowed) buffer line number at position POS.
4346 If POS is nil, use current buffer location.
4347 This is an exact copy of `line-number-at-pos' for use in emacs21."
4348 (let ((opoint (or pos (point))) start)
4349 (save-excursion
4350 (goto-char (point-min))
4351 (setq start (point))
4352 (goto-char opoint)
4353 (forward-line 0)
4354 (1+ (count-lines start (point))))))
4356 (defun markdown-nobreak-p ()
4357 "Return nil if it is acceptable to break the current line at the point."
4358 ;; inside in square brackets (e.g., link anchor text)
4359 (looking-back "\\[[^]]*"))
4361 (defun markdown-adaptive-fill-function ()
4362 "Return prefix for filling paragraph or nil if not determined."
4363 (cond
4364 ;; List item inside blockquote
4365 ((looking-at "^[ \t]*>[ \t]*\\([0-9]+\\.\\|[*+-]\\)[ \t]+")
4366 (replace-regexp-in-string
4367 "[0-9\\.*+-]" " " (match-string-no-properties 0)))
4368 ;; Blockquote
4369 ((looking-at "^[ \t]*>[ \t]*")
4370 (match-string-no-properties 0))
4371 ;; List items
4372 ((looking-at markdown-regex-list)
4373 (match-string-no-properties 0))
4374 ;; No match
4375 (t nil)))
4378 ;;; Extensions ================================================================
4380 (defun markdown-reload-extensions ()
4381 "Check settings, update font-lock keywords, and re-fontify buffer."
4382 (interactive)
4383 (when (eq major-mode 'markdown-mode)
4384 (setq markdown-mode-font-lock-keywords
4385 (append
4386 (when markdown-enable-math
4387 markdown-mode-font-lock-keywords-math)
4388 markdown-mode-font-lock-keywords-basic
4389 markdown-mode-font-lock-keywords-core))
4390 (setq font-lock-defaults '(markdown-mode-font-lock-keywords))
4391 (font-lock-refresh-defaults)))
4393 (defun markdown-enable-math (&optional arg)
4394 "Toggle support for inline and display LaTeX math expressions.
4395 With a prefix argument ARG, enable math mode if ARG is positive,
4396 and disable it otherwise. If called from Lisp, enable the mode
4397 if ARG is omitted or nil."
4398 (interactive (list (or current-prefix-arg 'toggle)))
4399 (setq markdown-enable-math
4400 (if (eq arg 'toggle)
4401 (not markdown-enable-math)
4402 (> (prefix-numeric-value arg) 0)))
4403 (if markdown-enable-math
4404 (message "markdown-mode math support enabled")
4405 (message "markdown-mode math support disabled"))
4406 (markdown-reload-extensions))
4409 ;;; Mode Definition ==========================================================
4411 (defun markdown-show-version ()
4412 "Show the version number in the minibuffer."
4413 (interactive)
4414 (message "markdown-mode, version %s" markdown-mode-version))
4416 ;;;###autoload
4417 (define-derived-mode markdown-mode text-mode "Markdown"
4418 "Major mode for editing Markdown files."
4419 ;; Natural Markdown tab width
4420 (setq tab-width 4)
4421 ;; Comments
4422 (make-local-variable 'comment-start)
4423 (setq comment-start "<!-- ")
4424 (make-local-variable 'comment-end)
4425 (setq comment-end " -->")
4426 (make-local-variable 'comment-start-skip)
4427 (setq comment-start-skip "<!--[ \t]*")
4428 (make-local-variable 'comment-column)
4429 (setq comment-column 0)
4430 ;; Font lock.
4431 (set (make-local-variable 'markdown-mode-font-lock-keywords) nil)
4432 (set (make-local-variable 'font-lock-defaults) nil)
4433 (set (make-local-variable 'font-lock-multiline) t)
4434 (markdown-reload-extensions)
4435 ;; Extensions
4436 (make-local-variable 'markdown-enable-math)
4437 (add-hook 'hack-local-variables-hook 'markdown-reload-extensions)
4438 ;; For imenu support
4439 (setq imenu-create-index-function 'markdown-imenu-create-index)
4440 ;; For menu support in XEmacs
4441 (easy-menu-add markdown-mode-menu markdown-mode-map)
4442 ;; Defun movement
4443 (set (make-local-variable 'beginning-of-defun-function)
4444 'markdown-beginning-of-defun)
4445 (set (make-local-variable 'end-of-defun-function)
4446 'markdown-end-of-defun)
4447 ;; Paragraph filling
4448 (set (make-local-variable 'paragraph-start)
4449 "\f\\|[ \t]*$\\|[ \t]*[*+-] \\|[ \t]*[0-9]+\\.\\|[ \t]*: ")
4450 (set (make-local-variable 'paragraph-separate)
4451 "\\(?:[ \t\f]\\|.* \\)*$")
4452 (set (make-local-variable 'adaptive-fill-first-line-regexp)
4453 "\\`[ \t]*>[ \t]*?\\'")
4454 (set (make-local-variable 'adaptive-fill-function)
4455 'markdown-adaptive-fill-function)
4456 ;; Outline mode
4457 (make-local-variable 'outline-regexp)
4458 (setq outline-regexp markdown-regex-header)
4459 (make-local-variable 'outline-level)
4460 (setq outline-level 'markdown-outline-level)
4461 ;; Cause use of ellipses for invisible text.
4462 (add-to-invisibility-spec '(outline . t))
4463 ;; Indentation and filling
4464 (make-local-variable 'fill-nobreak-predicate)
4465 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
4466 (setq indent-line-function markdown-indent-function)
4468 ;; Prepare hooks for XEmacs compatibility
4469 (when (featurep 'xemacs)
4470 (make-local-hook 'after-change-functions)
4471 (make-local-hook 'font-lock-extend-region-functions)
4472 (make-local-hook 'window-configuration-change-hook))
4474 ;; Multiline font lock
4475 (add-hook 'font-lock-extend-region-functions
4476 'markdown-font-lock-extend-region)
4478 ;; Anytime text changes make sure it gets fontified correctly
4479 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
4481 ;; If we left the buffer there is a really good chance we were
4482 ;; creating one of the wiki link documents. Make sure we get
4483 ;; refontified when we come back.
4484 (add-hook 'window-configuration-change-hook
4485 'markdown-fontify-buffer-wiki-links t t)
4487 ;; do the initial link fontification
4488 (markdown-fontify-buffer-wiki-links))
4490 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
4493 ;;; GitHub Flavored Markdown Mode ============================================
4495 (defvar gfm-font-lock-keywords
4496 (append
4497 ;; GFM features to match first
4498 (list
4499 (cons 'markdown-match-gfm-code-blocks '((1 markdown-pre-face)
4500 (2 markdown-language-keyword-face)
4501 (3 markdown-pre-face)
4502 (4 markdown-pre-face))))
4503 ;; Basic Markdown features (excluding possibly overridden ones)
4504 markdown-mode-font-lock-keywords-basic
4505 ;; GFM features to match last
4506 (list
4507 (cons markdown-regex-gfm-italic '(2 markdown-italic-face))))
4508 "Default highlighting expressions for GitHub-flavored Markdown mode.")
4510 ;;;###autoload
4511 (define-derived-mode gfm-mode markdown-mode "GFM"
4512 "Major mode for editing GitHub Flavored Markdown files."
4513 (setq markdown-link-space-sub-char "-")
4514 (set (make-local-variable 'font-lock-defaults)
4515 '(gfm-font-lock-keywords))
4516 (auto-fill-mode 0)
4517 ;; Use visual-line-mode if available, fall back to longlines-mode:
4518 (if (fboundp 'visual-line-mode)
4519 (visual-line-mode 1)
4520 (longlines-mode 1))
4521 ;; do the initial link fontification
4522 (markdown-fontify-buffer-wiki-links))
4525 (provide 'markdown-mode)
4527 ;;; markdown-mode.el ends here