More tweaks of skeleton documentation wrt \n behavior at bol/eol.
[bpt/emacs.git] / lisp / textmodes / enriched.el
CommitLineData
5e046f6d
JB
1;;; enriched.el --- read and save files in text/enriched format
2
ba318903 3;; Copyright (C) 1994-1996, 2001-2014 Free Software Foundation, Inc.
5e046f6d
JB
4
5;; Author: Boris Goldowsky <boris@gnu.org>
6;; Keywords: wp, faces
7
8;; This file is part of GNU Emacs.
9
1fecc8fe 10;; GNU Emacs is free software: you can redistribute it and/or modify
5e046f6d 11;; it under the terms of the GNU General Public License as published by
1fecc8fe
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
5e046f6d
JB
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
1fecc8fe 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
5e046f6d
JB
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
92f78ea3 34;; A separate file, enriched.txt, contains further documentation and other
5e046f6d
JB
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
c0a664d5 48 "Read and save files in text/enriched format."
5e046f6d
JB
49 :group 'wp)
50
51(defcustom enriched-verbose t
1fc7dabf 52 "If non-nil, give status messages when reading and writing files."
5e046f6d
JB
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.
403c7339 66Currently, Emacs can only display fixed-width fonts, but this may change.
5e046f6d
JB
67This face is used for text specifically marked as fixed-width, for example
68in 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.
74This 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.
83These 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.
94If this is a string, it is inserted. If it is a list, it should be a lambda
95expression, 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
e2577410 103(defvar enriched-translations
5e046f6d
JB
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.
131See `format-annotate-region' and `format-deannotate-region' for the definition
132of 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.
137Any property that is neither on this list nor dealt with by
138`enriched-translations' will generate a warning.")
139
140;;; Internal variables
141
5e046f6d
JB
142(defcustom enriched-mode-hook nil
143 "Hook run after entering/leaving Enriched mode.
144If you set variables in this hook, you should arrange for them to be restored
145to their old values if you leave Enriched mode. One way to do this is to add
146them 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.
152The value is a list of \(VAR VALUE VAR VALUE...).")
153(make-variable-buffer-local 'enriched-old-bindings)
154
998733b3
LT
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
609ee2ff
LT
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
b016851c
SM
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
5e046f6d
JB
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.
192These are files with embedded formatting information in the MIME standard
193text/enriched format.
e1ac4066
GM
194
195With a prefix argument ARG, enable the mode if ARG is positive,
196and disable it otherwise. If called from Lisp, enable the mode
197if ARG is omitted or nil.
198
998733b3 199Turning the mode on or off runs `enriched-mode-hook'.
5e046f6d
JB
200
201More information about Enriched mode is available in the file
92f78ea3 202\"enriched.txt\" in `data-directory'.
5e046f6d
JB
203
204Commands:
205
206\\{enriched-mode-map}"
fb1668f9 207 :group 'enriched :lighter " Enriched"
5e046f6d
JB
208 (cond ((null enriched-mode)
209 ;; Turn mode off
b016851c
SM
210 (remove-hook 'change-major-mode-hook
211 'enriched-before-change-major-mode 'local)
5e046f6d
JB
212 (setq buffer-file-format (delq 'text/enriched buffer-file-format))
213 ;; restore old variable values
214 (while enriched-old-bindings
998733b3
LT
215 (set (pop enriched-old-bindings) (pop enriched-old-bindings)))
216 (unless enriched-default-text-properties-local-flag
217 (kill-local-variable 'default-text-properties))
218 (kill-local-variable 'enriched-default-text-properties-local-flag)
219 (unless use-hard-newlines (use-hard-newlines 0)))
5e046f6d 220
609ee2ff
LT
221 ((and (memq 'text/enriched buffer-file-format)
222 (not enriched-rerun-flag))
5e046f6d
JB
223 ;; Mode already on; do nothing.
224 nil)
225
226 (t ; Turn mode on
b016851c
SM
227 (add-hook 'change-major-mode-hook
228 'enriched-before-change-major-mode nil 'local)
609ee2ff 229 (add-to-list 'buffer-file-format 'text/enriched)
5e046f6d
JB
230 ;; Save old variable values before we change them.
231 ;; These will be restored if we exit Enriched mode.
232 (setq enriched-old-bindings
233 (list 'buffer-display-table buffer-display-table
998733b3
LT
234 'default-text-properties default-text-properties
235 'use-hard-newlines use-hard-newlines))
236 (make-local-variable 'enriched-default-text-properties-local-flag)
237 (setq enriched-default-text-properties-local-flag
238 (local-variable-p 'default-text-properties))
5e046f6d 239 (make-local-variable 'default-text-properties)
609ee2ff
LT
240 (setq buffer-display-table enriched-display-table)
241 (use-hard-newlines 1 (if enriched-rerun-flag 'never nil))
5e046f6d
JB
242 (let ((sticky (plist-get default-text-properties 'front-sticky))
243 (p enriched-par-props))
244 (dolist (x p)
245 (add-to-list 'sticky x))
246 (if sticky
247 (setq default-text-properties
248 (plist-put default-text-properties
249 'front-sticky sticky)))))))
250
609ee2ff
LT
251(defun enriched-before-change-major-mode ()
252 (when enriched-mode
253 (while enriched-old-bindings
254 (set (pop enriched-old-bindings) (pop enriched-old-bindings)))))
255
609ee2ff
LT
256(defun enriched-after-change-major-mode ()
257 (when enriched-mode
258 (let ((enriched-rerun-flag t))
259 (enriched-mode 1))))
260
261(add-hook 'after-change-major-mode-hook 'enriched-after-change-major-mode)
262
5e046f6d 263
b016851c 264(fset 'enriched-mode-map enriched-mode-map)
5e046f6d
JB
265
266;;;
267;;; Some functions dealing with text-properties, especially indentation
268;;;
269
270(defun enriched-map-property-regions (prop func &optional from to)
271 "Apply a function to regions of the buffer based on a text property.
272For each contiguous region of the buffer for which the value of PROPERTY is
273eq, the FUNCTION will be called. Optional arguments FROM and TO specify the
274region over which to scan.
275
276The specified function receives three arguments: the VALUE of the property in
277the region, and the START and END of each region."
278 (save-excursion
279 (save-restriction
280 (if to (narrow-to-region (point-min) to))
281 (goto-char (or from (point-min)))
282 (let ((begin (point))
283 end
284 (marker (make-marker))
285 (val (get-text-property (point) prop)))
286 (while (setq end (text-property-not-all begin (point-max) prop val))
287 (move-marker marker end)
288 (funcall func val begin (marker-position marker))
289 (setq begin (marker-position marker)
290 val (get-text-property marker prop)))
291 (if (< begin (point-max))
292 (funcall func val begin (point-max)))))))
293
294(put 'enriched-map-property-regions 'lisp-indent-hook 1)
295
296(defun enriched-insert-indentation (&optional from to)
297 "Indent and justify each line in the region."
298 (save-excursion
299 (save-restriction
300 (if to (narrow-to-region (point-min) to))
301 (goto-char (or from (point-min)))
302 (if (not (bolp)) (forward-line 1))
303 (while (not (eobp))
304 (if (eolp)
305 nil ; skip blank lines
306 (indent-to (current-left-margin))
307 (justify-current-line t nil t))
308 (forward-line 1)))))
309
310;;;
311;;; Encoding Files
312;;;
313
314;;;###autoload
315(defun enriched-encode (from to orig-buf)
316 (if enriched-verbose (message "Enriched: encoding document..."))
30f0bc33
RS
317 (let ((inhibit-read-only t))
318 (save-restriction
319 (narrow-to-region from to)
320 (delete-to-left-margin)
321 (unjustify-region)
322 (goto-char from)
323 (format-replace-strings '(("<" . "<<")))
324 (format-insert-annotations
325 (format-annotate-region from (point-max) enriched-translations
326 'enriched-make-annotation enriched-ignore))
327 (goto-char from)
328 (insert (if (stringp enriched-initial-annotation)
329 enriched-initial-annotation
330 (save-excursion
331 ;; Eval this in the buffer we are annotating. This
332 ;; fixes a bug which was saving incorrect File-Width
333 ;; information, since we were looking at local
334 ;; variables in the wrong buffer.
335 (if orig-buf (set-buffer orig-buf))
336 (funcall enriched-initial-annotation))))
337 (enriched-map-property-regions 'hard
338 (lambda (v b e)
339 (if (and v (= ?\n (char-after b)))
340 (progn (goto-char b) (insert "\n"))))
341 (point) nil)
342 (if enriched-verbose (message nil))
343 ;; Return new end.
344 (point-max))))
5e046f6d
JB
345
346(defun enriched-make-annotation (internal-ann positive)
347 "Format an annotation INTERNAL-ANN.
348INTERNAL-ANN may be a string, for a flag, or a list of the form (PARAM VALUE).
349If POSITIVE is non-nil, this is the opening annotation;
350if nil, the matching close."
351 (cond ((stringp internal-ann)
352 (format enriched-annotation-format (if positive "" "/") internal-ann))
353 ;; Otherwise it is an annotation with parameters, represented as a list
354 (positive
355 (let ((item (car internal-ann))
356 (params (cdr internal-ann)))
357 (concat (format enriched-annotation-format "" item)
358 (mapconcat (lambda (i) (concat "<param>" i "</param>"))
359 params ""))))
360 (t (format enriched-annotation-format "/" (car internal-ann)))))
361
362(defun enriched-encode-other-face (old new)
363 "Generate annotations for random face change.
364One annotation each for foreground color, background color, italic, etc."
365 (cons (and old (enriched-face-ans old))
366 (and new (enriched-face-ans new))))
367
368(defun enriched-face-ans (face)
369 "Return annotations specifying FACE.
370FACE may be a list of faces instead of a single face;
371it can also be anything allowed as an element of a list
372which can be the value of the `face' text property."
373 (cond ((and (consp face) (eq (car face) 'foreground-color))
374 (list (list "x-color" (cdr face))))
375 ((and (consp face) (eq (car face) 'background-color))
376 (list (list "x-bg-color" (cdr face))))
377 ((and (listp face) (eq (car face) :foreground))
378 (list (list "x-color" (cadr face))))
379 ((and (listp face) (eq (car face) :background))
380 (list (list "x-bg-color" (cadr face))))
381 ((listp face)
382 (apply 'append (mapcar 'enriched-face-ans face)))
383 ((let* ((fg (face-attribute face :foreground))
384 (bg (face-attribute face :background))
385 (props (face-font face t))
386 (ans (cdr (format-annotate-single-property-change
387 'face nil props enriched-translations))))
388 (unless (eq fg 'unspecified)
389 (setq ans (cons (list "x-color" fg) ans)))
390 (unless (eq bg 'unspecified)
391 (setq ans (cons (list "x-bg-color" bg) ans)))
392 ans))))
393
394;;;
395;;; Decoding files
396;;;
397
398;;;###autoload
399(defun enriched-decode (from to)
400 (if enriched-verbose (message "Enriched: decoding document..."))
401 (use-hard-newlines 1 'never)
402 (save-excursion
403 (save-restriction
404 (narrow-to-region from to)
405 (goto-char from)
406
407 ;; Deal with header
408 (let ((file-width (enriched-get-file-width)))
409 (enriched-remove-header)
410
411 ;; Deal with newlines
412 (while (search-forward-regexp "\n\n+" nil t)
413 (if (current-justification)
414 (delete-char -1))
415 (set-hard-newline-properties (match-beginning 0) (point)))
416
417 ;; Translate annotations
418 (format-deannotate-region from (point-max) enriched-translations
419 'enriched-next-annotation)
420
421 ;; Indent or fill the buffer
422 (cond (file-width ; File was filled to this width
423 (setq fill-column file-width)
424 (if enriched-verbose (message "Indenting..."))
425 (enriched-insert-indentation))
426 (t ; File was not filled.
427 (if enriched-verbose (message "Filling paragraphs..."))
428 (fill-region (point-min) (point-max))))
429 (if enriched-verbose (message nil)))
430 (point-max))))
431
432(defun enriched-next-annotation ()
433 "Find and return next text/enriched annotation.
434Any \"<<\" strings encountered are converted to \"<\".
435Return value is \(begin end name positive-p), or nil if none was found."
436 (while (and (search-forward "<" nil 1)
437 (progn (goto-char (match-beginning 0))
438 (not (looking-at enriched-annotation-regexp))))
439 (forward-char 1)
e994155e 440 (if (eq ?< (char-after (point)))
5e046f6d
JB
441 (delete-char 1)
442 ;; A single < that does not start an annotation is an error,
443 ;; which we note and then ignore.
444 (message "Warning: malformed annotation in file at %s"
445 (1- (point)))))
446 (if (not (eobp))
447 (let* ((beg (match-beginning 0))
448 (end (match-end 0))
449 (name (downcase (buffer-substring
450 (match-beginning 2) (match-end 2))))
451 (pos (not (match-beginning 1))))
452 (list beg end name pos))))
453
454(defun enriched-get-file-width ()
455 "Look for file width information on this line."
456 (save-excursion
457 (if (search-forward "Text-Width: " (+ (point) 1000) t)
458 (read (current-buffer)))))
459
460(defun enriched-remove-header ()
461 "Remove file-format header at point."
462 (while (looking-at "^[-A-Za-z]+: .*\n")
463 (delete-region (point) (match-end 0)))
464 (if (looking-at "^\n")
465 (delete-char 1)))
466
467(defun enriched-decode-foreground (from to &optional color)
468 (if color
469 (list from to 'face (list ':foreground color))
470 (message "Warning: no color specified for <x-color>")
471 nil))
472
473(defun enriched-decode-background (from to &optional color)
474 (if color
475 (list from to 'face (list ':background color))
476 (message "Warning: no color specified for <x-bg-color>")
477 nil))
478\f
479;;; Handling the `display' property.
480
481
482(defun enriched-handle-display-prop (old new)
483 "Return a list of annotations for a change in the `display' property.
484OLD is the old value of the property, NEW is the new value. Value
485is a list `(CLOSE OPEN)', where CLOSE is a list of annotations to
486close and OPEN a list of annotations to open. Each of these lists
487has the form `(ANNOTATION PARAM ...)'."
488 (let ((annotation "x-display")
489 (param (prin1-to-string (or old new))))
490 (if (null old)
491 (cons nil (list (list annotation param)))
492 (cons (list (list annotation param)) nil))))
493
494(defun enriched-decode-display-prop (start end &optional param)
495 "Decode a `display' property for text between START and END.
496PARAM is a `<param>' found for the property.
497Value is a list `(START END SYMBOL VALUE)' with START and END denoting
3592613a 498the range of text to assign text property SYMBOL with value VALUE."
5e046f6d
JB
499 (let ((prop (when (stringp param)
500 (condition-case ()
501 (car (read-from-string param))
502 (error nil)))))
503 (unless prop
504 (message "Warning: invalid <x-display> parameter %s" param))
505 (list start end 'display prop)))
506
507;;; enriched.el ends here