]> code.delx.au - gnu-emacs/blob - lisp/textmodes/enriched.el
Add 2012 to FSF copyright years for Emacs files
[gnu-emacs] / lisp / textmodes / enriched.el
1 ;;; enriched.el --- read and save files in text/enriched format
2
3 ;; Copyright (C) 1994-1996, 2001-2012 Free Software Foundation, Inc.
4
5 ;; Author: Boris Goldowsky <boris@gnu.org>
6 ;; Keywords: wp, faces
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This file implements reading, editing, and saving files with
26 ;; text-properties such as faces, levels of indentation, and true line
27 ;; breaks distinguished from newlines just used to fit text into the window.
28
29 ;; The file format used is the MIME text/enriched format, which is a
30 ;; standard format defined in internet RFC 1563. All standard annotations
31 ;; are supported except for <smaller> and <bigger>, which are currently not
32 ;; possible to display.
33
34 ;; A separate file, enriched.doc, contains further documentation and other
35 ;; important information about this code. It also serves as an example
36 ;; file in text/enriched format. It should be in the etc directory of your
37 ;; emacs distribution.
38
39 ;;; Code:
40
41 (provide 'enriched)
42
43 ;;;
44 ;;; Variables controlling the display
45 ;;;
46
47 (defgroup enriched nil
48 "Read and save files in text/enriched format."
49 :group 'wp)
50
51 (defcustom enriched-verbose t
52 "If non-nil, give status messages when reading and writing files."
53 :type 'boolean
54 :group 'enriched)
55
56 ;;;
57 ;;; Set up faces & display table
58 ;;;
59
60 ;; Emacs doesn't have a "fixed" face by default, since all faces currently
61 ;; have to be fixed-width. So we just pick one that looks different from the
62 ;; default.
63 (defface fixed
64 '((t (:weight bold)))
65 "Face used for text that must be shown in fixed width.
66 Currently, Emacs can only display fixed-width fonts, but this may change.
67 This face is used for text specifically marked as fixed-width, for example
68 in text/enriched files."
69 :group 'enriched)
70
71 (defface excerpt
72 '((t (:slant italic)))
73 "Face used for text that is an excerpt from another document.
74 This is used in Enriched mode for text explicitly marked as an excerpt."
75 :group 'enriched)
76
77 (defconst enriched-display-table (or (copy-sequence standard-display-table)
78 (make-display-table)))
79 (aset enriched-display-table ?\f (make-vector (1- (frame-width)) ?-))
80
81 (defconst enriched-par-props '(left-margin right-margin justification)
82 "Text-properties that usually apply to whole paragraphs.
83 These are set front-sticky everywhere except at hard newlines.")
84
85 ;;;
86 ;;; Variables controlling the file format
87 ;;; (bidirectional)
88
89 (defconst enriched-initial-annotation
90 (lambda ()
91 (format "Content-Type: text/enriched\nText-Width: %d\n\n"
92 fill-column))
93 "What to insert at the start of a text/enriched file.
94 If this is a string, it is inserted. If it is a list, it should be a lambda
95 expression, which is evaluated to get the string to insert.")
96
97 (defconst enriched-annotation-format "<%s%s>"
98 "General format of enriched-text annotations.")
99
100 (defconst enriched-annotation-regexp "<\\(/\\)?\\([-A-Za-z0-9]+\\)>"
101 "Regular expression matching enriched-text annotations.")
102
103 (defvar enriched-translations
104 '((face (bold-italic "bold" "italic")
105 (bold "bold")
106 (italic "italic")
107 (underline "underline")
108 (fixed "fixed")
109 (excerpt "excerpt")
110 (default )
111 (nil enriched-encode-other-face))
112 (left-margin (4 "indent"))
113 (right-margin (4 "indentright"))
114 (justification (none "nofill")
115 (right "flushright")
116 (left "flushleft")
117 (full "flushboth")
118 (center "center"))
119 (PARAMETER (t "param")) ; Argument of preceding annotation
120 ;; The following are not part of the standard:
121 (FUNCTION (enriched-decode-foreground "x-color")
122 (enriched-decode-background "x-bg-color")
123 (enriched-decode-display-prop "x-display"))
124 (read-only (t "x-read-only"))
125 (display (nil enriched-handle-display-prop))
126 (unknown (nil format-annotate-value))
127 ; (font-size (2 "bigger") ; unimplemented
128 ; (-2 "smaller"))
129 )
130 "List of definitions of text/enriched annotations.
131 See `format-annotate-region' and `format-deannotate-region' for the definition
132 of this structure.")
133
134 (defconst enriched-ignore
135 '(front-sticky rear-nonsticky hard)
136 "Properties that are OK to ignore when saving text/enriched files.
137 Any property that is neither on this list nor dealt with by
138 `enriched-translations' will generate a warning.")
139
140 ;;; Internal variables
141
142 (defcustom enriched-mode-hook nil
143 "Hook run after entering/leaving Enriched mode.
144 If you set variables in this hook, you should arrange for them to be restored
145 to their old values if you leave Enriched mode. One way to do this is to add
146 them and their old values to `enriched-old-bindings'."
147 :type 'hook
148 :group 'enriched)
149
150 (defvar enriched-old-bindings nil
151 "Store old variable values that we change when entering mode.
152 The value is a list of \(VAR VALUE VAR VALUE...).")
153 (make-variable-buffer-local 'enriched-old-bindings)
154
155 ;; The next variable is buffer local if and only if Enriched mode is
156 ;; enabled. The buffer local value records whether
157 ;; `default-text-properties' should remain buffer local when disabling
158 ;; Enriched mode. For technical reasons, the default value should be t.
159 (defvar enriched-default-text-properties-local-flag t)
160
161 ;; Technical internal variable. Bound to t if `enriched-mode' is
162 ;; being rerun by a major mode to allow it to restore buffer-local
163 ;; variables and to correctly update `enriched-old-bindings'.
164 (defvar enriched-rerun-flag nil)
165
166 ;;;
167 ;;; Keybindings
168 ;;;
169
170 (defvar enriched-mode-map
171 (let ((map (make-sparse-keymap)))
172 (define-key map [remap move-beginning-of-line] 'beginning-of-line-text)
173 (define-key map "\C-m" 'reindent-then-newline-and-indent)
174 (define-key map
175 [remap newline-and-indent] 'reindent-then-newline-and-indent)
176 (define-key map "\M-j" 'facemenu-justification-menu)
177 (define-key map "\M-S" 'set-justification-center)
178 (define-key map "\C-x\t" 'increase-left-margin)
179 (define-key map "\C-c[" 'set-left-margin)
180 (define-key map "\C-c]" 'set-right-margin)
181 map)
182 "Keymap for Enriched mode.")
183
184 ;;;
185 ;;; Define the mode
186 ;;;
187
188 (put 'enriched-mode 'permanent-local t)
189 ;;;###autoload
190 (define-minor-mode enriched-mode
191 "Minor mode for editing text/enriched files.
192 These are files with embedded formatting information in the MIME standard
193 text/enriched format.
194 Turning the mode on or off runs `enriched-mode-hook'.
195
196 More information about Enriched mode is available in the file
197 etc/enriched.doc in the Emacs distribution directory.
198
199 Commands:
200
201 \\{enriched-mode-map}"
202 :group 'enriched :lighter " Enriched"
203 (cond ((null enriched-mode)
204 ;; Turn mode off
205 (remove-hook 'change-major-mode-hook
206 'enriched-before-change-major-mode 'local)
207 (setq buffer-file-format (delq 'text/enriched buffer-file-format))
208 ;; restore old variable values
209 (while enriched-old-bindings
210 (set (pop enriched-old-bindings) (pop enriched-old-bindings)))
211 (unless enriched-default-text-properties-local-flag
212 (kill-local-variable 'default-text-properties))
213 (kill-local-variable 'enriched-default-text-properties-local-flag)
214 (unless use-hard-newlines (use-hard-newlines 0)))
215
216 ((and (memq 'text/enriched buffer-file-format)
217 (not enriched-rerun-flag))
218 ;; Mode already on; do nothing.
219 nil)
220
221 (t ; Turn mode on
222 (add-hook 'change-major-mode-hook
223 'enriched-before-change-major-mode nil 'local)
224 (add-to-list 'buffer-file-format 'text/enriched)
225 ;; Save old variable values before we change them.
226 ;; These will be restored if we exit Enriched mode.
227 (setq enriched-old-bindings
228 (list 'buffer-display-table buffer-display-table
229 'default-text-properties default-text-properties
230 'use-hard-newlines use-hard-newlines))
231 (make-local-variable 'enriched-default-text-properties-local-flag)
232 (setq enriched-default-text-properties-local-flag
233 (local-variable-p 'default-text-properties))
234 (make-local-variable 'default-text-properties)
235 (setq buffer-display-table enriched-display-table)
236 (use-hard-newlines 1 (if enriched-rerun-flag 'never nil))
237 (let ((sticky (plist-get default-text-properties 'front-sticky))
238 (p enriched-par-props))
239 (dolist (x p)
240 (add-to-list 'sticky x))
241 (if sticky
242 (setq default-text-properties
243 (plist-put default-text-properties
244 'front-sticky sticky)))))))
245
246 (defun enriched-before-change-major-mode ()
247 (when enriched-mode
248 (while enriched-old-bindings
249 (set (pop enriched-old-bindings) (pop enriched-old-bindings)))))
250
251 (defun enriched-after-change-major-mode ()
252 (when enriched-mode
253 (let ((enriched-rerun-flag t))
254 (enriched-mode 1))))
255
256 (add-hook 'after-change-major-mode-hook 'enriched-after-change-major-mode)
257
258
259 (fset 'enriched-mode-map enriched-mode-map)
260
261 ;;;
262 ;;; Some functions dealing with text-properties, especially indentation
263 ;;;
264
265 (defun enriched-map-property-regions (prop func &optional from to)
266 "Apply a function to regions of the buffer based on a text property.
267 For each contiguous region of the buffer for which the value of PROPERTY is
268 eq, the FUNCTION will be called. Optional arguments FROM and TO specify the
269 region over which to scan.
270
271 The specified function receives three arguments: the VALUE of the property in
272 the region, and the START and END of each region."
273 (save-excursion
274 (save-restriction
275 (if to (narrow-to-region (point-min) to))
276 (goto-char (or from (point-min)))
277 (let ((begin (point))
278 end
279 (marker (make-marker))
280 (val (get-text-property (point) prop)))
281 (while (setq end (text-property-not-all begin (point-max) prop val))
282 (move-marker marker end)
283 (funcall func val begin (marker-position marker))
284 (setq begin (marker-position marker)
285 val (get-text-property marker prop)))
286 (if (< begin (point-max))
287 (funcall func val begin (point-max)))))))
288
289 (put 'enriched-map-property-regions 'lisp-indent-hook 1)
290
291 (defun enriched-insert-indentation (&optional from to)
292 "Indent and justify each line in the region."
293 (save-excursion
294 (save-restriction
295 (if to (narrow-to-region (point-min) to))
296 (goto-char (or from (point-min)))
297 (if (not (bolp)) (forward-line 1))
298 (while (not (eobp))
299 (if (eolp)
300 nil ; skip blank lines
301 (indent-to (current-left-margin))
302 (justify-current-line t nil t))
303 (forward-line 1)))))
304
305 ;;;
306 ;;; Encoding Files
307 ;;;
308
309 ;;;###autoload
310 (defun enriched-encode (from to orig-buf)
311 (if enriched-verbose (message "Enriched: encoding document..."))
312 (let ((inhibit-read-only t))
313 (save-restriction
314 (narrow-to-region from to)
315 (delete-to-left-margin)
316 (unjustify-region)
317 (goto-char from)
318 (format-replace-strings '(("<" . "<<")))
319 (format-insert-annotations
320 (format-annotate-region from (point-max) enriched-translations
321 'enriched-make-annotation enriched-ignore))
322 (goto-char from)
323 (insert (if (stringp enriched-initial-annotation)
324 enriched-initial-annotation
325 (save-excursion
326 ;; Eval this in the buffer we are annotating. This
327 ;; fixes a bug which was saving incorrect File-Width
328 ;; information, since we were looking at local
329 ;; variables in the wrong buffer.
330 (if orig-buf (set-buffer orig-buf))
331 (funcall enriched-initial-annotation))))
332 (enriched-map-property-regions 'hard
333 (lambda (v b e)
334 (if (and v (= ?\n (char-after b)))
335 (progn (goto-char b) (insert "\n"))))
336 (point) nil)
337 (if enriched-verbose (message nil))
338 ;; Return new end.
339 (point-max))))
340
341 (defun enriched-make-annotation (internal-ann positive)
342 "Format an annotation INTERNAL-ANN.
343 INTERNAL-ANN may be a string, for a flag, or a list of the form (PARAM VALUE).
344 If POSITIVE is non-nil, this is the opening annotation;
345 if nil, the matching close."
346 (cond ((stringp internal-ann)
347 (format enriched-annotation-format (if positive "" "/") internal-ann))
348 ;; Otherwise it is an annotation with parameters, represented as a list
349 (positive
350 (let ((item (car internal-ann))
351 (params (cdr internal-ann)))
352 (concat (format enriched-annotation-format "" item)
353 (mapconcat (lambda (i) (concat "<param>" i "</param>"))
354 params ""))))
355 (t (format enriched-annotation-format "/" (car internal-ann)))))
356
357 (defun enriched-encode-other-face (old new)
358 "Generate annotations for random face change.
359 One annotation each for foreground color, background color, italic, etc."
360 (cons (and old (enriched-face-ans old))
361 (and new (enriched-face-ans new))))
362
363 (defun enriched-face-ans (face)
364 "Return annotations specifying FACE.
365 FACE may be a list of faces instead of a single face;
366 it can also be anything allowed as an element of a list
367 which can be the value of the `face' text property."
368 (cond ((and (consp face) (eq (car face) 'foreground-color))
369 (list (list "x-color" (cdr face))))
370 ((and (consp face) (eq (car face) 'background-color))
371 (list (list "x-bg-color" (cdr face))))
372 ((and (listp face) (eq (car face) :foreground))
373 (list (list "x-color" (cadr face))))
374 ((and (listp face) (eq (car face) :background))
375 (list (list "x-bg-color" (cadr face))))
376 ((listp face)
377 (apply 'append (mapcar 'enriched-face-ans face)))
378 ((let* ((fg (face-attribute face :foreground))
379 (bg (face-attribute face :background))
380 (props (face-font face t))
381 (ans (cdr (format-annotate-single-property-change
382 'face nil props enriched-translations))))
383 (unless (eq fg 'unspecified)
384 (setq ans (cons (list "x-color" fg) ans)))
385 (unless (eq bg 'unspecified)
386 (setq ans (cons (list "x-bg-color" bg) ans)))
387 ans))))
388
389 ;;;
390 ;;; Decoding files
391 ;;;
392
393 ;;;###autoload
394 (defun enriched-decode (from to)
395 (if enriched-verbose (message "Enriched: decoding document..."))
396 (use-hard-newlines 1 'never)
397 (save-excursion
398 (save-restriction
399 (narrow-to-region from to)
400 (goto-char from)
401
402 ;; Deal with header
403 (let ((file-width (enriched-get-file-width)))
404 (enriched-remove-header)
405
406 ;; Deal with newlines
407 (while (search-forward-regexp "\n\n+" nil t)
408 (if (current-justification)
409 (delete-char -1))
410 (set-hard-newline-properties (match-beginning 0) (point)))
411
412 ;; Translate annotations
413 (format-deannotate-region from (point-max) enriched-translations
414 'enriched-next-annotation)
415
416 ;; Indent or fill the buffer
417 (cond (file-width ; File was filled to this width
418 (setq fill-column file-width)
419 (if enriched-verbose (message "Indenting..."))
420 (enriched-insert-indentation))
421 (t ; File was not filled.
422 (if enriched-verbose (message "Filling paragraphs..."))
423 (fill-region (point-min) (point-max))))
424 (if enriched-verbose (message nil)))
425 (point-max))))
426
427 (defun enriched-next-annotation ()
428 "Find and return next text/enriched annotation.
429 Any \"<<\" strings encountered are converted to \"<\".
430 Return value is \(begin end name positive-p), or nil if none was found."
431 (while (and (search-forward "<" nil 1)
432 (progn (goto-char (match-beginning 0))
433 (not (looking-at enriched-annotation-regexp))))
434 (forward-char 1)
435 (if (= ?< (char-after (point)))
436 (delete-char 1)
437 ;; A single < that does not start an annotation is an error,
438 ;; which we note and then ignore.
439 (message "Warning: malformed annotation in file at %s"
440 (1- (point)))))
441 (if (not (eobp))
442 (let* ((beg (match-beginning 0))
443 (end (match-end 0))
444 (name (downcase (buffer-substring
445 (match-beginning 2) (match-end 2))))
446 (pos (not (match-beginning 1))))
447 (list beg end name pos))))
448
449 (defun enriched-get-file-width ()
450 "Look for file width information on this line."
451 (save-excursion
452 (if (search-forward "Text-Width: " (+ (point) 1000) t)
453 (read (current-buffer)))))
454
455 (defun enriched-remove-header ()
456 "Remove file-format header at point."
457 (while (looking-at "^[-A-Za-z]+: .*\n")
458 (delete-region (point) (match-end 0)))
459 (if (looking-at "^\n")
460 (delete-char 1)))
461
462 (defun enriched-decode-foreground (from to &optional color)
463 (if color
464 (list from to 'face (list ':foreground color))
465 (message "Warning: no color specified for <x-color>")
466 nil))
467
468 (defun enriched-decode-background (from to &optional color)
469 (if color
470 (list from to 'face (list ':background color))
471 (message "Warning: no color specified for <x-bg-color>")
472 nil))
473 \f
474 ;;; Handling the `display' property.
475
476
477 (defun enriched-handle-display-prop (old new)
478 "Return a list of annotations for a change in the `display' property.
479 OLD is the old value of the property, NEW is the new value. Value
480 is a list `(CLOSE OPEN)', where CLOSE is a list of annotations to
481 close and OPEN a list of annotations to open. Each of these lists
482 has the form `(ANNOTATION PARAM ...)'."
483 (let ((annotation "x-display")
484 (param (prin1-to-string (or old new))))
485 (if (null old)
486 (cons nil (list (list annotation param)))
487 (cons (list (list annotation param)) nil))))
488
489 (defun enriched-decode-display-prop (start end &optional param)
490 "Decode a `display' property for text between START and END.
491 PARAM is a `<param>' found for the property.
492 Value is a list `(START END SYMBOL VALUE)' with START and END denoting
493 the range of text to assign text property SYMBOL with value VALUE."
494 (let ((prop (when (stringp param)
495 (condition-case ()
496 (car (read-from-string param))
497 (error nil)))))
498 (unless prop
499 (message "Warning: invalid <x-display> parameter %s" param))
500 (list start end 'display prop)))
501
502 ;;; enriched.el ends here