Remove buggy fallback code in muse-replace-regexp-in-string
[muse-el.git] / lisp / muse.el
blobf66b78b1f2df62bc10280f58d75ab31a3120e368
1 ;;; muse.el --- an authoring and publishing tool for Emacs
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5 ;; Emacs Lisp Archive Entry
6 ;; Filename: muse.el
7 ;; Version: 3.11
8 ;; Date: Fri 24-Aug-2007
9 ;; Keywords: hypermedia
10 ;; Author: John Wiegley (johnw AT gnu DOT org)
11 ;; Maintainer: Michael Olson <mwolson@gnu.org>
12 ;; Description: An authoring and publishing tool for Emacs
13 ;; URL: http://mwolson.org/projects/EmacsMuse.html
14 ;; Compatibility: Emacs21 XEmacs21 Emacs22
16 ;; This file is part of Emacs Muse. It is not part of GNU Emacs.
18 ;; Emacs Muse is free software; you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published
20 ;; by the Free Software Foundation; either version 3, or (at your
21 ;; option) any later version.
23 ;; Emacs Muse is distributed in the hope that it will be useful, but
24 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 ;; General Public License for more details.
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with Emacs Muse; see the file COPYING. If not, write to the
30 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
31 ;; Boston, MA 02110-1301, USA.
33 ;;; Commentary:
35 ;; Muse is a tool for easily authoring and publishing documents. It
36 ;; allows for rapid prototyping of hyperlinked text, which may then be
37 ;; exported to multiple output formats -- such as HTML, LaTeX,
38 ;; Texinfo, etc.
40 ;; The markup rules used by Muse are intended to be very friendly to
41 ;; people familiar with Emacs. See the included manual for more
42 ;; information.
44 ;;; Contributors:
46 ;;; Code:
48 ;; Indicate that this version of Muse supports nested tags
49 (provide 'muse-nested-tags)
51 (defvar muse-version "3.11"
52 "The version of Muse currently loaded")
54 (defun muse-version (&optional insert)
55 "Display the version of Muse that is currently loaded.
56 If INSERT is non-nil, insert the text instead of displaying it."
57 (interactive "P")
58 (if insert
59 (insert muse-version)
60 (message muse-version)))
62 (defgroup muse nil
63 "Options controlling the behavior of Muse.
64 The markup used by Muse is intended to be very friendly to people
65 familiar with Emacs."
66 :group 'hypermedia)
68 (defvar muse-under-windows-p (memq system-type '(ms-dos windows-nt)))
70 (provide 'muse)
72 (condition-case nil
73 (require 'derived)
74 (error nil))
75 (require 'wid-edit)
76 (require 'muse-regexps)
78 (defvar muse-update-values-hook nil
79 "Hook for values that are automatically generated.
80 This is to be used by add-on modules for Muse.
81 It is run just before colorizing or publishing a buffer.")
83 (defun muse-update-values ()
84 "Update various values that are automatically generated.
86 Call this after changing `muse-project-alist'."
87 (interactive)
88 (run-hooks 'muse-update-values-hook)
89 (dolist (buffer (buffer-list))
90 (when (buffer-live-p buffer)
91 (with-current-buffer buffer
92 (when (and (derived-mode-p 'muse-mode)
93 muse-current-project)
94 (setq muse-current-project nil)
95 (setq muse-current-project (muse-project-of-file)))))))
97 ;; Default file extension
99 ;; By default, use the .muse file extension.
100 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.muse\\'" . muse-mode-choose-mode))
102 ;; We need to have this at top-level, as well, so that any Muse or
103 ;; Planner documents opened during init will just work.
104 (add-to-list 'auto-mode-alist '("\\.muse\\'" . muse-mode-choose-mode))
106 (eval-when-compile
107 (defvar muse-ignored-extensions))
109 (defvar muse-ignored-extensions-regexp nil
110 "A regexp of extensions to omit from the ending of a Muse page name.
111 This is autogenerated from `muse-ignored-extensions'.")
113 (defun muse-update-file-extension (sym val)
114 "Update the value of `muse-file-extension'."
115 (let ((old (and (boundp sym) (symbol-value sym))))
116 (set sym val)
117 (when (and (featurep 'muse-mode)
118 (or (not (stringp val))
119 (not (stringp old))
120 (not (string= old val))))
121 ;; remove old auto-mode-alist association
122 (when (and (boundp sym) (stringp old))
123 (setq auto-mode-alist
124 (delete (cons (concat "\\." old "\\'")
125 'muse-mode-choose-mode)
126 auto-mode-alist)))
127 ;; associate the new file extension with muse-mode
128 (when (stringp val)
129 (add-to-list 'auto-mode-alist
130 (cons (concat "\\." val "\\'")
131 'muse-mode-choose-mode)))
132 ;; update the ignored extensions regexp
133 (when (fboundp 'muse-update-ignored-extensions-regexp)
134 (muse-update-ignored-extensions-regexp
135 'muse-ignored-extensions muse-ignored-extensions)))))
137 (defcustom muse-file-extension "muse"
138 "File extension of Muse files. Omit the period at the beginning.
139 If you don't want Muse files to have an extension, set this to nil."
140 :type '(choice
141 (const :tag "None" nil)
142 (string))
143 :set 'muse-update-file-extension
144 :group 'muse)
146 (defcustom muse-completing-read-function 'completing-read
147 "Function to call when prompting user to choose between a list of options.
148 This should take the same arguments as `completing-read'."
149 :type 'function
150 :group 'muse)
152 (defun muse-update-ignored-extensions-regexp (sym val)
153 "Update the value of `muse-ignored-extensions-regexp'."
154 (set sym val)
155 (if val
156 (setq muse-ignored-extensions-regexp
157 (concat "\\.\\("
158 (regexp-quote (or muse-file-extension "")) "\\|"
159 (mapconcat 'identity val "\\|")
160 "\\)\\'"))
161 (setq muse-ignored-extensions-regexp
162 (if muse-file-extension
163 (concat "\\.\\(" muse-file-extension "\\)\\'")
164 nil))))
166 (add-hook 'muse-update-values-hook
167 (lambda ()
168 (muse-update-ignored-extensions-regexp
169 'muse-ignored-extensions muse-ignored-extensions)))
171 (defcustom muse-ignored-extensions '("bz2" "gz" "[Zz]")
172 "A list of extensions to omit from the ending of a Muse page name.
173 These are regexps.
175 Don't put a period at the beginning of each extension unless you
176 understand that it is part of a regexp."
177 :type '(repeat (regexp :tag "Extension"))
178 :set 'muse-update-ignored-extensions-regexp
179 :group 'muse)
181 (defun muse-update-file-extension-after-init ()
182 ;; This is short, but it has to be a function, otherwise Emacs21
183 ;; does not load it properly when running after-init-hook
184 (unless (string= muse-file-extension "muse")
185 (let ((val muse-file-extension)
186 (muse-file-extension "muse"))
187 (muse-update-file-extension 'muse-file-extension val))))
189 ;; Once the user's init file has been processed, determine whether
190 ;; they want a file extension
191 (add-hook 'after-init-hook 'muse-update-file-extension-after-init)
193 ;; URL protocols
195 (require 'muse-protocols)
197 ;; Helper functions
199 (defsubst muse-delete-file-if-exists (file)
200 (when (file-exists-p file)
201 (delete-file file)
202 (message "Removed %s" file)))
204 (defsubst muse-time-less-p (t1 t2)
205 "Say whether time T1 is less than time T2."
206 (or (< (car t1) (car t2))
207 (and (= (car t1) (car t2))
208 (< (nth 1 t1) (nth 1 t2)))))
210 (eval-when-compile
211 (defvar muse-publishing-current-file nil))
213 (defun muse-current-file ()
214 "Return the name of the currently visited or published file."
215 (or (and (boundp 'muse-publishing-current-file)
216 muse-publishing-current-file)
217 (buffer-file-name)
218 (concat default-directory (buffer-name))))
220 (defun muse-page-name (&optional name)
221 "Return the canonical form of a Muse page name.
223 What this means is that the directory part of NAME is removed,
224 and the file extensions in `muse-ignored-extensions' are also
225 removed from NAME."
226 (save-match-data
227 (unless (and name (not (string= name "")))
228 (setq name (muse-current-file)))
229 (if name
230 (let ((page (file-name-nondirectory name)))
231 (if (and muse-ignored-extensions-regexp
232 (string-match muse-ignored-extensions-regexp page))
233 (replace-match "" t t page)
234 page)))))
236 (defun muse-display-warning (message)
237 "Display the given MESSAGE as a warning."
238 (if (fboundp 'display-warning)
239 (display-warning 'muse message
240 (if (featurep 'xemacs)
241 'warning
242 :warning))
243 (let ((buf (get-buffer-create "*Muse warnings*")))
244 (with-current-buffer buf
245 (goto-char (point-max))
246 (insert "Warning (muse): " message)
247 (unless (bolp)
248 (newline)))
249 (display-buffer buf)
250 (sit-for 0))))
252 (defun muse-eval-lisp (form)
253 "Evaluate the given form and return the result as a string."
254 (require 'pp)
255 (save-match-data
256 (condition-case err
257 (let ((object (eval (read form))))
258 (cond
259 ((stringp object) object)
260 ((and (listp object)
261 (not (eq object nil)))
262 (let ((string (pp-to-string object)))
263 (substring string 0 (1- (length string)))))
264 ((numberp object)
265 (number-to-string object))
266 ((eq object nil) "")
268 (pp-to-string object))))
269 (error
270 (muse-display-warning (format "%s: Error evaluating %s: %s"
271 (muse-page-name) form err))
272 "; INVALID LISP CODE"))))
274 (defmacro muse-with-temp-buffer (&rest body)
275 "Create a temporary buffer, and evaluate BODY there like `progn'.
276 See also `with-temp-file' and `with-output-to-string'.
278 Unlike `with-temp-buffer', this will never attempt to save the
279 temp buffer. It is meant to be used along with
280 `insert-file-contents' or `muse-insert-file-contents'.
282 Additionally, if `debug-on-error' is set to t, keep the buffer
283 around for debugging purposes rather than removing it."
284 (let ((temp-buffer (make-symbol "temp-buffer")))
285 `(let ((,temp-buffer (generate-new-buffer " *muse-temp*")))
286 (unwind-protect
287 (if debug-on-error
288 (with-current-buffer ,temp-buffer
289 ,@body)
290 (condition-case err
291 (with-current-buffer ,temp-buffer
292 ,@body)
293 (error
294 (if (and (boundp 'muse-batch-publishing-p)
295 muse-batch-publishing-p)
296 (progn
297 (message "%s: Error occured: %s"
298 (muse-page-name) err)
299 (backtrace))
300 (muse-display-warning
301 (format (concat "An error occurred while publishing"
302 " %s:\n %s\n\nSet debug-on-error to"
303 " `t' if you would like a backtrace.")
304 (muse-page-name) err))))))
305 (when (buffer-live-p ,temp-buffer)
306 (with-current-buffer ,temp-buffer
307 (set-buffer-modified-p nil))
308 (unless debug-on-error (kill-buffer ,temp-buffer)))))))
310 (put 'muse-with-temp-buffer 'lisp-indent-function 0)
311 (put 'muse-with-temp-buffer 'edebug-form-spec '(body))
313 (defun muse-insert-file-contents (filename &optional visit)
314 "Insert the contents of file FILENAME after point.
315 Do character code conversion, but none of the other unnecessary
316 things like format decoding or `find-file-hook'.
318 If VISIT is non-nil, the buffer's visited filename
319 and last save file modtime are set, and it is marked unmodified.
320 If visiting and the file does not exist, visiting is completed
321 before the error is signaled."
322 (let ((format-alist nil)
323 (after-insert-file-functions nil)
324 (find-buffer-file-type-function
325 (if (fboundp 'find-buffer-file-type)
326 (symbol-function 'find-buffer-file-type)
327 nil))
328 (inhibit-file-name-handlers
329 (append '(jka-compr-handler image-file-handler)
330 inhibit-file-name-handlers))
331 (inhibit-file-name-operation 'insert-file-contents))
332 (unwind-protect
333 (progn
334 (fset 'find-buffer-file-type (lambda (filename) t))
335 (insert-file-contents filename visit))
336 (if find-buffer-file-type-function
337 (fset 'find-buffer-file-type find-buffer-file-type-function)
338 (fmakunbound 'find-buffer-file-type)))))
340 (defun muse-write-file (filename)
341 "Write current buffer into file FILENAME.
342 Unlike `write-file', this does not visit the file, try to back it
343 up, or interact with vc.el in any way.
345 If the file was not written successfully, return nil. Otherwise,
346 return non-nil."
347 (let ((backup-inhibited t)
348 (buffer-file-name filename)
349 (buffer-file-truename (file-truename filename)))
350 (save-current-buffer
351 (save-restriction
352 (widen)
353 (if (not (file-writable-p buffer-file-name))
354 (prog1 nil
355 (muse-display-warning
356 (format "Cannot write file %s:\n %s" buffer-file-name
357 (let ((dir (file-name-directory buffer-file-name)))
358 (if (not (file-directory-p dir))
359 (if (file-exists-p dir)
360 (format "%s is not a directory" dir)
361 (format "No directory named %s exists" dir))
362 (if (not (file-exists-p buffer-file-name))
363 (format "Directory %s write-protected" dir)
364 "File is write-protected"))))))
365 (let ((coding-system-for-write
366 (or (and (boundp 'save-buffer-coding-system)
367 save-buffer-coding-system)
368 coding-system-for-write)))
369 (write-region (point-min) (point-max) buffer-file-name))
370 (when (boundp 'last-file-coding-system-used)
371 (when (boundp 'buffer-file-coding-system-explicit)
372 (setq buffer-file-coding-system-explicit
373 last-coding-system-used))
374 (if save-buffer-coding-system
375 (setq save-buffer-coding-system last-coding-system-used)
376 (setq buffer-file-coding-system last-coding-system-used)))
377 t)))))
379 (defun muse-collect-alist (list element &optional test)
380 "Collect items from LIST whose car is equal to ELEMENT.
381 If TEST is specified, use it to compare ELEMENT."
382 (unless test (setq test 'equal))
383 (let ((items nil))
384 (dolist (item list)
385 (when (funcall test element (car item))
386 (setq items (cons item items))))
387 items))
389 (defmacro muse-sort-with-closure (list predicate closure)
390 "Sort LIST, stably, comparing elements using PREDICATE.
391 Returns the sorted list. LIST is modified by side effects.
392 PREDICATE is called with two elements of list and CLOSURE.
393 PREDICATE should return non-nil if the first element should sort
394 before the second."
395 `(sort ,list (lambda (a b) (funcall ,predicate a b ,closure))))
397 (put 'muse-sort-with-closure 'lisp-indent-function 0)
398 (put 'muse-sort-with-closure 'edebug-form-spec '(form function-form form))
400 (defun muse-sort-by-rating (rated-list &optional test)
401 "Sort RATED-LIST according to the rating of each element.
402 The rating is stripped out in the returned list.
403 Default sorting is highest-first.
405 If TEST if specified, use it to sort the list. The default test is '>."
406 (unless test (setq test '>))
407 (mapcar (function cdr)
408 (muse-sort-with-closure
409 rated-list
410 (lambda (a b closure)
411 (let ((na (numberp (car a)))
412 (nb (numberp (car b))))
413 (cond ((and na nb) (funcall closure (car a) (car b)))
414 (na (not nb))
415 (t nil))))
416 test)))
418 (defun muse-escape-specials-in-string (specials string &optional reverse)
419 "Apply the transformations in SPECIALS to STRING.
421 The transforms should form a fully reversible and non-ambiguous
422 syntax when STRING is parsed from left to right.
424 If REVERSE is specified, reverse an already-escaped string."
425 (let ((rules (mapcar (lambda (rule)
426 (cons (regexp-quote (if reverse
427 (cdr rule)
428 (car rule)))
429 (if reverse (car rule) (cdr rule))))
430 specials)))
431 (with-temp-buffer
432 (insert string)
433 (goto-char (point-min))
434 (save-match-data
435 (while (not (eobp))
436 (unless (catch 'found
437 (dolist (rule rules)
438 (when (looking-at (car rule))
439 (replace-match (cdr rule) t t)
440 (throw 'found t))))
441 (forward-char))))
442 (buffer-string))))
444 (defun muse-trim-whitespace (string)
445 "Return a version of STRING with no initial nor trailing whitespace."
446 (muse-replace-regexp-in-string
447 (concat "\\`[" muse-regexp-blank "]+\\|[" muse-regexp-blank "]+\\'")
448 "" string))
450 (defun muse-path-sans-extension (path)
451 "Return PATH sans final \"extension\".
453 The extension, in a file name, is the part that follows the last `.',
454 except that a leading `.', if any, doesn't count.
456 This differs from `file-name-sans-extension' in that it will
457 never modify the directory part of the path."
458 (concat (file-name-directory path)
459 (file-name-nondirectory (file-name-sans-extension path))))
461 ;; The following code was extracted from cl
463 (defun muse-const-expr-p (x)
464 (cond ((consp x)
465 (or (eq (car x) 'quote)
466 (and (memq (car x) '(function function*))
467 (or (symbolp (nth 1 x))
468 (and (eq (and (consp (nth 1 x))
469 (car (nth 1 x))) 'lambda) 'func)))))
470 ((symbolp x) (and (memq x '(nil t)) t))
471 (t t)))
473 (put 'muse-assertion-failed 'error-conditions '(error))
474 (put 'muse-assertion-failed 'error-message "Assertion failed")
476 (defun muse-list* (arg &rest rest)
477 "Return a new list with specified args as elements, cons'd to last arg.
478 Thus, `(list* A B C D)' is equivalent to `(nconc (list A B C) D)', or to
479 `(cons A (cons B (cons C D)))'."
480 (cond ((not rest) arg)
481 ((not (cdr rest)) (cons arg (car rest)))
482 (t (let* ((n (length rest))
483 (copy (copy-sequence rest))
484 (last (nthcdr (- n 2) copy)))
485 (setcdr last (car (cdr last)))
486 (cons arg copy)))))
488 (defmacro muse-assert (form &optional show-args string &rest args)
489 "Verify that FORM returns non-nil; signal an error if not.
490 Second arg SHOW-ARGS means to include arguments of FORM in message.
491 Other args STRING and ARGS... are arguments to be passed to `error'.
492 They are not evaluated unless the assertion fails. If STRING is
493 omitted, a default message listing FORM itself is used."
494 (let ((sargs
495 (and show-args
496 (delq nil (mapcar
497 (function
498 (lambda (x)
499 (and (not (muse-const-expr-p x)) x)))
500 (cdr form))))))
501 (list 'progn
502 (list 'or form
503 (if string
504 (muse-list* 'error string (append sargs args))
505 (list 'signal '(quote muse-assertion-failed)
506 (muse-list* 'list (list 'quote form) sargs))))
507 nil)))
509 ;; Compatibility functions
511 (if (fboundp 'looking-back)
512 (defalias 'muse-looking-back 'looking-back)
513 (defun muse-looking-back (regexp &optional limit &rest ignored)
514 (save-excursion
515 (re-search-backward (concat "\\(?:" regexp "\\)\\=") limit t))))
517 (eval-and-compile
518 (if (fboundp 'line-end-position)
519 (defalias 'muse-line-end-position 'line-end-position)
520 (defun muse-line-end-position (&optional n)
521 (save-excursion (end-of-line n) (point))))
523 (if (fboundp 'line-beginning-position)
524 (defalias 'muse-line-beginning-position 'line-beginning-position)
525 (defun muse-line-beginning-position (&optional n)
526 (save-excursion (beginning-of-line n) (point))))
528 (if (fboundp 'match-string-no-properties)
529 (defalias 'muse-match-string-no-properties 'match-string-no-properties)
530 (defun muse-match-string-no-properties (num &optional string)
531 (match-string num string))))
533 (defun muse-replace-regexp-in-string (regexp replacement text &optional fixedcase literal)
534 "Replace REGEXP with REPLACEMENT in TEXT.
536 Return a new string containing the replacements.
538 If fourth arg FIXEDCASE is non-nil, do not alter case of replacement text.
539 If fifth arg LITERAL is non-nil, insert REPLACEMENT literally."
540 (cond
541 ((and (featurep 'xemacs) (fboundp 'replace-in-string))
542 (replace-in-string text regexp replacement literal))
543 ((fboundp 'replace-regexp-in-string)
544 (replace-regexp-in-string regexp replacement text fixedcase literal))
545 (t (error (concat "Neither `replace-in-string' nor "
546 "`replace-regexp-in-string' was found")))))
548 (if (fboundp 'add-to-invisibility-spec)
549 (defalias 'muse-add-to-invisibility-spec 'add-to-invisibility-spec)
550 (defun muse-add-to-invisibility-spec (element)
551 "Add ELEMENT to `buffer-invisibility-spec'.
552 See documentation for `buffer-invisibility-spec' for the kind of elements
553 that can be added."
554 (if (eq buffer-invisibility-spec t)
555 (setq buffer-invisibility-spec (list t)))
556 (setq buffer-invisibility-spec
557 (cons element buffer-invisibility-spec))))
559 (if (fboundp 'read-directory-name)
560 (defalias 'muse-read-directory-name 'read-directory-name)
561 (defun muse-read-directory-name (prompt &optional dir default-dirname mustmatch initial)
562 "Read directory name - see `read-file-name' for details."
563 (unless dir
564 (setq dir default-directory))
565 (read-file-name prompt dir (or default-dirname
566 (if initial (expand-file-name initial dir)
567 dir))
568 mustmatch initial)))
570 (defun muse-file-remote-p (file)
571 "Test whether FILE specifies a location on a remote system.
572 Return non-nil if the location is indeed remote.
574 For example, the filename \"/user@host:/foo\" specifies a location
575 on the system \"/user@host:\"."
576 (cond ((fboundp 'file-remote-p)
577 (file-remote-p file))
578 ((fboundp 'tramp-handle-file-remote-p)
579 (tramp-handle-file-remote-p file))
580 ((and (boundp 'ange-ftp-name-format)
581 (string-match (car ange-ftp-name-format) file))
583 (t nil)))
585 (if (fboundp 'delete-and-extract-region)
586 (defalias 'muse-delete-and-extract-region 'delete-and-extract-region)
587 (defun muse-delete-and-extract-region (start end)
588 "Delete the text between START and END and return it."
589 (prog1 (buffer-substring start end)
590 (delete-region start end))))
592 ;; Set face globally in a predictable fashion
593 (defun muse-copy-face (old new)
594 "Copy face OLD to NEW."
595 (if (featurep 'xemacs)
596 (copy-face old new 'all)
597 (copy-face old new)))
599 ;; Widget compatibility functions
601 (defun muse-widget-type-value-create (widget)
602 "Convert and instantiate the value of the :type attribute of WIDGET.
603 Store the newly created widget in the :children attribute.
605 The value of the :type attribute should be an unconverted widget type."
606 (let ((value (widget-get widget :value))
607 (type (widget-get widget :type)))
608 (widget-put widget :children
609 (list (widget-create-child-value widget
610 (widget-convert type)
611 value)))))
613 (defun muse-widget-child-value-get (widget)
614 "Get the value of the first member of :children in WIDGET."
615 (widget-value (car (widget-get widget :children))))
617 (defun muse-widget-type-match (widget value)
618 "Non-nil if the :type value of WIDGET matches VALUE.
620 The value of the :type attribute should be an unconverted widget type."
621 (widget-apply (widget-convert (widget-get widget :type)) :match value))
623 ;; Link-handling functions and variables
625 (defun muse-get-link (&optional target)
626 "Based on the match data, retrieve the link.
627 Use TARGET to get the string, if it is specified."
628 (muse-match-string-no-properties 1 target))
630 (defun muse-get-link-desc (&optional target)
631 "Based on the match data, retrieve the link description.
632 Use TARGET to get the string, if it is specified."
633 (muse-match-string-no-properties 2 target))
635 (defvar muse-link-specials
636 '(("[" . "%5B")
637 ("]" . "%5D")
638 ("%" . "%%"))
639 "Syntax used for escaping and unescaping links.
640 This allows brackets to occur in explicit links as long as you
641 use the standard Muse functions to create them.")
643 (defun muse-link-escape (text)
644 "Escape characters in TEXT that conflict with the explicit link
645 regexp."
646 (when (stringp text)
647 (muse-escape-specials-in-string muse-link-specials text)))
649 (defun muse-link-unescape (text)
650 "Un-escape characters in TEXT that conflict with the explicit
651 link regexp."
652 (when (stringp text)
653 (muse-escape-specials-in-string muse-link-specials text t)))
655 (defun muse-handle-url (&optional string)
656 "If STRING or point has a URL, match and return it."
657 (if (if string (string-match muse-url-regexp string)
658 (looking-at muse-url-regexp))
659 (match-string 0 string)))
661 (defcustom muse-implicit-link-functions '(muse-handle-url)
662 "A list of functions to handle an implicit link.
663 An implicit link is one that is not surrounded by brackets.
665 By default, Muse handles URLs only.
666 If you want to handle WikiWords, load muse-wiki.el."
667 :type 'hook
668 :options '(muse-handle-url)
669 :group 'muse)
671 (defun muse-handle-implicit-link (&optional link)
672 "Handle implicit links. If LINK is not specified, look at point.
673 An implicit link is one that is not surrounded by brackets.
674 By default, Muse handles URLs only.
675 If you want to handle WikiWords, load muse-wiki.el.
677 This function modifies the match data so that match 0 is the
678 link.
680 The match data is restored after each unsuccessful handler
681 function call. If LINK is specified, only restore at very end.
683 This behavior is needed because the part of the buffer that
684 `muse-implicit-link-regexp' matches must be narrowed to the part
685 that is an accepted link."
686 (let ((funcs muse-implicit-link-functions)
687 (res nil)
688 (data (match-data t)))
689 (while funcs
690 (setq res (funcall (car funcs) link))
691 (if res
692 (setq funcs nil)
693 (unless link (set-match-data data))
694 (setq funcs (cdr funcs))))
695 (when link (set-match-data data))
696 res))
698 (defcustom muse-explicit-link-functions nil
699 "A list of functions to handle an explicit link.
700 An explicit link is one [[like][this]] or [[this]]."
701 :type 'hook
702 :group 'muse)
704 (defun muse-handle-explicit-link (&optional link)
705 "Handle explicit links. If LINK is not specified, look at point.
706 An explicit link is one that looks [[like][this]] or [[this]].
708 The match data is preserved. If no handlers are able to process
709 LINK, return LINK (if specified) or the 1st match string. If
710 LINK is not specified, it is assumed that Muse has matched
711 against `muse-explicit-link-regexp' before calling this
712 function."
713 (let ((funcs muse-explicit-link-functions)
714 (res nil))
715 (save-match-data
716 (while funcs
717 (setq res (funcall (car funcs) link))
718 (if res
719 (setq funcs nil)
720 (setq funcs (cdr funcs)))))
721 (muse-link-unescape
722 (if res
724 (or link (muse-get-link))))))
726 ;; Movement functions
728 (defun muse-list-item-type (str)
729 "Determine the type of list given STR.
730 Returns either 'ul, 'ol, 'dl-term, 'dl-entry, or nil."
731 (save-match-data
732 (cond ((or (string= str "")
733 (< (length str) 2))
734 nil)
735 ((string-match muse-dl-entry-regexp str)
736 'dl-entry)
737 ((string-match muse-dl-term-regexp str)
738 'dl-term)
739 ((string-match muse-ol-item-regexp str)
740 'ol)
741 ((string-match muse-ul-item-regexp str)
742 'ul)
743 (t nil))))
745 (defun muse-list-item-critical-point (&optional offset)
746 "Figure out where the important markup character for the
747 currently-matched list item is.
749 If OFFSET is specified, it is the number of groupings outside of
750 the contents of `muse-list-item-regexp'."
751 (unless offset (setq offset 0))
752 (if (match-end (+ offset 2))
753 ;; at a definition list
754 (match-end (+ offset 2))
755 ;; at a different kind of list
756 (match-beginning (+ offset 1))))
758 (defun muse-forward-paragraph (&optional pattern)
759 "Move forward safely by one paragraph, or according to PATTERN."
760 (when (get-text-property (point) 'end-list)
761 (goto-char (next-single-property-change (point) 'end-list)))
762 (setq pattern (if pattern
763 (concat "^\\(?:" pattern "\\|\n\\|\\'\\)")
764 "^\\s-*\\(\n\\|\\'\\)"))
765 (let ((next-list-end (or (next-single-property-change (point) 'end-list)
766 (point-max))))
767 (forward-line 1)
768 (if (re-search-forward pattern nil t)
769 (goto-char (match-beginning 0))
770 (goto-char (point-max)))
771 (when (> (point) next-list-end)
772 (goto-char next-list-end))))
774 (defun muse-forward-list-item-1 (type empty-line indented-line)
775 "Determine whether a nested list item is after point."
776 (if (match-beginning 1)
777 ;; if we are given a dl entry, skip past everything on the same
778 ;; level, except for other dl entries
779 (and (eq type 'dl-entry)
780 (not (eq (char-after (match-beginning 2)) ?\:)))
781 ;; blank line encountered with no list item on the same
782 ;; level after it
783 (let ((beg (point)))
784 (forward-line 1)
785 (if (save-match-data
786 (and (looking-at indented-line)
787 (not (looking-at empty-line))))
788 ;; found that this blank line is followed by some
789 ;; indentation, plus other text, so we'll keep
790 ;; going
792 (goto-char beg)
793 nil))))
795 (defun muse-forward-list-item (type indent &optional no-skip-nested)
796 "Move forward to the next item of TYPE.
797 Return non-nil if successful, nil otherwise.
798 The beginning indentation is given by INDENT.
800 If NO-SKIP-NESTED is non-nil, do not skip past nested items.
801 Note that if you desire this behavior, you will also need to
802 provide a very liberal INDENT value, such as
803 \(concat \"[\" muse-regexp-blank \"]*\")."
804 (let* ((list-item (format muse-list-item-regexp indent))
805 (empty-line (concat "^[" muse-regexp-blank "]*\n"))
806 (indented-line (concat "^" indent "[" muse-regexp-blank "]"))
807 (list-pattern (concat "\\(?:" empty-line "\\)?"
808 "\\(" list-item "\\)")))
809 (while (progn
810 (muse-forward-paragraph list-pattern)
811 ;; make sure we don't go past boundary
812 (and (not (or (get-text-property (point) 'end-list)
813 (>= (point) (point-max))))
814 ;; move past markup that is part of another construct
815 (or (and (match-beginning 1)
816 (or (get-text-property
817 (muse-list-item-critical-point 1) 'muse-link)
818 (and (derived-mode-p 'muse-mode)
819 (get-text-property
820 (muse-list-item-critical-point 1)
821 'face))))
822 ;; skip nested items
823 (and (not no-skip-nested)
824 (muse-forward-list-item-1 type empty-line
825 indented-line))))))
826 (cond ((or (get-text-property (point) 'end-list)
827 (>= (point) (point-max)))
828 ;; at a list boundary, so stop
829 nil)
830 ((let ((str (when (match-beginning 2)
831 ;; get the entire line
832 (save-excursion
833 (goto-char (match-beginning 2))
834 (buffer-substring (muse-line-beginning-position)
835 (muse-line-end-position))))))
836 (and str (eq type (muse-list-item-type str))))
837 ;; same type, so indicate that there are more items to be
838 ;; parsed
839 (goto-char (match-beginning 1)))
841 (when (match-beginning 1)
842 (goto-char (match-beginning 1)))
843 ;; move to just before foreign list item markup
844 nil))))
846 (defun muse-goto-tag-end (tag nested)
847 "Move forward past the end of TAG.
849 If NESTED is non-nil, look for other instances of this tag that
850 may be nested inside of this tag, and skip past them."
851 (if (not nested)
852 (search-forward (concat "</" tag ">") nil t)
853 (let ((nesting 1)
854 (tag-regexp (concat "\\(<\\(/?\\)" tag "\\([ >]\\)\\)"))
855 (match-found nil))
856 (while (and (> nesting 0)
857 (setq match-found (re-search-forward tag-regexp nil t)))
858 ;; for the sake of font-locking code, skip matches in comments
859 (unless (get-text-property (match-beginning 0) 'muse-comment)
860 (if (string-equal (match-string 2) "/")
861 (and (string-equal (match-string 3) ">")
862 (setq nesting (1- nesting)))
863 (setq nesting (1+ nesting)))))
864 match-found)))
866 ;;; muse.el ends here