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