(use-hard-newlines): New minor mode function.
[bpt/emacs.git] / lisp / format.el
CommitLineData
a8581027 1;;; format.el --- read and save files in multiple formats
b578f267 2
732be465 3;; Copyright (c) 1994, 1995 Free Software Foundation
029894b9 4
7865eac6 5;; Author: Boris Goldowsky <boris@gnu.ai.mit.edu>
029894b9
BG
6
7;; This file is part of GNU Emacs.
8
9;; GNU Emacs is free software; you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
11;; the Free Software Foundation; either version 2, or (at your option)
12;; any later version.
b578f267 13
029894b9
BG
14;; GNU Emacs is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
b578f267 18
029894b9 19;; You should have received a copy of the GNU General Public License
b578f267
EN
20;; along with GNU Emacs; see the file COPYING. If not, write to the
21;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22;; Boston, MA 02111-1307, USA.
029894b9
BG
23
24;;; Commentary:
b578f267
EN
25
26;; This file defines a unified mechanism for saving & loading files stored
27;; in different formats. `format-alist' contains information that directs
029894b9
BG
28;; Emacs to call an encoding or decoding function when reading or writing
29;; files that match certain conditions.
30;;
b578f267
EN
31;; When a file is visited, its format is determined by matching the
32;; beginning of the file against regular expressions stored in
33;; `format-alist'. If this fails, you can manually translate the buffer
34;; using `format-decode-buffer'. In either case, the formats used are
35;; listed in the variable `buffer-file-format', and become the default
36;; format for saving the buffer. To save a buffer in a different format,
37;; change this variable, or use `format-write-file'.
029894b9
BG
38;;
39;; Auto-save files are normally created in the same format as the visited
b578f267
EN
40;; file, but the variable `auto-save-file-format' can be set to a
41;; particularly fast or otherwise preferred format to be used for
42;; auto-saving (or nil to do no encoding on auto-save files, but then you
43;; risk losing any text-properties in the buffer).
029894b9 44;;
b578f267
EN
45;; You can manually translate a buffer into or out of a particular format
46;; with the functions `format-encode-buffer' and `format-decode-buffer'.
47;; To translate just the region use the functions `format-encode-region'
48;; and `format-decode-region'.
029894b9 49;;
b578f267
EN
50;; You can define a new format by writing the encoding and decoding
51;; functions, and adding an entry to `format-alist'. See enriched.el for
52;; an example of how to implement a file format. There are various
53;; functions defined in this file that may be useful for writing the
54;; encoding and decoding functions:
55;; * `format-annotate-region' and `format-deannotate-region' allow a
56;; single alist of information to be used for encoding and decoding.
57;; The alist defines a correspondence between strings in the file
58;; ("annotations") and text-properties in the buffer.
029894b9
BG
59;; * `format-replace-strings' is similarly useful for doing simple
60;; string->string translations in a reversible manner.
61
b578f267
EN
62;;; Code:
63
029894b9
BG
64(put 'buffer-file-format 'permanent-local t)
65
66(defconst format-alist
67 '((text/enriched "Extended MIME text/enriched format."
68 "Content-[Tt]ype:[ \t]*text/enriched"
69 enriched-decode enriched-encode t enriched-mode)
70 (plain "Standard ASCII format, no text properties."
71 ;; Plain only exists so that there is an obvious neutral choice in
72 ;; the completion list.
73 nil nil nil nil nil))
74 "List of information about understood file formats.
75Elements are of the form \(NAME DOC-STR REGEXP FROM-FN TO-FN MODIFY MODE-FN).
76NAME is a symbol, which is stored in `buffer-file-format'.
77DOC-STR should be a single line providing more information about the
78 format. It is currently unused, but in the future will be shown to
79 the user if they ask for more information.
80REGEXP is a regular expression to match against the beginning of the file;
81 it should match only files in that format.
82FROM-FN is called to decode files in that format; it gets two args, BEGIN
83 and END, and can make any modifications it likes, returning the new
84 end. It must make sure that the beginning of the file no longer
85 matches REGEXP, or else it will get called again.
86TO-FN is called to encode a region into that format; it is also passed BEGIN
87 and END, and either returns a list of annotations like
88 `write-region-annotate-functions', or modifies the region and returns
89 the new end.
90MODIFY, if non-nil, means the TO-FN modifies the region. If nil, TO-FN may
91 not make any changes and should return a list of annotations.
92MODE-FN, if specified, is called when visiting a file with that format.")
93
94;;; Basic Functions (called from Lisp)
95
96(defun format-annotate-function (format from to)
97 "Returns annotations for writing region as FORMAT.
98FORMAT is a symbol naming one of the formats defined in `format-alist',
99it must be a single symbol, not a list like `buffer-file-format'.
100This function works like a function on `write-region-annotate-functions':
101it either returns a list of annotations, or returns with a different buffer
102current, which contains the modified text to write.
103
104For most purposes, consider using `format-encode-region' instead."
105 ;; This function is called by write-region (actually build-annotations)
106 ;; for each element of buffer-file-format.
107 (let* ((info (assq format format-alist))
108 (to-fn (nth 4 info))
109 (modify (nth 5 info)))
110 (if to-fn
111 (if modify
112 ;; To-function wants to modify region. Copy to safe place.
113 (let ((copy-buf (get-buffer-create " *Format Temp*")))
114 (copy-to-buffer copy-buf from to)
115 (set-buffer copy-buf)
116 (format-insert-annotations write-region-annotations-so-far from)
117 (funcall to-fn (point-min) (point-max))
118 nil)
119 ;; Otherwise just call function, it will return annotations.
120 (funcall to-fn from to)))))
121
122(defun format-decode (format length &optional visit-flag)
123 ;; This function is called by insert-file-contents whenever a file is read.
124 "Decode text from any known FORMAT.
125FORMAT is a symbol appearing in `format-alist' or a list of such symbols,
126or nil, in which case this function tries to guess the format of the data by
127matching against the regular expressions in `format-alist'. After a match is
128found and the region decoded, the alist is searched again from the beginning
129for another match.
130
131Second arg LENGTH is the number of characters following point to operate on.
132If optional third arg VISIT-FLAG is true, set `buffer-file-format'
133to the list of formats used, and call any mode functions defined for those
134formats.
135
136Returns the new length of the decoded region.
137
138For most purposes, consider using `format-decode-region' instead."
139 (let ((mod (buffer-modified-p))
140 (begin (point))
141 (end (+ (point) length)))
142 (if (null format)
143 ;; Figure out which format it is in, remember list in `format'.
144 (let ((try format-alist))
145 (while try
146 (let* ((f (car try))
147 (regexp (nth 2 f))
148 (p (point)))
149 (if (and regexp (looking-at regexp)
150 (< (match-end 0) (+ begin length)))
151 (progn
152 (setq format (cons (car f) format))
153 ;; Decode it
154 (if (nth 3 f) (setq end (funcall (nth 3 f) begin end)))
155 ;; Call visit function if required
156 (if (and visit-flag (nth 6 f)) (funcall (nth 6 f) 1))
157 ;; Safeguard against either of the functions changing pt.
158 (goto-char p)
159 ;; Rewind list to look for another format
160 (setq try format-alist))
161 (setq try (cdr try))))))
162 ;; Deal with given format(s)
163 (or (listp format) (setq format (list format)))
164 (let ((do format) f)
165 (while do
166 (or (setq f (assq (car do) format-alist))
167 (error "Unknown format" (car do)))
168 ;; Decode:
169 (if (nth 3 f) (setq end (funcall (nth 3 f) begin end)))
170 ;; Call visit function if required
171 (if (and visit-flag (nth 6 f)) (funcall (nth 6 f) 1))
172 (setq do (cdr do)))))
173 (if visit-flag
174 (setq buffer-file-format format))
175 (set-buffer-modified-p mod)
176 ;; Return new length of region
177 (- end begin)))
178
179;;;
180;;; Interactive functions & entry points
181;;;
182
183(defun format-decode-buffer (&optional format)
184 "Translate the buffer from some FORMAT.
185If the format is not specified, this function attempts to guess.
186`buffer-file-format' is set to the format used, and any mode-functions
187for the format are called."
188 (interactive
189 (list (format-read "Translate buffer from format (default: guess): ")))
190 (save-excursion
191 (goto-char (point-min))
192 (format-decode format (buffer-size) t)))
193
194(defun format-decode-region (from to &optional format)
195 "Decode the region from some format.
196Arg FORMAT is optional; if omitted the format will be determined by looking
197for identifying regular expressions at the beginning of the region."
198 (interactive
199 (list (region-beginning) (region-end)
200 (format-read "Translate region from format (default: guess): ")))
201 (save-excursion
202 (goto-char from)
203 (format-decode format (- to from) nil)))
204
205(defun format-encode-buffer (&optional format)
206 "Translate the buffer into FORMAT.
207FORMAT defaults to `buffer-file-format'. It is a symbol naming one of the
208formats defined in `format-alist', or a list of such symbols."
209 (interactive
210 (list (format-read (format "Translate buffer to format (default %s): "
211 buffer-file-format))))
212 (format-encode-region (point-min) (point-max) format))
213
214(defun format-encode-region (beg end &optional format)
215 "Translate the region into some FORMAT.
216FORMAT defaults to `buffer-file-format', it is a symbol naming
217one of the formats defined in `format-alist', or a list of such symbols."
218 (interactive
219 (list (region-beginning) (region-end)
220 (format-read (format "Translate region to format (default %s): "
221 buffer-file-format))))
222 (if (null format) (setq format buffer-file-format))
223 (if (symbolp format) (setq format (list format)))
224 (save-excursion
225 (goto-char end)
226 (let ((cur-buf (current-buffer))
227 (end (point-marker)))
228 (while format
229 (let* ((info (assq (car format) format-alist))
230 (to-fn (nth 4 info))
231 (modify (nth 5 info))
232 result)
233 (if to-fn
234 (if modify
235 (setq end (funcall to-fn beg end))
236 (format-insert-annotations (funcall to-fn beg end))))
237 (setq format (cdr format)))))))
238
239(defun format-write-file (filename format)
240 "Write current buffer into a FILE using some FORMAT.
241Makes buffer visit that file and sets the format as the default for future
242saves. If the buffer is already visiting a file, you can specify a directory
243name as FILE, to write a file of the same old name in that directory."
244 (interactive
245 ;; Same interactive spec as write-file, plus format question.
246 (let* ((file (if buffer-file-name
247 (read-file-name "Write file: "
248 nil nil nil nil)
249 (read-file-name "Write file: "
250 (cdr (assq 'default-directory
251 (buffer-local-variables)))
252 nil nil (buffer-name))))
253 (fmt (format-read (format "Write file `%s' in format: "
254 (file-name-nondirectory file)))))
255 (list file fmt)))
256 (setq buffer-file-format format)
257 (write-file filename))
258
ce6af52b
KH
259(defun format-find-file (filename format)
260 "Find the file FILE using data format FORMAT.
261If FORMAT is nil then do not do any format conversion."
262 (interactive
263 ;; Same interactive spec as write-file, plus format question.
264 (let* ((file (read-file-name "Find file: "))
265 (fmt (format-read (format "Read file `%s' in format: "
266 (file-name-nondirectory file)))))
267 (list file fmt)))
268 (let ((format-alist nil))
269 (find-file filename))
270 (if format
271 (format-decode-buffer format)))
272
273(defun format-insert-file (filename format &optional beg end)
274 "Insert the contents of file FILE using data format FORMAT.
275If FORMAT is nil then do not do any format conversion.
276The optional third and fourth arguments BEG and END specify
277the part of the file to read.
278
279The return value is like the value of `insert-file-contents':
280a list (ABSOLUTE-FILE-NAME . SIZE)."
281 (interactive
282 ;; Same interactive spec as write-file, plus format question.
283 (let* ((file (read-file-name "Find file: "))
284 (fmt (format-read (format "Read file `%s' in format: "
285 (file-name-nondirectory file)))))
286 (list file fmt)))
287 (let (value size)
288 (let ((format-alist nil))
289 (setq value (insert-file-contents filename nil beg end))
290 (setq size (nth 1 value)))
291 (if format
292 (setq size (format-decode size format)
293 value (cons (car value) size)))
294 value))
295
029894b9
BG
296(defun format-read (&optional prompt)
297 "Read and return the name of a format.
298Return value is a list, like `buffer-file-format'; it may be nil.
299Formats are defined in `format-alist'. Optional arg is the PROMPT to use."
300 (let* ((table (mapcar (lambda (x) (list (symbol-name (car x))))
301 format-alist))
302 (ans (completing-read (or prompt "Format: ") table nil t)))
303 (if (not (equal "" ans)) (list (intern ans)))))
304
305
306;;;
307;;; Below are some functions that may be useful in writing encoding and
308;;; decoding functions for use in format-alist.
309;;;
310
311(defun format-replace-strings (alist &optional reverse beg end)
312 "Do multiple replacements on the buffer.
313ALIST is a list of (from . to) pairs, which should be proper arguments to
314`search-forward' and `replace-match' respectively.
315Optional 2nd arg REVERSE, if non-nil, means the pairs are (to . from), so that
316you can use the same list in both directions if it contains only literal
317strings.
318Optional args BEGIN and END specify a region of the buffer to operate on."
319 (save-excursion
320 (save-restriction
321 (or beg (setq beg (point-min)))
322 (if end (narrow-to-region (point-min) end))
323 (while alist
324 (let ((from (if reverse (cdr (car alist)) (car (car alist))))
325 (to (if reverse (car (cdr alist)) (cdr (car alist)))))
326 (goto-char beg)
327 (while (search-forward from nil t)
328 (goto-char (match-beginning 0))
329 (insert to)
330 (set-text-properties (- (point) (length to)) (point)
331 (text-properties-at (point)))
332 (delete-region (point) (+ (point) (- (match-end 0)
333 (match-beginning 0)))))
334 (setq alist (cdr alist)))))))
335
336;;; Some list-manipulation functions that we need.
337
338(defun format-delq-cons (cons list)
339 "Remove the given CONS from LIST by side effect,
340and return the new LIST. Since CONS could be the first element
341of LIST, write `\(setq foo \(format-delq-cons element foo))' to be sure of
342changing the value of `foo'."
343 (if (eq cons list)
344 (cdr list)
345 (let ((p list))
346 (while (not (eq (cdr p) cons))
347 (if (null p) (error "format-delq-cons: not an element."))
348 (setq p (cdr p)))
349 ;; Now (cdr p) is the cons to delete
350 (setcdr p (cdr cons))
351 list)))
352
353(defun format-make-relatively-unique (a b)
354 "Delete common elements of lists A and B, return as pair.
355Compares using `equal'."
356 (let* ((acopy (copy-sequence a))
357 (bcopy (copy-sequence b))
358 (tail acopy))
359 (while tail
360 (let ((dup (member (car tail) bcopy))
361 (next (cdr tail)))
362 (if dup (setq acopy (format-delq-cons tail acopy)
363 bcopy (format-delq-cons dup bcopy)))
364 (setq tail next)))
365 (cons acopy bcopy)))
366
367(defun format-common-tail (a b)
368 "Given two lists that have a common tail, return it.
369Compares with `equal', and returns the part of A that is equal to the
370equivalent part of B. If even the last items of the two are not equal,
371returns nil."
372 (let ((la (length a))
373 (lb (length b)))
374 ;; Make sure they are the same length
375 (if (> la lb)
376 (setq a (nthcdr (- la lb) a))
377 (setq b (nthcdr (- lb la) b))))
378 (while (not (equal a b))
379 (setq a (cdr a)
380 b (cdr b)))
381 a)
382
383(defun format-reorder (items order)
384 "Arrange ITEMS to following partial ORDER.
385Elements of ITEMS equal to elements of ORDER will be rearranged to follow the
386ORDER. Unmatched items will go last."
387 (if order
388 (let ((item (member (car order) items)))
389 (if item
390 (cons (car item)
391 (format-reorder (format-delq-cons item items)
392 (cdr order)))
393 (format-reorder items (cdr order))))
394 items))
395
396(put 'face 'format-list-valued t) ; These text-properties take values
397(put 'unknown 'format-list-valued t) ; that are lists, the elements of which
398 ; should be considered separately.
399 ; See format-deannotate-region and
400 ; format-annotate-region.
401
402;;;
403;;; Decoding
404;;;
405
406(defun format-deannotate-region (from to translations next-fn)
407 "Translate annotations in the region into text properties.
408This sets text properties between FROM to TO as directed by the
409TRANSLATIONS and NEXT-FN arguments.
410
411NEXT-FN is a function that searches forward from point for an annotation.
412It should return a list of 4 elements: \(BEGIN END NAME POSITIVE). BEGIN and
413END are buffer positions bounding the annotation, NAME is the name searched
414for in TRANSLATIONS, and POSITIVE should be non-nil if this annotation marks
415the beginning of a region with some property, or nil if it ends the region.
416NEXT-FN should return nil if there are no annotations after point.
417
418The basic format of the TRANSLATIONS argument is described in the
419documentation for the `format-annotate-region' function. There are some
420additional things to keep in mind for decoding, though:
421
422When an annotation is found, the TRANSLATIONS list is searched for a
423text-property name and value that corresponds to that annotation. If the
424text-property has several annotations associated with it, it will be used only
425if the other annotations are also in effect at that point. The first match
426found whose annotations are all present is used.
427
428The text property thus determined is set to the value over the region between
429the opening and closing annotations. However, if the text-property name has a
430non-nil `format-list-valued' property, then the value will be consed onto the
431surrounding value of the property, rather than replacing that value.
432
433There are some special symbols that can be used in the \"property\" slot of
434the TRANSLATIONS list: PARAMETER and FUNCTION \(spelled in uppercase).
435Annotations listed under the pseudo-property PARAMETER are considered to be
436arguments of the immediately surrounding annotation; the text between the
437opening and closing parameter annotations is deleted from the buffer but saved
438as a string. The surrounding annotation should be listed under the
439pseudo-property FUNCTION. Instead of inserting a text-property for this
440annotation, the function listed in the VALUE slot is called to make whatever
441changes are appropriate. The function's first two arguments are the START and
442END locations, and the rest of the arguments are any PARAMETERs found in that
443region.
444
445Any annotations that are found by NEXT-FN but not defined by TRANSLATIONS
446are saved as values of the `unknown' text-property \(which is list-valued).
447The TRANSLATIONS list should usually contain an entry of the form
448 \(unknown \(nil format-annotate-value))
449to write these unknown annotations back into the file."
450 (save-excursion
451 (save-restriction
452 (narrow-to-region (point-min) to)
453 (goto-char from)
454 (let (next open-ans todo loc unknown-ans)
455 (while (setq next (funcall next-fn))
456 (let* ((loc (nth 0 next))
457 (end (nth 1 next))
458 (name (nth 2 next))
459 (positive (nth 3 next))
460 (found nil))
461
462 ;; Delete the annotation
463 (delete-region loc end)
464 (if positive
465 ;; Positive annotations are stacked, remembering location
466 (setq open-ans (cons (list name loc) open-ans))
467 ;; It is a negative annotation:
468 ;; Close the top annotation & add its text property.
469 ;; If the file's nesting is messed up, the close might not match
470 ;; the top thing on the open-annotations stack.
471 ;; If no matching annotation is open, just ignore the close.
472 (if (not (assoc name open-ans))
473 (message "Extra closing annotation (%s) in file" name)
474 ;; If one is open, but not on the top of the stack, close
475 ;; the things in between as well. Set `found' when the real
fa1f61e5 476 ;; one is closed.
029894b9
BG
477 (while (not found)
478 (let* ((top (car open-ans)) ; first on stack: should match.
479 (top-name (car top))
480 (start (car (cdr top))) ; location of start
481 (params (cdr (cdr top))) ; parameters
482 (aalist translations)
483 (matched nil))
484 (if (equal name top-name)
485 (setq found t)
486 (message "Improper nesting in file."))
487 ;; Look through property names in TRANSLATIONS
488 (while aalist
489 (let ((prop (car (car aalist)))
490 (alist (cdr (car aalist))))
491 ;; And look through values for each property
492 (while alist
493 (let ((value (car (car alist)))
494 (ans (cdr (car alist))))
495 (if (member top-name ans)
496 ;; This annotation is listed, but still have to
497 ;; check if multiple annotations are satisfied
498 (if (member 'nil (mapcar
499 (lambda (r)
500 (assoc r open-ans))
501 ans))
502 nil ; multiple ans not satisfied
059a4a90
RS
503 ;; Yes, all set.
504 ;; If there are multiple annotations going
505 ;; into one text property, adjust the
506 ;; begin points of the other annotations
507 ;; so that we don't get double marking.
508 (let ((to-reset ans)
509 this-one)
510 (while to-reset
511 (setq this-one
512 (assoc (car to-reset)
513 (cdr open-ans)))
514 (if this-one
515 (setcdr this-one (list loc)))
516 (setq to-reset (cdr to-reset))))
517 ;; Set loop variables to nil so loop
029894b9
BG
518 ;; will exit.
519 (setq alist nil aalist nil matched t
520 ;; pop annotation off stack.
521 open-ans (cdr open-ans))
522 (cond
523 ;; Check for pseudo-properties
524 ((eq prop 'PARAMETER)
525 ;; This is a parameter of the top open ann:
526 ;; delete text and use as arg.
527 (if open-ans
528 ;; (If nothing open, discard).
529 (setq open-ans
530 (cons (append (car open-ans)
531 (list
532 (buffer-substring
533 start loc)))
534 (cdr open-ans))))
535 (delete-region start loc))
536 ((eq prop 'FUNCTION)
537 ;; Not a property, but a function to call.
538 (let ((rtn (apply value start loc params)))
539 (if rtn (setq todo (cons rtn todo)))))
540 (t
541 ;; Normal property/value pair
542 (setq todo
543 (cons (list start loc prop value)
544 todo)))))))
545 (setq alist (cdr alist))))
546 (setq aalist (cdr aalist)))
547 (if matched
548 nil
549 ;; Didn't find any match for the annotation:
550 ;; Store as value of text-property `unknown'.
551 (setq open-ans (cdr open-ans))
552 (setq todo (cons (list start loc 'unknown top-name)
553 todo))
554 (setq unknown-ans (cons name unknown-ans)))))))))
555
556 ;; Once entire file has been scanned, add the properties.
557 (while todo
558 (let* ((item (car todo))
559 (from (nth 0 item))
560 (to (nth 1 item))
561 (prop (nth 2 item))
562 (val (nth 3 item)))
563
564 (put-text-property
565 from to prop
566 (cond ((numberp val) ; add to ambient value if numeric
567 (+ val (or (get-text-property from prop) 0)))
568 ((get prop 'format-list-valued) ; value gets consed onto
569 ; list-valued properties
570 (let ((prev (get-text-property from prop)))
571 (cons val (if (listp prev) prev (list prev)))))
572 (t val)))) ; normally, just set to val.
573 (setq todo (cdr todo)))
574
575 (if unknown-ans
576 (message "Unknown annotations: %s" unknown-ans))))))
577
578;;;
579;;; Encoding
580;;;
581
582(defun format-insert-annotations (list &optional offset)
583 "Apply list of annotations to buffer as `write-region' would.
584Inserts each element of the given LIST of buffer annotations at its
585appropriate place. Use second arg OFFSET if the annotations' locations are
586not relative to the beginning of the buffer: annotations will be inserted
587at their location-OFFSET+1 \(ie, the offset is treated as the character number
588of the first character in the buffer)."
589 (if (not offset)
590 (setq offset 0)
591 (setq offset (1- offset)))
592 (let ((l (reverse list)))
593 (while l
594 (goto-char (- (car (car l)) offset))
595 (insert (cdr (car l)))
596 (setq l (cdr l)))))
597
598(defun format-annotate-value (old new)
599 "Return OLD and NEW as a \(close . open) annotation pair.
600Useful as a default function for TRANSLATIONS alist when the value of the text
601property is the name of the annotation that you want to use, as it is for the
602`unknown' text property."
603 (cons (if old (list old))
604 (if new (list new))))
605
606(defun format-annotate-region (from to trans format-fn ignore)
607 "Generate annotations for text properties in the region.
608Searches for changes between FROM and TO, and describes them with a list of
609annotations as defined by alist TRANSLATIONS and FORMAT-FN. IGNORE lists text
610properties not to consider; any text properties that are neither ignored nor
611listed in TRANSLATIONS are warned about.
612If you actually want to modify the region, give the return value of this
613function to `format-insert-annotations'.
614
615Format of the TRANSLATIONS argument:
616
617Each element is a list whose car is a PROPERTY, and the following
618elements are VALUES of that property followed by the names of zero or more
619ANNOTATIONS. Whenever the property takes on that value, the annotations
620\(as formatted by FORMAT-FN) are inserted into the file.
621When the property stops having that value, the matching negated annotation
622will be inserted \(it may actually be closed earlier and reopened, if
623necessary, to keep proper nesting).
624
625If the property's value is a list, then each element of the list is dealt with
626separately.
627
628If a VALUE is numeric, then it is assumed that there is a single annotation
629and each occurrence of it increments the value of the property by that number.
630Thus, given the entry \(left-margin \(4 \"indent\")), if the left margin
631changes from 4 to 12, two <indent> annotations will be generated.
632
633If the VALUE is nil, then instead of annotations, a function should be
634specified. This function is used as a default: it is called for all
635transitions not explicitly listed in the table. The function is called with
636two arguments, the OLD and NEW values of the property. It should return
637lists of annotations like `format-annotate-location' does.
638
639 The same structure can be used in reverse for reading files."
640 (let ((all-ans nil) ; All annotations - becomes return value
641 (open-ans nil) ; Annotations not yet closed
642 (loc nil) ; Current location
643 (not-found nil)) ; Properties that couldn't be saved
644 (while (or (null loc)
645 (and (setq loc (next-property-change loc nil to))
646 (< loc to)))
647 (or loc (setq loc from))
648 (let* ((ans (format-annotate-location loc (= loc from) ignore trans))
649 (neg-ans (format-reorder (aref ans 0) open-ans))
650 (pos-ans (aref ans 1))
651 (ignored (aref ans 2)))
652 (setq not-found (append ignored not-found)
653 ignore (append ignored ignore))
654 ;; First do the negative (closing) annotations
655 (while neg-ans
656 ;; Check if it's missing. This can happen (eg, a numeric property
657 ;; going negative can generate closing annotations before there are
658 ;; any open). Warn user & ignore.
659 (if (not (member (car neg-ans) open-ans))
660 (message "Can't close %s: not open." (car neg-ans))
661 (while (not (equal (car neg-ans) (car open-ans)))
662 ;; To close anno. N, need to first close ans 1 to N-1,
663 ;; remembering to re-open them later.
664 (setq pos-ans (cons (car open-ans) pos-ans))
665 (setq all-ans
666 (cons (cons loc (funcall format-fn (car open-ans) nil))
667 all-ans))
668 (setq open-ans (cdr open-ans)))
669 ;; Now remove the one we're really interested in from open list.
670 (setq open-ans (cdr open-ans))
671 ;; And put the closing annotation here.
672 (setq all-ans
673 (cons (cons loc (funcall format-fn (car neg-ans) nil))
674 all-ans)))
675 (setq neg-ans (cdr neg-ans)))
676 ;; Now deal with positive (opening) annotations
677 (let ((p pos-ans))
678 (while pos-ans
679 (setq open-ans (cons (car pos-ans) open-ans))
680 (setq all-ans
681 (cons (cons loc (funcall format-fn (car pos-ans) t))
682 all-ans))
683 (setq pos-ans (cdr pos-ans))))))
684
685 ;; Close any annotations still open
686 (while open-ans
687 (setq all-ans
688 (cons (cons to (funcall format-fn (car open-ans) nil))
689 all-ans))
690 (setq open-ans (cdr open-ans)))
691 (if not-found
692 (message "These text properties could not be saved:\n %s"
693 not-found))
694 (nreverse all-ans)))
695
696;;; Internal functions for format-annotate-region.
697
698(defun format-annotate-location (loc all ignore trans)
699 "Return annotation(s) needed at LOCATION.
700This includes any properties that change between LOC-1 and LOC.
701If ALL is true, don't look at previous location, but generate annotations for
702all non-nil properties.
703Third argument IGNORE is a list of text-properties not to consider.
704
705Return value is a vector of 3 elements:
7061. List of names of the annotations to close
7072. List of the names of annotations to open.
7083. List of properties that were ignored or couldn't be annotated."
709 (let* ((prev-loc (1- loc))
710 (before-plist (if all nil (text-properties-at prev-loc)))
711 (after-plist (text-properties-at loc))
712 p negatives positives prop props not-found)
713 ;; make list of all property names involved
714 (setq p before-plist)
715 (while p
716 (if (not (memq (car p) props))
717 (setq props (cons (car p) props)))
718 (setq p (cdr (cdr p))))
719 (setq p after-plist)
720 (while p
721 (if (not (memq (car p) props))
722 (setq props (cons (car p) props)))
723 (setq p (cdr (cdr p))))
724
725 (while props
726 (setq prop (car props)
727 props (cdr props))
728 (if (memq prop ignore)
729 nil ; If it's been ignored before, ignore it now.
730 (let ((before (if all nil (car (cdr (memq prop before-plist)))))
731 (after (car (cdr (memq prop after-plist)))))
732 (if (equal before after)
733 nil ; no change; ignore
734 (let ((result (format-annotate-single-property-change
735 prop before after trans)))
736 (if (not result)
737 (setq not-found (cons prop not-found))
738 (setq negatives (nconc negatives (car result))
739 positives (nconc positives (cdr result)))))))))
740 (vector negatives positives not-found)))
741
742(defun format-annotate-single-property-change (prop old new trans)
743 "Return annotations for PROPERTY changing from OLD to NEW.
744These are searched for in the TRANSLATIONS alist.
745If NEW does not appear in the list, but there is a default function, then that
746function is called.
747Annotations to open and to close are returned as a dotted pair."
748 (let ((prop-alist (cdr (assoc prop trans)))
749 default)
750 (if (not prop-alist)
751 nil
752 ;; If property is numeric, nil means 0
753 (cond ((and (numberp old) (null new))
754 (setq new 0))
755 ((and (numberp new) (null old))
756 (setq old 0)))
757 ;; If either old or new is a list, have to treat both that way.
758 (if (or (consp old) (consp new))
759 (let* ((old (if (listp old) old (list old)))
760 (new (if (listp new) new (list new)))
761 (tail (format-common-tail old new))
762 close open)
763 (while old
764 (setq close
765 (append (car (format-annotate-atomic-property-change
766 prop-alist (car old) nil))
767 close)
768 old (cdr old)))
769 (while new
770 (setq open
771 (append (cdr (format-annotate-atomic-property-change
772 prop-alist nil (car new)))
773 open)
774 new (cdr new)))
775 (format-make-relatively-unique close open))
776 (format-annotate-atomic-property-change prop-alist old new)))))
777
778(defun format-annotate-atomic-property-change (prop-alist old new)
779 "Internal function annotate a single property change.
fa1f61e5 780PROP-ALIST is the relevant segment of a TRANSLATIONS list.
029894b9
BG
781OLD and NEW are the values."
782 (cond
783 ;; Numerical annotation - use difference
784 ((and (numberp old) (numberp new))
785 (let* ((entry (progn
786 (while (and (car (car prop-alist))
787 (not (numberp (car (car prop-alist)))))
788 (setq prop-alist (cdr prop-alist)))
789 (car prop-alist)))
790 (increment (car (car prop-alist)))
791 (n (ceiling (/ (float (- new old)) (float increment))))
792 (anno (car (cdr (car prop-alist)))))
793 (if (> n 0)
794 (cons nil (make-list n anno))
795 (cons (make-list (- n) anno) nil))))
796
797 ;; Standard annotation
798 (t (let ((close (and old (cdr (assoc old prop-alist))))
799 (open (and new (cdr (assoc new prop-alist)))))
800 (if (or close open)
801 (format-make-relatively-unique close open)
802 ;; Call "Default" function, if any
803 (let ((default (assq nil prop-alist)))
804 (if default
805 (funcall (car (cdr default)) old new))))))))
806
807;; format.el ends here