Improve markdown-mode-hook docstring
[markdown-mode.git] / markdown-mode.el
blob1ebc4551bbe7addff9fb0949a2865254cb33ef58
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>
19 ;; Author: Jason R. Blevins <jrblevin@sdf.org>
20 ;; Maintainer: Jason R. Blevins <jrblevin@sdf.org>
21 ;; Created: May 24, 2007
22 ;; Version: 1.8.1
23 ;; Keywords: Markdown, GitHub Flavored Markdown, itex
24 ;; URL: http://jblevins.org/projects/markdown-mode/
26 ;; This file is not part of GNU Emacs.
28 ;; This program is free software; you can redistribute it and/or modify
29 ;; it under the terms of the GNU General Public License as published by
30 ;; the Free Software Foundation; either version 2, or (at your option)
31 ;; any later version.
33 ;; This program is distributed in the hope that it will be useful,
34 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
35 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 ;; GNU General Public License for more details.
38 ;; You should have received a copy of the GNU General Public License
39 ;; along with this program; if not, write to the Free Software
40 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor,
41 ;; Boston, MA 02110-1301, USA.
43 ;;; Commentary:
45 ;; markdown-mode is a major mode for editing [Markdown][]-formatted
46 ;; text files in GNU Emacs. markdown-mode is free software, licensed
47 ;; under the GNU GPL.
49 ;; [Markdown]: http://daringfireball.net/projects/markdown/
51 ;; The latest stable version is markdown-mode 1.8.1, released on August 15, 2011:
53 ;; * [markdown-mode.el][]
54 ;; * [Screenshot][]
55 ;; * [Release notes][]
57 ;; [markdown-mode.el]: http://jblevins.org/projects/markdown-mode/markdown-mode.el
58 ;; [screenshot]: http://jblevins.org/projects/markdown-mode/screenshots/20110812-001.png
59 ;; [release notes]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
61 ;; markdown-mode is also available in several package managers, including:
63 ;; * Debian and Ubuntu Linux: [emacs-goodies-el][]
64 ;; * RedHat and Fedora Linux: [emacs-goodies][]
65 ;; * OpenBSD: [textproc/markdown-mode][]
66 ;; * Arch Linux (AUR): [emacs-markdown-mode-git][]
68 ;; [emacs-goodies-el]: http://packages.debian.org/emacs-goodies-el
69 ;; [emacs-goodies]: https://admin.fedoraproject.org/pkgdb/acls/name/emacs-goodies
70 ;; [textproc/markdown-mode]: http://pkgsrc.se/textproc/markdown-mode
71 ;; [emacs-markdown-mode-git]: http://aur.archlinux.org/packages.php?ID=30389
73 ;; The latest development version can be downloaded directly
74 ;; ([markdown-mode.el][devel.el]) or it can be obtained from the
75 ;; (browsable and clonable) Git repository at
76 ;; <http://jblevins.org/git/markdown-mode.git>. The entire repository,
77 ;; including the full project history, can be cloned via the Git protocol
78 ;; by running
80 ;; git clone git://jblevins.org/git/markdown-mode.git
82 ;; [devel.el]: http://jblevins.org/git/markdown-mode.git/plain/markdown-mode.el
84 ;;; Dependencies:
86 ;; markdown-mode requires easymenu, a standard package since GNU Emacs
87 ;; 19 and XEmacs 19, which provides a uniform interface for creating
88 ;; menus in GNU Emacs and XEmacs.
90 ;;; Installation:
92 ;; Make sure to place `markdown-mode.el` somewhere in the load-path and add
93 ;; the following lines to your `.emacs` file to associate markdown-mode
94 ;; with `.text` files:
96 ;; (autoload 'markdown-mode "markdown-mode"
97 ;; "Major mode for editing Markdown files" t)
98 ;; (setq auto-mode-alist
99 ;; (cons '("\\.text" . markdown-mode) auto-mode-alist))
101 ;; There is no consensus on an official file extension so change `.text` to
102 ;; `.mdwn`, `.md`, `.mdt`, or whatever you call your markdown files.
104 ;;; Customization:
106 ;; Although no configuration is *necessary* there are a few things
107 ;; that can be customized. The `M-x customize-mode` command
108 ;; provides an interface to all of the possible customizations:
110 ;; * `markdown-command' - the command used to run Markdown (default:
111 ;; `markdown'). This variable may be customized to pass
112 ;; command-line options to your Markdown processor of choice, but
113 ;; this command must accept input from `stdin`. If it does not, a
114 ;; simple wrapper script can be used to write `stdin` to a file
115 ;; and then pass that file to your Markdown interpreter. Ideally,
116 ;; this command will produce an XHTML fragment around which
117 ;; markdown-mode will wrap a header and footer (which can be
118 ;; further customized). However, it attempts to detect whether
119 ;; the command produces standalone XHTML output (via
120 ;; `markdown-xhtml-standalone-regexp'), in which case no header
121 ;; and footer content will be added.
123 ;; * `markdown-command-needs-filename' - set to non-nil if
124 ;; `markdown-command' does not accept input from stdin (default: nil).
125 ;; Instead, it will be passed a filename as the final command-line
126 ;; option. As a result, you will only be able to run Markdown
127 ;; from buffers which are visiting a file.
129 ;; * `markdown-hr-string' - string to use when inserting horizontal
130 ;; rules (default: `* * * * *').
132 ;; * `markdown-bold-underscore' - set to a non-nil value to use two
133 ;; underscores for bold instead of two asterisks (default: `nil').
135 ;; * `markdown-italic-underscore' - set to a non-nil value to use
136 ;; underscores for italic instead of asterisks (default: `nil').
138 ;; * `markdown-indent-function' - the function to use for automatic
139 ;; indentation (default: `markdown-indent-line').
141 ;; * `markdown-indent-on-enter' - set to a non-nil value to
142 ;; automatically indent new lines when the enter key is pressed
143 ;; (default: `t')
145 ;; * `markdown-follow-wiki-link-on-enter' - set to a non-nil value
146 ;; to automatically open a linked document in a new buffer if the
147 ;; cursor is an wiki link
148 ;; (default: `t')
150 ;; * `markdown-uri-types' - a list of protocols for URIs that
151 ;; `markdown-mode' should highlight.
153 ;; * `markdown-enable-math' - syntax highlighting for
154 ;; LaTeX fragments (default: `nil').
156 ;; * `markdown-css-path' - CSS file to link to in XHTML output.
158 ;; * `markdown-xhtml-header-content' - additional content to include
159 ;; in the XHTML `<head>` block.
161 ;; * `markdown-xhtml-standalone-regexp' - a regular expression which
162 ;; indicates whether the output of `markdown-command' is standalone
163 ;; XHTML (default: `^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)`). If
164 ;; this is not matched, we assume this output is a fragment and add
165 ;; our own header and footer.
167 ;; * `markdown-link-space-sub-char' - a character to replace spaces
168 ;; when mapping wiki links to filenames (default: `_`).
169 ;; For example, use an underscore for compatibility with the
170 ;; Python Markdown WikiLinks extension or a hyphen for compatibility
171 ;; with Github wiki links.
173 ;; Additionally, the faces used for syntax highlighting can be modified to
174 ;; your liking by issuing `M-x customize-group RET markdown-faces`
175 ;; or by using the "Markdown Faces" link at the bottom of the mode
176 ;; customization screen.
178 ;;; Usage:
180 ;; Keybindings are grouped by prefixes based on their function. For
181 ;; example, commands dealing with headers begin with `C-c C-t`. The
182 ;; primary commands in each group will are described below. You can
183 ;; obtain a list of all keybindings by pressing `C-c C-h`.
185 ;; * Anchors: `C-c C-a`
187 ;; `C-c C-a l` inserts inline links of the form `[text](url)`. If
188 ;; there is an active region, text in the region is used for the
189 ;; link text. `C-c C-a w` acts similarly for wiki links of the
190 ;; form `[[WikiLink]]`.
192 ;; * Commands: `C-c C-c`
194 ;; `C-c C-c m` will run Markdown on the current buffer and preview
195 ;; the output in another buffer while `C-c C-c p` runs Markdown on
196 ;; the current buffer and previews the output in a browser.
197 ;; `C-c C-c e` will run Markdown on the current buffer and save
198 ;; the result in the file `basename.html`, where `basename` is the
199 ;; name of the Markdown file with the extension removed. **This
200 ;; file will be overwritten without notice.** Press `C-c C-c v`
201 ;; to view the exported file in a browser.
203 ;; `C-c C-c c` will check for undefined references. If there are
204 ;; any, a small buffer will open with a list of undefined
205 ;; references and the line numbers on which they appear. In Emacs
206 ;; 22 and greater, selecting a reference from this list and
207 ;; pressing `RET` will insert an empty reference definition at the
208 ;; end of the buffer. Similarly, selecting the line number will
209 ;; jump to the corresponding line.
211 ;; * Images: `C-c C-i`
213 ;; `C-c C-i i` inserts an image, using the active region (if any)
214 ;; as the alt text.
216 ;; * Physical styles: `C-c C-p`
218 ;; These commands all act on text in the active region, if any,
219 ;; and insert empty markup fragments otherwise. `C-c C-p b` makes
220 ;; the selected text bold, `C-c C-p f` formats the region as
221 ;; fixed-width text, and `C-c C-p i` is used for italic text.
223 ;; * Logical styles: `C-c C-s`
225 ;; These commands all act on text in the active region, if any,
226 ;; and insert empty markup fragments otherwise. Logical styles
227 ;; include blockquote (`C-c C-s b`), preformatted (`C-c C-s p`),
228 ;; code (`C-c C-s c`), emphasis (`C-c C-s e`), and strong
229 ;; (`C-c C-s s`).
231 ;; * Headers: `C-c C-t`
233 ;; All header commands use text in the active region, if any, as
234 ;; the header text. To insert an atx or hash style level-n
235 ;; header, press `C-c C-t n` where n is between 1 and 6. For a
236 ;; top-level setext or underline style header press `C-c C-t t`
237 ;; (mnemonic: title) and for a second-level underline-style header
238 ;; press `C-c C-t s` (mnemonic: section).
240 ;; * Other elements:
242 ;; `C-c -` inserts a horizontal rule.
244 ;; * Wiki-Link Navigation:
246 ;; Use `M-p` and `M-n` to quickly jump to the previous and next
247 ;; wiki links, respectively.
249 ;; * Outline Navigation:
251 ;; Navigation between headings is possible using `outline-mode'.
252 ;; Use `C-M-n` and `C-M-p` to move between the next and previous
253 ;; visible headings. Similarly, `C-M-f` and `C-M-b` move to the
254 ;; next and previous visible headings at the same level as the one
255 ;; at the point. Finally, `C-M-u` will move up to a lower-level
256 ;; (more inclusive) visible heading.
258 ;; Many of the commands described above behave differently depending on
259 ;; whether Transient Mark mode is enabled or not. When it makes sense,
260 ;; if Transient Mark mode is on and a region is active, the command
261 ;; applies to the text in the region (e.g., `C-c C-p b` makes the region
262 ;; bold). For users who prefer to work outside of Transient Mark mode,
263 ;; in Emacs 22 it can be enabled temporarily by pressing `C-SPC C-SPC`.
265 ;; When applicable, commands that specifically act on the region even
266 ;; outside of Transient Mark mode have the same keybinding as the with
267 ;; the exception of an additional `C-` prefix. For example,
268 ;; `markdown-insert-blockquote' is bound to `C-c C-s b` and only acts on
269 ;; the region in Transient Mark mode while `markdown-blockquote-region'
270 ;; is bound to `C-c C-s C-b` and always applies to the region (when
271 ;; nonempty).
273 ;; markdown-mode attempts to be flexible in how it handles
274 ;; indentation. When you press `TAB` repeatedly, the point will cycle
275 ;; through several possible indentation levels corresponding to things
276 ;; you might have in mind when you press `RET` at the end of a line or
277 ;; `TAB`. For example, you may want to start a new list item,
278 ;; continue a list item with hanging indentation, indent for a nested
279 ;; pre block, and so on.
281 ;; markdown-mode supports outline-minor-mode as well as org-mode-style
282 ;; visibility cycling for atx- or hash-style headers. There are two
283 ;; types of visibility cycling: Pressing `S-TAB` cycles globally between
284 ;; the table of contents view (headers only), outline view (top-level
285 ;; headers only), and the full document view. Pressing `TAB` while the
286 ;; point is at a header will cycle through levels of visibility for the
287 ;; subtree: completely folded, visible children, and fully visible.
288 ;; Note that mixing hash and underline style headers will give undesired
289 ;; results.
291 ;;; Extensions:
293 ;; Besides supporting the basic Markdown syntax, markdown-mode also
294 ;; includes syntax highlighting for `[[Wiki Links]]` by default. Wiki
295 ;; links may be followed automatically by hitting the enter key when
296 ;; your curser is on a wiki link or by hitting `C-c C-f`. The
297 ;; autofollowing on enter key may be controlled with the
298 ;; `markdown-follow-wiki-link-on-enter' customization. Use `M-p` and
299 ;; `M-n` to quickly jump to the previous and next wiki links,
300 ;; respectively. Aliased or piped wiki links of the form
301 ;; `[[PageName|link text]]` are also supported.
303 ;; [SmartyPants][] support is possible by customizing `markdown-command'.
304 ;; If you install `SmartyPants.pl` at, say, `/usr/local/bin/smartypants`,
305 ;; then you can set `markdown-command' to `"markdown | smartypants"`.
306 ;; You can do this either by using `M-x customize-group markdown`
307 ;; or by placing the following in your `.emacs` file:
309 ;; (defun markdown-custom ()
310 ;; "markdown-mode-hook"
311 ;; (setq markdown-command "markdown | smartypants"))
312 ;; (add-hook 'markdown-mode-hook '(lambda() (markdown-custom)))
314 ;; [SmartyPants]: http://daringfireball.net/projects/smartypants/
316 ;; Experimental syntax highlighting for mathematical expressions written
317 ;; in LaTeX (only expressions denoted by `$..$`, `$$..$$`, or `\[..\]`)
318 ;; can be enabled by setting `markdown-enable-math' to a non-nil value,
319 ;; either via customize or by placing `(setq markdown-enable-itex t)`
320 ;; in `.emacs`, and restarting Emacs.
322 ;; A [GitHub Flavored Markdown](http://github.github.com/github-flavored-markdown/)
323 ;; mode, `gfm-mode', is also available. The GitHub implementation of
324 ;; differs slightly from standard Markdown. Most importantly, newlines are
325 ;; significant and trigger hard line breaks. As such, `gfm-mode' turns off
326 ;; `auto-fill-mode' and turns on `visual-line-mode' (or `longlines-mode' if
327 ;; `visual-line-mode' is not available).
329 ;;; Acknowledgments:
331 ;; markdown-mode has benefited greatly from the efforts of the
332 ;; following people:
334 ;; * Cyril Brulebois <cyril.brulebois@enst-bretagne.fr> for Debian packaging.
335 ;; * Conal Elliott <conal@conal.net> for a font-lock regexp patch.
336 ;; * Edward O'Connor <hober0@gmail.com> for a font-lock regexp fix and
337 ;; GitHub Flavored Markdown mode (`gfm-mode').
338 ;; * Greg Bognar <greg_bognar@hms.harvard.edu> for menus and running
339 ;; `markdown' with an active region.
340 ;; * Daniel Burrows <dburrows@debian.org> for filing Debian bug #456592.
341 ;; * Peter S. Galbraith <psg@debian.org> for maintaining emacs-goodies-el.
342 ;; * Dmitry Dzhus <mail@sphinx.net.ru> for reference checking functions.
343 ;; * Bryan Kyle <bryan.kyle@gmail.com> for indentation code.
344 ;; * Ben Voui <intrigeri@boum.org> for font-lock face customizations.
345 ;; * Ankit Solanki <ankit.solanki@gmail.com> for longlines.el
346 ;; compatibility and custom CSS.
347 ;; * Hilko Bengen <bengen@debian.org> for proper XHTML output.
348 ;; * Jose A. Ortega Ruiz <jao@gnu.org> for Emacs 23 fixes.
349 ;; * Alec Resnick <alec@sproutward.org> for bug reports.
350 ;; * Joost Kremers <j.kremers@em.uni-frankfurt.de> for bug reports
351 ;; regarding indentation.
352 ;; * Peter Williams <pezra@barelyenough.org> for fill-paragraph
353 ;; enhancements.
354 ;; * George Ogata <george.ogata@gmail.com> for fixing several
355 ;; byte-compilation warnings.
356 ;; * Eric Merritt <ericbmerritt@gmail.com> for wiki link features.
357 ;; * Philippe Ivaldi <pivaldi@sfr.fr> for XHTML preview
358 ;; customizations and XHTML export.
359 ;; * Jeremiah Dodds <jeremiah.dodds@gmail.com> for supporting
360 ;; Markdown processors which do not accept input from stdin.
361 ;; * Werner Dittmann <werner.dittmann@t-online.de> for bug reports
362 ;; regarding the cl dependency and auto-fill-mode and indentation.
363 ;; * Scott Pfister <scott.pfister@gmail.com> for generalizing the space
364 ;; substitution character for mapping wiki links to filenames.
365 ;; * Marcin Kasperski <marcin.kasperski@mekk.waw.pl> for a patch to
366 ;; escape shell commands.
367 ;; * Christopher J. Madsen <cjm@cjmweb.net> for patches to fix a match
368 ;; data bug and to prefer `visual-line-mode' in `gfm-mode'.
369 ;; * Shigeru Fukaya <shigeru.fukaya@gmail.com> for better adherence to
370 ;; Emacs Lisp coding conventions.
372 ;;; Bugs:
374 ;; Although markdown-mode is developed and tested primarily using
375 ;; GNU Emacs 24, compatibility with earlier Emacsen is also a
376 ;; priority.
378 ;; If you find any bugs in markdown-mode, please construct a test case
379 ;; or a patch and email me at <jrblevin@sdf.org>.
381 ;;; History:
383 ;; markdown-mode was written and is maintained by Jason Blevins. The
384 ;; first version was released on May 24, 2007.
386 ;; * 2007-05-24: Version 1.1
387 ;; * 2007-05-25: Version 1.2
388 ;; * 2007-06-05: [Version 1.3][]
389 ;; * 2007-06-29: Version 1.4
390 ;; * 2008-05-24: [Version 1.5][]
391 ;; * 2008-06-04: [Version 1.6][]
392 ;; * 2009-10-01: [Version 1.7][]
393 ;; * 2011-08-12: [Version 1.8][]
394 ;; * 2011-08-15: [Version 1.8.1][]
396 ;; [Version 1.3]: http://jblevins.org/projects/markdown-mode/rev-1-3
397 ;; [Version 1.5]: http://jblevins.org/projects/markdown-mode/rev-1-5
398 ;; [Version 1.6]: http://jblevins.org/projects/markdown-mode/rev-1-6
399 ;; [Version 1.7]: http://jblevins.org/projects/markdown-mode/rev-1-7
400 ;; [Version 1.8]: http://jblevins.org/projects/markdown-mode/rev-1-8
401 ;; [Version 1.8.1]: http://jblevins.org/projects/markdown-mode/rev-1-8-1
404 ;;; Code:
406 (require 'easymenu)
407 (require 'outline)
408 (eval-when-compile (require 'cl))
410 ;;; Constants =================================================================
412 (defconst markdown-mode-version "1.8.1"
413 "Markdown mode version number.")
415 (defconst markdown-output-buffer-name "*markdown-output*"
416 "Name of temporary buffer for markdown command output.")
418 ;;; Customizable variables ====================================================
420 (defvar markdown-mode-hook nil
421 "Hook run when entering Markdown mode.")
423 (defgroup markdown nil
424 "Major mode for editing text files in Markdown format."
425 :prefix "markdown-"
426 :group 'wp
427 :link '(url-link "http://jblevins.org/projects/markdown-mode/"))
429 (defcustom markdown-command "markdown"
430 "Command to run markdown."
431 :group 'markdown
432 :type 'string)
434 (defcustom markdown-command-needs-filename nil
435 "Set to non-nil if `markdown-command' does not accept input from stdin.
436 Instead, it will be passed a filename as the final command-line
437 option. As a result, you will only be able to run Markdown from
438 buffers which are visiting a file."
439 :group 'markdown
440 :type 'boolean)
442 (defcustom markdown-hr-string "* * * * *"
443 "String to use for horizonal rules."
444 :group 'markdown
445 :type 'string)
447 (defcustom markdown-bold-underscore nil
448 "Use two underscores for bold instead of two asterisks."
449 :group 'markdown
450 :type 'boolean)
452 (defcustom markdown-italic-underscore nil
453 "Use underscores for italic instead of asterisks."
454 :group 'markdown
455 :type 'boolean)
457 (defcustom markdown-indent-function 'markdown-indent-line
458 "Function to use to indent."
459 :group 'markdown
460 :type 'function)
462 (defcustom markdown-indent-on-enter t
463 "Automatically indent new lines when enter key is pressed."
464 :group 'markdown
465 :type 'boolean)
467 (defcustom markdown-follow-wiki-link-on-enter t
468 "Follow wiki link at point (if any) when the enter key is pressed."
469 :group 'markdown
470 :type 'boolean)
472 (defcustom markdown-uri-types
473 '("acap" "cid" "data" "dav" "fax" "file" "ftp" "gopher" "http" "https"
474 "imap" "ldap" "mailto" "mid" "modem" "news" "nfs" "nntp" "pop" "prospero"
475 "rtsp" "service" "sip" "tel" "telnet" "tip" "urn" "vemmi" "wais")
476 "Link types for syntax highlighting of URIs."
477 :group 'markdown
478 :type 'list)
480 (defcustom markdown-enable-math nil
481 "Syntax highlighting for inline LaTeX expressions.
482 This will not take effect until Emacs is restarted."
483 :group 'markdown
484 :type 'boolean)
486 (defcustom markdown-css-path ""
487 "URL of CSS file to link to in the output XHTML."
488 :group 'markdown
489 :type 'string)
491 (defcustom markdown-xhtml-header-content ""
492 "Additional content to include in the XHTML <head> block."
493 :group 'markdown
494 :type 'string)
496 (defcustom markdown-xhtml-standalone-regexp
497 "^\\(\<\?xml\\|\<!DOCTYPE\\|\<html\\)"
498 "Regexp indicating whether `markdown-command' output is standalone XHTML."
499 :group 'markdown
500 :type 'regexp)
502 (defcustom markdown-link-space-sub-char
504 "Character to use instead of spaces when mapping wiki links to filenames."
505 :group 'markdown
506 :type 'string)
508 ;;; Font lock =================================================================
510 (require 'font-lock)
512 (defvar markdown-italic-face 'markdown-italic-face
513 "Face name to use for italic text.")
515 (defvar markdown-bold-face 'markdown-bold-face
516 "Face name to use for bold text.")
518 (defvar markdown-header-face 'markdown-header-face
519 "Face name to use as a base for headers.")
521 (defvar markdown-header-face-1 'markdown-header-face-1
522 "Face name to use for level-1 headers.")
524 (defvar markdown-header-face-2 'markdown-header-face-2
525 "Face name to use for level-2 headers.")
527 (defvar markdown-header-face-3 'markdown-header-face-3
528 "Face name to use for level-3 headers.")
530 (defvar markdown-header-face-4 'markdown-header-face-4
531 "Face name to use for level-4 headers.")
533 (defvar markdown-header-face-5 'markdown-header-face-5
534 "Face name to use for level-5 headers.")
536 (defvar markdown-header-face-6 'markdown-header-face-6
537 "Face name to use for level-6 headers.")
539 (defvar markdown-inline-code-face 'markdown-inline-code-face
540 "Face name to use for inline code.")
542 (defvar markdown-list-face 'markdown-list-face
543 "Face name to use for list markers.")
545 (defvar markdown-blockquote-face 'markdown-blockquote-face
546 "Face name to use for blockquote.")
548 (defvar markdown-pre-face 'markdown-pre-face
549 "Face name to use for preformatted text.")
551 (defvar markdown-link-face 'markdown-link-face
552 "Face name to use for links.")
554 (defvar markdown-missing-link-face 'markdown-missing-link-face
555 "Face name to use for links where the linked file does not exist.")
557 (defvar markdown-reference-face 'markdown-reference-face
558 "Face name to use for reference.")
560 (defvar markdown-url-face 'markdown-url-face
561 "Face name to use for URLs.")
563 (defvar markdown-link-title-face 'markdown-link-title-face
564 "Face name to use for reference link titles.")
566 (defvar markdown-comment-face 'markdown-comment-face
567 "Face name to use for HTML comments.")
569 (defvar markdown-math-face 'markdown-math-face
570 "Face name to use for LaTeX expressions.")
572 (defgroup markdown-faces nil
573 "Faces used in Markdown Mode"
574 :group 'markdown
575 :group 'faces)
577 (defface markdown-italic-face
578 '((t (:inherit font-lock-variable-name-face :slant italic)))
579 "Face for italic text."
580 :group 'markdown-faces)
582 (defface markdown-bold-face
583 '((t (:inherit font-lock-variable-name-face :weight bold)))
584 "Face for bold text."
585 :group 'markdown-faces)
587 (defface markdown-header-face
588 '((t (:inherit font-lock-function-name-face :weight bold)))
589 "Base face for headers."
590 :group 'markdown-faces)
592 (defface markdown-header-face-1
593 '((t (:inherit markdown-header-face)))
594 "Face for level-1 headers."
595 :group 'markdown-faces)
597 (defface markdown-header-face-2
598 '((t (:inherit markdown-header-face)))
599 "Face for level-2 headers."
600 :group 'markdown-faces)
602 (defface markdown-header-face-3
603 '((t (:inherit markdown-header-face)))
604 "Face for level-3 headers."
605 :group 'markdown-faces)
607 (defface markdown-header-face-4
608 '((t (:inherit markdown-header-face)))
609 "Face for level-4 headers."
610 :group 'markdown-faces)
612 (defface markdown-header-face-5
613 '((t (:inherit markdown-header-face)))
614 "Face for level-5 headers."
615 :group 'markdown-faces)
617 (defface markdown-header-face-6
618 '((t (:inherit markdown-header-face)))
619 "Face for level-6 headers."
620 :group 'markdown-faces)
622 (defface markdown-inline-code-face
623 '((t (:inherit font-lock-constant-face)))
624 "Face for inline code."
625 :group 'markdown-faces)
627 (defface markdown-list-face
628 '((t (:inherit font-lock-builtin-face)))
629 "Face for list item markers."
630 :group 'markdown-faces)
632 (defface markdown-blockquote-face
633 '((t (:inherit font-lock-doc-face)))
634 "Face for blockquote sections."
635 :group 'markdown-faces)
637 (defface markdown-pre-face
638 '((t (:inherit font-lock-constant-face)))
639 "Face for preformatted text."
640 :group 'markdown-faces)
642 (defface markdown-link-face
643 '((t (:inherit font-lock-keyword-face)))
644 "Face for links."
645 :group 'markdown-faces)
647 (defface markdown-missing-link-face
648 '((t (:inherit font-lock-warning-face)))
649 "Face for missing links."
650 :group 'markdown-faces)
652 (defface markdown-reference-face
653 '((t (:inherit font-lock-type-face)))
654 "Face for link references."
655 :group 'markdown-faces)
657 (defface markdown-url-face
658 '((t (:inherit font-lock-string-face)))
659 "Face for URLs."
660 :group 'markdown-faces)
662 (defface markdown-link-title-face
663 '((t (:inherit font-lock-comment-face)))
664 "Face for reference link titles."
665 :group 'markdown-faces)
667 (defface markdown-comment-face
668 '((t (:inherit font-lock-comment-face)))
669 "Face for HTML comments."
670 :group 'markdown-faces)
672 (defface markdown-math-face
673 '((t (:inherit font-lock-string-face)))
674 "Face for LaTeX expressions."
675 :group 'markdown-faces)
677 (defconst markdown-regex-link-inline
678 "\\(!?\\[[^]]*?\\]\\)\\(([^\\)]*)\\)"
679 "Regular expression for a [text](file) or an image link ![text](file).")
681 (defconst markdown-regex-link-reference
682 "\\(!?\\[[^]]+?\\]\\)[ ]?\\(\\[[^]]*?\\]\\)"
683 "Regular expression for a reference link [text][id].")
685 (defconst markdown-regex-reference-definition
686 "^ \\{0,3\\}\\(\\[.+?\\]\\):\\s *\\(.*?\\)\\s *\\( \"[^\"]*\"$\\|$\\)"
687 "Regular expression for a link definition [id]: ...")
689 (defconst markdown-regex-header-1-atx
690 "^\\(# \\)\\(.*?\\)\\($\\| #+$\\)"
691 "Regular expression for level 1 atx-style (hash mark) headers.")
693 (defconst markdown-regex-header-2-atx
694 "^\\(## \\)\\(.*?\\)\\($\\| #+$\\)"
695 "Regular expression for level 2 atx-style (hash mark) headers.")
697 (defconst markdown-regex-header-3-atx
698 "^\\(### \\)\\(.*?\\)\\($\\| #+$\\)"
699 "Regular expression for level 3 atx-style (hash mark) headers.")
701 (defconst markdown-regex-header-4-atx
702 "^\\(#### \\)\\(.*?\\)\\($\\| #+$\\)"
703 "Regular expression for level 4 atx-style (hash mark) headers.")
705 (defconst markdown-regex-header-5-atx
706 "^\\(##### \\)\\(.*?\\)\\($\\| #+$\\)"
707 "Regular expression for level 5 atx-style (hash mark) headers.")
709 (defconst markdown-regex-header-6-atx
710 "^\\(###### \\)\\(.*?\\)\\($\\| #+$\\)"
711 "Regular expression for level 6 atx-style (hash mark) headers.")
713 (defconst markdown-regex-header-1-setext
714 "^\\(.*\\)\n\\(===+\\)$"
715 "Regular expression for level 1 setext-style (underline) headers.")
717 (defconst markdown-regex-header-2-setext
718 "^\\(.*\\)\n\\(---+\\)$"
719 "Regular expression for level 2 setext-style (underline) headers.")
721 (defconst markdown-regex-hr
722 "^\\(\\*[ ]?\\*[ ]?\\*[ ]?[\\* ]*\\|-[ ]?-[ ]?-[--- ]*\\)$"
723 "Regular expression for matching Markdown horizontal rules.")
725 (defconst markdown-regex-code
726 "\\(^\\|[^\\]\\)\\(\\(`\\{1,2\\}\\)\\([^ \\]\\|[^ ]\\(.\\|\n[^\n]\\)*?[^ \\]\\)\\3\\)"
727 "Regular expression for matching inline code fragments.")
729 (defconst markdown-regex-pre
730 "^\\( \\|\t\\).*$"
731 "Regular expression for matching preformatted text sections.")
733 (defconst markdown-regex-list
734 "^[ \t]*\\([0-9]+\\.\\|[\\*\\+-]\\) "
735 "Regular expression for matching list markers.")
737 (defconst markdown-regex-bold
738 "\\(^\\|[^\\]\\)\\(\\([*_]\\{2\\}\\)\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)"
739 "Regular expression for matching bold text.")
741 (defconst markdown-regex-italic
742 "\\(^\\|[^\\]\\)\\(\\([*_]\\)\\([^ \\]\\3\\|[^ ]\\(.\\|\n[^\n]\\)*?[^\\ ]\\3\\)\\)"
743 "Regular expression for matching italic text.")
745 (defconst markdown-regex-blockquote
746 "^>.*$"
747 "Regular expression for matching blockquote lines.")
749 (defconst markdown-regex-line-break
750 " $"
751 "Regular expression for matching line breaks.")
753 (defconst markdown-regex-wiki-link
754 "\\[\\[\\([^]|]+\\)\\(|\\([^]]+\\)\\)?\\]\\]"
755 "Regular expression for matching wiki links.
756 This matches typical bracketed [[WikiLinks]] as well as 'aliased'
757 wiki links of the form [[PageName|link text]]. In this regular
758 expression, #1 matches the page name and #3 matches the link
759 text.")
761 (defconst markdown-regex-uri
762 (concat
763 "\\(" (mapconcat 'identity markdown-uri-types "\\|")
764 "\\):[^]\t\n\r<>,;() ]+")
765 "Regular expression for matching inline URIs.")
767 (defconst markdown-regex-angle-uri
768 (concat
769 "\\(<\\)\\("
770 (mapconcat 'identity markdown-uri-types "\\|")
771 "\\):[^]\t\n\r<>,;()]+\\(>\\)")
772 "Regular expression for matching inline URIs in angle brackets.")
774 (defconst markdown-regex-email
775 "<\\(\\sw\\|\\s_\\|\\s.\\)+@\\(\\sw\\|\\s_\\|\\s.\\)+>"
776 "Regular expression for matching inline email addresses.")
778 (defconst markdown-regex-latex-expression
779 "\\(^\\|[^\\]\\)\\(\\$\\($\\([^\\$]\\|\\\\.\\)*\\$\\|\\([^\\$]\\|\\\\.\\)*\\)\\$\\)"
780 "Regular expression for itex $..$ or $$..$$ math mode expressions.")
782 (defconst markdown-regex-latex-display
783 "^\\\\\\[\\(.\\|\n\\)*?\\\\\\]$"
784 "Regular expression for itex \[..\] display mode expressions.")
786 (defconst markdown-regex-list-indent
787 "^\\(\\s *\\)\\([0-9]+\\.\\|[\\*\\+-]\\)\\(\\s +\\)"
788 "Regular expression for matching indentation of list items.")
790 (defvar markdown-mode-font-lock-keywords-basic
791 (list
792 '(markdown-match-pre-blocks 0 markdown-pre-face t t)
793 (cons markdown-regex-blockquote 'markdown-blockquote-face)
794 (cons markdown-regex-header-1-setext 'markdown-header-face-1)
795 (cons markdown-regex-header-2-setext 'markdown-header-face-2)
796 (cons markdown-regex-header-1-atx 'markdown-header-face-1)
797 (cons markdown-regex-header-2-atx 'markdown-header-face-2)
798 (cons markdown-regex-header-3-atx 'markdown-header-face-3)
799 (cons markdown-regex-header-4-atx 'markdown-header-face-4)
800 (cons markdown-regex-header-5-atx 'markdown-header-face-5)
801 (cons markdown-regex-header-6-atx 'markdown-header-face-6)
802 (cons markdown-regex-hr 'markdown-header-face)
803 '(markdown-match-comments 0 markdown-comment-face t t)
804 (cons markdown-regex-code '(2 markdown-inline-code-face))
805 (cons markdown-regex-angle-uri 'markdown-link-face)
806 (cons markdown-regex-uri 'markdown-link-face)
807 (cons markdown-regex-email 'markdown-link-face)
808 (cons markdown-regex-list 'markdown-list-face)
809 (cons markdown-regex-link-inline
810 '((1 markdown-link-face t)
811 (2 markdown-url-face t)))
812 (cons markdown-regex-link-reference
813 '((1 markdown-link-face t)
814 (2 markdown-reference-face t)))
815 (cons markdown-regex-reference-definition
816 '((1 markdown-reference-face t)
817 (2 markdown-url-face t)
818 (3 markdown-link-title-face t)))
819 (cons markdown-regex-bold '(2 markdown-bold-face))
820 (cons markdown-regex-italic '(2 markdown-italic-face))
822 "Syntax highlighting for Markdown files.")
824 (defconst markdown-mode-font-lock-keywords-latex
825 (list
826 ;; Math mode $..$ or $$..$$
827 (cons markdown-regex-latex-expression '(2 markdown-math-face))
828 ;; Display mode equations with brackets: \[ \]
829 (cons markdown-regex-latex-display 'markdown-math-face)
830 ;; Equation reference (eq:foo)
831 (cons "(eq:\\w+)" 'markdown-reference-face)
832 ;; Equation reference \eqref{foo}
833 (cons "\\\\eqref{\\w+}" 'markdown-reference-face))
834 "Syntax highlighting for LaTeX fragments.")
836 (defvar markdown-mode-font-lock-keywords
837 (append
838 (if markdown-enable-math
839 markdown-mode-font-lock-keywords-latex)
840 markdown-mode-font-lock-keywords-basic)
841 "Default highlighting expressions for Markdown mode.")
845 ;;; Compatibility =============================================================
847 ;; Handle replace-regexp-in-string in XEmacs 21
848 (defun markdown-replace-regexp-in-string (regexp rep string)
849 "Compatibility wrapper to provide `replace-regexp-in-string'."
850 (if (featurep 'xemacs)
851 (replace-in-string string regexp rep)
852 (replace-regexp-in-string regexp rep string)))
856 ;;; Markdown parsing functions ================================================
858 (defun markdown-cur-line-blank-p ()
859 "Return t if the current line is blank and nil otherwise."
860 (save-excursion
861 (beginning-of-line)
862 (re-search-forward "^\\s *$" (point-at-eol) t)))
864 (defun markdown-prev-line-blank-p ()
865 "Return t if the previous line is blank and nil otherwise.
866 If we are at the first line, then consider the previous line to be blank."
867 (save-excursion
868 (if (= (point-at-bol) (point-min))
870 (forward-line -1)
871 (markdown-cur-line-blank-p))))
873 (defun markdown-prev-line-indent-p ()
874 "Return t if the previous line is indented and nil otherwise."
875 (save-excursion
876 (forward-line -1)
877 (goto-char (point-at-bol))
878 (if (re-search-forward "^\\s " (point-at-eol) t) t)))
880 (defun markdown-cur-line-indent ()
881 "Return the number of leading whitespace characters in the current line."
882 (save-excursion
883 (goto-char (point-at-bol))
884 (re-search-forward "^\\s +" (point-at-eol) t)
885 (current-column)))
887 (defun markdown-prev-line-indent ()
888 "Return the number of leading whitespace characters in the previous line."
889 (save-excursion
890 (forward-line -1)
891 (markdown-cur-line-indent)))
893 (defun markdown-cur-non-list-indent ()
894 "Return the number of leading whitespace characters in the current line."
895 (save-excursion
896 (beginning-of-line)
897 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
898 (current-column))))
900 (defun markdown-prev-non-list-indent ()
901 "Return position of the first non-list-marker on the previous line."
902 (save-excursion
903 (forward-line -1)
904 (markdown-cur-non-list-indent)))
906 (defun markdown--next-block ()
907 "Move the point to the start of the next text block."
908 (forward-line)
909 (while (and (or (not (markdown-prev-line-blank-p))
910 (markdown-cur-line-blank-p))
911 (not (eobp)))
912 (forward-line)))
914 (defun markdown--end-of-level (level)
915 "Move the point to the end of region with indentation at least LEVEL."
916 (let (indent)
917 (while (and (not (< (setq indent (markdown-cur-line-indent)) level))
918 (not (>= indent (+ level 4)))
919 (not (eobp)))
920 (markdown--next-block))
921 (unless (eobp)
922 ;; Move back before any trailing blank lines
923 (while (and (markdown-prev-line-blank-p)
924 (not (bobp)))
925 (forward-line -1))
926 (forward-line -1)
927 (end-of-line))))
929 ; From html-helper-mode
930 (defun markdown-match-comments (last)
931 "Match HTML comments from the point to LAST."
932 (cond ((search-forward "<!--" last t)
933 (backward-char 4)
934 (let ((beg (point)))
935 (cond ((search-forward-regexp "--[ \t]*>" last t)
936 (set-match-data (list beg (point)))
938 (t nil))))
939 (t nil)))
941 (defun markdown-match-pre-blocks (last)
942 "Match Markdown pre blocks from point to LAST.
943 A region matches as if it is indented at least four spaces
944 relative to the nearest previous block of lesser non-list-marker
945 indentation."
947 (let (cur-begin cur-end cur-indent prev-indent prev-list stop match found)
948 ;; Don't start in the middle of a block
949 (unless (and (bolp)
950 (markdown-prev-line-blank-p)
951 (not (markdown-cur-line-blank-p)))
952 (markdown--next-block))
954 ;; Move to the first full block in the region with indent 4 or more
955 (while (and (not (>= (setq cur-indent (markdown-cur-line-indent)) 4))
956 (not (>= (point) last)))
957 (markdown--next-block))
958 (setq cur-begin (point))
959 (markdown--end-of-level cur-indent)
960 (setq cur-end (point))
961 (setq match nil)
962 (setq stop (> cur-begin cur-end))
964 (while (and (<= cur-end last) (not stop) (not match))
965 ;; Move to the nearest preceding block of lesser (non-marker) indentation
966 (setq prev-indent (+ cur-indent 1))
967 (goto-char cur-begin)
968 (setq found nil)
969 (while (and (>= prev-indent cur-indent)
970 (not (and prev-list
971 (eq prev-indent cur-indent)))
972 (not (bobp)))
974 ;; Move point to the last line of the previous block.
975 (forward-line -1)
976 (while (and (markdown-cur-line-blank-p)
977 (not (bobp)))
978 (forward-line -1))
980 ;; Update the indentation level using either the
981 ;; non-list-marker indentation, if the previous line is the
982 ;; start of a list, or the actual indentation.
983 (setq prev-list (markdown-cur-non-list-indent))
984 (setq prev-indent (or prev-list
985 (markdown-cur-line-indent)))
986 (setq found t))
988 ;; If the loop didn't execute
989 (unless found
990 (setq prev-indent 0))
992 ;; Compare with prev-indent minus its remainder mod 4
993 (setq prev-indent (- prev-indent (mod prev-indent 4)))
995 ;; Set match data and return t if we have a match
996 (if (>= cur-indent (+ prev-indent 4))
997 ;; Match
998 (progn
999 (setq match t)
1000 (set-match-data (list cur-begin cur-end))
1001 ;; Leave point at end of block
1002 (goto-char cur-end)
1003 (forward-line))
1005 ;; Move to the next block (if possible)
1006 (goto-char cur-end)
1007 (markdown--next-block)
1008 (setq cur-begin (point))
1009 (setq cur-indent (markdown-cur-line-indent))
1010 (markdown--end-of-level cur-indent)
1011 (setq cur-end (point))
1012 (setq stop (equal cur-begin cur-end))))
1013 match))
1015 (defun markdown-font-lock-extend-region ()
1016 "Extend the search region to include an entire block of text.
1017 This helps improve font locking for block constructs such as pre blocks."
1018 ;; Avoid compiler warnings about these global variables from font-lock.el.
1019 ;; See the documentation for variable `font-lock-extend-region-functions'.
1020 (eval-when-compile (defvar font-lock-beg) (defvar font-lock-end))
1021 (save-excursion
1022 (goto-char font-lock-beg)
1023 (let ((found (re-search-backward "\n\n" nil t)))
1024 (when found
1025 (goto-char font-lock-end)
1026 (when (re-search-forward "\n\n" nil t)
1027 (beginning-of-line)
1028 (setq font-lock-end (point)))
1029 (setq font-lock-beg found)))))
1033 ;;; Syntax Table ==============================================================
1035 (defvar markdown-mode-syntax-table
1036 (let ((markdown-mode-syntax-table (make-syntax-table)))
1037 (modify-syntax-entry ?\" "w" markdown-mode-syntax-table)
1038 markdown-mode-syntax-table)
1039 "Syntax table for `markdown-mode'.")
1043 ;;; Element Insertion =========================================================
1045 (defun markdown-wrap-or-insert (s1 s2)
1046 "Insert the strings S1 and S2.
1047 If Transient Mark mode is on and a region is active, wrap the strings S1
1048 and S2 around the region."
1049 (if (and transient-mark-mode mark-active)
1050 (let ((a (region-beginning)) (b (region-end)))
1051 (goto-char a)
1052 (insert s1)
1053 (goto-char (+ b (length s1)))
1054 (insert s2))
1055 (insert s1 s2)))
1057 (defun markdown-insert-hr ()
1058 "Insert a horizonal rule using `markdown-hr-string'."
1059 (interactive)
1060 ;; Leading blank line
1061 (when (and (>= (point) (+ (point-min) 2))
1062 (not (looking-back "\n\n" 2)))
1063 (insert "\n"))
1064 ;; Insert custom HR string
1065 (insert (concat markdown-hr-string "\n"))
1066 ;; Following blank line
1067 (backward-char)
1068 (unless (looking-at "\n\n")
1069 (insert "\n")))
1071 (defun markdown-insert-bold ()
1072 "Insert markup for a bold word or phrase.
1073 If Transient Mark mode is on and a region is active, it is made bold."
1074 (interactive)
1075 (if markdown-bold-underscore
1076 (markdown-wrap-or-insert "__" "__")
1077 (markdown-wrap-or-insert "**" "**"))
1078 (backward-char 2))
1080 (defun markdown-insert-italic ()
1081 "Insert markup for an italic word or phrase.
1082 If Transient Mark mode is on and a region is active, it is made italic."
1083 (interactive)
1084 (if markdown-italic-underscore
1085 (markdown-wrap-or-insert "_" "_")
1086 (markdown-wrap-or-insert "*" "*"))
1087 (backward-char 1))
1089 (defun markdown-insert-code ()
1090 "Insert markup for an inline code fragment.
1091 If Transient Mark mode is on and a region is active, it is marked
1092 as inline code."
1093 (interactive)
1094 (markdown-wrap-or-insert "`" "`")
1095 (backward-char 1))
1097 (defun markdown-insert-link ()
1098 "Insert an inline link of the form []().
1099 If Transient Mark mode is on and a region is active, it is used
1100 as the link text."
1101 (interactive)
1102 (markdown-wrap-or-insert "[" "]")
1103 (insert "()")
1104 (backward-char 1))
1106 (defun markdown-insert-wiki-link ()
1107 "Insert a wiki link of the form [[WikiLink]].
1108 If Transient Mark mode is on and a region is active, it is used
1109 as the link text."
1110 (interactive)
1111 (markdown-wrap-or-insert "[[" "]]")
1112 (backward-char 2))
1114 (defun markdown-insert-image ()
1115 "Insert an inline image tag of the form ![]().
1116 If Transient Mark mode is on and a region is active, it is used
1117 as the alt text of the image."
1118 (interactive)
1119 (markdown-wrap-or-insert "![" "]")
1120 (insert "()")
1121 (backward-char 1))
1123 (defun markdown-insert-header-1 ()
1124 "Insert a first level atx-style (hash mark) header.
1125 If Transient Mark mode is on and a region is active, it is used
1126 as the header text."
1127 (interactive)
1128 (markdown-insert-header 1))
1130 (defun markdown-insert-header-2 ()
1131 "Insert a second level atx-style (hash mark) header.
1132 If Transient Mark mode is on and a region is active, it is used
1133 as the header text."
1134 (interactive)
1135 (markdown-insert-header 2))
1137 (defun markdown-insert-header-3 ()
1138 "Insert a third level atx-style (hash mark) header.
1139 If Transient Mark mode is on and a region is active, it is used
1140 as the header text."
1141 (interactive)
1142 (markdown-insert-header 3))
1144 (defun markdown-insert-header-4 ()
1145 "Insert a fourth level atx-style (hash mark) header.
1146 If Transient Mark mode is on and a region is active, it is used
1147 as the header text."
1148 (interactive)
1149 (markdown-insert-header 4))
1151 (defun markdown-insert-header-5 ()
1152 "Insert a fifth level atx-style (hash mark) header.
1153 If Transient Mark mode is on and a region is active, it is used
1154 as the header text."
1155 (interactive)
1156 (markdown-insert-header 5))
1158 (defun markdown-insert-header-6 ()
1159 "Insert a sixth level atx-style (hash mark) header.
1160 If Transient Mark mode is on and a region is active, it is used
1161 as the header text."
1162 (interactive)
1163 (markdown-insert-header 6))
1165 (defun markdown-insert-header (n)
1166 "Insert an atx-style (hash mark) header.
1167 With no prefix argument, insert a level-1 header. With prefix N,
1168 insert a level-N header. If Transient Mark mode is on and the
1169 region is active, it is used as the header text."
1170 (interactive "p")
1171 (unless n ; Test to see if n is defined
1172 (setq n 1)) ; Default to level 1 header
1173 (let (hdr hdrl hdrr)
1174 (dotimes (count n hdr)
1175 (setq hdr (concat "#" hdr))) ; Build a hash mark header string
1176 (setq hdrl (concat hdr " "))
1177 (setq hdrr (concat " " hdr))
1178 (markdown-wrap-or-insert hdrl hdrr))
1179 (backward-char (+ 1 n)))
1181 (defun markdown-insert-title ()
1182 "Insert a setext-style (underline) first level header.
1183 If Transient Mark mode is on and a region is active, it is used
1184 as the header text."
1185 (interactive)
1186 (if (and transient-mark-mode mark-active)
1187 (let ((a (region-beginning))
1188 (b (region-end))
1189 (len 0)
1190 (hdr))
1191 (setq len (- b a))
1192 (dotimes (count len hdr)
1193 (setq hdr (concat "=" hdr))) ; Build a === title underline
1194 (end-of-line)
1195 (insert "\n" hdr "\n"))
1196 (insert "\n==========\n")
1197 (backward-char 12)))
1199 (defun markdown-insert-section ()
1200 "Insert a setext-style (underline) second level header.
1201 If Transient Mark mode is on and a region is active, it is used
1202 as the header text."
1203 (interactive)
1204 (if (and transient-mark-mode mark-active)
1205 (let ((a (region-beginning))
1206 (b (region-end))
1207 (len 0)
1208 (hdr))
1209 (setq len (- b a))
1210 (dotimes (count len hdr)
1211 (setq hdr (concat "-" hdr))) ; Build a --- section underline
1212 (end-of-line)
1213 (insert "\n" hdr "\n"))
1214 (insert "\n----------\n")
1215 (backward-char 12)))
1217 (defun markdown-insert-blockquote ()
1218 "Start a blockquote section (or blockquote the region).
1219 If Transient Mark mode is on and a region is active, it is used as
1220 the blockquote text."
1221 (interactive)
1222 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1223 (markdown-blockquote-region (region-beginning) (region-end))
1224 (insert "> ")))
1226 (defun markdown-block-region (beg end prefix)
1227 "Format the region using a block prefix.
1228 Arguments BEG and END specify the beginning and end of the
1229 region. The characters PREFIX will appear at the beginning
1230 of each line."
1231 (if mark-active
1232 (save-excursion
1233 ;; Ensure that there is a leading blank line
1234 (goto-char beg)
1235 (when (and (>= (point) (+ (point-min) 2))
1236 (not (looking-back "\n\n" 2)))
1237 (insert "\n")
1238 (setq beg (1+ beg))
1239 (setq end (1+ end)))
1240 ;; Move back before any blank lines at the end
1241 (goto-char end)
1242 (while (and (looking-back "\n" 1)
1243 (not (equal (point) (point-min))))
1244 (backward-char)
1245 (setq end (1- end)))
1246 ;; Ensure that there is a trailing blank line
1247 (goto-char end)
1248 (if (not (or (looking-at "\n\n")
1249 (and (equal (1+ end) (point-max)) (looking-at "\n"))))
1250 (insert "\n"))
1251 ;; Insert PREFIX
1252 (goto-char beg)
1253 (beginning-of-line)
1254 (while (< (point-at-bol) end)
1255 (insert prefix)
1256 (setq end (+ (length prefix) end))
1257 (forward-line)))))
1259 (defun markdown-blockquote-region (beg end)
1260 "Blockquote the region.
1261 Arguments BEG and END specify the beginning and end of the region."
1262 (interactive "*r")
1263 (markdown-block-region beg end "> "))
1265 (defun markdown-insert-pre ()
1266 "Start a preformatted section (or apply to the region).
1267 If Transient Mark mode is on and a region is active, it is marked
1268 as preformatted text."
1269 (interactive)
1270 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1271 (markdown-pre-region (region-beginning) (region-end))
1272 (insert " ")))
1274 (defun markdown-pre-region (beg end)
1275 "Format the region as preformatted text.
1276 Arguments BEG and END specify the beginning and end of the region."
1277 (interactive "*r")
1278 (markdown-block-region beg end " "))
1280 ;;; Indentation ====================================================================
1282 (defun markdown-indent-find-next-position (cur-pos positions)
1283 "Return the position after the index of CUR-POS in POSITIONS."
1284 (while (and positions
1285 (not (equal cur-pos (car positions))))
1286 (setq positions (cdr positions)))
1287 (or (cadr positions) 0))
1289 (defun markdown-indent-line ()
1290 "Indent the current line using some heuristics.
1291 If the _previous_ command was either `markdown-enter-key' or
1292 `markdown-cycle', then we should cycle to the next
1293 reasonable indentation position. Otherwise, we could have been
1294 called directly by `markdown-enter-key', by an initial call of
1295 `markdown-cycle', or indirectly by `auto-fill-mode'. In
1296 these cases, indent to the default position."
1297 (interactive)
1298 (let ((positions (markdown-calc-indents))
1299 (cur-pos (current-column)))
1300 (if (not (equal this-command 'markdown-cycle))
1301 (indent-line-to (car positions))
1302 (setq positions (sort (delete-dups positions) '<))
1303 (indent-line-to
1304 (markdown-indent-find-next-position cur-pos positions)))))
1306 (defun markdown-calc-indents ()
1307 "Return a list of indentation columns to cycle through.
1308 The first element in the returned list should be considered the
1309 default indentation level."
1310 (let (pos prev-line-pos positions)
1312 ;; Previous line indent
1313 (setq prev-line-pos (markdown-prev-line-indent))
1314 (setq positions (cons prev-line-pos positions))
1316 ;; Previous non-list-marker indent
1317 (setq pos (markdown-prev-non-list-indent))
1318 (if pos
1319 (setq positions (cons pos positions)))
1321 ;; Indentation of the previous line + tab-width
1322 (cond
1323 (prev-line-pos
1324 (setq positions (cons (+ prev-line-pos tab-width) positions)))
1326 (setq positions (cons tab-width positions))))
1328 ;; Indentation of the previous line - tab-width
1329 (if (and prev-line-pos
1330 (> prev-line-pos tab-width))
1331 (setq positions (cons (- prev-line-pos tab-width) positions)))
1333 ;; Indentation of preceeding list item
1334 (setq pos
1335 (save-excursion
1336 (forward-line -1)
1337 (catch 'break
1338 (while (not (equal (point) (point-min)))
1339 (forward-line -1)
1340 (goto-char (point-at-bol))
1341 (when (re-search-forward markdown-regex-list-indent (point-at-eol) t)
1342 (throw 'break (length (match-string 1)))))
1343 nil)))
1344 (if (and pos (not (eq pos prev-line-pos)))
1345 (setq positions (cons pos positions)))
1347 ;; First column
1348 (setq positions (cons 0 positions))
1350 (reverse positions)))
1352 (defun markdown-do-normal-return ()
1353 "Insert a newline and optionally indent the next line."
1354 (newline)
1355 (if markdown-indent-on-enter
1356 (funcall indent-line-function)))
1358 (defun markdown-enter-key ()
1359 "Handle RET according to context.
1360 If there is a wiki link at the point, follow it unless
1361 `markdown-follow-wiki-link-on-enter' is nil. Otherwise, process
1362 it in the usual way."
1363 (interactive)
1364 (if (and markdown-follow-wiki-link-on-enter (markdown-wiki-link-p))
1365 (markdown-follow-wiki-link-at-point)
1366 (markdown-do-normal-return)))
1370 ;;; Keymap ====================================================================
1372 (defvar markdown-mode-map
1373 (let ((map (make-keymap)))
1374 ;; Element insertion
1375 (define-key map "\C-c\C-al" 'markdown-insert-link)
1376 (define-key map "\C-c\C-aw" 'markdown-insert-wiki-link)
1377 (define-key map "\C-c\C-ii" 'markdown-insert-image)
1378 (define-key map "\C-c\C-t1" 'markdown-insert-header-1)
1379 (define-key map "\C-c\C-t2" 'markdown-insert-header-2)
1380 (define-key map "\C-c\C-t3" 'markdown-insert-header-3)
1381 (define-key map "\C-c\C-t4" 'markdown-insert-header-4)
1382 (define-key map "\C-c\C-t5" 'markdown-insert-header-5)
1383 (define-key map "\C-c\C-t6" 'markdown-insert-header-6)
1384 (define-key map "\C-c\C-pb" 'markdown-insert-bold)
1385 (define-key map "\C-c\C-ss" 'markdown-insert-bold)
1386 (define-key map "\C-c\C-pi" 'markdown-insert-italic)
1387 (define-key map "\C-c\C-se" 'markdown-insert-italic)
1388 (define-key map "\C-c\C-pf" 'markdown-insert-code)
1389 (define-key map "\C-c\C-sc" 'markdown-insert-code)
1390 (define-key map "\C-c\C-sb" 'markdown-insert-blockquote)
1391 (define-key map "\C-c\C-s\C-b" 'markdown-blockquote-region)
1392 (define-key map "\C-c\C-sp" 'markdown-insert-pre)
1393 (define-key map "\C-c\C-s\C-p" 'markdown-pre-region)
1394 (define-key map "\C-c-" 'markdown-insert-hr)
1395 (define-key map "\C-c\C-tt" 'markdown-insert-title)
1396 (define-key map "\C-c\C-ts" 'markdown-insert-section)
1397 ;; WikiLink Following
1398 (define-key map "\C-c\C-f" 'markdown-follow-wiki-link-at-point)
1399 (define-key map "\M-n" 'markdown-next-wiki-link)
1400 (define-key map "\M-p" 'markdown-previous-wiki-link)
1401 ;; Indentation
1402 (define-key map "\C-m" 'markdown-enter-key)
1403 ;; Visibility cycling
1404 (define-key map (kbd "<tab>") 'markdown-cycle)
1405 (define-key map (kbd "<S-iso-lefttab>") 'markdown-shifttab)
1406 ;; Header navigation
1407 (define-key map (kbd "C-M-n") 'outline-next-visible-heading)
1408 (define-key map (kbd "C-M-p") 'outline-previous-visible-heading)
1409 (define-key map (kbd "C-M-f") 'outline-forward-same-level)
1410 (define-key map (kbd "C-M-b") 'outline-backward-same-level)
1411 (define-key map (kbd "C-M-u") 'outline-up-heading)
1412 ;; Markdown functions
1413 (define-key map "\C-c\C-cm" 'markdown)
1414 (define-key map "\C-c\C-cp" 'markdown-preview)
1415 (define-key map "\C-c\C-ce" 'markdown-export)
1416 (define-key map "\C-c\C-cv" 'markdown-export-and-view)
1417 ;; References
1418 (define-key map "\C-c\C-cc" 'markdown-check-refs)
1419 map)
1420 "Keymap for Markdown major mode.")
1422 ;;; Menu ==================================================================
1424 (easy-menu-define markdown-mode-menu markdown-mode-map
1425 "Menu for Markdown mode"
1426 '("Markdown"
1427 ("Show/Hide"
1428 ["Cycle visibility" markdown-cycle (outline-on-heading-p)]
1429 ["Cycle global visibility" markdown-shifttab])
1430 "---"
1431 ["Compile" markdown]
1432 ["Preview" markdown-preview]
1433 ["Export" markdown-export]
1434 ["Export & View" markdown-export-and-view]
1435 "---"
1436 ("Headers (setext)"
1437 ["Insert Title" markdown-insert-title]
1438 ["Insert Section" markdown-insert-section])
1439 ("Headers (atx)"
1440 ["First level" markdown-insert-header-1]
1441 ["Second level" markdown-insert-header-2]
1442 ["Third level" markdown-insert-header-3]
1443 ["Fourth level" markdown-insert-header-4]
1444 ["Fifth level" markdown-insert-header-5]
1445 ["Sixth level" markdown-insert-header-6])
1446 "---"
1447 ["Bold" markdown-insert-bold]
1448 ["Italic" markdown-insert-italic]
1449 ["Blockquote" markdown-insert-blockquote]
1450 ["Preformatted" markdown-insert-pre]
1451 ["Code" markdown-insert-code]
1452 "---"
1453 ["Insert inline link" markdown-insert-link]
1454 ["Insert image" markdown-insert-image]
1455 ["Insert horizontal rule" markdown-insert-hr]
1456 "---"
1457 ["Check references" markdown-check-refs]
1458 "---"
1459 ["Version" markdown-show-version]
1464 ;;; References ================================================================
1466 ;;; Undefined reference checking code by Dmitry Dzhus <mail@sphinx.net.ru>.
1468 (defconst markdown-refcheck-buffer
1469 "*Undefined references for %buffer%*"
1470 "Pattern for name of buffer for listing undefined references.
1471 The string %buffer% will be replaced by the corresponding
1472 `markdown-mode' buffer name.")
1474 (defun markdown-has-reference-definition (reference)
1475 "Find out whether Markdown REFERENCE is defined.
1477 REFERENCE should include the square brackets, like [this]."
1478 (let ((reference (downcase reference)))
1479 (save-excursion
1480 (goto-char (point-min))
1481 (catch 'found
1482 (while (re-search-forward markdown-regex-reference-definition nil t)
1483 (when (string= reference (downcase (match-string-no-properties 1)))
1484 (throw 'found t)))))))
1486 (defun markdown-get-undefined-refs ()
1487 "Return a list of undefined Markdown references.
1489 Result is an alist of pairs (reference . occurencies), where
1490 occurencies is itself another alist of pairs (label .
1491 line-number).
1493 For example, an alist corresponding to [Nice editor][Emacs] at line 12,
1494 \[GNU Emacs][Emacs] at line 45 and [manual][elisp] at line 127 is
1495 \((\"[emacs]\" (\"[Nice editor]\" . 12) (\"[GNU Emacs]\" . 45)) (\"[elisp]\" (\"[manual]\" . 127)))."
1496 (let ((missing))
1497 (save-excursion
1498 (goto-char (point-min))
1499 (while
1500 (re-search-forward markdown-regex-link-reference nil t)
1501 (let* ((label (match-string-no-properties 1))
1502 (reference (match-string-no-properties 2))
1503 (target (downcase (if (string= reference "[]") label reference))))
1504 (unless (markdown-has-reference-definition target)
1505 (let ((entry (assoc target missing)))
1506 (if (not entry)
1507 (add-to-list 'missing (cons target
1508 (list (cons label (markdown-line-number-at-pos)))) t)
1509 (setcdr entry
1510 (append (cdr entry) (list (cons label (markdown-line-number-at-pos))))))))))
1511 missing)))
1513 (defun markdown-add-missing-ref-definition (ref buffer &optional recheck)
1514 "Add blank REF definition to the end of BUFFER.
1516 REF is a Markdown reference in square brackets, like \"[lisp-history]\".
1518 When RECHECK is non-nil, BUFFER gets rechecked for undefined
1519 references so that REF disappears from the list of those links."
1520 (with-current-buffer buffer
1521 (when (not (eq major-mode 'markdown-mode))
1522 (error "Not available in current mode"))
1523 (goto-char (point-max))
1524 (indent-new-comment-line)
1525 (insert (concat ref ": ")))
1526 (switch-to-buffer-other-window buffer)
1527 (goto-char (point-max))
1528 (when recheck
1529 (markdown-check-refs t)))
1531 ;; Button which adds an empty Markdown reference definition to the end
1532 ;; of buffer specified as its 'target-buffer property. Reference name
1533 ;; is button's label
1534 (when (>= emacs-major-version 22)
1535 (define-button-type 'markdown-ref-button
1536 'help-echo "Push to create an empty reference definition"
1537 'face 'bold
1538 'action (lambda (b)
1539 (markdown-add-missing-ref-definition
1540 (button-label b) (button-get b 'target-buffer) t))))
1542 ;; Button jumping to line in buffer specified as its 'target-buffer
1543 ;; property. Line number is button's 'line property.
1544 (when (>= emacs-major-version 22)
1545 (define-button-type 'goto-line-button
1546 'help-echo "Push to go to this line"
1547 'face 'italic
1548 'action (lambda (b)
1549 (message (button-get b 'buffer))
1550 (switch-to-buffer-other-window (button-get b 'target-buffer))
1551 ;; use call-interactively to silence compiler
1552 (call-interactively 'goto-line (button-get b 'target-line)))))
1554 (defun markdown-check-refs (&optional silent)
1555 "Show all undefined Markdown references in current `markdown-mode' buffer.
1557 If SILENT is non-nil, do not message anything when no undefined
1558 references found.
1560 Links which have empty reference definitions are considered to be
1561 defined."
1562 (interactive "P")
1563 (when (not (eq major-mode 'markdown-mode))
1564 (error "Not available in current mode"))
1565 (let ((oldbuf (current-buffer))
1566 (refs (markdown-get-undefined-refs))
1567 (refbuf (get-buffer-create (markdown-replace-regexp-in-string
1568 "%buffer%" (buffer-name)
1569 markdown-refcheck-buffer))))
1570 (if (null refs)
1571 (progn
1572 (when (not silent)
1573 (message "No undefined references found"))
1574 (kill-buffer refbuf))
1575 (with-current-buffer refbuf
1576 (when view-mode
1577 (View-exit-and-edit))
1578 (erase-buffer)
1579 (insert "Following references lack definitions:")
1580 (newline 2)
1581 (dolist (ref refs)
1582 (let ((button-label (format "%s" (car ref))))
1583 (if (>= emacs-major-version 22)
1584 ;; Create a reference button in Emacs 22
1585 (insert-text-button button-label
1586 :type 'markdown-ref-button
1587 'target-buffer oldbuf)
1588 ;; Insert reference as text in Emacs < 22
1589 (insert button-label)))
1590 (insert " (")
1591 (dolist (occurency (cdr ref))
1592 (let ((line (cdr occurency)))
1593 (if (>= emacs-major-version 22)
1594 ;; Create a line number button in Emacs 22
1595 (insert-button (number-to-string line)
1596 :type 'goto-line-button
1597 'target-buffer oldbuf
1598 'target-line line)
1599 ;; Insert line number as text in Emacs < 22
1600 (insert (number-to-string line)))
1601 (insert " "))) (delete-char -1)
1602 (insert ")")
1603 (newline))
1604 (view-buffer-other-window refbuf)
1605 (goto-char (point-min))
1606 (forward-line 2)))))
1608 ;;; Outline ===================================================================
1610 ;; The following visibility cycling code was taken from org-mode
1611 ;; by Carsten Dominik and adapted for markdown-mode.
1613 (defvar markdown-cycle-global-status 1)
1614 (defvar markdown-cycle-subtree-status nil)
1616 ;; Based on org-end-of-subtree from org.el
1617 (defun markdown-end-of-subtree (&optional invisible-OK)
1618 "Move to the end of the current subtree.
1619 Only visible heading lines are considered, unless INVISIBLE-OK is
1620 non-nil."
1621 (outline-back-to-heading invisible-OK)
1622 (let ((first t)
1623 (level (funcall outline-level)))
1624 (while (and (not (eobp))
1625 (or first (> (funcall outline-level) level)))
1626 (setq first nil)
1627 (outline-next-heading))
1628 (if (memq (preceding-char) '(?\n ?\^M))
1629 (progn
1630 ;; Go to end of line before heading
1631 (forward-char -1)
1632 (if (memq (preceding-char) '(?\n ?\^M))
1633 ;; leave blank line before heading
1634 (forward-char -1)))))
1635 (point))
1637 ;; Based on org-cycle from org.el.
1638 (defun markdown-cycle (&optional arg)
1639 "Visibility cycling for Markdown mode.
1640 If ARG is t, perform global visibility cycling. If the point is
1641 at an atx-style header, cycle visibility of the corresponding
1642 subtree. Otherwise, insert a tab using `indent-relative'."
1643 (interactive "P")
1644 (cond
1645 ((eq arg t) ;; Global cycling
1646 (cond
1647 ((and (eq last-command this-command)
1648 (eq markdown-cycle-global-status 2))
1649 ;; Move from overview to contents
1650 (hide-sublevels 1)
1651 (message "CONTENTS")
1652 (setq markdown-cycle-global-status 3))
1654 ((and (eq last-command this-command)
1655 (eq markdown-cycle-global-status 3))
1656 ;; Move from contents to all
1657 (show-all)
1658 (message "SHOW ALL")
1659 (setq markdown-cycle-global-status 1))
1662 ;; Defaults to overview
1663 (hide-body)
1664 (message "OVERVIEW")
1665 (setq markdown-cycle-global-status 2))))
1667 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
1668 ;; At a heading: rotate between three different views
1669 (outline-back-to-heading)
1670 (let ((goal-column 0) eoh eol eos)
1671 ;; Determine boundaries
1672 (save-excursion
1673 (outline-back-to-heading)
1674 (save-excursion
1675 (beginning-of-line 2)
1676 (while (and (not (eobp)) ;; this is like `next-line'
1677 (get-char-property (1- (point)) 'invisible))
1678 (beginning-of-line 2)) (setq eol (point)))
1679 (outline-end-of-heading) (setq eoh (point))
1680 (markdown-end-of-subtree t)
1681 (skip-chars-forward " \t\n")
1682 (beginning-of-line 1) ; in case this is an item
1683 (setq eos (1- (point))))
1684 ;; Find out what to do next and set `this-command'
1685 (cond
1686 ((= eos eoh)
1687 ;; Nothing is hidden behind this heading
1688 (message "EMPTY ENTRY")
1689 (setq markdown-cycle-subtree-status nil))
1690 ((>= eol eos)
1691 ;; Entire subtree is hidden in one line: open it
1692 (show-entry)
1693 (show-children)
1694 (message "CHILDREN")
1695 (setq markdown-cycle-subtree-status 'children))
1696 ((and (eq last-command this-command)
1697 (eq markdown-cycle-subtree-status 'children))
1698 ;; We just showed the children, now show everything.
1699 (show-subtree)
1700 (message "SUBTREE")
1701 (setq markdown-cycle-subtree-status 'subtree))
1703 ;; Default action: hide the subtree.
1704 (hide-subtree)
1705 (message "FOLDED")
1706 (setq markdown-cycle-subtree-status 'folded)))))
1709 (indent-for-tab-command))))
1711 ;; Based on org-shifttab from org.el.
1712 (defun markdown-shifttab ()
1713 "Global visibility cycling.
1714 Calls `markdown-cycle' with argument t."
1715 (interactive)
1716 (markdown-cycle t))
1718 ;;; Commands ==================================================================
1720 (defun markdown (&optional output-buffer-name)
1721 "Run `markdown' on current buffer and insert output in buffer BUFFER-OUTPUT."
1722 (interactive)
1723 (let ((title (buffer-name))
1724 (begin-region)
1725 (end-region))
1726 (if (and (boundp 'transient-mark-mode) transient-mark-mode mark-active)
1727 (setq begin-region (region-beginning)
1728 end-region (region-end))
1729 (setq begin-region (point-min)
1730 end-region (point-max)))
1732 (unless output-buffer-name
1733 (setq output-buffer-name markdown-output-buffer-name))
1735 (if markdown-command-needs-filename
1736 ;; Handle case when `markdown-command' does not read from stdin
1737 (if (not buffer-file-name)
1738 (error "Must be visiting a file")
1739 (shell-command (concat markdown-command " "
1740 (shell-quote-argument buffer-file-name))
1741 output-buffer-name))
1742 ;; Pass region to `markdown-command' via stdin
1743 (shell-command-on-region begin-region end-region markdown-command
1744 output-buffer-name))
1746 ;; Add header and footer and switch to html-mode.
1747 (save-current-buffer
1748 (set-buffer output-buffer-name)
1749 (goto-char (point-min))
1750 (unless (markdown-output-standalone-p)
1751 (markdown-add-xhtml-header-and-footer title))
1752 (html-mode))
1754 ;; Ensure buffer gets raised, even with short command output
1755 (switch-to-buffer-other-window output-buffer-name)))
1757 (defun markdown-output-standalone-p ()
1758 "Determine whether `markdown-command' output is standalone XHTML.
1759 Standalone XHTML output is identified by an occurrence of
1760 `markdown-xhtml-standalone-regexp' in the first five lines of output."
1761 (re-search-forward
1762 markdown-xhtml-standalone-regexp
1763 (save-excursion (goto-char (point-min)) (forward-line 4) (point))
1766 (defun markdown-add-xhtml-header-and-footer (title)
1767 "Wrap XHTML header and footer with given TITLE around current buffer."
1768 (insert "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
1769 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n"
1770 "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n\n"
1771 "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\n"
1772 "<head>\n<title>")
1773 (insert title)
1774 (insert "</title>\n")
1775 (if (> (length markdown-css-path) 0)
1776 (insert "<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\""
1777 markdown-css-path
1778 "\" />\n"))
1779 (when (> (length markdown-xhtml-header-content) 0)
1780 (insert markdown-xhtml-header-content))
1781 (insert "\n</head>\n\n"
1782 "<body>\n\n")
1783 (goto-char (point-max))
1784 (insert "\n"
1785 "</body>\n"
1786 "</html>\n"))
1788 (defun markdown-preview ()
1789 "Run `markdown' on the current buffer and preview the output in a browser."
1790 (interactive)
1791 (markdown markdown-output-buffer-name)
1792 (browse-url-of-buffer markdown-output-buffer-name))
1794 (defun markdown-export-file-name ()
1795 "Attempt to generate a filename for Markdown output.
1796 If the current buffer is visiting a file, we construct a new
1797 output filename based on that filename. Otherwise, return nil."
1798 (when (buffer-file-name)
1799 (concat (file-name-sans-extension (buffer-file-name)) ".html")))
1801 (defun markdown-export ()
1802 "Run Markdown on the current buffer, save to a file, and return the filename.
1803 The resulting filename will be constructed using the current filename, but
1804 with the extension removed and replaced with .html."
1805 (interactive)
1806 (let ((output-file (markdown-export-file-name))
1807 (output-buffer-name))
1808 (when output-file
1809 (setq output-buffer-name (buffer-name (find-file-noselect output-file)))
1810 (markdown output-buffer-name)
1811 (with-current-buffer output-buffer-name
1812 (save-buffer)
1813 (kill-buffer-and-window))
1814 output-file)))
1816 (defun markdown-export-and-view ()
1817 "Export to XHTML using `markdown-export' and browse the resulting file."
1818 (interactive)
1819 (browse-url (markdown-export)))
1821 ;;; WikiLink Following/Markup =================================================
1823 (require 'thingatpt)
1825 (defun markdown-wiki-link-p ()
1826 "Return non-nil when `point' is at a true wiki link.
1827 A true wiki link name matches `markdown-regex-wiki-link' but does not
1828 match the current file name after conversion. This modifies the data
1829 returned by `match-data'. Note that the potential wiki link name must
1830 be available via `match-string'."
1831 (let ((case-fold-search nil))
1832 (and (thing-at-point-looking-at markdown-regex-wiki-link)
1833 (or (not buffer-file-name)
1834 (not (string-equal (buffer-file-name)
1835 (markdown-convert-wiki-link-to-filename
1836 (match-string 1)))))
1837 (not (save-match-data
1838 (save-excursion))))))
1840 (defun markdown-convert-wiki-link-to-filename (name)
1841 "Generate a filename from the wiki link NAME.
1842 Spaces in NAME are replaced with `markdown-link-space-sub-char'."
1843 (let ((basename (markdown-replace-regexp-in-string
1844 "[[:space:]\n]" markdown-link-space-sub-char name)))
1845 (concat basename
1846 (if (buffer-file-name)
1847 (concat "."
1848 (file-name-extension (buffer-file-name)))))))
1850 (defun markdown-follow-wiki-link (name)
1851 "Follow the wiki link NAME.
1852 Convert the name to a file name and call `find-file'. Ensure that
1853 the new buffer remains in `markdown-mode'."
1854 (let ((filename (markdown-convert-wiki-link-to-filename name)))
1855 (find-file filename))
1856 (markdown-mode))
1858 (defun markdown-follow-wiki-link-at-point ()
1859 "Find Wiki Link at point.
1860 See `markdown-wiki-link-p' and `markdown-follow-wiki-link'."
1861 (interactive)
1862 (if (markdown-wiki-link-p)
1863 (markdown-follow-wiki-link (match-string 1))
1864 (error "Point is not at a Wiki Link")))
1866 (defun markdown-next-wiki-link ()
1867 "Jump to next wiki link.
1868 See `markdown-wiki-link-p'."
1869 (interactive)
1870 (if (markdown-wiki-link-p)
1871 ; At a wiki link already, move past it.
1872 (goto-char (+ 1 (match-end 0))))
1873 (save-match-data
1874 ; Search for the next wiki link and move to the beginning.
1875 (re-search-forward markdown-regex-wiki-link nil t)
1876 (goto-char (match-beginning 0))))
1878 (defun markdown-previous-wiki-link ()
1879 "Jump to previous wiki link.
1880 See `markdown-wiki-link-p'."
1881 (interactive)
1882 (re-search-backward markdown-regex-wiki-link nil t))
1884 (defun markdown-highlight-wiki-link (from to face)
1885 "Highlight the wiki link in the region between FROM and TO using FACE."
1886 (put-text-property from to 'font-lock-face face))
1888 (defun markdown-unfontify-region-wiki-links (from to)
1889 "Remove wiki link faces from the region specified by FROM and TO."
1890 (interactive "nfrom: \nnto: ")
1891 (remove-text-properties from to '(font-lock-face markdown-link-face))
1892 (remove-text-properties from to '(font-lock-face markdown-missing-link-face)))
1894 (defun markdown-fontify-region-wiki-links (from to)
1895 "Search region given by FROM and TO for wiki links and fontify them.
1896 If a wiki link is found check to see if the backing file exists
1897 and highlight accordingly."
1898 (goto-char from)
1899 (while (re-search-forward markdown-regex-wiki-link to t)
1900 (let ((highlight-beginning (match-beginning 0))
1901 (highlight-end (match-end 0))
1902 (file-name
1903 (markdown-convert-wiki-link-to-filename (match-string 1))))
1904 (if (file-exists-p file-name)
1905 (markdown-highlight-wiki-link
1906 highlight-beginning highlight-end markdown-link-face)
1907 (markdown-highlight-wiki-link
1908 highlight-beginning highlight-end markdown-missing-link-face)))))
1910 (defun markdown-extend-changed-region (from to)
1911 "Extend region given by FROM and TO so that we can fontify all links.
1912 The region is extended to the first newline before and the first
1913 newline after."
1914 ;; start looking for the first new line before 'from
1915 (goto-char from)
1916 (re-search-backward "\n" nil t)
1917 (let ((new-from (point-min))
1918 (new-to (point-max)))
1919 (if (not (= (point) from))
1920 (setq new-from (point)))
1921 ;; do the same thing for the first new line after 'to
1922 (goto-char to)
1923 (re-search-forward "\n" nil t)
1924 (if (not (= (point) to))
1925 (setq new-to (point)))
1926 (list new-from new-to)))
1928 (defun markdown-check-change-for-wiki-link (from to change)
1929 "Check region between FROM and TO for wiki links and re-fontfy as needed.
1930 Designed to be used with the `after-change-functions' hook.
1931 CHANGE is the number of bytes of pre-change text replaced by the
1932 given range."
1933 (interactive "nfrom: \nnto: \nnchange: ")
1934 (let* ((inhibit-quit t)
1935 (modified (buffer-modified-p))
1936 (buffer-undo-list t)
1937 (inhibit-read-only t)
1938 (inhibit-point-motion-hooks t)
1939 (inhibit-modification-hooks t)
1940 (current-point (point))
1941 deactivate-mark)
1942 (unwind-protect
1943 (save-match-data
1944 (save-restriction
1945 ;; Extend the region to fontify so that it starts
1946 ;; and ends at safe places.
1947 (multiple-value-bind (new-from new-to)
1948 (markdown-extend-changed-region from to)
1949 ;; Unfontify existing fontification (start from scratch)
1950 (markdown-unfontify-region-wiki-links new-from new-to)
1951 ;; Now do the fontification.
1952 (markdown-fontify-region-wiki-links new-from new-to)))
1953 (unless modified
1954 (if (fboundp 'restore-buffer-modified-p)
1955 (restore-buffer-modified-p nil)
1956 (set-buffer-modified-p nil))))
1957 (goto-char current-point))))
1959 (defun markdown-fontify-buffer-wiki-links ()
1960 "Refontify all wiki links in the buffer."
1961 (interactive)
1962 (markdown-check-change-for-wiki-link (point-min) (point-max) 0))
1964 ;;; Miscellaneous =============================================================
1966 (defun markdown-line-number-at-pos (&optional pos)
1967 "Return (narrowed) buffer line number at position POS.
1968 If POS is nil, use current buffer location.
1969 This is an exact copy of `line-number-at-pos' for use in emacs21."
1970 (let ((opoint (or pos (point))) start)
1971 (save-excursion
1972 (goto-char (point-min))
1973 (setq start (point))
1974 (goto-char opoint)
1975 (forward-line 0)
1976 (1+ (count-lines start (point))))))
1978 (defun markdown-nobreak-p ()
1979 "Return nil if it is acceptable to break the current line at the point."
1980 ;; inside in square brackets (e.g., link anchor text)
1981 (looking-back "\\[[^]]*"))
1985 ;;; Mode definition ==========================================================
1987 (defun markdown-show-version ()
1988 "Show the version number in the minibuffer."
1989 (interactive)
1990 (message "markdown-mode, version %s" markdown-mode-version))
1992 ;;;###autoload
1993 (define-derived-mode markdown-mode text-mode "Markdown"
1994 "Major mode for editing Markdown files."
1995 ;; Natural Markdown tab width
1996 (setq tab-width 4)
1997 ;; Comments
1998 (make-local-variable 'comment-start)
1999 (setq comment-start "<!-- ")
2000 (make-local-variable 'comment-end)
2001 (setq comment-end " -->")
2002 (make-local-variable 'comment-start-skip)
2003 (setq comment-start-skip "<!--[ \t]*")
2004 (make-local-variable 'comment-column)
2005 (setq comment-column 0)
2006 ;; Font lock.
2007 (set (make-local-variable 'font-lock-defaults)
2008 '(markdown-mode-font-lock-keywords))
2009 (set (make-local-variable 'font-lock-multiline) t)
2010 ;; For menu support in XEmacs
2011 (easy-menu-add markdown-mode-menu markdown-mode-map)
2012 ;; Make filling work with lists (unordered, ordered, and definition)
2013 (set (make-local-variable 'paragraph-start)
2014 "\f\\|[ \t]*$\\|^[ \t]*[*+-] \\|^[ \t*][0-9]+\\.\\|^[ \t]*: ")
2015 ;; Outline mode
2016 (make-local-variable 'outline-regexp)
2017 (setq outline-regexp "#+")
2018 ;; Cause use of ellipses for invisible text.
2019 (add-to-invisibility-spec '(outline . t))
2020 ;; Indentation and filling
2021 (make-local-variable 'fill-nobreak-predicate)
2022 (add-hook 'fill-nobreak-predicate 'markdown-nobreak-p)
2023 (setq indent-line-function markdown-indent-function)
2025 ;; Prepare hooks for XEmacs compatibility
2026 (when (featurep 'xemacs)
2027 (make-local-hook 'after-change-functions)
2028 (make-local-hook 'font-lock-extend-region-functions)
2029 (make-local-hook 'window-configuration-change-hook))
2031 ;; Multiline font lock
2032 (add-hook 'font-lock-extend-region-functions
2033 'markdown-font-lock-extend-region)
2035 ;; Anytime text changes make sure it gets fontified correctly
2036 (add-hook 'after-change-functions 'markdown-check-change-for-wiki-link t t)
2038 ;; If we left the buffer there is a really good chance we were
2039 ;; creating one of the wiki link documents. Make sure we get
2040 ;; refontified when we come back.
2041 (add-hook 'window-configuration-change-hook
2042 'markdown-fontify-buffer-wiki-links t t)
2044 ;; do the initial link fontification
2045 (markdown-fontify-buffer-wiki-links))
2047 ;(add-to-list 'auto-mode-alist '("\\.text$" . markdown-mode))
2049 ;;; GitHub Flavored Markdown Mode ============================================
2051 (define-derived-mode gfm-mode markdown-mode "GFM"
2052 "Major mode for editing GitHub Flavored Markdown files."
2053 (auto-fill-mode 0)
2054 ;; Use visual-line-mode if available, fall back to longlines-mode:
2055 (if (fboundp 'visual-line-mode)
2056 (visual-line-mode 1)
2057 (longlines-mode 1)))
2059 (provide 'markdown-mode)
2061 ;;; markdown-mode.el ends here