Add markdown-footnote-kill (C-c C-f k)
[markdown-mode.git] / markdown-mode.el
blob7afefdebe1e7529b99e0f17bef0bca88d6388de2
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>
21 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
22 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
23 ;; Created: May 24, 2007
24 ;; Version: 1.8.1
25 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
26 ;; URL: http://jblevins.org/projects/markdown-mode/
28 ;; This file is not part of GNU Emacs.
30 ;; This program is free software; you can redistribute it and/or modify
31 ;; it under the terms of the GNU General Public License as published by
32 ;; the Free Software Foundation; either version 2, or (at your option)
33 ;; any later version.
35 ;; This program is distributed in the hope that it will be useful,
36 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
37 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 ;; GNU General Public License for more details.
40 ;; You should have received a copy of the GNU General Public License
41 ;; along with this program; if not, write to the Free Software
42 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
43 ;; Boston, MA 02110-1301, USA.
45 ;;; Commentary:
47 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
48 ;; text files in GNU Emacs. markdown-mode is free software, licensed
49 ;; under the GNU GPL.
51 ;; [Markdown]: http://daringfireball.net/projects/markdown/
53 ;; The latest stable version is markdown-mode 1.8.1, released on August 15, 2011:
55 ;; * [markdown-mode.el][]
56 ;; * [Screenshot][]
57 ;; * [Release notes][]
59 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
60 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
61 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
63 ;; markdown-mode is also available in several package managers, including:
65 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
66 ;; * RedHat and Fedora Linux: [emacs-goodies][]
67 ;; * OpenBSD: [textproc/markdown-mode][]
68 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
70 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
71 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
72 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
73 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
75 ;; The latest development version can be downloaded directly
76 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
77 ;; (browsable and clonable) Git repository at
78 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
79 ;; including the full project history, can be cloned via the Git protocol
80 ;; by running
82 ;; git clone git://jblevins.org/git/markdown-mode.git
84 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
86 ;;; Dependencies:
88 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
89 ;; 19 and XEmacs 19, which provides a uniform interface for creating
90 ;; menus in GNU Emacs and XEmacs.
92 ;;; Installation:
94 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
95 ;; the following lines to your `.emacs` file to associate markdown-mode
96 ;; with `.text` files:
98 ;; (autoload 'markdown-mode "markdown-mode"
99 ;; "Major mode for editing Markdown files" t)
100 ;; (setq auto-mode-alist
101 ;; (cons '("\\.text" . markdown-mode) auto-mode-alist))
103 ;; There is no consensus on an official file extension so change `.text` to
104 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
106 ;;; Customization:
108 ;; Although no configuration is *necessary* there are a few things
109 ;; that can be customized. The `M-x customize-mode` command
110 ;; provides an interface to all of the possible customizations:
112 ;; * `markdown-command' - the command used to run Markdown (default:
113 ;; `markdown'). This variable may be customized to pass
114 ;; command-line options to your Markdown processor of choice, but
115 ;; this command must accept input from `stdin`. If it does not, a
116 ;; simple wrapper script can be used to write `stdin` to a file
117 ;; and then pass that file to your Markdown interpreter. Ideally,
118 ;; this command will produce an XHTML fragment around which
119 ;; markdown-mode will wrap a header and footer (which can be
120 ;; further customized). However, it attempts to detect whether
121 ;; the command produces standalone XHTML output (via
122 ;; `markdown-xhtml-standalone-regexp'), in which case no header
123 ;; and footer content will be added.
125 ;; * `markdown-command-needs-filename' - set to non-nil if
126 ;; `markdown-command' does not accept input from stdin (default: nil).
127 ;; Instead, it will be passed a filename as the final command-line
128 ;; option. As a result, you will only be able to run Markdown
129 ;; from buffers which are visiting a file.
131 ;; * `markdown-hr-string' - string to use when inserting horizontal
132 ;; rules (default: `* * * * *').
134 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
135 ;; underscores for bold instead of two asterisks (default: `nil').
137 ;; * `markdown-italic-underscore' - set to a non-nil value to use
138 ;; underscores for italic instead of asterisks (default: `nil').
140 ;; * `markdown-indent-function' - the function to use for automatic
141 ;; indentation (default: `markdown-indent-line').
143 ;; * `markdown-indent-on-enter' - set to a non-nil value to
144 ;; automatically indent new lines when the enter key is pressed
145 ;; (default: `t')
147 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
148 ;; to automatically open a linked document in a new buffer if the
149 ;; cursor is an wiki link
150 ;; (default: `t')
152 ;; * `markdown-wiki-link-alias-first' - set to a non-nil value to
153 ;; treat aliased wiki links like `[[link text|PageName]]`.
154 ;; When set to nil, they will be treated as `[[PageName|link text]]'.
156 ;; * `markdown-uri-types' - a list of protocols for URIs that
157 ;; `markdown-mode' should highlight.
159 ;; * `markdown-enable-math' - syntax highlighting for
160 ;; LaTeX fragments (default: `nil').
162 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
164 ;; * `markdown-xhtml-header-content' - additional content to include
165 ;; in the XHTML `<head>` block.
167 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
168 ;; indicates whether the output of `markdown-command' is standalone
169 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
170 ;; this is not matched, we assume this output is a fragment and add
171 ;; our own header and footer.
173 ;; * `markdown-link-space-sub-char' - a character to replace spaces
174 ;; when mapping wiki links to filenames (default: `_`).
175 ;; For example, use an underscore for compatibility with the
176 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
177 ;; with Github wiki links.
179 ;; Additionally, the faces used for syntax highlighting can be modified to
180 ;; your liking by issuing `M-x customize-group RET markdown-faces`
181 ;; or by using the "Markdown Faces" link at the bottom of the mode
182 ;; customization screen.
184 ;;; Usage:
186 ;; Keybindings are grouped by prefixes based on their function. For
187 ;; example, commands dealing with headers begin with `C-c C-t`. The
188 ;; primary commands in each group will are described below. You can
189 ;; obtain a list of all keybindings by pressing `C-c C-h`.
191 ;; * Anchors: `C-c C-a`
193 ;; `C-c C-a l` inserts inline links of the form `[text](url)`.
194 ;; `C-c C-a r` inserts reference links of the form `[text][label]`.
195 ;; The label definition will be placed at the end of the current
196 ;; block. `C-c C-a w` acts similarly for wiki links of the form
197 ;; `[[WikiLink]]`. In all cases, if there is an active region, the
198 ;; text in the region is used as the link text.
200 ;; * Commands: `C-c C-c`
202 ;; `C-c C-c m` will run Markdown on the current buffer and preview
203 ;; the output in another buffer while `C-c C-c p` runs Markdown on
204 ;; the current buffer and previews the output in a browser.
205 ;; `C-c C-c e` will run Markdown on the current buffer and save
206 ;; the result in the file `basename.html`, where `basename` is the
207 ;; name of the Markdown file with the extension removed. **This
208 ;; file will be overwritten without notice.** Press `C-c C-c v`
209 ;; to view the exported file in a browser.
211 ;; `C-c C-c c` will check for undefined references. If there are
212 ;; any, a small buffer will open with a list of undefined
213 ;; references and the line numbers on which they appear. In Emacs
214 ;; 22 and greater, selecting a reference from this list and
215 ;; pressing `RET` will insert an empty reference definition at the
216 ;; end of the buffer. Similarly, selecting the line number will
217 ;; jump to the corresponding line.
219 ;; * Images: `C-c C-i`
221 ;; `C-c C-i i` inserts an image, using the active region (if any)
222 ;; as the alt text.
224 ;; * Physical styles: `C-c C-p`
226 ;; These commands all act on text in the active region, if any,
227 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
228 ;; the selected text bold, `C-c C-p f` formats the region as
229 ;; fixed-width text, and `C-c C-p i` is used for italic text.
231 ;; * Logical styles: `C-c C-s`
233 ;; These commands all act on text in the active region, if any,
234 ;; and insert empty markup fragments otherwise. Logical styles
235 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
236 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
237 ;; (`C-c C-s s`).
239 ;; * Headers: `C-c C-t`
241 ;; All header commands use text in the active region, if any, as
242 ;; the header text. To insert an atx or hash style level-n
243 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
244 ;; top-level setext or underline style header press `C-c C-t t`
245 ;; (mnemonic: title) and for a second-level underline-style header
246 ;; press `C-c C-t s` (mnemonic: section).
248 ;; * Footnotes: `C-c C-f`
250 ;; To create a new footnote at the point, press `C-c C-f n`.
251 ;; Press `C-c C-f g` with the point at a footnote to jump to the
252 ;; location where the footnote text is defined. Then, press
253 ;; `C-c C-f b` to return to the footnote marker in the main text.
255 ;; * Other elements:
257 ;; `C-c -` inserts a horizontal rule.
259 ;; * Wiki-Link Navigation:
261 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
262 ;; wiki links, respectively.
264 ;; * Outline Navigation:
266 ;; Navigation between headings is possible using `outline-mode'.
267 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
268 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
269 ;; next and previous visible headings at the same level as the one
270 ;; at the point. Finally, `C-M-u` will move up to a lower-level
271 ;; (more inclusive) visible heading.
273 ;; Many of the commands described above behave differently depending on
274 ;; whether Transient Mark mode is enabled or not. When it makes sense,
275 ;; if Transient Mark mode is on and a region is active, the command
276 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
277 ;; bold). For users who prefer to work outside of Transient Mark mode,
278 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
280 ;; When applicable, commands that specifically act on the region even
281 ;; outside of Transient Mark mode have the same keybinding as the with
282 ;; the exception of an additional `C-` prefix. For example,
283 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
284 ;; the region in Transient Mark mode while `markdown-blockquote-region'
285 ;; is bound to `C-c C-s C-b` and always applies to the region (when
286 ;; nonempty).
288 ;; markdown-mode attempts to be flexible in how it handles
289 ;; indentation. When you press `TAB` repeatedly, the point will cycle
290 ;; through several possible indentation levels corresponding to things
291 ;; you might have in mind when you press `RET` at the end of a line or
292 ;; `TAB`. For example, you may want to start a new list item,
293 ;; continue a list item with hanging indentation, indent for a nested
294 ;; pre block, and so on.
296 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
297 ;; visibility cycling for atx- or hash-style headers. There are two
298 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
299 ;; the table of contents view (headers only), outline view (top-level
300 ;; headers only), and the full document view. Pressing `TAB` while the
301 ;; point is at a header will cycle through levels of visibility for the
302 ;; subtree: completely folded, visible children, and fully visible.
303 ;; Note that mixing hash and underline style headers will give undesired
304 ;; results.
306 ;;; Extensions:
308 ;; Besides supporting the basic Markdown syntax, markdown-mode also
309 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
310 ;; links may be followed automatically by hitting the enter key when
311 ;; your curser is on a wiki link or by hitting `C-c C-w`. The
312 ;; autofollowing on enter key may be controlled with the
313 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
314 ;; `M-n` to quickly jump to the previous and next wiki links,
315 ;; respectively. Aliased or piped wiki links of the form
316 ;; `[[link text|PageName]]` are also supported. Since some wikis
317 ;; reverse these components, set `markdown-wiki-link-alias-first'
318 ;; to nil to treat them as `[[PageName|link text]]`.
320 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
321 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
322 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
323 ;; You can do this either by using `M-x customize-group markdown`
324 ;; or by placing the following in your `.emacs` file:
326 ;; (defun markdown-custom ()
327 ;; "markdown-mode-hook"
328 ;; (setq markdown-command "markdown | smartypants"))
329 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
331 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
333 ;; Experimental syntax highlighting for mathematical expressions written
334 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
335 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
336 ;; either via customize or by placing `(setq markdown-enable-itex t)`
337 ;; in `.emacs`, and restarting Emacs.
339 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
340 ;; mode, `gfm-mode', is also available. The GitHub implementation of
341 ;; differs slightly from standard Markdown. Most importantly, newlines are
342 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
343 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
344 ;; `visual-line-mode' is not available). Wiki links in this mode will be
345 ;; treated as on GitHub, with hyphens replacing spaces in filenames and
346 ;; where the first letter of the filename capitalized. For example,
347 ;; `[[wiki link]]' will map to a file named `Wiki-link` with the same
348 ;; extension as the current file.
350 ;;; Acknowledgments:
352 ;; markdown-mode has benefited greatly from the efforts of the
353 ;; following people:
355 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
356 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
357 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
358 ;; GitHub Flavored Markdown mode (`gfm-mode').
359 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
360 ;; `markdown' with an active region.
361 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
362 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
363 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
364 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
365 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
366 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
367 ;; compatibility and custom CSS.
368 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
369 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
370 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
371 ;; * Joost Kremers <joostkremers@fastmail.fm> for footnote-handling
372 ;; functions and bug reports regarding indentation.
373 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
374 ;; enhancements.
375 ;; * George Ogata <george.ogata@gmail.com> for fixing several
376 ;; byte-compilation warnings.
377 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
378 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
379 ;; customizations and XHTML export.
380 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
381 ;; Markdown processors which do not accept input from stdin.
382 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
383 ;; regarding the cl dependency and auto-fill-mode and indentation.
384 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
385 ;; substitution character for mapping wiki links to filenames.
386 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
387 ;; escape shell commands.
388 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
389 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
390 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
391 ;; Emacs Lisp coding conventions.
392 ;; * Donald Curtis <dcurtis@coe.edu> for fixing the `paragraph-fill' regexp.
393 ;; * Kevin Porter <kportertx@gmail.com> for wiki link handling in `gfm-mode'.
395 ;;; Bugs:
397 ;; Although markdown-mode is developed and tested primarily using
398 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
399 ;; priority.
401 ;; If you find any bugs in markdown-mode, please construct a test case
402 ;; or a patch and email me at <jrblevin@sdf.org>.
404 ;;; History:
406 ;; markdown-mode was written and is maintained by Jason Blevins. The
407 ;; first version was released on May 24, 2007.
409 ;; * 2007-05-24: Version 1.1
410 ;; * 2007-05-25: Version 1.2
411 ;; * 2007-06-05: [Version 1.3][]
412 ;; * 2007-06-29: Version 1.4
413 ;; * 2008-05-24: [Version 1.5][]
414 ;; * 2008-06-04: [Version 1.6][]
415 ;; * 2009-10-01: [Version 1.7][]
416 ;; * 2011-08-12: [Version 1.8][]
417 ;; * 2011-08-15: [Version 1.8.1][]
419 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
420 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
421 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
422 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
423 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
424 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
427 ;;; Code:
429 (require 'easymenu)
430 (require 'outline)
431 (eval-when-compile (require 'cl))
433 ;;; Constants =================================================================
435 (defconst markdown-mode-version "1.8.1"
436 "Markdown mode version number.")
438 (defconst markdown-output-buffer-name "*markdown-output*"
439 "Name of temporary buffer for markdown command output.")
441 ;;; Customizable variables ====================================================
443 (defvar markdown-mode-hook nil
444 "Hook run when entering Markdown mode.")
446 (defgroup markdown nil
447 "Major mode for editing text files in Markdown format."
448 :prefix "markdown-"
449 :group 'wp
450 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
452 (defcustom markdown-command "markdown"
453 "Command to run markdown."
454 :group 'markdown
455 :type 'string)
457 (defcustom markdown-command-needs-filename nil
458 "Set to non-nil if `markdown-command' does not accept input from stdin.
459 Instead, it will be passed a filename as the final command-line
460 option. As a result, you will only be able to run Markdown from
461 buffers which are visiting a file."
462 :group 'markdown
463 :type 'boolean)
465 (defcustom markdown-hr-string "* * * * *"
466 "String to use for horizonal rules."
467 :group 'markdown
468 :type 'string)
470 (defcustom markdown-bold-underscore nil
471 "Use two underscores for bold instead of two asterisks."
472 :group 'markdown
473 :type 'boolean)
475 (defcustom markdown-italic-underscore nil
476 "Use underscores for italic instead of asterisks."
477 :group 'markdown
478 :type 'boolean)
480 (defcustom markdown-indent-function 'markdown-indent-line
481 "Function to use to indent."
482 :group 'markdown
483 :type 'function)
485 (defcustom markdown-indent-on-enter t
486 "Automatically indent new lines when enter key is pressed."
487 :group 'markdown
488 :type 'boolean)
490 (defcustom markdown-follow-wiki-link-on-enter t
491 "Follow wiki link at point (if any) when the enter key is pressed."
492 :group 'markdown
493 :type 'boolean)
495 (defcustom markdown-wiki-link-alias-first t
496 "When non-nil, treat aliased wiki links like [[alias text|PageName]].
497 Otherwise, they will be treated as [[PageName|alias text]]."
498 :group 'markdown
499 :type 'boolean)
501 (defcustom markdown-uri-types
502 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
503 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
504 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
505 "Link types for syntax highlighting of URIs."
506 :group 'markdown
507 :type 'list)
509 (defcustom markdown-enable-math nil
510 "Syntax highlighting for inline LaTeX expressions.
511 This will not take effect until Emacs is restarted."
512 :group 'markdown
513 :type 'boolean)
515 (defcustom markdown-css-path ""
516 "URL of CSS file to link to in the output XHTML."
517 :group 'markdown
518 :type 'string)
520 (defcustom markdown-xhtml-header-content ""
521 "Additional content to include in the XHTML <head> block."
522 :group 'markdown
523 :type 'string)
525 (defcustom markdown-xhtml-standalone-regexp
526 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
527 "Regexp indicating whether `markdown-command' output is standalone XHTML."
528 :group 'markdown
529 :type 'regexp)
531 (defcustom markdown-link-space-sub-char
533 "Character to use instead of spaces when mapping wiki links to filenames."
534 :group 'markdown
535 :type 'string)
537 (defcustom markdown-footnote-location 'end
538 "Position where new footnotes are inserted in the document."
539 :group 'markdown
540 :type '(choice (const :tag "At the end of the document" end)
541 (const :tag "Immediately after the paragraph" immediately)
542 (const :tag "Before next header" header)))
544 ;;; Font lock =================================================================
546 (require 'font-lock)
548 (defvar markdown-italic-face 'markdown-italic-face
549 "Face name to use for italic text.")
551 (defvar markdown-bold-face 'markdown-bold-face
552 "Face name to use for bold text.")
554 (defvar markdown-header-face 'markdown-header-face
555 "Face name to use as a base for headers.")
557 (defvar markdown-header-face-1 'markdown-header-face-1
558 "Face name to use for level-1 headers.")
560 (defvar markdown-header-face-2 'markdown-header-face-2
561 "Face name to use for level-2 headers.")
563 (defvar markdown-header-face-3 'markdown-header-face-3
564 "Face name to use for level-3 headers.")
566 (defvar markdown-header-face-4 'markdown-header-face-4
567 "Face name to use for level-4 headers.")
569 (defvar markdown-header-face-5 'markdown-header-face-5
570 "Face name to use for level-5 headers.")
572 (defvar markdown-header-face-6 'markdown-header-face-6
573 "Face name to use for level-6 headers.")
575 (defvar markdown-inline-code-face 'markdown-inline-code-face
576 "Face name to use for inline code.")
578 (defvar markdown-list-face 'markdown-list-face
579 "Face name to use for list markers.")
581 (defvar markdown-blockquote-face 'markdown-blockquote-face
582 "Face name to use for blockquote.")
584 (defvar markdown-pre-face 'markdown-pre-face
585 "Face name to use for preformatted text.")
587 (defvar markdown-link-face 'markdown-link-face
588 "Face name to use for links.")
590 (defvar markdown-missing-link-face 'markdown-missing-link-face
591 "Face name to use for links where the linked file does not exist.")
593 (defvar markdown-reference-face 'markdown-reference-face
594 "Face name to use for reference.")
596 (defvar markdown-footnote-face 'markdown-footnote-face
597 "Face name to use for footnote identifiers.")
599 (defvar markdown-url-face 'markdown-url-face
600 "Face name to use for URLs.")
602 (defvar markdown-link-title-face 'markdown-link-title-face
603 "Face name to use for reference link titles.")
605 (defvar markdown-comment-face 'markdown-comment-face
606 "Face name to use for HTML comments.")
608 (defvar markdown-math-face 'markdown-math-face
609 "Face name to use for LaTeX expressions.")
611 (defgroup markdown-faces nil
612 "Faces used in Markdown Mode"
613 :group 'markdown
614 :group 'faces)
616 (defface markdown-italic-face
617 '((t (:inherit font-lock-variable-name-face :slant italic)))
618 "Face for italic text."
619 :group 'markdown-faces)
621 (defface markdown-bold-face
622 '((t (:inherit font-lock-variable-name-face :weight bold)))
623 "Face for bold text."
624 :group 'markdown-faces)
626 (defface markdown-header-face
627 '((t (:inherit font-lock-function-name-face :weight bold)))
628 "Base face for headers."
629 :group 'markdown-faces)
631 (defface markdown-header-face-1
632 '((t (:inherit markdown-header-face)))
633 "Face for level-1 headers."
634 :group 'markdown-faces)
636 (defface markdown-header-face-2
637 '((t (:inherit markdown-header-face)))
638 "Face for level-2 headers."
639 :group 'markdown-faces)
641 (defface markdown-header-face-3
642 '((t (:inherit markdown-header-face)))
643 "Face for level-3 headers."
644 :group 'markdown-faces)
646 (defface markdown-header-face-4
647 '((t (:inherit markdown-header-face)))
648 "Face for level-4 headers."
649 :group 'markdown-faces)
651 (defface markdown-header-face-5
652 '((t (:inherit markdown-header-face)))
653 "Face for level-5 headers."
654 :group 'markdown-faces)
656 (defface markdown-header-face-6
657 '((t (:inherit markdown-header-face)))
658 "Face for level-6 headers."
659 :group 'markdown-faces)
661 (defface markdown-inline-code-face
662 '((t (:inherit font-lock-constant-face)))
663 "Face for inline code."
664 :group 'markdown-faces)
666 (defface markdown-list-face
667 '((t (:inherit font-lock-builtin-face)))
668 "Face for list item markers."
669 :group 'markdown-faces)
671 (defface markdown-blockquote-face
672 '((t (:inherit font-lock-doc-face)))
673 "Face for blockquote sections."
674 :group 'markdown-faces)
676 (defface markdown-pre-face
677 '((t (:inherit font-lock-constant-face)))
678 "Face for preformatted text."
679 :group 'markdown-faces)
681 (defface markdown-link-face
682 '((t (:inherit font-lock-keyword-face)))
683 "Face for links."
684 :group 'markdown-faces)
686 (defface markdown-missing-link-face
687 '((t (:inherit font-lock-warning-face)))
688 "Face for missing links."
689 :group 'markdown-faces)
691 (defface markdown-reference-face
692 '((t (:inherit font-lock-type-face)))
693 "Face for link references."
694 :group 'markdown-faces)
696 (defface markdown-footnote-face
697 '((t (:inherit font-lock-keyword-face)))
698 "Face for footnote markers."
699 :group 'markdown-faces)
701 (defface markdown-url-face
702 '((t (:inherit font-lock-string-face)))
703 "Face for URLs."
704 :group 'markdown-faces)
706 (defface markdown-link-title-face
707 '((t (:inherit font-lock-comment-face)))
708 "Face for reference link titles."
709 :group 'markdown-faces)
711 (defface markdown-comment-face
712 '((t (:inherit font-lock-comment-face)))
713 "Face for HTML comments."
714 :group 'markdown-faces)
716 (defface markdown-math-face
717 '((t (:inherit font-lock-string-face)))
718 "Face for LaTeX expressions."
719 :group 'markdown-faces)
721 (defconst markdown-regex-link-inline
722 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
723 "Regular expression for a [text](file) or an image link ![text](file).")
725 (defconst markdown-regex-link-reference
726 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
727 "Regular expression for a reference link [text][id].")
729 (defconst markdown-regex-reference-definition
730 "^ \\{0,3\\}\\(\\[.*\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
731 "Regular expression for a link definition [id]: ...")
733 (defconst markdown-regex-footnote
734 "\\(\\[\\^.+?\\]\\)"
735 "Regular expression for a footnote marker [^fn].")
737 (defconst markdown-regex-header
738 "#+\\|\\S-.*\n\\(?:\\(===+\\)\\|\\(---+\\)\\)$"
739 "Regexp identifying Markdown headers.")
741 (defconst markdown-regex-header-1-atx
742 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
743 "Regular expression for level 1 atx-style (hash mark) headers.")
745 (defconst markdown-regex-header-2-atx
746 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
747 "Regular expression for level 2 atx-style (hash mark) headers.")
749 (defconst markdown-regex-header-3-atx
750 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
751 "Regular expression for level 3 atx-style (hash mark) headers.")
753 (defconst markdown-regex-header-4-atx
754 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
755 "Regular expression for level 4 atx-style (hash mark) headers.")
757 (defconst markdown-regex-header-5-atx
758 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
759 "Regular expression for level 5 atx-style (hash mark) headers.")
761 (defconst markdown-regex-header-6-atx
762 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
763 "Regular expression for level 6 atx-style (hash mark) headers.")
765 (defconst markdown-regex-header-1-setext
766 "^\\(.*\\)\n\\(===+\\)$"
767 "Regular expression for level 1 setext-style (underline) headers.")
769 (defconst markdown-regex-header-2-setext
770 "^\\(.*\\)\n\\(---+\\)$"
771 "Regular expression for level 2 setext-style (underline) headers.")
773 (defconst markdown-regex-hr
774 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
775 "Regular expression for matching Markdown horizontal rules.")
777 (defconst markdown-regex-code
778 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ]\\(.\\|\n[^\n]\\)*?[^ \\]\\)\\3\\)"
779 "Regular expression for matching inline code fragments.")
781 (defconst markdown-regex-pre
782 "^\\( \\|\t\\).*$"
783 "Regular expression for matching preformatted text sections.")
785 (defconst markdown-regex-list
786 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
787 "Regular expression for matching list markers.")
789 (defconst markdown-regex-bold
790 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)"
791 "Regular expression for matching bold text.")
793 (defconst markdown-regex-italic
794 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
795 "Regular expression for matching italic text.")
797 (defconst markdown-regex-blockquote
798 "^>.*$"
799 "Regular expression for matching blockquote lines.")
801 (defconst markdown-regex-line-break
802 " $"
803 "Regular expression for matching line breaks.")
805 (defconst markdown-regex-wiki-link
806 "\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]"
807 "Regular expression for matching wiki links.
808 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
809 wiki links of the form [[PageName|link text]]. In this regular
810 expression, #1 matches the page name and #3 matches the link
811 text.")
813 (defconst markdown-regex-uri
814 (concat
815 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
816 "\\):[^]\t\n\r<>,;() ]+")
817 "Regular expression for matching inline URIs.")
819 (defconst markdown-regex-angle-uri
820 (concat
821 "\\(<\\)\\("
822 (mapconcat 'identity markdown-uri-types "\\|")
823 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
824 "Regular expression for matching inline URIs in angle brackets.")
826 (defconst markdown-regex-email
827 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
828 "Regular expression for matching inline email addresses.")
830 (defconst markdown-regex-latex-expression
831 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
832 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
834 (defconst markdown-regex-latex-display
835 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
836 "Regular expression for itex \[..\] display mode expressions.")
838 (defconst markdown-regex-list-indent
839 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
840 "Regular expression for matching indentation of list items.")
842 (defvar markdown-mode-font-lock-keywords-basic
843 (list
844 '(markdown-match-pre-blocks 0 markdown-pre-face t t)
845 '(markdown-match-fenced-code-blocks 0 markdown-pre-face t t)
846 (cons markdown-regex-blockquote 'markdown-blockquote-face)
847 (cons markdown-regex-header-1-setext 'markdown-header-face-1)
848 (cons markdown-regex-header-2-setext 'markdown-header-face-2)
849 (cons markdown-regex-header-1-atx 'markdown-header-face-1)
850 (cons markdown-regex-header-2-atx 'markdown-header-face-2)
851 (cons markdown-regex-header-3-atx 'markdown-header-face-3)
852 (cons markdown-regex-header-4-atx 'markdown-header-face-4)
853 (cons markdown-regex-header-5-atx 'markdown-header-face-5)
854 (cons markdown-regex-header-6-atx 'markdown-header-face-6)
855 (cons markdown-regex-hr 'markdown-header-face)
856 '(markdown-match-comments 0 markdown-comment-face t t)
857 (cons markdown-regex-code '(2 markdown-inline-code-face))
858 (cons markdown-regex-angle-uri 'markdown-link-face)
859 (cons markdown-regex-uri 'markdown-link-face)
860 (cons markdown-regex-email 'markdown-link-face)
861 (cons markdown-regex-list 'markdown-list-face)
862 (cons markdown-regex-link-inline
863 '((1 markdown-link-face t)
864 (2 markdown-url-face t)))
865 (cons markdown-regex-link-reference
866 '((1 markdown-link-face t)
867 (2 markdown-reference-face t)))
868 (cons markdown-regex-reference-definition
869 '((1 markdown-reference-face t)
870 (2 markdown-url-face t)
871 (3 markdown-link-title-face t)))
872 (cons markdown-regex-footnote 'markdown-footnote-face)
873 (cons markdown-regex-bold '(2 markdown-bold-face))
874 (cons markdown-regex-italic '(2 markdown-italic-face))
876 "Syntax highlighting for Markdown files.")
878 (defconst markdown-mode-font-lock-keywords-latex
879 (list
880 ;; Math mode $..$ or $$..$$
881 (cons markdown-regex-latex-expression '(2 markdown-math-face))
882 ;; Display mode equations with brackets: \[ \]
883 (cons markdown-regex-latex-display 'markdown-math-face)
884 ;; Equation reference (eq:foo)
885 (cons "(eq:\\w+)" 'markdown-reference-face)
886 ;; Equation reference \eqref{foo}
887 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
888 "Syntax highlighting for LaTeX fragments.")
890 (defvar markdown-mode-font-lock-keywords
891 (append
892 (if markdown-enable-math
893 markdown-mode-font-lock-keywords-latex)
894 markdown-mode-font-lock-keywords-basic)
895 "Default highlighting expressions for Markdown mode.")
897 ;; Footnotes
898 (defvar markdown-footnote-counter 0
899 "Counter for footnote numbers.")
900 (make-variable-buffer-local 'markdown-footnote-counter)
902 (defconst markdown-footnote-chars
903 "[[:alnum:]-]"
904 "Regular expression maching any character that is allowed in a footnote identifier.")
908 ;;; Compatibility =============================================================
910 ;; Handle replace-regexp-in-string in XEmacs 21
911 (defun markdown-replace-regexp-in-string (regexp rep string)
912 "Compatibility wrapper to provide `replace-regexp-in-string'."
913 (if (featurep 'xemacs)
914 (replace-in-string string regexp rep)
915 (replace-regexp-in-string regexp rep string)))
919 ;;; Markdown parsing functions ================================================
921 (defun markdown-cur-line-blank-p ()
922 "Return t if the current line is blank and nil otherwise."
923 (save-excursion
924 (beginning-of-line)
925 (re-search-forward "^\\s *$" (point-at-eol) t)))
927 (defun markdown-prev-line-blank-p ()
928 "Return t if the previous line is blank and nil otherwise.
929 If we are at the first line, then consider the previous line to be blank."
930 (save-excursion
931 (if (= (point-at-bol) (point-min))
933 (forward-line -1)
934 (markdown-cur-line-blank-p))))
936 (defun markdown-next-line-blank-p ()
937 "Return t if the next line is blank and nil otherwise.
938 If we are at the last line, then consider the next line to be blank."
939 (save-excursion
940 (if (= (point-at-bol) (point-max))
942 (forward-line 1)
943 (markdown-cur-line-blank-p))))
945 (defun markdown-prev-line-indent-p ()
946 "Return t if the previous line is indented and nil otherwise."
947 (save-excursion
948 (forward-line -1)
949 (goto-char (point-at-bol))
950 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
952 (defun markdown-cur-line-indent ()
953 "Return the number of leading whitespace characters in the current line."
954 (save-excursion
955 (goto-char (point-at-bol))
956 (re-search-forward "^\\s +" (point-at-eol) t)
957 (current-column)))
959 (defun markdown-prev-line-indent ()
960 "Return the number of leading whitespace characters in the previous line."
961 (save-excursion
962 (forward-line -1)
963 (markdown-cur-line-indent)))
965 (defun markdown-next-line-indent ()
966 "Return the number of leading whitespace characters in the next line."
967 (save-excursion
968 (forward-line 1)
969 (markdown-cur-line-indent)))
971 (defun markdown-cur-non-list-indent ()
972 "Return the number of leading whitespace characters in the current line."
973 (save-excursion
974 (beginning-of-line)
975 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
976 (current-column))))
978 (defun markdown-prev-non-list-indent ()
979 "Return position of the first non-list-marker on the previous line."
980 (save-excursion
981 (forward-line -1)
982 (markdown-cur-non-list-indent)))
984 (defun markdown--next-block ()
985 "Move the point to the start of the next text block."
986 (forward-line)
987 (while (and (or (not (markdown-prev-line-blank-p))
988 (markdown-cur-line-blank-p))
989 (not (eobp)))
990 (forward-line)))
992 (defun markdown--end-of-level (level)
993 "Move the point to the end of region with indentation at least LEVEL."
994 (let (indent)
995 (while (and (not (< (setq indent (markdown-cur-line-indent)) level))
996 (not (>= indent (+ level 4)))
997 (not (eobp)))
998 (markdown--next-block))
999 (unless (eobp)
1000 ;; Move back before any trailing blank lines
1001 (while (and (markdown-prev-line-blank-p)
1002 (not (bobp)))
1003 (forward-line -1))
1004 (forward-line -1)
1005 (end-of-line))))
1007 ; From html-helper-mode
1008 (defun markdown-match-comments (last)
1009 "Match HTML comments from the point to LAST."
1010 (cond ((search-forward "<!--" last t)
1011 (backward-char 4)
1012 (let ((beg (point)))
1013 (cond ((search-forward-regexp "--[ \t]*>" last t)
1014 (set-match-data (list beg (point)))
1016 (t nil))))
1017 (t nil)))
1019 (defun markdown-match-pre-blocks (last)
1020 "Match Markdown pre blocks from point to LAST.
1021 A region matches as if it is indented at least four spaces
1022 relative to the nearest previous block of lesser non-list-marker
1023 indentation."
1025 (let (cur-begin cur-end cur-indent prev-indent prev-list stop match found)
1026 ;; Don't start in the middle of a block
1027 (unless (and (bolp)
1028 (markdown-prev-line-blank-p)
1029 (not (markdown-cur-line-blank-p)))
1030 (markdown--next-block))
1032 ;; Move to the first full block in the region with indent 4 or more
1033 (while (and (not (>= (setq cur-indent (markdown-cur-line-indent)) 4))
1034 (not (>= (point) last)))
1035 (markdown--next-block))
1036 (setq cur-begin (point))
1037 (markdown--end-of-level cur-indent)
1038 (setq cur-end (point))
1039 (setq match nil)
1040 (setq stop (> cur-begin cur-end))
1042 (while (and (<= cur-end last) (not stop) (not match))
1043 ;; Move to the nearest preceding block of lesser (non-marker) indentation
1044 (setq prev-indent (+ cur-indent 1))
1045 (goto-char cur-begin)
1046 (setq found nil)
1047 (while (and (>= prev-indent cur-indent)
1048 (not (and prev-list
1049 (eq prev-indent cur-indent)))
1050 (not (bobp)))
1052 ;; Move point to the last line of the previous block.
1053 (forward-line -1)
1054 (while (and (markdown-cur-line-blank-p)
1055 (not (bobp)))
1056 (forward-line -1))
1058 ;; Update the indentation level using either the
1059 ;; non-list-marker indentation, if the previous line is the
1060 ;; start of a list, or the actual indentation.
1061 (setq prev-list (markdown-cur-non-list-indent))
1062 (setq prev-indent (or prev-list
1063 (markdown-cur-line-indent)))
1064 (setq found t))
1066 ;; If the loop didn't execute
1067 (unless found
1068 (setq prev-indent 0))
1070 ;; Compare with prev-indent minus its remainder mod 4
1071 (setq prev-indent (- prev-indent (mod prev-indent 4)))
1073 ;; Set match data and return t if we have a match
1074 (if (>= cur-indent (+ prev-indent 4))
1075 ;; Match
1076 (progn
1077 (setq match t)
1078 (set-match-data (list cur-begin cur-end))
1079 ;; Leave point at end of block
1080 (goto-char cur-end)
1081 (forward-line))
1083 ;; Move to the next block (if possible)
1084 (goto-char cur-end)
1085 (markdown--next-block)
1086 (setq cur-begin (point))
1087 (setq cur-indent (markdown-cur-line-indent))
1088 (markdown--end-of-level cur-indent)
1089 (setq cur-end (point))
1090 (setq stop (equal cur-begin cur-end))))
1091 match))
1093 (defun markdown-match-fenced-code-blocks (last)
1094 "Match fenced code blocks from the point to LAST."
1095 (cond ((search-forward-regexp "^\\([~]\\{3,\\}\\)" last t)
1096 (beginning-of-line)
1097 (let ((beg (point)))
1098 (forward-line)
1099 (cond ((search-forward-regexp
1100 (concat "^" (match-string 1) "~*") last t)
1101 (set-match-data (list beg (point)))
1103 (t nil))))
1104 (t nil)))
1106 (defun markdown-font-lock-extend-region ()
1107 "Extend the search region to include an entire block of text.
1108 This helps improve font locking for block constructs such as pre blocks."
1109 ;; Avoid compiler warnings about these global variables from font-lock.el.
1110 ;; See the documentation for variable `font-lock-extend-region-functions'.
1111 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1112 (save-excursion
1113 (goto-char font-lock-beg)
1114 (let ((found (re-search-backward "\n\n" nil t)))
1115 (when found
1116 (goto-char font-lock-end)
1117 (when (re-search-forward "\n\n" nil t)
1118 (beginning-of-line)
1119 (setq font-lock-end (point)))
1120 (setq font-lock-beg found)))))
1124 ;;; Syntax Table ==============================================================
1126 (defvar markdown-mode-syntax-table
1127 (let ((markdown-mode-syntax-table (make-syntax-table)))
1128 (modify-syntax-entry ?\" "w" markdown-mode-syntax-table)
1129 markdown-mode-syntax-table)
1130 "Syntax table for `markdown-mode'.")
1134 ;;; Element Insertion =========================================================
1136 (defun markdown-wrap-or-insert (s1 s2)
1137 "Insert the strings S1 and S2.
1138 If Transient Mark mode is on and a region is active, wrap the strings S1
1139 and S2 around the region."
1140 (if (and transient-mark-mode mark-active)
1141 (let ((a (region-beginning)) (b (region-end)))
1142 (goto-char a)
1143 (insert s1)
1144 (goto-char (+ b (length s1)))
1145 (insert s2))
1146 (insert s1 s2)))
1148 (defun markdown-insert-hr ()
1149 "Insert a horizonal rule using `markdown-hr-string'."
1150 (interactive)
1151 ;; Leading blank line
1152 (when (and (>= (point) (+ (point-min) 2))
1153 (not (looking-back "\n\n" 2)))
1154 (insert "\n"))
1155 ;; Insert custom HR string
1156 (insert (concat markdown-hr-string "\n"))
1157 ;; Following blank line
1158 (backward-char)
1159 (unless (looking-at "\n\n")
1160 (insert "\n")))
1162 (defun markdown-insert-bold ()
1163 "Insert markup for a bold word or phrase.
1164 If Transient Mark mode is on and a region is active, it is made bold."
1165 (interactive)
1166 (if markdown-bold-underscore
1167 (markdown-wrap-or-insert "__" "__")
1168 (markdown-wrap-or-insert "**" "**"))
1169 (backward-char 2))
1171 (defun markdown-insert-italic ()
1172 "Insert markup for an italic word or phrase.
1173 If Transient Mark mode is on and a region is active, it is made italic."
1174 (interactive)
1175 (if markdown-italic-underscore
1176 (markdown-wrap-or-insert "_" "_")
1177 (markdown-wrap-or-insert "*" "*"))
1178 (backward-char 1))
1180 (defun markdown-insert-code ()
1181 "Insert markup for an inline code fragment.
1182 If Transient Mark mode is on and a region is active, it is marked
1183 as inline code."
1184 (interactive)
1185 (markdown-wrap-or-insert "`" "`")
1186 (backward-char 1))
1188 (defun markdown-insert-link ()
1189 "Insert an inline link of the form []().
1190 If Transient Mark mode is on and a region is active, it is used
1191 as the link text."
1192 (interactive)
1193 (markdown-wrap-or-insert "[" "]")
1194 (insert "()")
1195 (backward-char 1))
1197 (defun markdown-insert-reference-link-dwim ()
1198 "Insert a reference link of the form [text][label] at point.
1199 If Transient Mark mode is on and a region is active, the region
1200 is used as the link text. Otherwise, the link text will be read
1201 from the minibuffer. The link URL, label, and title will be read
1202 from the minibuffer. The link label definition is placed at the
1203 end of the current paragraph."
1204 (interactive)
1205 (if (and transient-mark-mode mark-active)
1206 (call-interactively 'markdown-insert-reference-link-region)
1207 (call-interactively 'markdown-insert-reference-link)))
1209 (defun markdown-insert-reference-link-region (url label title)
1210 "Insert a reference link at point using the region as the link text."
1211 (interactive "sLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1212 (let ((text (buffer-substring (region-beginning) (region-end))))
1213 (delete-region (region-beginning) (region-end))
1214 (markdown-insert-reference-link text url label title)))
1216 (defun markdown-insert-reference-link (text url label title)
1217 "Insert a reference link at point.
1218 The link label definition is placed at the end of the current
1219 paragraph."
1220 (interactive "sLink Text: \nsLink URL: \nsLink Label (optional): \nsLink Title (optional): ")
1221 (let (end)
1222 (insert (concat "[" text "][" label "]"))
1223 (setq end (point))
1224 (forward-paragraph)
1225 (insert "\n[")
1226 (if (> (length label) 0)
1227 (insert label)
1228 (insert text))
1229 (insert (concat "]: " url))
1230 (unless (> (length url) 0)
1231 (setq end (point)))
1232 (when (> (length title) 0)
1233 (insert (concat " \"" title "\"")))
1234 (insert "\n")
1235 (unless (looking-at "\n")
1236 (insert "\n"))
1237 (goto-char end)))
1239 (defun markdown-insert-wiki-link ()
1240 "Insert a wiki link of the form [[WikiLink]].
1241 If Transient Mark mode is on and a region is active, it is used
1242 as the link text."
1243 (interactive)
1244 (markdown-wrap-or-insert "[[" "]]")
1245 (backward-char 2))
1247 (defun markdown-insert-image ()
1248 "Insert an inline image tag of the form ![]().
1249 If Transient Mark mode is on and a region is active, it is used
1250 as the alt text of the image."
1251 (interactive)
1252 (markdown-wrap-or-insert "![" "]")
1253 (insert "()")
1254 (backward-char 1))
1256 (defun markdown-insert-header-1 ()
1257 "Insert a first level atx-style (hash mark) header.
1258 If Transient Mark mode is on and a region is active, it is used
1259 as the header text."
1260 (interactive)
1261 (markdown-insert-header 1))
1263 (defun markdown-insert-header-2 ()
1264 "Insert a second level atx-style (hash mark) header.
1265 If Transient Mark mode is on and a region is active, it is used
1266 as the header text."
1267 (interactive)
1268 (markdown-insert-header 2))
1270 (defun markdown-insert-header-3 ()
1271 "Insert a third level atx-style (hash mark) header.
1272 If Transient Mark mode is on and a region is active, it is used
1273 as the header text."
1274 (interactive)
1275 (markdown-insert-header 3))
1277 (defun markdown-insert-header-4 ()
1278 "Insert a fourth level atx-style (hash mark) header.
1279 If Transient Mark mode is on and a region is active, it is used
1280 as the header text."
1281 (interactive)
1282 (markdown-insert-header 4))
1284 (defun markdown-insert-header-5 ()
1285 "Insert a fifth level atx-style (hash mark) header.
1286 If Transient Mark mode is on and a region is active, it is used
1287 as the header text."
1288 (interactive)
1289 (markdown-insert-header 5))
1291 (defun markdown-insert-header-6 ()
1292 "Insert a sixth level atx-style (hash mark) header.
1293 If Transient Mark mode is on and a region is active, it is used
1294 as the header text."
1295 (interactive)
1296 (markdown-insert-header 6))
1298 (defun markdown-insert-header (n)
1299 "Insert an atx-style (hash mark) header.
1300 With no prefix argument, insert a level-1 header. With prefix N,
1301 insert a level-N header. If Transient Mark mode is on and the
1302 region is active, it is used as the header text."
1303 (interactive "p")
1304 (unless n ; Test to see if n is defined
1305 (setq n 1)) ; Default to level 1 header
1306 (let (hdr hdrl hdrr)
1307 (dotimes (count n hdr)
1308 (setq hdr (concat "#" hdr))) ; Build a hash mark header string
1309 (setq hdrl (concat hdr " "))
1310 (setq hdrr (concat " " hdr))
1311 (markdown-wrap-or-insert hdrl hdrr))
1312 (backward-char (+ 1 n)))
1314 (defun markdown-insert-title ()
1315 "Insert a setext-style (underline) first level header.
1316 If Transient Mark mode is on and a region is active, it is used
1317 as the header text."
1318 (interactive)
1319 (if (and transient-mark-mode mark-active)
1320 (let ((a (region-beginning))
1321 (b (region-end))
1322 (len 0)
1323 (hdr))
1324 (setq len (- b a))
1325 (dotimes (count len hdr)
1326 (setq hdr (concat "=" hdr))) ; Build a === title underline
1327 (end-of-line)
1328 (insert "\n" hdr "\n"))
1329 (insert "\n==========\n")
1330 (backward-char 12)))
1332 (defun markdown-insert-section ()
1333 "Insert a setext-style (underline) second level header.
1334 If Transient Mark mode is on and a region is active, it is used
1335 as the header text."
1336 (interactive)
1337 (if (and transient-mark-mode mark-active)
1338 (let ((a (region-beginning))
1339 (b (region-end))
1340 (len 0)
1341 (hdr))
1342 (setq len (- b a))
1343 (dotimes (count len hdr)
1344 (setq hdr (concat "-" hdr))) ; Build a --- section underline
1345 (end-of-line)
1346 (insert "\n" hdr "\n"))
1347 (insert "\n----------\n")
1348 (backward-char 12)))
1350 (defun markdown-insert-blockquote ()
1351 "Start a blockquote section (or blockquote the region).
1352 If Transient Mark mode is on and a region is active, it is used as
1353 the blockquote text."
1354 (interactive)
1355 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1356 (markdown-blockquote-region (region-beginning) (region-end))
1357 (insert "> ")))
1359 (defun markdown-block-region (beg end prefix)
1360 "Format the region using a block prefix.
1361 Arguments BEG and END specify the beginning and end of the
1362 region. The characters PREFIX will appear at the beginning
1363 of each line."
1364 (if mark-active
1365 (save-excursion
1366 ;; Ensure that there is a leading blank line
1367 (goto-char beg)
1368 (when (and (>= (point) (+ (point-min) 2))
1369 (not (looking-back "\n\n" 2)))
1370 (insert "\n")
1371 (setq beg (1+ beg))
1372 (setq end (1+ end)))
1373 ;; Move back before any blank lines at the end
1374 (goto-char end)
1375 (while (and (looking-back "\n" 1)
1376 (not (equal (point) (point-min))))
1377 (backward-char)
1378 (setq end (1- end)))
1379 ;; Ensure that there is a trailing blank line
1380 (goto-char end)
1381 (if (not (or (looking-at "\n\n")
1382 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
1383 (insert "\n"))
1384 ;; Insert PREFIX
1385 (goto-char beg)
1386 (beginning-of-line)
1387 (while (< (point-at-bol) end)
1388 (insert prefix)
1389 (setq end (+ (length prefix) end))
1390 (forward-line)))))
1392 (defun markdown-blockquote-region (beg end)
1393 "Blockquote the region.
1394 Arguments BEG and END specify the beginning and end of the region."
1395 (interactive "*r")
1396 (markdown-block-region beg end "> "))
1398 (defun markdown-insert-pre ()
1399 "Start a preformatted section (or apply to the region).
1400 If Transient Mark mode is on and a region is active, it is marked
1401 as preformatted text."
1402 (interactive)
1403 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1404 (markdown-pre-region (region-beginning) (region-end))
1405 (insert " ")))
1407 (defun markdown-pre-region (beg end)
1408 "Format the region as preformatted text.
1409 Arguments BEG and END specify the beginning and end of the region."
1410 (interactive "*r")
1411 (markdown-block-region beg end " "))
1413 ;;; Footnotes ======================================================================
1415 (defun markdown-footnote-counter-inc ()
1416 "Increment markdown-footnote-counter and return the new value."
1417 (when (= markdown-footnote-counter 0) ; hasn't been updated in this buffer yet.
1418 (save-excursion
1419 (goto-char (point-min))
1420 (while (re-search-forward (concat "^\\[\\^\\(" markdown-footnote-chars "*?\\)\\]:")
1421 (point-max) t)
1422 (let ((fn (string-to-number (match-string 1))))
1423 (when (> fn markdown-footnote-counter)
1424 (setq markdown-footnote-counter fn))))))
1425 (incf markdown-footnote-counter))
1427 (defun markdown-footnote-new ()
1428 "Insert a footnote with a new number and jump to a position to enter the
1429 footnote text."
1430 (interactive)
1431 (let ((fn (markdown-footnote-counter-inc)))
1432 (insert (format "[^%d]" fn))
1433 (markdown-footnote-text-find-new-location)
1434 (insert (format "[^%d]: " fn))))
1436 (defun markdown-footnote-text-find-new-location ()
1437 "Position the cursor at the proper location for a new footnote text."
1438 (cond
1439 ((eq markdown-footnote-location 'end) (goto-char (point-max)))
1440 ((eq markdown-footnote-location 'immediately) (forward-paragraph))
1441 ((eq markdown-footnote-location 'header)
1442 ;; search for a header. if none is found, go to the end of the document.
1443 (catch 'eof
1444 (while (progn
1445 (forward-paragraph)
1446 (unless (re-search-forward markdown-regex-header nil t)
1447 (throw 'eof nil))
1448 (backward-paragraph)
1449 (not (looking-at (concat "\n" markdown-regex-header))))))))
1450 ;; make sure we're on an empty line:
1451 (unless (markdown-cur-line-blank-p)
1452 (insert "\n"))
1453 ;; and make sure the previous line is empty:
1454 (unless (markdown-prev-line-blank-p)
1455 (insert "\n"))
1456 ;; then make sure there's an empty line following the footnote:
1457 (unless (markdown-next-line-blank-p)
1458 (insert "\n")
1459 (forward-line -1)))
1461 (defun markdown-footnote-kill ()
1462 "Kill the footnote at point.
1463 The footnote text is killed (and added to the kill ring), the
1464 footnote marker is deleted. Point has to be either at the
1465 footnote marker or in the footnote text."
1466 (interactive)
1467 (let (return-pos)
1468 (when (markdown-footnote-text-positions) ; if we're in a footnote text
1469 (markdown-footnote-return) ; we first move to the marker
1470 (setq return-pos 'text)) ; and remember our return position
1471 (let ((marker (markdown-footnote-delete-marker)))
1472 (unless marker
1473 (error "Not at a footnote"))
1474 (let ((text-pos (markdown-footnote-find-text (car marker))))
1475 (unless text-pos
1476 (error "No text for footnote `%s'" (car marker)))
1477 (goto-char text-pos)
1478 (let ((pos (markdown-footnote-kill-text)))
1479 (setq return-pos
1480 (if (and pos (eq return-pos 'text))
1482 (cadr marker))))))
1483 (goto-char return-pos)))
1485 (defun markdown-footnote-delete-marker ()
1486 "Delete a footnote marker at point.
1487 Returns a list (ID START) containing the footnote ID and the
1488 start position of the marker before deletion. If no footnote
1489 marker was deleted, this function returns NIL."
1490 (let ((marker (markdown-footnote-marker-positions)))
1491 (when marker
1492 (delete-region (second marker) (third marker))
1493 (butlast marker))))
1495 (defun markdown-footnote-kill-text ()
1496 "Kill footnote text at point.
1497 Returns the start position of the footnote text before deletion,
1498 or NIL if point was not inside a footnote text.
1500 The killed text is placed in the kill ring (without the footnote
1501 number)."
1502 (let ((fn (markdown-footnote-text-positions)))
1503 (when fn
1504 (let ((text (delete-and-extract-region (second fn) (third fn))))
1505 (string-match (concat "\\[\\" (first fn) "\\]:[[:space:]]*\\(\\(.*\n?\\)*\\)") text)
1506 (kill-new (match-string 1 text))
1507 (second fn)))))
1509 (defun markdown-footnote-goto-text ()
1510 "Jump to the text of the footnote at point."
1511 (interactive)
1512 (let ((fn (car (markdown-footnote-marker-positions))))
1513 (unless fn
1514 (error "Not at a footnote marker"))
1515 (let ((new-pos (markdown-footnote-find-text fn)))
1516 (unless new-pos
1517 (error "No definition found for footnote `%s'" fn))
1518 (goto-char new-pos))))
1520 (defun markdown-footnote-return ()
1521 "Return from a footnote to its footnote number in the main text."
1522 (interactive)
1523 (let ((fn (save-excursion
1524 (car (markdown-footnote-text-positions)))))
1525 (unless fn
1526 (error "Not in a footnote"))
1527 (let ((new-pos (markdown-footnote-find-marker fn)))
1528 (unless new-pos
1529 (error "Footnote marker `%s' not found" fn))
1530 (goto-char new-pos))))
1532 (defun markdown-footnote-find-marker (id)
1533 "Find the location of the footnote marker with ID.
1534 The actual buffer position returned is the position directly
1535 following the marker's closing bracket. If no marker is found,
1536 NIL is returned."
1537 (save-excursion
1538 (goto-char (point-min))
1539 (when (re-search-forward (concat "\\[" id "\\]\\([^:]\\|\\'\\)") nil t)
1540 (skip-chars-backward "^]")
1541 (point))))
1543 (defun markdown-footnote-find-text (id)
1544 "Find the location of the text of footnote ID.
1545 The actual buffer position returned is the position of the first
1546 character of the text, after the footnote's identifier. If no
1547 footnote text is found, NIL is returned."
1548 (save-excursion
1549 (goto-char (point-min))
1550 (when (re-search-forward (concat "^\\[" id "\\]:") nil t)
1551 (skip-chars-forward "[:space:]")
1552 (point))))
1554 (defun markdown-footnote-marker-positions ()
1555 "Return the position and ID of the footnote marker point is on.
1556 The return value is a list (ID START END). If point is not on a
1557 footnote, NIL is returned."
1558 ;; first make sure we're at a footnote marker
1559 (if (or (looking-back (concat "\\[\\^" markdown-footnote-chars "*\\]?") (point-at-bol))
1560 (looking-at (concat "\\[?\\^" markdown-footnote-chars "*?\\]")))
1561 (save-excursion
1562 ;; move point between [ and ^:
1563 (if (looking-at "\\[")
1564 (forward-char 1)
1565 (skip-chars-backward "^["))
1566 (looking-at (concat "\\(\\^" markdown-footnote-chars "*?\\)\\]"))
1567 (list (match-string 1) (1- (match-beginning 1)) (1+ (match-end 1))))))
1569 (defun markdown-footnote-text-positions ()
1570 "Return the start and end positions of the footnote text point is in.
1571 The exact return value is a list of three elements: (ID START
1572 END). The start position is the position of the opening bracket
1573 of the footnote id. The end position is directly after the
1574 newline that ends the footnote. If point is not in a footnote,
1575 NIL is returned instead."
1576 (save-excursion
1577 (let ((fn (progn
1578 (backward-paragraph)
1579 ;; if we're in a multiparagraph footnote, we need to back up further
1580 (while (>= (markdown-next-line-indent) 4)
1581 (backward-paragraph))
1582 (forward-line)
1583 (if (looking-at (concat "^\\[\\(\\^" markdown-footnote-chars "*?\\)\\]:"))
1584 (list (match-string 1) (point))))))
1585 (when fn
1586 (while (progn
1587 (forward-paragraph)
1588 (>= (markdown-next-line-indent) 4)))
1589 (append fn (list (point)))))))
1591 ;;; Indentation ====================================================================
1593 (defun markdown-indent-find-next-position (cur-pos positions)
1594 "Return the position after the index of CUR-POS in POSITIONS."
1595 (while (and positions
1596 (not (equal cur-pos (car positions))))
1597 (setq positions (cdr positions)))
1598 (or (cadr positions) 0))
1600 (defun markdown-indent-line ()
1601 "Indent the current line using some heuristics.
1602 If the _previous_ command was either `markdown-enter-key' or
1603 `markdown-cycle', then we should cycle to the next
1604 reasonable indentation position. Otherwise, we could have been
1605 called directly by `markdown-enter-key', by an initial call of
1606 `markdown-cycle', or indirectly by `auto-fill-mode'. In
1607 these cases, indent to the default position."
1608 (interactive)
1609 (let ((positions (markdown-calc-indents))
1610 (cur-pos (current-column)))
1611 (if (not (equal this-command 'markdown-cycle))
1612 (indent-line-to (car positions))
1613 (setq positions (sort (delete-dups positions) '<))
1614 (indent-line-to
1615 (markdown-indent-find-next-position cur-pos positions)))))
1617 (defun markdown-calc-indents ()
1618 "Return a list of indentation columns to cycle through.
1619 The first element in the returned list should be considered the
1620 default indentation level."
1621 (let (pos prev-line-pos positions)
1623 ;; Previous line indent
1624 (setq prev-line-pos (markdown-prev-line-indent))
1625 (setq positions (cons prev-line-pos positions))
1627 ;; Previous non-list-marker indent
1628 (setq pos (markdown-prev-non-list-indent))
1629 (when pos
1630 (setq positions (cons pos positions))
1631 (setq positions (cons (+ pos tab-width) positions)))
1633 ;; Indentation of the previous line + tab-width
1634 (cond
1635 (prev-line-pos
1636 (setq positions (cons (+ prev-line-pos tab-width) positions)))
1638 (setq positions (cons tab-width positions))))
1640 ;; Indentation of the previous line - tab-width
1641 (if (and prev-line-pos
1642 (> prev-line-pos tab-width))
1643 (setq positions (cons (- prev-line-pos tab-width) positions)))
1645 ;; Indentation of preceeding list item
1646 (setq pos
1647 (save-excursion
1648 (forward-line -1)
1649 (catch 'break
1650 (while (not (equal (point) (point-min)))
1651 (forward-line -1)
1652 (goto-char (point-at-bol))
1653 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1654 (throw 'break (length (match-string 1)))))
1655 nil)))
1656 (if (and pos (not (eq pos prev-line-pos)))
1657 (setq positions (cons pos positions)))
1659 ;; First column
1660 (setq positions (cons 0 positions))
1662 (reverse positions)))
1664 (defun markdown-do-normal-return ()
1665 "Insert a newline and optionally indent the next line."
1666 (newline)
1667 (if markdown-indent-on-enter
1668 (funcall indent-line-function)))
1670 (defun markdown-enter-key ()
1671 "Handle RET according to context.
1672 If there is a wiki link at the point, follow it unless
1673 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1674 it in the usual way."
1675 (interactive)
1676 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
1677 (markdown-follow-wiki-link-at-point)
1678 (markdown-do-normal-return)))
1682 ;;; Keymap ====================================================================
1684 (defvar markdown-mode-map
1685 (let ((map (make-keymap)))
1686 ;; Element insertion
1687 (define-key map "\C-c\C-al" 'markdown-insert-link)
1688 (define-key map "\C-c\C-ar" 'markdown-insert-reference-link-dwim)
1689 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
1690 (define-key map "\C-c\C-ii" 'markdown-insert-image)
1691 (define-key map "\C-c\C-t1" 'markdown-insert-header-1)
1692 (define-key map "\C-c\C-t2" 'markdown-insert-header-2)
1693 (define-key map "\C-c\C-t3" 'markdown-insert-header-3)
1694 (define-key map "\C-c\C-t4" 'markdown-insert-header-4)
1695 (define-key map "\C-c\C-t5" 'markdown-insert-header-5)
1696 (define-key map "\C-c\C-t6" 'markdown-insert-header-6)
1697 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
1698 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
1699 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
1700 (define-key map "\C-c\C-se" 'markdown-insert-italic)
1701 (define-key map "\C-c\C-pf" 'markdown-insert-code)
1702 (define-key map "\C-c\C-sc" 'markdown-insert-code)
1703 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
1704 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
1705 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
1706 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
1707 (define-key map "\C-c-" 'markdown-insert-hr)
1708 (define-key map "\C-c\C-tt" 'markdown-insert-title)
1709 (define-key map "\C-c\C-ts" 'markdown-insert-section)
1710 ;; Footnotes
1711 (define-key map "\C-c\C-fn" 'markdown-footnote-new)
1712 (define-key map "\C-c\C-fg" 'markdown-footnote-goto-text)
1713 (define-key map "\C-c\C-fb" 'markdown-footnote-return)
1714 (define-key map "\C-c\C-fk" 'markdown-footnote-kill)
1715 ;; WikiLink Following
1716 (define-key map "\C-c\C-w" 'markdown-follow-wiki-link-at-point)
1717 (define-key map "\M-n" 'markdown-next-wiki-link)
1718 (define-key map "\M-p" 'markdown-previous-wiki-link)
1719 ;; Indentation
1720 (define-key map "\C-m" 'markdown-enter-key)
1721 ;; Visibility cycling
1722 (define-key map (kbd "<tab>") 'markdown-cycle)
1723 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
1724 ;; Header navigation
1725 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
1726 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
1727 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
1728 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
1729 (define-key map (kbd "C-M-u") 'outline-up-heading)
1730 ;; Markdown functions
1731 (define-key map "\C-c\C-cm" 'markdown)
1732 (define-key map "\C-c\C-cp" 'markdown-preview)
1733 (define-key map "\C-c\C-ce" 'markdown-export)
1734 (define-key map "\C-c\C-cv" 'markdown-export-and-view)
1735 ;; References
1736 (define-key map "\C-c\C-cc" 'markdown-check-refs)
1737 map)
1738 "Keymap for Markdown major mode.")
1740 ;;; Menu ==================================================================
1742 (easy-menu-define markdown-mode-menu markdown-mode-map
1743 "Menu for Markdown mode"
1744 '("Markdown"
1745 ("Show/Hide"
1746 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
1747 ["Cycle global visibility" markdown-shifttab])
1748 "---"
1749 ["Compile" markdown]
1750 ["Preview" markdown-preview]
1751 ["Export" markdown-export]
1752 ["Export & View" markdown-export-and-view]
1753 "---"
1754 ("Headers (setext)"
1755 ["Insert Title" markdown-insert-title]
1756 ["Insert Section" markdown-insert-section])
1757 ("Headers (atx)"
1758 ["First level" markdown-insert-header-1]
1759 ["Second level" markdown-insert-header-2]
1760 ["Third level" markdown-insert-header-3]
1761 ["Fourth level" markdown-insert-header-4]
1762 ["Fifth level" markdown-insert-header-5]
1763 ["Sixth level" markdown-insert-header-6])
1764 "---"
1765 ["Bold" markdown-insert-bold]
1766 ["Italic" markdown-insert-italic]
1767 ["Blockquote" markdown-insert-blockquote]
1768 ["Preformatted" markdown-insert-pre]
1769 ["Code" markdown-insert-code]
1770 "---"
1771 ["Insert inline link" markdown-insert-link]
1772 ["Insert reference link" markdown-insert-reference-link-dwim]
1773 ["Insert image" markdown-insert-image]
1774 ["Insert horizontal rule" markdown-insert-hr]
1775 "---"
1776 ("Footnotes"
1777 ["Insert footnote" markdown-footnote-new]
1778 ["Jump to footnote text" markdown-footnote-goto-text]
1779 ["Return from footnote" markdown-footnote-return])
1780 "---"
1781 ["Check references" markdown-check-refs]
1782 "---"
1783 ["Version" markdown-show-version]
1788 ;;; References ================================================================
1790 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
1792 (defconst markdown-refcheck-buffer
1793 "*Undefined references for %buffer%*"
1794 "Pattern for name of buffer for listing undefined references.
1795 The string %buffer% will be replaced by the corresponding
1796 `markdown-mode' buffer name.")
1798 (defun markdown-has-reference-definition (reference)
1799 "Find out whether Markdown REFERENCE is defined.
1801 REFERENCE should include the square brackets, like [this]."
1802 (let ((reference (downcase reference)))
1803 (save-excursion
1804 (goto-char (point-min))
1805 (catch 'found
1806 (while (re-search-forward markdown-regex-reference-definition nil t)
1807 (when (string= reference (downcase (match-string-no-properties 1)))
1808 (throw 'found t)))))))
1810 (defun markdown-get-undefined-refs ()
1811 "Return a list of undefined Markdown references.
1813 Result is an alist of pairs (reference . occurencies), where
1814 occurencies is itself another alist of pairs (label .
1815 line-number).
1817 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
1818 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
1819 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
1820 (let ((missing))
1821 (save-excursion
1822 (goto-char (point-min))
1823 (while
1824 (re-search-forward markdown-regex-link-reference nil t)
1825 (let* ((label (match-string-no-properties 1))
1826 (reference (match-string-no-properties 2))
1827 (target (downcase (if (string= reference "[]") label reference))))
1828 (unless (markdown-has-reference-definition target)
1829 (let ((entry (assoc target missing)))
1830 (if (not entry)
1831 (add-to-list 'missing (cons target
1832 (list (cons label (markdown-line-number-at-pos)))) t)
1833 (setcdr entry
1834 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
1835 missing)))
1837 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
1838 "Add blank REF definition to the end of BUFFER.
1840 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
1842 When RECHECK is non-nil, BUFFER gets rechecked for undefined
1843 references so that REF disappears from the list of those links."
1844 (with-current-buffer buffer
1845 (when (not (eq major-mode 'markdown-mode))
1846 (error "Not available in current mode"))
1847 (goto-char (point-max))
1848 (indent-new-comment-line)
1849 (insert (concat ref ": ")))
1850 (switch-to-buffer-other-window buffer)
1851 (goto-char (point-max))
1852 (when recheck
1853 (markdown-check-refs t)))
1855 ;; Button which adds an empty Markdown reference definition to the end
1856 ;; of buffer specified as its 'target-buffer property. Reference name
1857 ;; is button's label
1858 (when (>= emacs-major-version 22)
1859 (define-button-type 'markdown-ref-button
1860 'help-echo "Push to create an empty reference definition"
1861 'face 'bold
1862 'action (lambda (b)
1863 (markdown-add-missing-ref-definition
1864 (button-label b) (button-get b 'target-buffer) t))))
1866 ;; Button jumping to line in buffer specified as its 'target-buffer
1867 ;; property. Line number is button's 'line property.
1868 (when (>= emacs-major-version 22)
1869 (define-button-type 'goto-line-button
1870 'help-echo "Push to go to this line"
1871 'face 'italic
1872 'action (lambda (b)
1873 (message (button-get b 'buffer))
1874 (switch-to-buffer-other-window (button-get b 'target-buffer))
1875 ;; use call-interactively to silence compiler
1876 (call-interactively 'goto-line (button-get b 'target-line)))))
1878 (defun markdown-check-refs (&optional silent)
1879 "Show all undefined Markdown references in current `markdown-mode' buffer.
1881 If SILENT is non-nil, do not message anything when no undefined
1882 references found.
1884 Links which have empty reference definitions are considered to be
1885 defined."
1886 (interactive "P")
1887 (when (not (eq major-mode 'markdown-mode))
1888 (error "Not available in current mode"))
1889 (let ((oldbuf (current-buffer))
1890 (refs (markdown-get-undefined-refs))
1891 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
1892 "%buffer%" (buffer-name)
1893 markdown-refcheck-buffer))))
1894 (if (null refs)
1895 (progn
1896 (when (not silent)
1897 (message "No undefined references found"))
1898 (kill-buffer refbuf))
1899 (with-current-buffer refbuf
1900 (when view-mode
1901 (View-exit-and-edit))
1902 (erase-buffer)
1903 (insert "Following references lack definitions:")
1904 (newline 2)
1905 (dolist (ref refs)
1906 (let ((button-label (format "%s" (car ref))))
1907 (if (>= emacs-major-version 22)
1908 ;; Create a reference button in Emacs 22
1909 (insert-text-button button-label
1910 :type 'markdown-ref-button
1911 'target-buffer oldbuf)
1912 ;; Insert reference as text in Emacs < 22
1913 (insert button-label)))
1914 (insert " (")
1915 (dolist (occurency (cdr ref))
1916 (let ((line (cdr occurency)))
1917 (if (>= emacs-major-version 22)
1918 ;; Create a line number button in Emacs 22
1919 (insert-button (number-to-string line)
1920 :type 'goto-line-button
1921 'target-buffer oldbuf
1922 'target-line line)
1923 ;; Insert line number as text in Emacs < 22
1924 (insert (number-to-string line)))
1925 (insert " "))) (delete-char -1)
1926 (insert ")")
1927 (newline))
1928 (view-buffer-other-window refbuf)
1929 (goto-char (point-min))
1930 (forward-line 2)))))
1932 ;;; Outline ===================================================================
1934 ;; The following visibility cycling code was taken from org-mode
1935 ;; by Carsten Dominik and adapted for markdown-mode.
1937 (defvar markdown-cycle-global-status 1)
1938 (defvar markdown-cycle-subtree-status nil)
1940 ;; Based on org-end-of-subtree from org.el
1941 (defun markdown-end-of-subtree (&optional invisible-OK)
1942 "Move to the end of the current subtree.
1943 Only visible heading lines are considered, unless INVISIBLE-OK is
1944 non-nil."
1945 (outline-back-to-heading invisible-OK)
1946 (let ((first t)
1947 (level (funcall outline-level)))
1948 (while (and (not (eobp))
1949 (or first (> (funcall outline-level) level)))
1950 (setq first nil)
1951 (outline-next-heading))
1952 (if (memq (preceding-char) '(?\n ?\^M))
1953 (progn
1954 ;; Go to end of line before heading
1955 (forward-char -1)
1956 (if (memq (preceding-char) '(?\n ?\^M))
1957 ;; leave blank line before heading
1958 (forward-char -1)))))
1959 (point))
1961 ;; Based on org-cycle from org.el.
1962 (defun markdown-cycle (&optional arg)
1963 "Visibility cycling for Markdown mode.
1964 If ARG is t, perform global visibility cycling. If the point is
1965 at an atx-style header, cycle visibility of the corresponding
1966 subtree. Otherwise, insert a tab using `indent-relative'."
1967 (interactive "P")
1968 (cond
1969 ((eq arg t) ;; Global cycling
1970 (cond
1971 ((and (eq last-command this-command)
1972 (eq markdown-cycle-global-status 2))
1973 ;; Move from overview to contents
1974 (hide-sublevels 1)
1975 (message "CONTENTS")
1976 (setq markdown-cycle-global-status 3))
1978 ((and (eq last-command this-command)
1979 (eq markdown-cycle-global-status 3))
1980 ;; Move from contents to all
1981 (show-all)
1982 (message "SHOW ALL")
1983 (setq markdown-cycle-global-status 1))
1986 ;; Defaults to overview
1987 (hide-body)
1988 (message "OVERVIEW")
1989 (setq markdown-cycle-global-status 2))))
1991 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
1992 ;; At a heading: rotate between three different views
1993 (outline-back-to-heading)
1994 (let ((goal-column 0) eoh eol eos)
1995 ;; Determine boundaries
1996 (save-excursion
1997 (outline-back-to-heading)
1998 (save-excursion
1999 (beginning-of-line 2)
2000 (while (and (not (eobp)) ;; this is like `next-line'
2001 (get-char-property (1- (point)) 'invisible))
2002 (beginning-of-line 2)) (setq eol (point)))
2003 (outline-end-of-heading) (setq eoh (point))
2004 (markdown-end-of-subtree t)
2005 (skip-chars-forward " \t\n")
2006 (beginning-of-line 1) ; in case this is an item
2007 (setq eos (1- (point))))
2008 ;; Find out what to do next and set `this-command'
2009 (cond
2010 ((= eos eoh)
2011 ;; Nothing is hidden behind this heading
2012 (message "EMPTY ENTRY")
2013 (setq markdown-cycle-subtree-status nil))
2014 ((>= eol eos)
2015 ;; Entire subtree is hidden in one line: open it
2016 (show-entry)
2017 (show-children)
2018 (message "CHILDREN")
2019 (setq markdown-cycle-subtree-status 'children))
2020 ((and (eq last-command this-command)
2021 (eq markdown-cycle-subtree-status 'children))
2022 ;; We just showed the children, now show everything.
2023 (show-subtree)
2024 (message "SUBTREE")
2025 (setq markdown-cycle-subtree-status 'subtree))
2027 ;; Default action: hide the subtree.
2028 (hide-subtree)
2029 (message "FOLDED")
2030 (setq markdown-cycle-subtree-status 'folded)))))
2033 (indent-for-tab-command))))
2035 ;; Based on org-shifttab from org.el.
2036 (defun markdown-shifttab ()
2037 "Global visibility cycling.
2038 Calls `markdown-cycle' with argument t."
2039 (interactive)
2040 (markdown-cycle t))
2042 (defun markdown-outline-level ()
2043 "Return the depth to which a statement is nested in the outline."
2044 (cond
2045 ((match-end 1) 1)
2046 ((match-end 2) 2)
2047 ((- (match-end 0) (match-beginning 0)))))
2049 ;;; Commands ==================================================================
2051 (defun markdown (&optional output-buffer-name)
2052 "Run `markdown' on current buffer and insert output in buffer BUFFER-OUTPUT."
2053 (interactive)
2054 (let ((title (buffer-name))
2055 (begin-region)
2056 (end-region))
2057 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
2058 (setq begin-region (region-beginning)
2059 end-region (region-end))
2060 (setq begin-region (point-min)
2061 end-region (point-max)))
2063 (unless output-buffer-name
2064 (setq output-buffer-name markdown-output-buffer-name))
2066 (if markdown-command-needs-filename
2067 ;; Handle case when `markdown-command' does not read from stdin
2068 (if (not buffer-file-name)
2069 (error "Must be visiting a file")
2070 (shell-command (concat markdown-command " "
2071 (shell-quote-argument buffer-file-name))
2072 output-buffer-name))
2073 ;; Pass region to `markdown-command' via stdin
2074 (shell-command-on-region begin-region end-region markdown-command
2075 output-buffer-name))
2077 ;; Add header and footer and switch to html-mode.
2078 (save-current-buffer
2079 (set-buffer output-buffer-name)
2080 (goto-char (point-min))
2081 (unless (markdown-output-standalone-p)
2082 (markdown-add-xhtml-header-and-footer title))
2083 (html-mode))
2085 ;; Ensure buffer gets raised, even with short command output
2086 (switch-to-buffer-other-window output-buffer-name)))
2088 (defun markdown-output-standalone-p ()
2089 "Determine whether `markdown-command' output is standalone XHTML.
2090 Standalone XHTML output is identified by an occurrence of
2091 `markdown-xhtml-standalone-regexp' in the first five lines of output."
2092 (re-search-forward
2093 markdown-xhtml-standalone-regexp
2094 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
2097 (defun markdown-add-xhtml-header-and-footer (title)
2098 "Wrap XHTML header and footer with given TITLE around current buffer."
2099 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
2100 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
2101 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
2102 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
2103 "<head>\n<title>")
2104 (insert title)
2105 (insert "</title>\n")
2106 (if (> (length markdown-css-path) 0)
2107 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
2108 markdown-css-path
2109 "\" />\n"))
2110 (when (> (length markdown-xhtml-header-content) 0)
2111 (insert markdown-xhtml-header-content))
2112 (insert "\n</head>\n\n"
2113 "<body>\n\n")
2114 (goto-char (point-max))
2115 (insert "\n"
2116 "</body>\n"
2117 "</html>\n"))
2119 (defun markdown-preview ()
2120 "Run `markdown' on the current buffer and preview the output in a browser."
2121 (interactive)
2122 (markdown markdown-output-buffer-name)
2123 (browse-url-of-buffer markdown-output-buffer-name))
2125 (defun markdown-export-file-name ()
2126 "Attempt to generate a filename for Markdown output.
2127 If the current buffer is visiting a file, we construct a new
2128 output filename based on that filename. Otherwise, return nil."
2129 (when (buffer-file-name)
2130 (concat (file-name-sans-extension (buffer-file-name)) ".html")))
2132 (defun markdown-export ()
2133 "Run Markdown on the current buffer, save to a file, and return the filename.
2134 The resulting filename will be constructed using the current filename, but
2135 with the extension removed and replaced with .html."
2136 (interactive)
2137 (let ((output-file (markdown-export-file-name))
2138 (output-buffer-name))
2139 (when output-file
2140 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
2141 (markdown output-buffer-name)
2142 (with-current-buffer output-buffer-name
2143 (save-buffer)
2144 (kill-buffer-and-window))
2145 output-file)))
2147 (defun markdown-export-and-view ()
2148 "Export to XHTML using `markdown-export' and browse the resulting file."
2149 (interactive)
2150 (browse-url (markdown-export)))
2152 ;;; WikiLink Following/Markup =================================================
2154 (require 'thingatpt)
2156 (defun markdown-wiki-link-p ()
2157 "Return non-nil when `point' is at a true wiki link.
2158 A true wiki link name matches `markdown-regex-wiki-link' but does not
2159 match the current file name after conversion. This modifies the data
2160 returned by `match-data'. Note that the potential wiki link name must
2161 be available via `match-string'."
2162 (let ((case-fold-search nil))
2163 (and (thing-at-point-looking-at markdown-regex-wiki-link)
2164 (or (not buffer-file-name)
2165 (not (string-equal (buffer-file-name)
2166 (markdown-convert-wiki-link-to-filename
2167 (markdown-wiki-link-link)))))
2168 (not (save-match-data
2169 (save-excursion))))))
2171 (defun markdown-wiki-link-link ()
2172 "Return the link part of the wiki link using current match data.
2173 The location of the link component depends on the value of
2174 `markdown-wiki-link-alias-first'."
2175 (if markdown-wiki-link-alias-first
2176 (or (match-string 3) (match-string 1))
2177 (match-string 1)))
2179 (defun markdown-convert-wiki-link-to-filename (name)
2180 "Generate a filename from the wiki link NAME.
2181 Spaces in NAME are replaced with `markdown-link-space-sub-char'.
2182 When in `gfm-mode', follow GitHub's conventions where [[Test Test]]
2183 and [[test test]] both map to Test-test.ext."
2184 (let ((basename (markdown-replace-regexp-in-string
2185 "[[:space:]\n]" markdown-link-space-sub-char name)))
2186 (when (eq major-mode 'gfm-mode)
2187 (setq basename (concat (upcase (substring basename 0 1))
2188 (downcase (substring basename 1 nil)))))
2189 (concat basename
2190 (if (buffer-file-name)
2191 (concat "."
2192 (file-name-extension (buffer-file-name)))))))
2194 (defun markdown-follow-wiki-link (name)
2195 "Follow the wiki link NAME.
2196 Convert the name to a file name and call `find-file'. Ensure that
2197 the new buffer remains in `markdown-mode'."
2198 (let ((filename (markdown-convert-wiki-link-to-filename name)))
2199 (find-file filename))
2200 (markdown-mode))
2202 (defun markdown-follow-wiki-link-at-point ()
2203 "Find Wiki Link at point.
2204 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
2205 (interactive)
2206 (if (markdown-wiki-link-p)
2207 (markdown-follow-wiki-link (markdown-wiki-link-link))
2208 (error "Point is not at a Wiki Link")))
2210 (defun markdown-next-wiki-link ()
2211 "Jump to next wiki link.
2212 See `markdown-wiki-link-p'."
2213 (interactive)
2214 (if (markdown-wiki-link-p)
2215 ; At a wiki link already, move past it.
2216 (goto-char (+ 1 (match-end 0))))
2217 (save-match-data
2218 ; Search for the next wiki link and move to the beginning.
2219 (re-search-forward markdown-regex-wiki-link nil t)
2220 (goto-char (match-beginning 0))))
2222 (defun markdown-previous-wiki-link ()
2223 "Jump to previous wiki link.
2224 See `markdown-wiki-link-p'."
2225 (interactive)
2226 (re-search-backward markdown-regex-wiki-link nil t))
2228 (defun markdown-highlight-wiki-link (from to face)
2229 "Highlight the wiki link in the region between FROM and TO using FACE."
2230 (put-text-property from to 'font-lock-face face))
2232 (defun markdown-unfontify-region-wiki-links (from to)
2233 "Remove wiki link faces from the region specified by FROM and TO."
2234 (interactive "nfrom: \nnto: ")
2235 (remove-text-properties from to '(font-lock-face markdown-link-face))
2236 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
2238 (defun markdown-fontify-region-wiki-links (from to)
2239 "Search region given by FROM and TO for wiki links and fontify them.
2240 If a wiki link is found check to see if the backing file exists
2241 and highlight accordingly."
2242 (goto-char from)
2243 (while (re-search-forward markdown-regex-wiki-link to t)
2244 (let ((highlight-beginning (match-beginning 0))
2245 (highlight-end (match-end 0))
2246 (file-name
2247 (markdown-convert-wiki-link-to-filename
2248 (markdown-wiki-link-link))))
2249 (if (file-exists-p file-name)
2250 (markdown-highlight-wiki-link
2251 highlight-beginning highlight-end markdown-link-face)
2252 (markdown-highlight-wiki-link
2253 highlight-beginning highlight-end markdown-missing-link-face)))))
2255 (defun markdown-extend-changed-region (from to)
2256 "Extend region given by FROM and TO so that we can fontify all links.
2257 The region is extended to the first newline before and the first
2258 newline after."
2259 ;; start looking for the first new line before 'from
2260 (goto-char from)
2261 (re-search-backward "\n" nil t)
2262 (let ((new-from (point-min))
2263 (new-to (point-max)))
2264 (if (not (= (point) from))
2265 (setq new-from (point)))
2266 ;; do the same thing for the first new line after 'to
2267 (goto-char to)
2268 (re-search-forward "\n" nil t)
2269 (if (not (= (point) to))
2270 (setq new-to (point)))
2271 (list new-from new-to)))
2273 (defun markdown-check-change-for-wiki-link (from to change)
2274 "Check region between FROM and TO for wiki links and re-fontfy as needed.
2275 Designed to be used with the `after-change-functions' hook.
2276 CHANGE is the number of bytes of pre-change text replaced by the
2277 given range."
2278 (interactive "nfrom: \nnto: \nnchange: ")
2279 (let* ((inhibit-quit t)
2280 (modified (buffer-modified-p))
2281 (buffer-undo-list t)
2282 (inhibit-read-only t)
2283 (inhibit-point-motion-hooks t)
2284 (inhibit-modification-hooks t)
2285 (current-point (point))
2286 deactivate-mark)
2287 (unwind-protect
2288 (save-match-data
2289 (save-restriction
2290 ;; Extend the region to fontify so that it starts
2291 ;; and ends at safe places.
2292 (multiple-value-bind (new-from new-to)
2293 (markdown-extend-changed-region from to)
2294 ;; Unfontify existing fontification (start from scratch)
2295 (markdown-unfontify-region-wiki-links new-from new-to)
2296 ;; Now do the fontification.
2297 (markdown-fontify-region-wiki-links new-from new-to)))
2298 (unless modified
2299 (if (fboundp 'restore-buffer-modified-p)
2300 (restore-buffer-modified-p nil)
2301 (set-buffer-modified-p nil))))
2302 (goto-char current-point))))
2304 (defun markdown-fontify-buffer-wiki-links ()
2305 "Refontify all wiki links in the buffer."
2306 (interactive)
2307 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
2309 ;;; Miscellaneous =============================================================
2311 (defun markdown-line-number-at-pos (&optional pos)
2312 "Return (narrowed) buffer line number at position POS.
2313 If POS is nil, use current buffer location.
2314 This is an exact copy of `line-number-at-pos' for use in emacs21."
2315 (let ((opoint (or pos (point))) start)
2316 (save-excursion
2317 (goto-char (point-min))
2318 (setq start (point))
2319 (goto-char opoint)
2320 (forward-line 0)
2321 (1+ (count-lines start (point))))))
2323 (defun markdown-nobreak-p ()
2324 "Return nil if it is acceptable to break the current line at the point."
2325 ;; inside in square brackets (e.g., link anchor text)
2326 (looking-back "\\[[^]]*"))
2330 ;;; Mode definition ==========================================================
2332 (defun markdown-show-version ()
2333 "Show the version number in the minibuffer."
2334 (interactive)
2335 (message "markdown-mode, version %s" markdown-mode-version))
2337 ;;;###autoload
2338 (define-derived-mode markdown-mode text-mode "Markdown"
2339 "Major mode for editing Markdown files."
2340 ;; Natural Markdown tab width
2341 (setq tab-width 4)
2342 ;; Comments
2343 (make-local-variable 'comment-start)
2344 (setq comment-start "<!-- ")
2345 (make-local-variable 'comment-end)
2346 (setq comment-end " -->")
2347 (make-local-variable 'comment-start-skip)
2348 (setq comment-start-skip "<!--[ \t]*")
2349 (make-local-variable 'comment-column)
2350 (setq comment-column 0)
2351 ;; Font lock.
2352 (set (make-local-variable 'font-lock-defaults)
2353 '(markdown-mode-font-lock-keywords))
2354 (set (make-local-variable 'font-lock-multiline) t)
2355 ;; For menu support in XEmacs
2356 (easy-menu-add markdown-mode-menu markdown-mode-map)
2357 ;; Make filling work with lists (unordered, ordered, and definition)
2358 (set (make-local-variable 'paragraph-start)
2359 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t]*[0-9]+\\.\\|^[ \t]*: ")
2360 ;; Outline mode
2361 (make-local-variable 'outline-regexp)
2362 (setq outline-regexp markdown-regex-header)
2363 (make-local-variable 'outline-level)
2364 (setq outline-level 'markdown-outline-level)
2365 ;; Cause use of ellipses for invisible text.
2366 (add-to-invisibility-spec '(outline . t))
2367 ;; Indentation and filling
2368 (make-local-variable 'fill-nobreak-predicate)
2369 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
2370 (setq indent-line-function markdown-indent-function)
2372 ;; Prepare hooks for XEmacs compatibility
2373 (when (featurep 'xemacs)
2374 (make-local-hook 'after-change-functions)
2375 (make-local-hook 'font-lock-extend-region-functions)
2376 (make-local-hook 'window-configuration-change-hook))
2378 ;; Multiline font lock
2379 (add-hook 'font-lock-extend-region-functions
2380 'markdown-font-lock-extend-region)
2382 ;; Anytime text changes make sure it gets fontified correctly
2383 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
2385 ;; If we left the buffer there is a really good chance we were
2386 ;; creating one of the wiki link documents. Make sure we get
2387 ;; refontified when we come back.
2388 (add-hook 'window-configuration-change-hook
2389 'markdown-fontify-buffer-wiki-links t t)
2391 ;; do the initial link fontification
2392 (markdown-fontify-buffer-wiki-links))
2394 ;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
2396 ;;; GitHub Flavored Markdown Mode ============================================
2398 (define-derived-mode gfm-mode markdown-mode "GFM"
2399 "Major mode for editing GitHub Flavored Markdown files."
2400 (setq markdown-link-space-sub-char "-")
2401 (auto-fill-mode 0)
2402 ;; Use visual-line-mode if available, fall back to longlines-mode:
2403 (if (fboundp 'visual-line-mode)
2404 (visual-line-mode 1)
2405 (longlines-mode 1))
2406 ;; do the initial link fontification
2407 (markdown-fontify-buffer-wiki-links))
2410 (provide 'markdown-mode)
2412 ;;; markdown-mode.el ends here