goto the beginning of buffer before the renumbering lines
[markdown-mode.git] / markdown-mode.el
blob0bfe5ffdb47c5751f6a1f7bd6ec5ec38f9ed3f94
1 ;;; markdown-mode.el --- Emacs Major mode for Markdown-formatted text files
3 ;; Copyright (C) 2007-2011 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>
25 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
26 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
27 ;; Created: May 24, 2007
28 ;; Version: 1.8.1
29 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
30 ;; URL: http://jblevins.org/projects/markdown-mode/
32 ;; This file is not part of GNU Emacs.
34 ;; This program is free software; you can redistribute it and/or modify
35 ;; it under the terms of the GNU General Public License as published by
36 ;; the Free Software Foundation; either version 2, or (at your option)
37 ;; any later version.
39 ;; This program is distributed in the hope that it will be useful,
40 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
41 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 ;; GNU General Public License for more details.
44 ;; You should have received a copy of the GNU General Public License
45 ;; along with this program; if not, write to the Free Software
46 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
47 ;; Boston, MA 02110-1301, USA.
49 ;;; Commentary:
51 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
52 ;; text files in GNU Emacs. markdown-mode is free software, licensed
53 ;; under the GNU GPL.
55 ;; [Markdown]: http://daringfireball.net/projects/markdown/
57 ;; The latest stable version is markdown-mode 1.8.1, released on August 15, 2011:
59 ;; * [markdown-mode.el][]
60 ;; * [Screenshot][]
61 ;; * [Release notes][]
63 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
64 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
65 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
67 ;; markdown-mode is also available in several package managers, including:
69 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
70 ;; * RedHat and Fedora Linux: [emacs-goodies][]
71 ;; * OpenBSD: [textproc/markdown-mode][]
72 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
73 ;; * MacPorts: [markdown-mode.el][macports-package] ([pending][macports-ticket])
75 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
76 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
77 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
78 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
79 ;; [macports-package]: https://trac.macports.org/browser/trunk/dports/editors/markdown-mode.el/Portfile
80 ;; [macports-ticket]: http://trac.macports.org/ticket/35716
82 ;; The latest development version can be downloaded directly
83 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
84 ;; (browsable and clonable) Git repository at
85 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
86 ;; including the full project history, can be cloned via the Git protocol
87 ;; by running
89 ;; git clone git://jblevins.org/git/markdown-mode.git
91 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
93 ;;; Dependencies:
95 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
96 ;; 19 and XEmacs 19, which provides a uniform interface for creating
97 ;; menus in GNU Emacs and XEmacs.
99 ;;; Installation:
101 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
102 ;; the following lines to your `.emacs` file to associate markdown-mode
103 ;; with `.text` files:
105 ;; (autoload 'markdown-mode "markdown-mode"
106 ;; "Major mode for editing Markdown files" t)
107 ;; (add-to-list 'auto-mode-alist '("\\.text\\'" . markdown-mode))
109 ;; There is no consensus on an official file extension so change `.text` to
110 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
112 ;;; Customization:
114 ;; Although no configuration is *necessary* there are a few things
115 ;; that can be customized. The `M-x customize-mode` command
116 ;; provides an interface to all of the possible customizations:
118 ;; * `markdown-command' - the command used to run Markdown (default:
119 ;; `markdown'). This variable may be customized to pass
120 ;; command-line options to your Markdown processor of choice, but
121 ;; this command must accept input from `stdin`. If it does not, a
122 ;; simple wrapper script can be used to write `stdin` to a file
123 ;; and then pass that file to your Markdown interpreter. Ideally,
124 ;; this command will produce an XHTML fragment around which
125 ;; markdown-mode will wrap a header and footer (which can be
126 ;; further customized). However, it attempts to detect whether
127 ;; the command produces standalone XHTML output (via
128 ;; `markdown-xhtml-standalone-regexp'), in which case no header
129 ;; and footer content will be added.
131 ;; * `markdown-command-needs-filename' - set to non-nil if
132 ;; `markdown-command' does not accept input from stdin (default: nil).
133 ;; Instead, it will be passed a filename as the final command-line
134 ;; option. As a result, you will only be able to run Markdown
135 ;; 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-string' - string to use when inserting horizontal
146 ;; rules (default: `* * * * *').
148 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
149 ;; underscores for bold instead of two asterisks (default: `nil').
151 ;; * `markdown-italic-underscore' - set to a non-nil value to use
152 ;; underscores for italic instead of asterisks (default: `nil').
154 ;; * `markdown-indent-function' - the function to use for automatic
155 ;; indentation (default: `markdown-indent-line').
157 ;; * `markdown-indent-on-enter' - set to a non-nil value to
158 ;; automatically indent new lines when the enter key is pressed
159 ;; (default: `t')
161 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
162 ;; to automatically open a linked document in a new buffer if the
163 ;; cursor is an wiki link
164 ;; (default: `t')
166 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
167 ;; treat aliased wiki links like `[[link text|PageName]]`.
168 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
170 ;; * `markdown-uri-types' - a list of protocols for URIs that
171 ;; `markdown-mode' should highlight.
173 ;; * `markdown-enable-math' - syntax highlighting for
174 ;; LaTeX fragments (default: `nil').
176 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
178 ;; * `markdown-content-type' - when set to a nonempty string, an
179 ;; `http-equiv` attribute will be included in the XHTML `<head>`
180 ;; block. If needed, the suggested values are
181 ;; `application/xhtml+xml` or `text/html`.
183 ;; * `markdown-coding-system' - used for specifying the character
184 ;; set identifier in the `http-equiv` attribute (see
185 ;; `markdown-content-type'). When set to `nil',
186 ;; `buffer-file-coding-system' will be used (and falling back to
187 ;; `iso-8859-1' when unavailable). Common settings are `utf-8'
188 ;; and `iso-latin-1'.
190 ;; * `markdown-xhtml-header-content' - additional content to include
191 ;; in the XHTML `<head>` block.
193 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
194 ;; indicates whether the output of `markdown-command' is standalone
195 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
196 ;; this is not matched, we assume this output is a fragment and add
197 ;; our own header and footer.
199 ;; * `markdown-link-space-sub-char' - a character to replace spaces
200 ;; when mapping wiki links to filenames (default: `_`).
201 ;; For example, use an underscore for compatibility with the
202 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
203 ;; with Github wiki links.
205 ;; Additionally, the faces used for syntax highlighting can be modified to
206 ;; your liking by issuing `M-x customize-group RET markdown-faces`
207 ;; or by using the "Markdown Faces" link at the bottom of the mode
208 ;; customization screen.
210 ;; [Marked]: https://itunes.apple.com/us/app/marked/id448925439?ls=1&mt=12&partnerId=30&siteID=GpHp3Acs1Yo
212 ;;; Usage:
214 ;; Keybindings are grouped by prefixes based on their function. For
215 ;; example, commands dealing with headers begin with `C-c C-t`. The
216 ;; primary commands in each group will are described below. You can
217 ;; obtain a list of all keybindings by pressing `C-c C-h`.
219 ;; * Anchors: `C-c C-a`
221 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
222 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
223 ;; The label definition will be placed at the end of the current
224 ;; block. `C-c C-a w` acts similarly for wiki links of the form
225 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
226 ;; text in the region is used as the link text.
228 ;; * Commands: `C-c C-c`
230 ;; *Compile:* `C-c C-c m` will run Markdown on the current buffer
231 ;; and show the output in another buffer. *Preview*: `C-c C-c p`
232 ;; runs Markdown on the current buffer and previews, stores the
233 ;; output in a temporary file, and displays the file in a browser.
234 ;; *Export:* `C-c C-c e` will run Markdown on the current buffer
235 ;; and save the result in the file `basename.html`, where
236 ;; `basename` is the name of the Markdown file with the extension
237 ;; removed. *Export and View:* press `C-c C-c v` to export the
238 ;; file and view it in a browser. **For both export commands, the
239 ;; output file will be overwritten without notice.**
240 ;; *Open:* `C-c C-c o` will open the Markdown source file directly
241 ;; using `markdown-open-command'.
243 ;; To summarize:
245 ;; - `C-c C-c m`: `markdown-command' > `*markdown-output*` buffer.
246 ;; - `C-c C-c p`: `markdown-command' > temporary file > browser.
247 ;; - `C-c C-c e`: `markdown-command' > `basename.html`.
248 ;; - `C-c C-c v`: `markdown-command' > `basename.html` > browser.
249 ;; - `C-c C-c o`: `markdown-open-command'.
251 ;; `C-c C-c c` will check for undefined references. If there are
252 ;; any, a small buffer will open with a list of undefined
253 ;; references and the line numbers on which they appear. In Emacs
254 ;; 22 and greater, selecting a reference from this list and
255 ;; pressing `RET` will insert an empty reference definition at the
256 ;; end of the buffer. Similarly, selecting the line number will
257 ;; jump to the corresponding line.
259 ;; * Images: `C-c C-i`
261 ;; `C-c C-i i` inserts an image, using the active region (if any)
262 ;; as the alt text.
264 ;; * Physical styles: `C-c C-p`
266 ;; These commands all act on text in the active region, if any,
267 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
268 ;; the selected text bold, `C-c C-p f` formats the region as
269 ;; fixed-width text, and `C-c C-p i` is used for italic text.
271 ;; * Logical styles: `C-c C-s`
273 ;; These commands all act on text in the active region, if any,
274 ;; and insert empty markup fragments otherwise. Logical styles
275 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
276 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
277 ;; (`C-c C-s s`).
279 ;; * Headers: `C-c C-t`
281 ;; All header commands use text in the active region, if any, as
282 ;; the header text. To insert an atx or hash style level-n
283 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
284 ;; top-level setext or underline style header press `C-c C-t t`
285 ;; (mnemonic: title) and for a second-level underline-style header
286 ;; press `C-c C-t s` (mnemonic: section).
288 ;; * Footnotes: `C-c C-f`
290 ;; To create a new footnote at the point, press `C-c C-f n`.
291 ;; Press `C-c C-f g` with the point at a footnote to jump to the
292 ;; location where the footnote text is defined. Then, press
293 ;; `C-c C-f b` to return to the footnote marker in the main text.
294 ;; When the point is at a footnote marker or in the body of a
295 ;; footnote, press `C-c C-f k` to kill the footnote and add the
296 ;; text to the kill ring.
298 ;; * Other elements:
300 ;; `C-c -` inserts a horizontal rule.
302 ;; * Links:
304 ;; Press `C-c C-o` when the point is on an inline or reference
305 ;; link to open the URL in a browser.
307 ;; * Wiki-Link Navigation:
309 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
310 ;; wiki links, respectively.
312 ;; * Outline Navigation:
314 ;; Navigation between headings is possible using `outline-mode'.
315 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
316 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
317 ;; next and previous visible headings at the same level as the one
318 ;; at the point. Finally, `C-M-u` will move up to a lower-level
319 ;; (more inclusive) visible heading.
321 ;; Many of the commands described above behave differently depending on
322 ;; whether Transient Mark mode is enabled or not. When it makes sense,
323 ;; if Transient Mark mode is on and a region is active, the command
324 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
325 ;; bold). For users who prefer to work outside of Transient Mark mode,
326 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
328 ;; When applicable, commands that specifically act on the region even
329 ;; outside of Transient Mark mode have the same keybinding as the with
330 ;; the exception of an additional `C-` prefix. For example,
331 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
332 ;; the region in Transient Mark mode while `markdown-blockquote-region'
333 ;; is bound to `C-c C-s C-b` and always applies to the region (when
334 ;; nonempty).
336 ;; markdown-mode attempts to be flexible in how it handles
337 ;; indentation. When you press `TAB` repeatedly, the point will cycle
338 ;; through several possible indentation levels corresponding to things
339 ;; you might have in mind when you press `RET` at the end of a line or
340 ;; `TAB`. For example, you may want to start a new list item,
341 ;; continue a list item with hanging indentation, indent for a nested
342 ;; pre block, and so on.
344 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
345 ;; visibility cycling for atx- or hash-style headers. There are two
346 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
347 ;; the table of contents view (headers only), outline view (top-level
348 ;; headers only), and the full document view. Pressing `TAB` while the
349 ;; point is at a header will cycle through levels of visibility for the
350 ;; subtree: completely folded, visible children, and fully visible.
351 ;; Note that mixing hash and underline style headers will give undesired
352 ;; results.
354 ;;; Extensions:
356 ;; Besides supporting the basic Markdown syntax, markdown-mode also
357 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
358 ;; links may be followed automatically by hitting the enter key when
359 ;; your curser is on a wiki link or by hitting `C-c C-w`. The
360 ;; autofollowing on enter key may be controlled with the
361 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
362 ;; `M-n` to quickly jump to the previous and next wiki links,
363 ;; respectively. Aliased or piped wiki links of the form
364 ;; `[[link text|PageName]]` are also supported. Since some wikis
365 ;; reverse these components, set `markdown-wiki-link-alias-first'
366 ;; to nil to treat them as `[[PageName|link text]]`.
368 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
369 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
370 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
371 ;; You can do this either by using `M-x customize-group markdown`
372 ;; or by placing the following in your `.emacs` file:
374 ;; (defun markdown-custom ()
375 ;; "markdown-mode-hook"
376 ;; (setq markdown-command "markdown | smartypants"))
377 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
379 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
381 ;; Experimental syntax highlighting for mathematical expressions written
382 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
383 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
384 ;; either via customize or by placing `(setq markdown-enable-itex t)`
385 ;; in `.emacs`, and restarting Emacs.
387 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
388 ;; mode, `gfm-mode', is also available. The GitHub implementation of
389 ;; differs slightly from standard Markdown. Most importantly, newlines are
390 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
391 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
392 ;; `visual-line-mode' is not available). Wiki links in this mode will be
393 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
394 ;; where the first letter of the filename capitalized. For example,
395 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
396 ;; extension as the current file.
398 ;;; Acknowledgments:
400 ;; markdown-mode has benefited greatly from the efforts of the
401 ;; following people:
403 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
404 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
405 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
406 ;; GitHub Flavored Markdown mode (`gfm-mode').
407 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
408 ;; `markdown' with an active region.
409 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
410 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
411 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
412 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
413 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
414 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
415 ;; compatibility and custom CSS.
416 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
417 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
418 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
419 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
420 ;; functions and bug reports regarding indentation.
421 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
422 ;; enhancements.
423 ;; * George Ogata <george.ogata@gmail.com> for fixing several
424 ;; byte-compilation warnings.
425 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
426 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
427 ;; customizations and XHTML export.
428 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
429 ;; Markdown processors which do not accept input from stdin.
430 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
431 ;; regarding the cl dependency and auto-fill-mode and indentation.
432 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
433 ;; substitution character for mapping wiki links to filenames.
434 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
435 ;; escape shell commands.
436 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
437 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
438 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
439 ;; Emacs Lisp coding conventions.
440 ;; * Donald Ephraim Curtis <dcurtis@milkbox.net> for fixing the `paragraph-fill'
441 ;; regexp, refactoring the compilation and preview functions,
442 ;; heading font-lock generalizations, and imenu support.
443 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
444 ;; * Max Penet <max.penet@gmail.com> and Peter Eisentraut <peter_e@gmx.net>
445 ;; for an autoload token for `gfm-mode'.
446 ;; * Ian Yang <me@iany.me> for improving the reference definition regex.
447 ;; * Akinori Musha <knu@idaemons.org> for an imenu index function.
448 ;; * Michael Sperber <sperber@deinprogramm.de> for XEmacs fixes.
449 ;; * Francois Gannaz <francois.gannaz@free.fr> for suggestingcharset
450 ;; declaration in XHTML output.
451 ;; * Zhenlei Jia <zhenlei.jia@gmail.com> for smart (dedention)
452 ;; un-indentation function.
453 ;; * Matus Goljer <dota.keys@gmail.com> for improved wiki link following.
454 ;; * Peter Jones <pjones@pmade.com> for link following functions.
455 ;; * Bryan Fink <bryan.fink@gmail.com> for a bug report regarding
456 ;; externally modified files.
457 ;; * Vegard Vesterheim <vegard.vesterheim@uninett.no> and Carsten Dominik
458 ;; for a bug fix related to orgtbl-mode.
460 ;;; Bugs:
462 ;; Although markdown-mode is developed and tested primarily using
463 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
464 ;; priority.
466 ;; If you find any bugs in markdown-mode, please construct a test case
467 ;; or a patch and email me at <jrblevin@sdf.org>.
469 ;;; History:
471 ;; markdown-mode was written and is maintained by Jason Blevins. The
472 ;; first version was released on May 24, 2007.
474 ;; * 2007-05-24: Version 1.1
475 ;; * 2007-05-25: Version 1.2
476 ;; * 2007-06-05: [Version 1.3][]
477 ;; * 2007-06-29: Version 1.4
478 ;; * 2008-05-24: [Version 1.5][]
479 ;; * 2008-06-04: [Version 1.6][]
480 ;; * 2009-10-01: [Version 1.7][]
481 ;; * 2011-08-12: [Version 1.8][]
482 ;; * 2011-08-15: [Version 1.8.1][]
484 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
485 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
486 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
487 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
488 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
489 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
492 ;;; Code:
494 (require 'easymenu)
495 (require 'outline)
496 (eval-when-compile (require 'cl))
498 ;;; Constants =================================================================
500 (defconst markdown-mode-version "1.8.1"
501 "Markdown mode version number.")
503 (defconst markdown-output-buffer-name "*markdown-output*"
504 "Name of temporary buffer for markdown command output.")
506 ;;; Customizable variables ====================================================
508 (defvar markdown-mode-hook nil
509 "Hook run when entering Markdown mode.")
511 (defgroup markdown nil
512 "Major mode for editing text files in Markdown format."
513 :prefix "markdown-"
514 :group 'wp
515 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
517 (defcustom markdown-command "markdown"
518 "Command to run markdown."
519 :group 'markdown
520 :type 'string)
522 (defcustom markdown-command-needs-filename nil
523 "Set to non-nil if `markdown-command' does not accept input from stdin.
524 Instead, it will be passed a filename as the final command-line
525 option. As a result, you will only be able to run Markdown from
526 buffers which are visiting a file."
527 :group 'markdown
528 :type 'boolean)
530 (defcustom markdown-open-command nil
531 "Command used for opening Markdown files directly.
532 For example, a standalone Markdown previewer. This command will
533 be called with a single argument: the filename of the current
534 buffer."
535 :group 'markdown
536 :type 'string)
538 (defcustom markdown-hr-string "* * * * *"
539 "String to use for horizonal rules."
540 :group 'markdown
541 :type 'string)
543 (defcustom markdown-bold-underscore nil
544 "Use two underscores for bold instead of two asterisks."
545 :group 'markdown
546 :type 'boolean)
548 (defcustom markdown-italic-underscore nil
549 "Use underscores for italic instead of asterisks."
550 :group 'markdown
551 :type 'boolean)
553 (defcustom markdown-indent-function 'markdown-indent-line
554 "Function to use to indent."
555 :group 'markdown
556 :type 'function)
558 (defcustom markdown-indent-on-enter t
559 "Automatically indent new lines when enter key is pressed."
560 :group 'markdown
561 :type 'boolean)
563 (defcustom markdown-follow-wiki-link-on-enter t
564 "Follow wiki link at point (if any) when the enter key is pressed."
565 :group 'markdown
566 :type 'boolean)
568 (defcustom markdown-wiki-link-alias-first t
569 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
570 Otherwise, they will be treated as [[PageName|alias text]]."
571 :group 'markdown
572 :type 'boolean)
574 (defcustom markdown-uri-types
575 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
576 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
577 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
578 "Link types for syntax highlighting of URIs."
579 :group 'markdown
580 :type 'list)
582 (defcustom markdown-enable-math nil
583 "Syntax highlighting for inline LaTeX expressions.
584 This will not take effect until Emacs is restarted."
585 :group 'markdown
586 :type 'boolean)
588 (defcustom markdown-css-path ""
589 "URL of CSS file to link to in the output XHTML."
590 :group 'markdown
591 :type 'string)
593 (defcustom markdown-content-type ""
594 "Content type string for the http-equiv header in XHTML output.
595 When set to a non-empty string, insert the http-equiv attribute.
596 Otherwise, this attribute is omitted."
597 :group 'markdown
598 :type 'string)
600 (defcustom markdown-coding-system nil
601 "Character set string for the http-equiv header in XHTML output.
602 Defaults to `buffer-file-coding-system' (and falling back to
603 `iso-8859-1' when not available). Common settings are `utf-8'
604 and `iso-latin-1'. Use `list-coding-systems' for more choices."
605 :group 'markdown
606 :type 'coding-system)
608 (defcustom markdown-xhtml-header-content ""
609 "Additional content to include in the XHTML <head> block."
610 :group 'markdown
611 :type 'string)
613 (defcustom markdown-xhtml-standalone-regexp
614 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
615 "Regexp indicating whether `markdown-command' output is standalone XHTML."
616 :group 'markdown
617 :type 'regexp)
619 (defcustom markdown-link-space-sub-char
621 "Character to use instead of spaces when mapping wiki links to filenames."
622 :group 'markdown
623 :type 'string)
625 (defcustom markdown-footnote-location 'end
626 "Position where new footnotes are inserted in the document."
627 :group 'markdown
628 :type '(choice (const :tag "At the end of the document" end)
629 (const :tag "Immediately after the paragraph" immediately)
630 (const :tag "Before next header" header)))
632 ;;; Font lock =================================================================
634 (require 'font-lock)
636 (defvar markdown-italic-face 'markdown-italic-face
637 "Face name to use for italic text.")
639 (defvar markdown-bold-face 'markdown-bold-face
640 "Face name to use for bold text.")
642 (defvar markdown-header-delimiter-face 'markdown-header-delimiter-face
643 "Face name to use as a base for header delimiters.")
645 (defvar markdown-header-rule-face 'markdown-header-rule-face
646 "Face name to use as a base for header rules.")
648 (defvar markdown-header-face 'markdown-header-face
649 "Face name to use as a base for headers.")
651 (defvar markdown-header-face-1 'markdown-header-face-1
652 "Face name to use for level-1 headers.")
654 (defvar markdown-header-face-2 'markdown-header-face-2
655 "Face name to use for level-2 headers.")
657 (defvar markdown-header-face-3 'markdown-header-face-3
658 "Face name to use for level-3 headers.")
660 (defvar markdown-header-face-4 'markdown-header-face-4
661 "Face name to use for level-4 headers.")
663 (defvar markdown-header-face-5 'markdown-header-face-5
664 "Face name to use for level-5 headers.")
666 (defvar markdown-header-face-6 'markdown-header-face-6
667 "Face name to use for level-6 headers.")
669 (defvar markdown-inline-code-face 'markdown-inline-code-face
670 "Face name to use for inline code.")
672 (defvar markdown-list-face 'markdown-list-face
673 "Face name to use for list markers.")
675 (defvar markdown-blockquote-face 'markdown-blockquote-face
676 "Face name to use for blockquote.")
678 (defvar markdown-pre-face 'markdown-pre-face
679 "Face name to use for preformatted text.")
681 (defvar markdown-link-face 'markdown-link-face
682 "Face name to use for links.")
684 (defvar markdown-missing-link-face 'markdown-missing-link-face
685 "Face name to use for links where the linked file does not exist.")
687 (defvar markdown-reference-face 'markdown-reference-face
688 "Face name to use for reference.")
690 (defvar markdown-footnote-face 'markdown-footnote-face
691 "Face name to use for footnote identifiers.")
693 (defvar markdown-url-face 'markdown-url-face
694 "Face name to use for URLs.")
696 (defvar markdown-link-title-face 'markdown-link-title-face
697 "Face name to use for reference link titles.")
699 (defvar markdown-comment-face 'markdown-comment-face
700 "Face name to use for HTML comments.")
702 (defvar markdown-math-face 'markdown-math-face
703 "Face name to use for LaTeX expressions.")
705 (defgroup markdown-faces nil
706 "Faces used in Markdown Mode"
707 :group 'markdown
708 :group 'faces)
710 (defface markdown-italic-face
711 '((t (:inherit font-lock-variable-name-face :slant italic)))
712 "Face for italic text."
713 :group 'markdown-faces)
715 (defface markdown-bold-face
716 '((t (:inherit font-lock-variable-name-face :weight bold)))
717 "Face for bold text."
718 :group 'markdown-faces)
720 (defface markdown-header-rule-face
721 '((t (:inherit font-lock-function-name-face :weight bold)))
722 "Base face for headers rules."
723 :group 'markdown-faces)
725 (defface markdown-header-delimiter-face
726 '((t (:inherit font-lock-function-name-face :weight bold)))
727 "Base face for headers hash delimiter."
728 :group 'markdown-faces)
730 (defface markdown-header-face
731 '((t (:inherit font-lock-function-name-face :weight bold)))
732 "Base face for headers."
733 :group 'markdown-faces)
735 (defface markdown-header-face-1
736 '((t (:inherit markdown-header-face)))
737 "Face for level-1 headers."
738 :group 'markdown-faces)
740 (defface markdown-header-face-2
741 '((t (:inherit markdown-header-face)))
742 "Face for level-2 headers."
743 :group 'markdown-faces)
745 (defface markdown-header-face-3
746 '((t (:inherit markdown-header-face)))
747 "Face for level-3 headers."
748 :group 'markdown-faces)
750 (defface markdown-header-face-4
751 '((t (:inherit markdown-header-face)))
752 "Face for level-4 headers."
753 :group 'markdown-faces)
755 (defface markdown-header-face-5
756 '((t (:inherit markdown-header-face)))
757 "Face for level-5 headers."
758 :group 'markdown-faces)
760 (defface markdown-header-face-6
761 '((t (:inherit markdown-header-face)))
762 "Face for level-6 headers."
763 :group 'markdown-faces)
765 (defface markdown-inline-code-face
766 '((t (:inherit font-lock-constant-face)))
767 "Face for inline code."
768 :group 'markdown-faces)
770 (defface markdown-list-face
771 '((t (:inherit font-lock-builtin-face)))
772 "Face for list item markers."
773 :group 'markdown-faces)
775 (defface markdown-blockquote-face
776 '((t (:inherit font-lock-doc-face)))
777 "Face for blockquote sections."
778 :group 'markdown-faces)
780 (defface markdown-pre-face
781 '((t (:inherit font-lock-constant-face)))
782 "Face for preformatted text."
783 :group 'markdown-faces)
785 (defface markdown-link-face
786 '((t (:inherit font-lock-keyword-face)))
787 "Face for links."
788 :group 'markdown-faces)
790 (defface markdown-missing-link-face
791 '((t (:inherit font-lock-warning-face)))
792 "Face for missing links."
793 :group 'markdown-faces)
795 (defface markdown-reference-face
796 '((t (:inherit font-lock-type-face)))
797 "Face for link references."
798 :group 'markdown-faces)
800 (defface markdown-footnote-face
801 '((t (:inherit font-lock-keyword-face)))
802 "Face for footnote markers."
803 :group 'markdown-faces)
805 (defface markdown-url-face
806 '((t (:inherit font-lock-string-face)))
807 "Face for URLs."
808 :group 'markdown-faces)
810 (defface markdown-link-title-face
811 '((t (:inherit font-lock-comment-face)))
812 "Face for reference link titles."
813 :group 'markdown-faces)
815 (defface markdown-comment-face
816 '((t (:inherit font-lock-comment-face)))
817 "Face for HTML comments."
818 :group 'markdown-faces)
820 (defface markdown-math-face
821 '((t (:inherit font-lock-string-face)))
822 "Face for LaTeX expressions."
823 :group 'markdown-faces)
825 (defconst markdown-regex-link-inline
826 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
827 "Regular expression for a [text](file) or an image link ![text](file).")
829 (defconst markdown-regex-link-reference
830 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
831 "Regular expression for a reference link [text][id].")
833 (defconst markdown-regex-reference-definition
834 "^ \\{0,3\\}\\(\\[[^^\n]+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
835 "Regular expression for a link definition [id]: ...")
837 (defconst markdown-regex-footnote
838 "\\(\\[\\^.+?\\]\\)"
839 "Regular expression for a footnote marker [^fn].")
841 (defconst markdown-regex-header
842 "#+\\|\\S-.*\n\\(?:\\(===+\\)\\|\\(---+\\)\\)$"
843 "Regexp identifying Markdown headers.")
845 (defconst markdown-regex-header-1-atx
846 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
847 "Regular expression for level 1 atx-style (hash mark) headers.")
849 (defconst markdown-regex-header-2-atx
850 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
851 "Regular expression for level 2 atx-style (hash mark) headers.")
853 (defconst markdown-regex-header-3-atx
854 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
855 "Regular expression for level 3 atx-style (hash mark) headers.")
857 (defconst markdown-regex-header-4-atx
858 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
859 "Regular expression for level 4 atx-style (hash mark) headers.")
861 (defconst markdown-regex-header-5-atx
862 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
863 "Regular expression for level 5 atx-style (hash mark) headers.")
865 (defconst markdown-regex-header-6-atx
866 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
867 "Regular expression for level 6 atx-style (hash mark) headers.")
869 (defconst markdown-regex-header-1-setext
870 "^\\(.*\\)\n\\(===+\\)$"
871 "Regular expression for level 1 setext-style (underline) headers.")
873 (defconst markdown-regex-header-2-setext
874 "^\\(.*\\)\n\\(---+\\)$"
875 "Regular expression for level 2 setext-style (underline) headers.")
877 (defconst markdown-regex-hr
878 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
879 "Regular expression for matching Markdown horizontal rules.")
881 (defconst markdown-regex-code
882 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ]\\(.\\|\n[^\n]\\)*?[^ \\]\\)\\3\\)"
883 "Regular expression for matching inline code fragments.")
885 (defconst markdown-regex-pre
886 "^\\( \\|\t\\).*$"
887 "Regular expression for matching preformatted text sections.")
889 (defconst markdown-regex-list
890 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
891 "Regular expression for matching list markers.")
893 (defconst markdown-regex-bold
894 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)"
895 "Regular expression for matching bold text.")
897 (defconst markdown-regex-italic
898 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
899 "Regular expression for matching italic text.")
901 (defconst markdown-regex-blockquote
902 "^>.*$"
903 "Regular expression for matching blockquote lines.")
905 (defconst markdown-regex-line-break
906 " $"
907 "Regular expression for matching line breaks.")
909 (defconst markdown-regex-wiki-link
910 "\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]"
911 "Regular expression for matching wiki links.
912 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
913 wiki links of the form [[PageName|link text]]. In this regular
914 expression, #1 matches the page name and #3 matches the link
915 text.")
917 (defconst markdown-regex-uri
918 (concat
919 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
920 "\\):[^]\t\n\r<>,;() ]+")
921 "Regular expression for matching inline URIs.")
923 (defconst markdown-regex-angle-uri
924 (concat
925 "\\(<\\)\\("
926 (mapconcat 'identity markdown-uri-types "\\|")
927 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
928 "Regular expression for matching inline URIs in angle brackets.")
930 (defconst markdown-regex-email
931 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
932 "Regular expression for matching inline email addresses.")
934 (defconst markdown-regex-latex-expression
935 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
936 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
938 (defconst markdown-regex-latex-display
939 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
940 "Regular expression for itex \[..\] display mode expressions.")
942 (defconst markdown-regex-list-indent
943 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
944 "Regular expression for matching indentation of list items.")
946 (defvar markdown-mode-font-lock-keywords-basic
947 (list
948 '(markdown-match-pre-blocks 0 markdown-pre-face t t)
949 '(markdown-match-fenced-code-blocks 0 markdown-pre-face t t)
950 (cons markdown-regex-blockquote 'markdown-blockquote-face)
951 (cons markdown-regex-header-1-setext '((1 markdown-header-face-1)
952 (2 markdown-header-rule-face)))
953 (cons markdown-regex-header-2-setext '((1 markdown-header-face-2)
954 (2 markdown-header-rule-face)))
955 (cons markdown-regex-header-1-atx '((1 markdown-header-delimiter-face)
956 (2 markdown-header-face-1)
957 (3 markdown-header-delimiter-face)))
958 (cons markdown-regex-header-2-atx '((1 markdown-header-delimiter-face)
959 (2 markdown-header-face-2)
960 (3 markdown-header-delimiter-face)))
961 (cons markdown-regex-header-3-atx '((1 markdown-header-delimiter-face)
962 (2 markdown-header-face-3)
963 (3 markdown-header-delimiter-face)))
964 (cons markdown-regex-header-4-atx '((1 markdown-header-delimiter-face)
965 (2 markdown-header-face-4)
966 (3 markdown-header-delimiter-face)))
967 (cons markdown-regex-header-5-atx '((1 markdown-header-delimiter-face)
968 (2 markdown-header-face-5)
969 (3 markdown-header-delimiter-face)))
970 (cons markdown-regex-header-6-atx '((1 markdown-header-delimiter-face)
971 (2 markdown-header-face-6)
972 (3 markdown-header-delimiter-face)))
973 (cons markdown-regex-hr 'markdown-header-face)
974 '(markdown-match-comments 0 markdown-comment-face t t)
975 (cons markdown-regex-code '(2 markdown-inline-code-face))
976 (cons markdown-regex-angle-uri 'markdown-link-face)
977 (cons markdown-regex-uri 'markdown-link-face)
978 (cons markdown-regex-email 'markdown-link-face)
979 (cons markdown-regex-list 'markdown-list-face)
980 (cons markdown-regex-link-inline
981 '((1 markdown-link-face t)
982 (2 markdown-url-face t)))
983 (cons markdown-regex-link-reference
984 '((1 markdown-link-face t)
985 (2 markdown-reference-face t)))
986 (cons markdown-regex-reference-definition
987 '((1 markdown-reference-face t)
988 (2 markdown-url-face t)
989 (3 markdown-link-title-face t)))
990 (cons markdown-regex-footnote 'markdown-footnote-face)
991 (cons markdown-regex-bold '(2 markdown-bold-face))
992 (cons markdown-regex-italic '(2 markdown-italic-face))
994 "Syntax highlighting for Markdown files.")
996 (defconst markdown-mode-font-lock-keywords-latex
997 (list
998 ;; Math mode $..$ or $$..$$
999 (cons markdown-regex-latex-expression '(2 markdown-math-face))
1000 ;; Display mode equations with brackets: \[ \]
1001 (cons markdown-regex-latex-display 'markdown-math-face)
1002 ;; Equation reference (eq:foo)
1003 (cons "(eq:\\w+)" 'markdown-reference-face)
1004 ;; Equation reference \eqref{foo}
1005 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
1006 "Syntax highlighting for LaTeX fragments.")
1008 (defvar markdown-mode-font-lock-keywords
1009 (append
1010 (if markdown-enable-math
1011 markdown-mode-font-lock-keywords-latex)
1012 markdown-mode-font-lock-keywords-basic)
1013 "Default highlighting expressions for Markdown mode.")
1015 ;; Footnotes
1016 (defvar markdown-footnote-counter 0
1017 "Counter for footnote numbers.")
1018 (make-variable-buffer-local 'markdown-footnote-counter)
1020 (defconst markdown-footnote-chars
1021 "[[:alnum:]-]"
1022 "Regular expression maching any character that is allowed in a footnote identifier.")
1026 ;;; Compatibility =============================================================
1028 ;; Handle replace-regexp-in-string in XEmacs 21
1029 (defun markdown-replace-regexp-in-string (regexp rep string)
1030 "Compatibility wrapper to provide `replace-regexp-in-string'."
1031 (if (featurep 'xemacs)
1032 (replace-in-string string regexp rep)
1033 (replace-regexp-in-string regexp rep string)))
1035 (eval-and-compile
1036 (if (boundp 'mark-active)
1037 (defun markdown-mark-active () ; Emacs
1038 mark-active)
1039 (defalias 'markdown-mark-active 'region-exists-p))) ; XEmacs
1041 (defun markdown-transient-mark-mode-active ()
1042 (cond
1043 ((boundp 'transient-mark-mode)
1044 (and transient-mark-mode (markdown-mark-active)))
1045 ((boundp 'zmacs-regions)
1046 (and zmacs-regions (markdown-mark-active)))))
1050 ;;; Markdown parsing functions ================================================
1052 (defun markdown-cur-line-blank-p ()
1053 "Return t if the current line is blank and nil otherwise."
1054 (save-excursion
1055 (beginning-of-line)
1056 (re-search-forward "^\\s *$" (point-at-eol) t)))
1058 (defun markdown-prev-line-blank-p ()
1059 "Return t if the previous line is blank and nil otherwise.
1060 If we are at the first line, then consider the previous line to be blank."
1061 (save-excursion
1062 (if (= (point-at-bol) (point-min))
1064 (forward-line -1)
1065 (markdown-cur-line-blank-p))))
1067 (defun markdown-next-line-blank-p ()
1068 "Return t if the next line is blank and nil otherwise.
1069 If we are at the last line, then consider the next line to be blank."
1070 (save-excursion
1071 (if (= (point-at-bol) (point-max))
1073 (forward-line 1)
1074 (markdown-cur-line-blank-p))))
1076 (defun markdown-prev-line-indent-p ()
1077 "Return t if the previous line is indented and nil otherwise."
1078 (save-excursion
1079 (forward-line -1)
1080 (goto-char (point-at-bol))
1081 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
1083 (defun markdown-cur-line-indent ()
1084 "Return the number of leading whitespace characters in the current line."
1085 (save-excursion
1086 (goto-char (point-at-bol))
1087 (re-search-forward "^\\s +" (point-at-eol) t)
1088 (current-column)))
1090 (defun markdown-prev-line-indent ()
1091 "Return the number of leading whitespace characters in the previous line."
1092 (save-excursion
1093 (forward-line -1)
1094 (markdown-cur-line-indent)))
1096 (defun markdown-next-line-indent ()
1097 "Return the number of leading whitespace characters in the next line."
1098 (save-excursion
1099 (forward-line 1)
1100 (markdown-cur-line-indent)))
1102 (defun markdown-cur-non-list-indent ()
1103 "Return the number of leading whitespace characters in the current line."
1104 (save-excursion
1105 (beginning-of-line)
1106 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1107 (current-column))))
1109 (defun markdown-prev-non-list-indent ()
1110 "Return position of the first non-list-marker on the previous line."
1111 (save-excursion
1112 (forward-line -1)
1113 (markdown-cur-non-list-indent)))
1115 (defun markdown--next-block ()
1116 "Move the point to the start of the next text block."
1117 (forward-line)
1118 (while (and (or (not (markdown-prev-line-blank-p))
1119 (markdown-cur-line-blank-p))
1120 (not (eobp)))
1121 (forward-line)))
1123 (defun markdown--end-of-level (level)
1124 "Move the point to the end of region with indentation at least LEVEL."
1125 (let (indent)
1126 (while (and (not (< (setq indent (markdown-cur-line-indent)) level))
1127 (not (>= indent (+ level 4)))
1128 (not (eobp)))
1129 (markdown--next-block))
1130 (unless (eobp)
1131 ;; Move back before any trailing blank lines
1132 (while (and (markdown-prev-line-blank-p)
1133 (not (bobp)))
1134 (forward-line -1))
1135 (forward-line -1)
1136 (end-of-line))))
1138 ;; From html-helper-mode
1139 (defun markdown-match-comments (last)
1140 "Match HTML comments from the point to LAST."
1141 (cond ((search-forward "<!--" last t)
1142 (backward-char 4)
1143 (let ((beg (point)))
1144 (cond ((search-forward-regexp "--[ \t]*>" last t)
1145 (set-match-data (list beg (point)))
1147 (t nil))))
1148 (t nil)))
1150 (defun markdown-match-pre-blocks (last)
1151 "Match Markdown pre blocks from point to LAST.
1152 A region matches as if it is indented at least four spaces
1153 relative to the nearest previous block of lesser non-list-marker
1154 indentation."
1156 (let (cur-begin cur-end cur-indent prev-indent prev-list stop match found)
1157 ;; Don't start in the middle of a block
1158 (unless (and (bolp)
1159 (markdown-prev-line-blank-p)
1160 (not (markdown-cur-line-blank-p)))
1161 (markdown--next-block))
1163 ;; Move to the first full block in the region with indent 4 or more
1164 (while (and (not (>= (setq cur-indent (markdown-cur-line-indent)) 4))
1165 (not (>= (point) last)))
1166 (markdown--next-block))
1167 (setq cur-begin (point))
1168 (markdown--end-of-level cur-indent)
1169 (setq cur-end (point))
1170 (setq match nil)
1171 (setq stop (> cur-begin cur-end))
1173 (while (and (<= cur-end last) (not stop) (not match))
1174 ;; Move to the nearest preceding block of lesser (non-marker) indentation
1175 (setq prev-indent (+ cur-indent 1))
1176 (goto-char cur-begin)
1177 (setq found nil)
1178 (while (and (>= prev-indent cur-indent)
1179 (not (and prev-list
1180 (eq prev-indent cur-indent)))
1181 (not (bobp)))
1183 ;; Move point to the last line of the previous block.
1184 (forward-line -1)
1185 (while (and (markdown-cur-line-blank-p)
1186 (not (bobp)))
1187 (forward-line -1))
1189 ;; Update the indentation level using either the
1190 ;; non-list-marker indentation, if the previous line is the
1191 ;; start of a list, or the actual indentation.
1192 (setq prev-list (markdown-cur-non-list-indent))
1193 (setq prev-indent (or prev-list
1194 (markdown-cur-line-indent)))
1195 (setq found t))
1197 ;; If the loop didn't execute
1198 (unless found
1199 (setq prev-indent 0))
1201 ;; Compare with prev-indent minus its remainder mod 4
1202 (setq prev-indent (- prev-indent (mod prev-indent 4)))
1204 ;; Set match data and return t if we have a match
1205 (if (>= cur-indent (+ prev-indent 4))
1206 ;; Match
1207 (progn
1208 (setq match t)
1209 (set-match-data (list cur-begin cur-end))
1210 ;; Leave point at end of block
1211 (goto-char cur-end)
1212 (forward-line))
1214 ;; Move to the next block (if possible)
1215 (goto-char cur-end)
1216 (markdown--next-block)
1217 (setq cur-begin (point))
1218 (setq cur-indent (markdown-cur-line-indent))
1219 (markdown--end-of-level cur-indent)
1220 (setq cur-end (point))
1221 (setq stop (equal cur-begin cur-end))))
1222 match))
1224 (defun markdown-match-fenced-code-blocks (last)
1225 "Match fenced code blocks from the point to LAST."
1226 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1227 (beginning-of-line)
1228 (let ((beg (point)))
1229 (forward-line)
1230 (cond ((search-forward-regexp
1231 (concat "^" (match-string 1) "~*") last t)
1232 (set-match-data (list beg (point)))
1234 (t nil))))
1235 (t nil)))
1237 (defun markdown-font-lock-extend-region ()
1238 "Extend the search region to include an entire block of text.
1239 This helps improve font locking for block constructs such as pre blocks."
1240 ;; Avoid compiler warnings about these global variables from font-lock.el.
1241 ;; See the documentation for variable `font-lock-extend-region-functions'.
1242 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1243 (save-excursion
1244 (goto-char font-lock-beg)
1245 (let ((found (re-search-backward "\n\n" nil t)))
1246 (when found
1247 (goto-char font-lock-end)
1248 (when (re-search-forward "\n\n" nil t)
1249 (beginning-of-line)
1250 (setq font-lock-end (point)))
1251 (setq font-lock-beg found)))))
1255 ;;; Syntax Table ==============================================================
1257 (defvar markdown-mode-syntax-table
1258 (let ((markdown-mode-syntax-table (make-syntax-table)))
1259 (modify-syntax-entry ?\" "w" markdown-mode-syntax-table)
1260 markdown-mode-syntax-table)
1261 "Syntax table for `markdown-mode'.")
1265 ;;; Element Insertion =========================================================
1267 (defun markdown-wrap-or-insert (s1 s2)
1268 "Insert the strings S1 and S2.
1269 If Transient Mark mode is on and a region is active, wrap the strings S1
1270 and S2 around the region."
1271 (if (markdown-transient-mark-mode-active)
1272 (let ((a (region-beginning)) (b (region-end)))
1273 (goto-char a)
1274 (insert s1)
1275 (goto-char (+ b (length s1)))
1276 (insert s2))
1277 (insert s1 s2)))
1279 (defun markdown-insert-hr ()
1280 "Insert a horizonal rule using `markdown-hr-string'."
1281 (interactive)
1282 ;; Leading blank line
1283 (when (and (>= (point) (+ (point-min) 2))
1284 (not (looking-back "\n\n" 2)))
1285 (insert "\n"))
1286 ;; Insert custom HR string
1287 (insert (concat markdown-hr-string "\n"))
1288 ;; Following blank line
1289 (backward-char)
1290 (unless (looking-at "\n\n")
1291 (insert "\n")))
1293 (defun markdown-insert-bold ()
1294 "Insert markup for a bold word or phrase.
1295 If Transient Mark mode is on and a region is active, it is made bold."
1296 (interactive)
1297 (if markdown-bold-underscore
1298 (markdown-wrap-or-insert "__" "__")
1299 (markdown-wrap-or-insert "**" "**"))
1300 (backward-char 2))
1302 (defun markdown-insert-italic ()
1303 "Insert markup for an italic word or phrase.
1304 If Transient Mark mode is on and a region is active, it is made italic."
1305 (interactive)
1306 (if markdown-italic-underscore
1307 (markdown-wrap-or-insert "_" "_")
1308 (markdown-wrap-or-insert "*" "*"))
1309 (backward-char 1))
1311 (defun markdown-insert-code ()
1312 "Insert markup for an inline code fragment.
1313 If Transient Mark mode is on and a region is active, it is marked
1314 as inline code."
1315 (interactive)
1316 (markdown-wrap-or-insert "`" "`")
1317 (backward-char 1))
1319 (defun markdown-insert-link ()
1320 "Insert an inline link of the form []().
1321 If Transient Mark mode is on and a region is active, it is used
1322 as the link text."
1323 (interactive)
1324 (markdown-wrap-or-insert "[" "]")
1325 (insert "()")
1326 (backward-char 1))
1328 (defun markdown-insert-reference-link-dwim ()
1329 "Insert a reference link of the form [text][label] at point.
1330 If Transient Mark mode is on and a region is active, the region
1331 is used as the link text. Otherwise, the link text will be read
1332 from the minibuffer. The link URL, label, and title will be read
1333 from the minibuffer. The link label definition is placed at the
1334 end of the current paragraph."
1335 (interactive)
1336 (if (markdown-transient-mark-mode-active)
1337 (call-interactively 'markdown-insert-reference-link-region)
1338 (call-interactively 'markdown-insert-reference-link)))
1340 (defun markdown-insert-reference-link-region (url label title)
1341 "Insert a reference link at point using the region as the link text."
1342 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1343 (let ((text (buffer-substring (region-beginning) (region-end))))
1344 (delete-region (region-beginning) (region-end))
1345 (markdown-insert-reference-link text url label title)))
1347 (defun markdown-insert-reference-link (text url label title)
1348 "Insert a reference link at point.
1349 The link label definition is placed at the end of the current
1350 paragraph."
1351 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1352 (let (end)
1353 (insert (concat "[" text "][" label "]"))
1354 (setq end (point))
1355 (forward-paragraph)
1356 (insert "\n[")
1357 (if (> (length label) 0)
1358 (insert label)
1359 (insert text))
1360 (insert (concat "]: " url))
1361 (unless (> (length url) 0)
1362 (setq end (point)))
1363 (when (> (length title) 0)
1364 (insert (concat " \"" title "\"")))
1365 (insert "\n")
1366 (unless (looking-at "\n")
1367 (insert "\n"))
1368 (goto-char end)))
1370 (defun markdown-insert-wiki-link ()
1371 "Insert a wiki link of the form [[WikiLink]].
1372 If Transient Mark mode is on and a region is active, it is used
1373 as the link text."
1374 (interactive)
1375 (markdown-wrap-or-insert "[[" "]]")
1376 (backward-char 2))
1378 (defun markdown-insert-image ()
1379 "Insert an inline image tag of the form ![]().
1380 If Transient Mark mode is on and a region is active, it is used
1381 as the alt text of the image."
1382 (interactive)
1383 (markdown-wrap-or-insert "![" "]")
1384 (insert "()")
1385 (backward-char 1))
1387 (defun markdown-insert-header-1 ()
1388 "Insert a first level atx-style (hash mark) header.
1389 If Transient Mark mode is on and a region is active, it is used
1390 as the header text."
1391 (interactive)
1392 (markdown-insert-header 1))
1394 (defun markdown-insert-header-2 ()
1395 "Insert a second level atx-style (hash mark) header.
1396 If Transient Mark mode is on and a region is active, it is used
1397 as the header text."
1398 (interactive)
1399 (markdown-insert-header 2))
1401 (defun markdown-insert-header-3 ()
1402 "Insert a third level atx-style (hash mark) header.
1403 If Transient Mark mode is on and a region is active, it is used
1404 as the header text."
1405 (interactive)
1406 (markdown-insert-header 3))
1408 (defun markdown-insert-header-4 ()
1409 "Insert a fourth level atx-style (hash mark) header.
1410 If Transient Mark mode is on and a region is active, it is used
1411 as the header text."
1412 (interactive)
1413 (markdown-insert-header 4))
1415 (defun markdown-insert-header-5 ()
1416 "Insert a fifth level atx-style (hash mark) header.
1417 If Transient Mark mode is on and a region is active, it is used
1418 as the header text."
1419 (interactive)
1420 (markdown-insert-header 5))
1422 (defun markdown-insert-header-6 ()
1423 "Insert a sixth level atx-style (hash mark) header.
1424 If Transient Mark mode is on and a region is active, it is used
1425 as the header text."
1426 (interactive)
1427 (markdown-insert-header 6))
1429 (defun markdown-insert-header (n)
1430 "Insert an atx-style (hash mark) header.
1431 With no prefix argument, insert a level-1 header. With prefix N,
1432 insert a level-N header. If Transient Mark mode is on and the
1433 region is active, it is used as the header text."
1434 (interactive "p")
1435 (unless n ; Test to see if n is defined
1436 (setq n 1)) ; Default to level 1 header
1437 (let (hdr hdrl hdrr)
1438 (dotimes (count n hdr)
1439 (setq hdr (concat "#" hdr))) ; Build a hash mark header string
1440 (setq hdrl (concat hdr " "))
1441 (setq hdrr (concat " " hdr))
1442 (markdown-wrap-or-insert hdrl hdrr))
1443 (backward-char (+ 1 n)))
1445 (defun markdown-insert-title ()
1446 "Insert a setext-style (underline) first level header.
1447 If Transient Mark mode is on and a region is active, it is used
1448 as the header text."
1449 (interactive)
1450 (if (markdown-transient-mark-mode-active)
1451 (let ((a (region-beginning))
1452 (b (region-end))
1453 (len 0)
1454 (hdr))
1455 (setq len (- b a))
1456 (dotimes (count len hdr)
1457 (setq hdr (concat "=" hdr))) ; Build a === title underline
1458 (end-of-line)
1459 (insert "\n" hdr "\n"))
1460 (insert "\n==========\n")
1461 (backward-char 12)))
1463 (defun markdown-insert-section ()
1464 "Insert a setext-style (underline) second level header.
1465 If Transient Mark mode is on and a region is active, it is used
1466 as the header text."
1467 (interactive)
1468 (if (markdown-transient-mark-mode-active)
1469 (let ((a (region-beginning))
1470 (b (region-end))
1471 (len 0)
1472 (hdr))
1473 (setq len (- b a))
1474 (dotimes (count len hdr)
1475 (setq hdr (concat "-" hdr))) ; Build a --- section underline
1476 (end-of-line)
1477 (insert "\n" hdr "\n"))
1478 (insert "\n----------\n")
1479 (backward-char 12)))
1481 (defun markdown-insert-blockquote ()
1482 "Start a blockquote section (or blockquote the region).
1483 If Transient Mark mode is on and a region is active, it is used as
1484 the blockquote text."
1485 (interactive)
1486 (if (markdown-transient-mark-mode-active)
1487 (markdown-blockquote-region (region-beginning) (region-end))
1488 (insert "> ")))
1490 (defun markdown-block-region (beg end prefix)
1491 "Format the region using a block prefix.
1492 Arguments BEG and END specify the beginning and end of the
1493 region. The characters PREFIX will appear at the beginning
1494 of each line."
1495 (if mark-active
1496 (save-excursion
1497 ;; Ensure that there is a leading blank line
1498 (goto-char beg)
1499 (when (and (>= (point) (+ (point-min) 2))
1500 (not (looking-back "\n\n" 2)))
1501 (insert "\n")
1502 (setq beg (1+ beg))
1503 (setq end (1+ end)))
1504 ;; Move back before any blank lines at the end
1505 (goto-char end)
1506 (while (and (looking-back "\n" 1)
1507 (not (equal (point) (point-min))))
1508 (backward-char)
1509 (setq end (1- end)))
1510 ;; Ensure that there is a trailing blank line
1511 (goto-char end)
1512 (if (not (or (looking-at "\n\n")
1513 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
1514 (insert "\n"))
1515 ;; Insert PREFIX
1516 (goto-char beg)
1517 (beginning-of-line)
1518 (while (< (point-at-bol) end)
1519 (insert prefix)
1520 (setq end (+ (length prefix) end))
1521 (forward-line)))))
1523 (defun markdown-blockquote-region (beg end)
1524 "Blockquote the region.
1525 Arguments BEG and END specify the beginning and end of the region."
1526 (interactive "*r")
1527 (markdown-block-region beg end "> "))
1529 (defun markdown-insert-pre ()
1530 "Start a preformatted section (or apply to the region).
1531 If Transient Mark mode is on and a region is active, it is marked
1532 as preformatted text."
1533 (interactive)
1534 (if (markdown-transient-mark-mode-active)
1535 (markdown-pre-region (region-beginning) (region-end))
1536 (insert " ")))
1538 (defun markdown-pre-region (beg end)
1539 "Format the region as preformatted text.
1540 Arguments BEG and END specify the beginning and end of the region."
1541 (interactive "*r")
1542 (markdown-block-region beg end " "))
1544 ;;; Footnotes ======================================================================
1546 (defun markdown-footnote-counter-inc ()
1547 "Increment markdown-footnote-counter and return the new value."
1548 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
1549 (save-excursion
1550 (goto-char (point-min))
1551 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
1552 (point-max) t)
1553 (let ((fn (string-to-number (match-string 1))))
1554 (when (> fn markdown-footnote-counter)
1555 (setq markdown-footnote-counter fn))))))
1556 (incf markdown-footnote-counter))
1558 (defun markdown-footnote-new ()
1559 "Insert a footnote with a new number and jump to a position to enter the
1560 footnote text."
1561 (interactive)
1562 (let ((fn (markdown-footnote-counter-inc)))
1563 (insert (format "[^%d]" fn))
1564 (markdown-footnote-text-find-new-location)
1565 (insert (format "[^%d]: " fn))))
1567 (defun markdown-footnote-text-find-new-location ()
1568 "Position the cursor at the proper location for a new footnote text."
1569 (cond
1570 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
1571 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
1572 ((eq markdown-footnote-location 'header)
1573 ;; search for a header. if none is found, go to the end of the document.
1574 (catch 'eof
1575 (while (progn
1576 (forward-paragraph)
1577 (unless (re-search-forward markdown-regex-header nil t)
1578 (throw 'eof nil))
1579 (backward-paragraph)
1580 (not (looking-at (concat "\n" markdown-regex-header))))))))
1581 ;; make sure we're on an empty line:
1582 (unless (markdown-cur-line-blank-p)
1583 (insert "\n"))
1584 ;; and make sure the previous line is empty:
1585 (unless (markdown-prev-line-blank-p)
1586 (insert "\n"))
1587 ;; then make sure there's an empty line following the footnote:
1588 (unless (markdown-next-line-blank-p)
1589 (insert "\n")
1590 (forward-line -1)))
1592 (defun markdown-footnote-kill ()
1593 "Kill the footnote at point.
1594 The footnote text is killed (and added to the kill ring), the
1595 footnote marker is deleted. Point has to be either at the
1596 footnote marker or in the footnote text."
1597 (interactive)
1598 (let (return-pos)
1599 (when (markdown-footnote-text-positions) ; if we're in a footnote text
1600 (markdown-footnote-return) ; we first move to the marker
1601 (setq return-pos 'text)) ; and remember our return position
1602 (let ((marker (markdown-footnote-delete-marker)))
1603 (unless marker
1604 (error "Not at a footnote"))
1605 (let ((text-pos (markdown-footnote-find-text (car marker))))
1606 (unless text-pos
1607 (error "No text for footnote `%s'" (car marker)))
1608 (goto-char text-pos)
1609 (let ((pos (markdown-footnote-kill-text)))
1610 (setq return-pos
1611 (if (and pos (eq return-pos 'text))
1613 (cadr marker))))))
1614 (goto-char return-pos)))
1616 (defun markdown-footnote-delete-marker ()
1617 "Delete a footnote marker at point.
1618 Returns a list (ID START) containing the footnote ID and the
1619 start position of the marker before deletion. If no footnote
1620 marker was deleted, this function returns NIL."
1621 (let ((marker (markdown-footnote-marker-positions)))
1622 (when marker
1623 (delete-region (second marker) (third marker))
1624 (butlast marker))))
1626 (defun markdown-footnote-kill-text ()
1627 "Kill footnote text at point.
1628 Returns the start position of the footnote text before deletion,
1629 or NIL if point was not inside a footnote text.
1631 The killed text is placed in the kill ring (without the footnote
1632 number)."
1633 (let ((fn (markdown-footnote-text-positions)))
1634 (when fn
1635 (let ((text (delete-and-extract-region (second fn) (third fn))))
1636 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
1637 (kill-new (match-string 1 text))
1638 (second fn)))))
1640 (defun markdown-footnote-goto-text ()
1641 "Jump to the text of the footnote at point."
1642 (interactive)
1643 (let ((fn (car (markdown-footnote-marker-positions))))
1644 (unless fn
1645 (error "Not at a footnote marker"))
1646 (let ((new-pos (markdown-footnote-find-text fn)))
1647 (unless new-pos
1648 (error "No definition found for footnote `%s'" fn))
1649 (goto-char new-pos))))
1651 (defun markdown-footnote-return ()
1652 "Return from a footnote to its footnote number in the main text."
1653 (interactive)
1654 (let ((fn (save-excursion
1655 (car (markdown-footnote-text-positions)))))
1656 (unless fn
1657 (error "Not in a footnote"))
1658 (let ((new-pos (markdown-footnote-find-marker fn)))
1659 (unless new-pos
1660 (error "Footnote marker `%s' not found" fn))
1661 (goto-char new-pos))))
1663 (defun markdown-footnote-find-marker (id)
1664 "Find the location of the footnote marker with ID.
1665 The actual buffer position returned is the position directly
1666 following the marker's closing bracket. If no marker is found,
1667 NIL is returned."
1668 (save-excursion
1669 (goto-char (point-min))
1670 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
1671 (skip-chars-backward "^]")
1672 (point))))
1674 (defun markdown-footnote-find-text (id)
1675 "Find the location of the text of footnote ID.
1676 The actual buffer position returned is the position of the first
1677 character of the text, after the footnote's identifier. If no
1678 footnote text is found, NIL is returned."
1679 (save-excursion
1680 (goto-char (point-min))
1681 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
1682 (skip-chars-forward "[:space:]")
1683 (point))))
1685 (defun markdown-footnote-marker-positions ()
1686 "Return the position and ID of the footnote marker point is on.
1687 The return value is a list (ID START END). If point is not on a
1688 footnote, NIL is returned."
1689 ;; first make sure we're at a footnote marker
1690 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
1691 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
1692 (save-excursion
1693 ;; move point between [ and ^:
1694 (if (looking-at "\\[")
1695 (forward-char 1)
1696 (skip-chars-backward "^["))
1697 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
1698 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
1700 (defun markdown-footnote-text-positions ()
1701 "Return the start and end positions of the footnote text point is in.
1702 The exact return value is a list of three elements: (ID START
1703 END). The start position is the position of the opening bracket
1704 of the footnote id. The end position is directly after the
1705 newline that ends the footnote. If point is not in a footnote,
1706 NIL is returned instead."
1707 (save-excursion
1708 (let ((fn (progn
1709 (backward-paragraph)
1710 ;; if we're in a multiparagraph footnote, we need to back up further
1711 (while (>= (markdown-next-line-indent) 4)
1712 (backward-paragraph))
1713 (forward-line)
1714 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
1715 (list (match-string 1) (point))))))
1716 (when fn
1717 (while (progn
1718 (forward-paragraph)
1719 (>= (markdown-next-line-indent) 4)))
1720 (append fn (list (point)))))))
1722 ;;; Indentation ====================================================================
1724 (defun markdown-indent-find-next-position (cur-pos positions)
1725 "Return the position after the index of CUR-POS in POSITIONS."
1726 (while (and positions
1727 (not (equal cur-pos (car positions))))
1728 (setq positions (cdr positions)))
1729 (or (cadr positions) 0))
1731 (defun markdown-indent-line ()
1732 "Indent the current line using some heuristics.
1733 If the _previous_ command was either `markdown-enter-key' or
1734 `markdown-cycle', then we should cycle to the next
1735 reasonable indentation position. Otherwise, we could have been
1736 called directly by `markdown-enter-key', by an initial call of
1737 `markdown-cycle', or indirectly by `auto-fill-mode'. In
1738 these cases, indent to the default position."
1739 (interactive)
1740 (let ((positions (markdown-calc-indents))
1741 (cur-pos (current-column)))
1742 (if (not (equal this-command 'markdown-cycle))
1743 (indent-line-to (car positions))
1744 (setq positions (sort (delete-dups positions) '<))
1745 (indent-line-to
1746 (markdown-indent-find-next-position cur-pos positions)))))
1748 (defun markdown-calc-indents ()
1749 "Return a list of indentation columns to cycle through.
1750 The first element in the returned list should be considered the
1751 default indentation level."
1752 (let (pos prev-line-pos positions)
1754 ;; Previous line indent
1755 (setq prev-line-pos (markdown-prev-line-indent))
1756 (setq positions (cons prev-line-pos positions))
1758 ;; Previous non-list-marker indent
1759 (setq pos (markdown-prev-non-list-indent))
1760 (when pos
1761 (setq positions (cons pos positions))
1762 (setq positions (cons (+ pos tab-width) positions)))
1764 ;; Indentation of the previous line + tab-width
1765 (cond
1766 (prev-line-pos
1767 (setq positions (cons (+ prev-line-pos tab-width) positions)))
1769 (setq positions (cons tab-width positions))))
1771 ;; Indentation of the previous line - tab-width
1772 (if (and prev-line-pos
1773 (> prev-line-pos tab-width))
1774 (setq positions (cons (- prev-line-pos tab-width) positions)))
1776 ;; Indentation of preceeding list item
1777 (setq pos
1778 (save-excursion
1779 (forward-line -1)
1780 (catch 'break
1781 (while (not (equal (point) (point-min)))
1782 (forward-line -1)
1783 (goto-char (point-at-bol))
1784 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1785 (throw 'break (length (match-string 1)))))
1786 nil)))
1787 (if (and pos (not (eq pos prev-line-pos)))
1788 (setq positions (cons pos positions)))
1790 ;; First column
1791 (setq positions (cons 0 positions))
1793 (reverse positions)))
1795 (defun markdown-do-normal-return ()
1796 "Insert a newline and optionally indent the next line."
1797 (newline)
1798 (if markdown-indent-on-enter
1799 (funcall indent-line-function)))
1801 (defun markdown-enter-key ()
1802 "Handle RET according to context.
1803 If there is a wiki link at the point, follow it unless
1804 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1805 it in the usual way."
1806 (interactive)
1807 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
1808 (markdown-follow-wiki-link-at-point)
1809 (markdown-do-normal-return)))
1811 (defun markdown-dedent-or-delete (arg)
1812 "Handle BACKSPACE by cycling through indentation points.
1813 When BACKSPACE is pressed, if there is only whitespace
1814 before the current point, then dedent the line one level.
1815 Otherwise, do normal delete by repeating
1816 `backward-delete-char-untabify' ARG times."
1817 (interactive "*p")
1818 (let ((cur-pos (current-column))
1819 (start-of-indention (save-excursion
1820 (back-to-indentation)
1821 (current-column))))
1822 (if (and (> cur-pos 0) (= cur-pos start-of-indention))
1823 (let ((result 0))
1824 (dolist (i (markdown-calc-indents))
1825 (when (< i cur-pos)
1826 (setq result (max result i))))
1827 (indent-line-to result))
1828 (backward-delete-char-untabify arg))))
1832 ;;; Keymap ====================================================================
1834 (defvar markdown-mode-map
1835 (let ((map (make-keymap)))
1836 ;; Element insertion
1837 (define-key map "\C-c\C-al" 'markdown-insert-link)
1838 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
1839 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
1840 (define-key map "\C-c\C-ii" 'markdown-insert-image)
1841 (define-key map "\C-c\C-t1" 'markdown-insert-header-1)
1842 (define-key map "\C-c\C-t2" 'markdown-insert-header-2)
1843 (define-key map "\C-c\C-t3" 'markdown-insert-header-3)
1844 (define-key map "\C-c\C-t4" 'markdown-insert-header-4)
1845 (define-key map "\C-c\C-t5" 'markdown-insert-header-5)
1846 (define-key map "\C-c\C-t6" 'markdown-insert-header-6)
1847 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
1848 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
1849 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
1850 (define-key map "\C-c\C-se" 'markdown-insert-italic)
1851 (define-key map "\C-c\C-pf" 'markdown-insert-code)
1852 (define-key map "\C-c\C-sc" 'markdown-insert-code)
1853 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
1854 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
1855 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
1856 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
1857 (define-key map "\C-c-" 'markdown-insert-hr)
1858 (define-key map "\C-c\C-tt" 'markdown-insert-title)
1859 (define-key map "\C-c\C-ts" 'markdown-insert-section)
1860 ;; Footnotes
1861 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
1862 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
1863 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
1864 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
1865 ;; Regular Link Following
1866 (define-key map "\C-c\C-o" 'markdown-follow-link-at-point)
1867 ;; WikiLink Following
1868 (define-key map "\C-c\C-w" 'markdown-follow-wiki-link-at-point)
1869 (define-key map "\M-n" 'markdown-next-wiki-link)
1870 (define-key map "\M-p" 'markdown-previous-wiki-link)
1871 ;; Indentation
1872 (define-key map "\C-m" 'markdown-enter-key)
1873 (define-key map (kbd "<backspace>") 'markdown-dedent-or-delete)
1874 ;; Visibility cycling
1875 (define-key map (kbd "<tab>") 'markdown-cycle)
1876 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
1877 (define-key map (kbd "<S-tab>") 'markdown-shifttab)
1878 (define-key map (kbd "<backtab>") 'markdown-shifttab)
1879 ;; Header navigation
1880 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
1881 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
1882 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
1883 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
1884 (define-key map (kbd "C-M-u") 'outline-up-heading)
1885 ;; Markdown functions
1886 (define-key map "\C-c\C-cm" 'markdown-other-window)
1887 (define-key map "\C-c\C-cp" 'markdown-preview)
1888 (define-key map "\C-c\C-ce" 'markdown-export)
1889 (define-key map "\C-c\C-cv" 'markdown-export-and-preview)
1890 (define-key map "\C-c\C-co" 'markdown-open)
1891 ;; References
1892 (define-key map "\C-c\C-cc" 'markdown-check-refs)
1893 map)
1894 "Keymap for Markdown major mode.")
1896 ;;; Menu ==================================================================
1898 (easy-menu-define markdown-mode-menu markdown-mode-map
1899 "Menu for Markdown mode"
1900 '("Markdown"
1901 ("Show/Hide"
1902 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
1903 ["Cycle global visibility" markdown-shifttab])
1904 "---"
1905 ["Compile" markdown-other-window]
1906 ["Preview" markdown-preview]
1907 ["Export" markdown-export]
1908 ["Export & View" markdown-export-and-preview]
1909 ["Open" markdown-open]
1910 "---"
1911 ("Headers (setext)"
1912 ["Insert Title" markdown-insert-title]
1913 ["Insert Section" markdown-insert-section])
1914 ("Headers (atx)"
1915 ["First level" markdown-insert-header-1]
1916 ["Second level" markdown-insert-header-2]
1917 ["Third level" markdown-insert-header-3]
1918 ["Fourth level" markdown-insert-header-4]
1919 ["Fifth level" markdown-insert-header-5]
1920 ["Sixth level" markdown-insert-header-6])
1921 "---"
1922 ["Bold" markdown-insert-bold]
1923 ["Italic" markdown-insert-italic]
1924 ["Blockquote" markdown-insert-blockquote]
1925 ["Preformatted" markdown-insert-pre]
1926 ["Code" markdown-insert-code]
1927 "---"
1928 ["Insert inline link" markdown-insert-link]
1929 ["Insert reference link" markdown-insert-reference-link-dwim]
1930 ["Insert image" markdown-insert-image]
1931 ["Insert horizontal rule" markdown-insert-hr]
1932 "---"
1933 ("Footnotes"
1934 ["Insert footnote" markdown-footnote-new]
1935 ["Jump to footnote text" markdown-footnote-goto-text]
1936 ["Return from footnote" markdown-footnote-return])
1937 "---"
1938 ["Check references" markdown-check-refs]
1939 "---"
1940 ["Version" markdown-show-version]
1945 ;;; imenu =====================================================================
1947 (defun markdown-imenu-create-index ()
1948 (let* ((root '(nil . nil))
1949 cur-alist
1950 (cur-level 0)
1951 (pattern "^\\(\\(#+\\)[ \t]*\\(.+\\)\\|\\([^# \t\n=-].*\\)\n===+\\|\\([^# \t\n=-].*\\)\n---+\\)$")
1952 (empty-heading "-")
1953 (self-heading ".")
1954 hashes pos level heading)
1955 (save-excursion
1956 (goto-char (point-min))
1957 (while (re-search-forward pattern (point-max) t)
1958 (cond
1959 ((setq hashes (match-string-no-properties 2))
1960 (setq heading (match-string-no-properties 3)
1961 pos (match-beginning 1)
1962 level (length hashes)))
1963 ((setq heading (match-string-no-properties 4))
1964 (setq pos (match-beginning 4)
1965 level 1))
1966 ((setq heading (match-string-no-properties 5))
1967 (setq pos (match-beginning 5)
1968 level 2)))
1969 (let ((alist (list (cons heading pos))))
1970 (cond
1971 ((= cur-level level) ; new sibling
1972 (setcdr cur-alist alist)
1973 (setq cur-alist alist))
1974 ((< cur-level level) ; first child
1975 (dotimes (i (- level cur-level 1))
1976 (setq alist (list (cons empty-heading alist))))
1977 (if cur-alist
1978 (let* ((parent (car cur-alist))
1979 (self-pos (cdr parent)))
1980 (setcdr parent (cons (cons self-heading self-pos) alist)))
1981 (setcdr root alist)) ; primogenitor
1982 (setq cur-alist alist)
1983 (setq cur-level level))
1984 (t ; new sibling of an ancestor
1985 (let ((sibling-alist (last (cdr root))))
1986 (dotimes (i (1- level))
1987 (setq sibling-alist (last (cdar sibling-alist))))
1988 (setcdr sibling-alist alist)
1989 (setq cur-alist alist))
1990 (setq cur-level level)))))
1991 (cdr root))))
1993 ;;; References ================================================================
1995 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
1997 (defconst markdown-refcheck-buffer
1998 "*Undefined references for %buffer%*"
1999 "Pattern for name of buffer for listing undefined references.
2000 The string %buffer% will be replaced by the corresponding
2001 `markdown-mode' buffer name.")
2003 (defun markdown-has-reference-definition (reference)
2004 "Find out whether Markdown REFERENCE is defined.
2006 REFERENCE should include the square brackets, like [this]."
2007 (let ((reference (downcase reference)))
2008 (save-excursion
2009 (goto-char (point-min))
2010 (catch 'found
2011 (while (re-search-forward markdown-regex-reference-definition nil t)
2012 (when (string= reference (downcase (match-string-no-properties 1)))
2013 (throw 'found (match-string-no-properties 2))))))))
2015 (defun markdown-get-undefined-refs ()
2016 "Return a list of undefined Markdown references.
2018 Result is an alist of pairs (reference . occurencies), where
2019 occurencies is itself another alist of pairs (label .
2020 line-number).
2022 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
2023 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
2024 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
2025 (let ((missing))
2026 (save-excursion
2027 (goto-char (point-min))
2028 (while
2029 (re-search-forward markdown-regex-link-reference nil t)
2030 (let* ((label (match-string-no-properties 1))
2031 (reference (match-string-no-properties 2))
2032 (target (downcase (if (string= reference "[]") label reference))))
2033 (unless (markdown-has-reference-definition target)
2034 (let ((entry (assoc target missing)))
2035 (if (not entry)
2036 (add-to-list 'missing (cons target
2037 (list (cons label (markdown-line-number-at-pos)))) t)
2038 (setcdr entry
2039 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
2040 missing)))
2042 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
2043 "Add blank REF definition to the end of BUFFER.
2045 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
2047 When RECHECK is non-nil, BUFFER gets rechecked for undefined
2048 references so that REF disappears from the list of those links."
2049 (with-current-buffer buffer
2050 (when (not (eq major-mode 'markdown-mode))
2051 (error "Not available in current mode"))
2052 (goto-char (point-max))
2053 (indent-new-comment-line)
2054 (insert (concat ref ": ")))
2055 (switch-to-buffer-other-window buffer)
2056 (goto-char (point-max))
2057 (when recheck
2058 (markdown-check-refs t)))
2060 ;; Button which adds an empty Markdown reference definition to the end
2061 ;; of buffer specified as its 'target-buffer property. Reference name
2062 ;; is button's label
2063 (when (>= emacs-major-version 22)
2064 (define-button-type 'markdown-ref-button
2065 'help-echo "Push to create an empty reference definition"
2066 'face 'bold
2067 'action (lambda (b)
2068 (markdown-add-missing-ref-definition
2069 (button-label b) (button-get b 'target-buffer) t))))
2071 ;; Button jumping to line in buffer specified as its 'target-buffer
2072 ;; property. Line number is button's 'line property.
2073 (when (>= emacs-major-version 22)
2074 (define-button-type 'goto-line-button
2075 'help-echo "Push to go to this line"
2076 'face 'italic
2077 'action (lambda (b)
2078 (message (button-get b 'buffer))
2079 (switch-to-buffer-other-window (button-get b 'target-buffer))
2080 ;; use call-interactively to silence compiler
2081 (call-interactively 'goto-line (button-get b 'target-line)))))
2083 (defun markdown-check-refs (&optional silent)
2084 "Show all undefined Markdown references in current `markdown-mode' buffer.
2086 If SILENT is non-nil, do not message anything when no undefined
2087 references found.
2089 Links which have empty reference definitions are considered to be
2090 defined."
2091 (interactive "P")
2092 (when (not (eq major-mode 'markdown-mode))
2093 (error "Not available in current mode"))
2094 (let ((oldbuf (current-buffer))
2095 (refs (markdown-get-undefined-refs))
2096 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
2097 "%buffer%" (buffer-name)
2098 markdown-refcheck-buffer))))
2099 (if (null refs)
2100 (progn
2101 (when (not silent)
2102 (message "No undefined references found"))
2103 (kill-buffer refbuf))
2104 (with-current-buffer refbuf
2105 (when view-mode
2106 (View-exit-and-edit))
2107 (erase-buffer)
2108 (insert "Following references lack definitions:")
2109 (newline 2)
2110 (dolist (ref refs)
2111 (let ((button-label (format "%s" (car ref))))
2112 (if (>= emacs-major-version 22)
2113 ;; Create a reference button in Emacs 22
2114 (insert-text-button button-label
2115 :type 'markdown-ref-button
2116 'target-buffer oldbuf)
2117 ;; Insert reference as text in Emacs < 22
2118 (insert button-label)))
2119 (insert " (")
2120 (dolist (occurency (cdr ref))
2121 (let ((line (cdr occurency)))
2122 (if (>= emacs-major-version 22)
2123 ;; Create a line number button in Emacs 22
2124 (insert-button (number-to-string line)
2125 :type 'goto-line-button
2126 'target-buffer oldbuf
2127 'target-line line)
2128 ;; Insert line number as text in Emacs < 22
2129 (insert (number-to-string line)))
2130 (insert " "))) (delete-char -1)
2131 (insert ")")
2132 (newline))
2133 (view-buffer-other-window refbuf)
2134 (goto-char (point-min))
2135 (forward-line 2)))))
2138 ;;; Lists =====================================================================
2141 (defun markdown--cleanup-list-numbers-level (&optional pfx)
2142 "Update the numbering for pfx (as a string of spaces).
2144 Assume that the previously found match was for a numbered item in a list."
2145 (let ((cpfx pfx)
2146 (idx 0)
2147 (continue t)
2148 (step t)
2149 (sep nil))
2150 (while continue
2151 (setq step t)
2152 (cond
2153 ((looking-at "^\\([\s-]*\\)[0-9]+\\. ")
2154 (setq cpfx (match-string-no-properties 1))
2155 (cond
2156 ((string= cpfx pfx)
2157 (replace-match
2158 (concat pfx (number-to-string (setq idx (1+ idx))) ". "))
2159 (setq sep nil))
2160 ;; indented a level
2161 ((string< pfx cpfx)
2162 (setq sep (markdown--cleanup-list-numbers-level cpfx))
2163 (setq step nil))
2164 ;; exit the loop
2166 (setq step nil)
2167 (setq continue nil))))
2169 ((looking-at "^\\([\s-]*\\)[^ \n\r].*$")
2170 (setq cpfx (match-string-no-properties 1))
2171 (cond
2172 ;; reset if separated before
2173 ((string= cpfx pfx) (when sep (setq idx 0)))
2174 ((string< cpfx pfx)
2175 (setq step nil)
2176 (setq continue nil))))
2177 (t (setq sep t)))
2179 (when step
2180 (beginning-of-line)
2181 (setq continue (= (forward-line) 0))))
2182 sep))
2184 ;;;###autoload
2185 (defun markdown-cleanup-list-numbers ()
2186 "Update the numbering of numbered markdown lists"
2187 (interactive)
2188 (save-excursion
2189 (goto-char (point-min))
2190 (markdown--cleanup-list-numbers-level "")))
2194 ;;; Outline ===================================================================
2196 ;; The following visibility cycling code was taken from org-mode
2197 ;; by Carsten Dominik and adapted for markdown-mode.
2199 (defvar markdown-cycle-global-status 1)
2200 (defvar markdown-cycle-subtree-status nil)
2202 ;; Based on org-end-of-subtree from org.el
2203 (defun markdown-end-of-subtree (&optional invisible-OK)
2204 "Move to the end of the current subtree.
2205 Only visible heading lines are considered, unless INVISIBLE-OK is
2206 non-nil."
2207 (outline-back-to-heading invisible-OK)
2208 (let ((first t)
2209 (level (funcall outline-level)))
2210 (while (and (not (eobp))
2211 (or first (> (funcall outline-level) level)))
2212 (setq first nil)
2213 (outline-next-heading))
2214 (if (memq (preceding-char) '(?\n ?\^M))
2215 (progn
2216 ;; Go to end of line before heading
2217 (forward-char -1)
2218 (if (memq (preceding-char) '(?\n ?\^M))
2219 ;; leave blank line before heading
2220 (forward-char -1)))))
2221 (point))
2223 ;; Based on org-cycle from org.el.
2224 (defun markdown-cycle (&optional arg)
2225 "Visibility cycling for Markdown mode.
2226 If ARG is t, perform global visibility cycling. If the point is
2227 at an atx-style header, cycle visibility of the corresponding
2228 subtree. Otherwise, insert a tab using `indent-relative'."
2229 (interactive "P")
2230 (cond
2231 ((eq arg t) ;; Global cycling
2232 (cond
2233 ((and (eq last-command this-command)
2234 (eq markdown-cycle-global-status 2))
2235 ;; Move from overview to contents
2236 (hide-sublevels 1)
2237 (message "CONTENTS")
2238 (setq markdown-cycle-global-status 3))
2240 ((and (eq last-command this-command)
2241 (eq markdown-cycle-global-status 3))
2242 ;; Move from contents to all
2243 (show-all)
2244 (message "SHOW ALL")
2245 (setq markdown-cycle-global-status 1))
2248 ;; Defaults to overview
2249 (hide-body)
2250 (message "OVERVIEW")
2251 (setq markdown-cycle-global-status 2))))
2253 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2254 ;; At a heading: rotate between three different views
2255 (outline-back-to-heading)
2256 (let ((goal-column 0) eoh eol eos)
2257 ;; Determine boundaries
2258 (save-excursion
2259 (outline-back-to-heading)
2260 (save-excursion
2261 (beginning-of-line 2)
2262 (while (and (not (eobp)) ;; this is like `next-line'
2263 (get-char-property (1- (point)) 'invisible))
2264 (beginning-of-line 2)) (setq eol (point)))
2265 (outline-end-of-heading) (setq eoh (point))
2266 (markdown-end-of-subtree t)
2267 (skip-chars-forward " \t\n")
2268 (beginning-of-line 1) ; in case this is an item
2269 (setq eos (1- (point))))
2270 ;; Find out what to do next and set `this-command'
2271 (cond
2272 ((= eos eoh)
2273 ;; Nothing is hidden behind this heading
2274 (message "EMPTY ENTRY")
2275 (setq markdown-cycle-subtree-status nil))
2276 ((>= eol eos)
2277 ;; Entire subtree is hidden in one line: open it
2278 (show-entry)
2279 (show-children)
2280 (message "CHILDREN")
2281 (setq markdown-cycle-subtree-status 'children))
2282 ((and (eq last-command this-command)
2283 (eq markdown-cycle-subtree-status 'children))
2284 ;; We just showed the children, now show everything.
2285 (show-subtree)
2286 (message "SUBTREE")
2287 (setq markdown-cycle-subtree-status 'subtree))
2289 ;; Default action: hide the subtree.
2290 (hide-subtree)
2291 (message "FOLDED")
2292 (setq markdown-cycle-subtree-status 'folded)))))
2295 (indent-for-tab-command))))
2297 ;; Based on org-shifttab from org.el.
2298 (defun markdown-shifttab ()
2299 "Global visibility cycling.
2300 Calls `markdown-cycle' with argument t."
2301 (interactive)
2302 (markdown-cycle t))
2304 (defun markdown-outline-level ()
2305 "Return the depth to which a statement is nested in the outline."
2306 (cond
2307 ((match-end 1) 1)
2308 ((match-end 2) 2)
2309 ((- (match-end 0) (match-beginning 0)))))
2311 ;;; Commands ==================================================================
2313 (defun markdown (&optional output-buffer-name)
2314 "Run `markdown' on current buffer and insert output in buffer given by
2315 `output-buffer-name' (defaults to `markdown-output-buffer-name'). Return the
2316 OUTPUT-BUFFER used."
2317 (interactive)
2318 (save-window-excursion
2319 (let ((begin-region)
2320 (end-region))
2321 (if (markdown-transient-mark-mode-active)
2322 (setq begin-region (region-beginning)
2323 end-region (region-end))
2324 (setq begin-region (point-min)
2325 end-region (point-max)))
2327 (unless output-buffer-name
2328 (setq output-buffer-name markdown-output-buffer-name))
2330 (cond
2331 ;; Handle case when `markdown-command' does not read from stdin
2332 (markdown-command-needs-filename
2333 (if (not buffer-file-name)
2334 (error "Must be visiting a file")
2335 (shell-command (concat markdown-command " "
2336 (shell-quote-argument buffer-file-name))
2337 output-buffer-name)))
2338 ;; Pass region to `markdown-command' via stdin
2340 (shell-command-on-region begin-region end-region markdown-command
2341 output-buffer-name))))
2342 output-buffer-name))
2344 (defun markdown-standalone (&optional output-buffer-name)
2345 "special function to provide html standalone output"
2346 (interactive)
2347 (setq output-buffer-name (markdown output-buffer-name))
2348 (with-current-buffer output-buffer-name
2349 (set-buffer output-buffer-name)
2350 (goto-char (point-min))
2351 (unless (markdown-output-standalone-p)
2352 (markdown-add-xhtml-header-and-footer output-buffer-name))
2353 (html-mode))
2354 output-buffer-name)
2356 (defun markdown-other-window (&optional output-buffer-name)
2357 " Run `markdown' on current buffer and display in other window"
2358 (interactive)
2359 (display-buffer (markdown-standalone output-buffer-name)))
2361 (defun markdown-output-standalone-p ()
2362 "Determine whether `markdown-command' output is standalone XHTML.
2363 Standalone XHTML output is identified by an occurrence of
2364 `markdown-xhtml-standalone-regexp' in the first five lines of output."
2365 (re-search-forward
2366 markdown-xhtml-standalone-regexp
2367 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
2370 (defun markdown-add-xhtml-header-and-footer (title)
2371 "Wrap XHTML header and footer with given TITLE around current buffer."
2372 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
2373 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
2374 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
2375 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
2376 "<head>\n<title>")
2377 (insert title)
2378 (insert "</title>\n")
2379 (when (> (length markdown-content-type) 0)
2380 (insert
2381 (format
2382 "<meta http-equiv=\"Content-Type\" content=\"%s;charset=%s\"/>\n"
2383 markdown-content-type
2384 (or (and markdown-coding-system
2385 (fboundp 'coding-system-get)
2386 (coding-system-get markdown-coding-system
2387 'mime-charset))
2388 (and (fboundp 'coding-system-get)
2389 (coding-system-get buffer-file-coding-system
2390 'mime-charset))
2391 "iso-8859-1"))))
2392 (if (> (length markdown-css-path) 0)
2393 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
2394 markdown-css-path
2395 "\" />\n"))
2396 (when (> (length markdown-xhtml-header-content) 0)
2397 (insert markdown-xhtml-header-content))
2398 (insert "\n</head>\n\n"
2399 "<body>\n\n")
2400 (goto-char (point-max))
2401 (insert "\n"
2402 "</body>\n"
2403 "</html>\n"))
2405 (defun markdown-preview (&optional output-buffer-name)
2406 "Run `markdown' on the current buffer and preview the output in a browser."
2407 (interactive)
2408 (browse-url-of-buffer (markdown markdown-output-buffer-name)))
2410 (defun markdown-export-file-name (&optional extension)
2411 "Attempt to generate a filename for Markdown output.
2412 If the current buffer is visiting a file, we construct a new
2413 output filename based on that filename. Otherwise, return nil."
2414 (when (buffer-file-name)
2415 (unless extension
2416 (setq extension ".html"))
2417 (concat
2418 (cond
2419 ((buffer-file-name)
2420 (file-name-sans-extension (buffer-file-name)))
2421 (t (buffer-name)))
2422 extension)))
2424 (defun markdown-export (&optional output-file)
2425 "Run Markdown on the current buffer, save to a file, and return the filename.
2426 The resulting filename will be constructed using the current filename, but
2427 with the extension removed and replaced with .html."
2428 (interactive)
2429 (unless output-file
2430 (setq output-file (markdown-export-file-name ".html")))
2431 (when output-file
2432 (let ((output-buffer-name))
2433 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
2434 (markdown-standalone output-buffer-name)
2435 (with-current-buffer output-buffer-name
2436 (save-buffer))
2437 output-file)))
2439 (defun markdown-export-and-preview ()
2440 "Export to XHTML using `markdown-export' and browse the resulting file."
2441 (interactive)
2442 (browse-url (markdown-export)))
2444 (defun markdown-open ()
2445 "Open file for the current buffer with `markdown-open-command'."
2446 (interactive)
2447 (if (not markdown-open-command)
2448 (error "Variable `markdown-open-command' must be set")
2449 (if (not buffer-file-name)
2450 (error "Must be visiting a file")
2451 (call-process markdown-open-command
2452 nil nil nil buffer-file-name))))
2454 ;;; Links =====================================================================
2456 (require 'thingatpt)
2458 (defun markdown-link-p ()
2459 "Return non-nil when `point' is at a non-wiki link.
2460 See `markdown-wiki-link-p' for more information."
2461 (let ((case-fold-search nil))
2462 (and (not (markdown-wiki-link-p))
2463 (or (thing-at-point-looking-at markdown-regex-link-inline)
2464 (thing-at-point-looking-at markdown-regex-link-reference)))))
2466 (defun markdown-link-link ()
2467 "Return the link part of the regular (non-wiki) link at point.
2468 Works with both inline and reference style links. If point is
2469 not at a link or the link reference is not defined returns nil."
2470 (cond
2471 ((thing-at-point-looking-at markdown-regex-link-inline)
2472 (substring-no-properties (match-string 2) 1 -1))
2473 ((thing-at-point-looking-at markdown-regex-link-reference)
2474 (let* ((label (match-string-no-properties 1))
2475 (reference (match-string-no-properties 2))
2476 (target (downcase (if (string= reference "[]") label reference))))
2477 (markdown-has-reference-definition target)))
2478 (t (error "Not on a markdown link"))))
2480 (defun markdown-follow-link-at-point ()
2481 "Open the current non-wiki link in a browser."
2482 (interactive)
2483 (if (markdown-link-p) (browse-url (markdown-link-link))))
2486 ;;; WikiLink Following/Markup =================================================
2488 (defun markdown-wiki-link-p ()
2489 "Return non-nil when `point' is at a true wiki link.
2490 A true wiki link name matches `markdown-regex-wiki-link' but does not
2491 match the current file name after conversion. This modifies the data
2492 returned by `match-data'. Note that the potential wiki link name must
2493 be available via `match-string'."
2494 (let ((case-fold-search nil))
2495 (and (thing-at-point-looking-at markdown-regex-wiki-link)
2496 (or (not buffer-file-name)
2497 (not (string-equal (buffer-file-name)
2498 (markdown-convert-wiki-link-to-filename
2499 (markdown-wiki-link-link)))))
2500 (not (save-match-data
2501 (save-excursion))))))
2503 (defun markdown-wiki-link-link ()
2504 "Return the link part of the wiki link using current match data.
2505 The location of the link component depends on the value of
2506 `markdown-wiki-link-alias-first'."
2507 (if markdown-wiki-link-alias-first
2508 (or (match-string 3) (match-string 1))
2509 (match-string 1)))
2511 (defun markdown-convert-wiki-link-to-filename (name)
2512 "Generate a filename from the wiki link NAME.
2513 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
2514 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
2515 and [[test test]] both map to Test-test.ext."
2516 (let ((basename (markdown-replace-regexp-in-string
2517 "[[:space:]\n]" markdown-link-space-sub-char name)))
2518 (when (eq major-mode 'gfm-mode)
2519 (setq basename (concat (upcase (substring basename 0 1))
2520 (downcase (substring basename 1 nil)))))
2521 (concat basename
2522 (if (buffer-file-name)
2523 (concat "."
2524 (file-name-extension (buffer-file-name)))))))
2526 (defun markdown-follow-wiki-link (name &optional other)
2527 "Follow the wiki link NAME.
2528 Convert the name to a file name and call `find-file'. Ensure that
2529 the new buffer remains in `markdown-mode'."
2530 (let ((filename (markdown-convert-wiki-link-to-filename name))
2531 (wp (file-name-directory buffer-file-name)))
2532 (when other (other-window 1))
2533 (find-file (concat wp filename)))
2534 (when (not (eq major-mode 'markdown-mode))
2535 (markdown-mode)))
2537 (defun markdown-follow-wiki-link-at-point (&optional arg)
2538 "Find Wiki Link at point.
2539 With prefix argument C-u open the file in other window.
2541 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
2542 (interactive "P")
2543 (if (markdown-wiki-link-p)
2544 (markdown-follow-wiki-link (markdown-wiki-link-link) arg)
2545 (error "Point is not at a Wiki Link")))
2547 (defun markdown-next-wiki-link ()
2548 "Jump to next wiki link.
2549 See `markdown-wiki-link-p'."
2550 (interactive)
2551 (if (markdown-wiki-link-p)
2552 ;; At a wiki link already, move past it.
2553 (goto-char (+ 1 (match-end 0))))
2554 (save-match-data
2555 ;; Search for the next wiki link and move to the beginning.
2556 (re-search-forward markdown-regex-wiki-link nil t)
2557 (goto-char (match-beginning 0))))
2559 (defun markdown-previous-wiki-link ()
2560 "Jump to previous wiki link.
2561 See `markdown-wiki-link-p'."
2562 (interactive)
2563 (re-search-backward markdown-regex-wiki-link nil t))
2565 (defun markdown-highlight-wiki-link (from to face)
2566 "Highlight the wiki link in the region between FROM and TO using FACE."
2567 (put-text-property from to 'font-lock-face face))
2569 (defun markdown-unfontify-region-wiki-links (from to)
2570 "Remove wiki link faces from the region specified by FROM and TO."
2571 (interactive "nfrom: \nnto: ")
2572 (remove-text-properties from to '(font-lock-face markdown-link-face))
2573 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
2575 (defun markdown-fontify-region-wiki-links (from to)
2576 "Search region given by FROM and TO for wiki links and fontify them.
2577 If a wiki link is found check to see if the backing file exists
2578 and highlight accordingly."
2579 (goto-char from)
2580 (save-match-data
2581 (while (re-search-forward markdown-regex-wiki-link to t)
2582 (let ((highlight-beginning (match-beginning 0))
2583 (highlight-end (match-end 0))
2584 (file-name
2585 (markdown-convert-wiki-link-to-filename (match-string 1))))
2586 (if (file-exists-p file-name)
2587 (markdown-highlight-wiki-link
2588 highlight-beginning highlight-end markdown-link-face)
2589 (markdown-highlight-wiki-link
2590 highlight-beginning highlight-end markdown-link-face)
2591 (markdown-highlight-wiki-link
2592 highlight-beginning highlight-end markdown-missing-link-face))))))
2594 (defun markdown-extend-changed-region (from to)
2595 "Extend region given by FROM and TO so that we can fontify all links.
2596 The region is extended to the first newline before and the first
2597 newline after."
2598 ;; start looking for the first new line before 'from
2599 (goto-char from)
2600 (re-search-backward "\n" nil t)
2601 (let ((new-from (point-min))
2602 (new-to (point-max)))
2603 (if (not (= (point) from))
2604 (setq new-from (point)))
2605 ;; do the same thing for the first new line after 'to
2606 (goto-char to)
2607 (re-search-forward "\n" nil t)
2608 (if (not (= (point) to))
2609 (setq new-to (point)))
2610 (values new-from new-to)))
2612 (defun markdown-check-change-for-wiki-link (from to change)
2613 "Check region between FROM and TO for wiki links and re-fontfy as needed.
2614 Designed to be used with the `after-change-functions' hook.
2615 CHANGE is the number of bytes of pre-change text replaced by the
2616 given range."
2617 (interactive "nfrom: \nnto: \nnchange: ")
2618 (let* ((modified (buffer-modified-p))
2619 (buffer-undo-list t)
2620 (inhibit-read-only t)
2621 (inhibit-point-motion-hooks t)
2622 deactivate-mark
2623 buffer-file-truename)
2624 (unwind-protect
2625 (save-excursion
2626 (save-match-data
2627 (save-restriction
2628 ;; Extend the region to fontify so that it starts
2629 ;; and ends at safe places.
2630 (multiple-value-bind (new-from new-to)
2631 (markdown-extend-changed-region from to)
2632 ;; Unfontify existing fontification (start from scratch)
2633 (markdown-unfontify-region-wiki-links new-from new-to)
2634 ;; Now do the fontification.
2635 (markdown-fontify-region-wiki-links new-from new-to)))))
2636 (and (not modified)
2637 (buffer-modified-p)
2638 (set-buffer-modified-p nil)))))
2640 (defun markdown-fontify-buffer-wiki-links ()
2641 "Refontify all wiki links in the buffer."
2642 (interactive)
2643 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
2645 ;;; Miscellaneous =============================================================
2647 (defun markdown-line-number-at-pos (&optional pos)
2648 "Return (narrowed) buffer line number at position POS.
2649 If POS is nil, use current buffer location.
2650 This is an exact copy of `line-number-at-pos' for use in emacs21."
2651 (let ((opoint (or pos (point))) start)
2652 (save-excursion
2653 (goto-char (point-min))
2654 (setq start (point))
2655 (goto-char opoint)
2656 (forward-line 0)
2657 (1+ (count-lines start (point))))))
2659 (defun markdown-nobreak-p ()
2660 "Return nil if it is acceptable to break the current line at the point."
2661 ;; inside in square brackets (e.g., link anchor text)
2662 (looking-back "\\[[^]]*"))
2666 ;;; Mode definition ==========================================================
2668 (defun markdown-show-version ()
2669 "Show the version number in the minibuffer."
2670 (interactive)
2671 (message "markdown-mode, version %s" markdown-mode-version))
2673 ;;;###autoload
2674 (define-derived-mode markdown-mode text-mode "Markdown"
2675 "Major mode for editing Markdown files."
2676 ;; Natural Markdown tab width
2677 (setq tab-width 4)
2678 ;; Comments
2679 (make-local-variable 'comment-start)
2680 (setq comment-start "<!-- ")
2681 (make-local-variable 'comment-end)
2682 (setq comment-end " -->")
2683 (make-local-variable 'comment-start-skip)
2684 (setq comment-start-skip "<!--[ \t]*")
2685 (make-local-variable 'comment-column)
2686 (setq comment-column 0)
2687 ;; Font lock.
2688 (set (make-local-variable 'font-lock-defaults)
2689 '(markdown-mode-font-lock-keywords))
2690 (set (make-local-variable 'font-lock-multiline) t)
2691 ;; For imenu support
2692 (setq imenu-create-index-function 'markdown-imenu-create-index)
2693 ;; For menu support in XEmacs
2694 (easy-menu-add markdown-mode-menu markdown-mode-map)
2695 ;; Make filling work with lists (unordered, ordered, and definition)
2696 (set (make-local-variable 'paragraph-start)
2697 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
2698 ;; Outline mode
2699 (make-local-variable 'outline-regexp)
2700 (setq outline-regexp markdown-regex-header)
2701 (make-local-variable 'outline-level)
2702 (setq outline-level 'markdown-outline-level)
2703 ;; Cause use of ellipses for invisible text.
2704 (add-to-invisibility-spec '(outline . t))
2705 ;; Indentation and filling
2706 (make-local-variable 'fill-nobreak-predicate)
2707 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
2708 (setq indent-line-function markdown-indent-function)
2710 ;; Prepare hooks for XEmacs compatibility
2711 (when (featurep 'xemacs)
2712 (make-local-hook 'after-change-functions)
2713 (make-local-hook 'font-lock-extend-region-functions)
2714 (make-local-hook 'window-configuration-change-hook))
2716 ;; Multiline font lock
2717 (add-hook 'font-lock-extend-region-functions
2718 'markdown-font-lock-extend-region)
2720 ;; Anytime text changes make sure it gets fontified correctly
2721 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
2723 ;; If we left the buffer there is a really good chance we were
2724 ;; creating one of the wiki link documents. Make sure we get
2725 ;; refontified when we come back.
2726 (add-hook 'window-configuration-change-hook
2727 'markdown-fontify-buffer-wiki-links t t)
2729 ;; do the initial link fontification
2730 (markdown-fontify-buffer-wiki-links))
2732 ;;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
2734 ;;; GitHub Flavored Markdown Mode ============================================
2736 ;;;###autoload
2737 (define-derived-mode gfm-mode markdown-mode "GFM"
2738 "Major mode for editing GitHub Flavored Markdown files."
2739 (setq markdown-link-space-sub-char "-")
2740 (auto-fill-mode 0)
2741 ;; Use visual-line-mode if available, fall back to longlines-mode:
2742 (if (fboundp 'visual-line-mode)
2743 (visual-line-mode 1)
2744 (longlines-mode 1))
2745 ;; do the initial link fontification
2746 (markdown-fontify-buffer-wiki-links))
2749 (provide 'markdown-mode)
2751 ;;; markdown-mode.el ends here