(synch_process_death, synch_process_retcode): Delete extra declaration.
[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
503 ;; Yes, use the current property name &
504 ;; value. Set loop variables to nil so loop
505 ;; will exit.
506 (setq alist nil aalist nil matched t
507 ;; pop annotation off stack.
508 open-ans (cdr open-ans))
509 (cond
510 ;; Check for pseudo-properties
511 ((eq prop 'PARAMETER)
512 ;; This is a parameter of the top open ann:
513 ;; delete text and use as arg.
514 (if open-ans
515 ;; (If nothing open, discard).
516 (setq open-ans
517 (cons (append (car open-ans)
518 (list
519 (buffer-substring
520 start loc)))
521 (cdr open-ans))))
522 (delete-region start loc))
523 ((eq prop 'FUNCTION)
524 ;; Not a property, but a function to call.
525 (let ((rtn (apply value start loc params)))
526 (if rtn (setq todo (cons rtn todo)))))
527 (t
528 ;; Normal property/value pair
529 (setq todo
530 (cons (list start loc prop value)
531 todo)))))))
532 (setq alist (cdr alist))))
533 (setq aalist (cdr aalist)))
534 (if matched
535 nil
536 ;; Didn't find any match for the annotation:
537 ;; Store as value of text-property `unknown'.
538 (setq open-ans (cdr open-ans))
539 (setq todo (cons (list start loc 'unknown top-name)
540 todo))
541 (setq unknown-ans (cons name unknown-ans)))))))))
542
543 ;; Once entire file has been scanned, add the properties.
544 (while todo
545 (let* ((item (car todo))
546 (from (nth 0 item))
547 (to (nth 1 item))
548 (prop (nth 2 item))
549 (val (nth 3 item)))
550
551 (put-text-property
552 from to prop
553 (cond ((numberp val) ; add to ambient value if numeric
554 (+ val (or (get-text-property from prop) 0)))
555 ((get prop 'format-list-valued) ; value gets consed onto
556 ; list-valued properties
557 (let ((prev (get-text-property from prop)))
558 (cons val (if (listp prev) prev (list prev)))))
559 (t val)))) ; normally, just set to val.
560 (setq todo (cdr todo)))
561
562 (if unknown-ans
563 (message "Unknown annotations: %s" unknown-ans))))))
564
565;;;
566;;; Encoding
567;;;
568
569(defun format-insert-annotations (list &optional offset)
570 "Apply list of annotations to buffer as `write-region' would.
571Inserts each element of the given LIST of buffer annotations at its
572appropriate place. Use second arg OFFSET if the annotations' locations are
573not relative to the beginning of the buffer: annotations will be inserted
574at their location-OFFSET+1 \(ie, the offset is treated as the character number
575of the first character in the buffer)."
576 (if (not offset)
577 (setq offset 0)
578 (setq offset (1- offset)))
579 (let ((l (reverse list)))
580 (while l
581 (goto-char (- (car (car l)) offset))
582 (insert (cdr (car l)))
583 (setq l (cdr l)))))
584
585(defun format-annotate-value (old new)
586 "Return OLD and NEW as a \(close . open) annotation pair.
587Useful as a default function for TRANSLATIONS alist when the value of the text
588property is the name of the annotation that you want to use, as it is for the
589`unknown' text property."
590 (cons (if old (list old))
591 (if new (list new))))
592
593(defun format-annotate-region (from to trans format-fn ignore)
594 "Generate annotations for text properties in the region.
595Searches for changes between FROM and TO, and describes them with a list of
596annotations as defined by alist TRANSLATIONS and FORMAT-FN. IGNORE lists text
597properties not to consider; any text properties that are neither ignored nor
598listed in TRANSLATIONS are warned about.
599If you actually want to modify the region, give the return value of this
600function to `format-insert-annotations'.
601
602Format of the TRANSLATIONS argument:
603
604Each element is a list whose car is a PROPERTY, and the following
605elements are VALUES of that property followed by the names of zero or more
606ANNOTATIONS. Whenever the property takes on that value, the annotations
607\(as formatted by FORMAT-FN) are inserted into the file.
608When the property stops having that value, the matching negated annotation
609will be inserted \(it may actually be closed earlier and reopened, if
610necessary, to keep proper nesting).
611
612If the property's value is a list, then each element of the list is dealt with
613separately.
614
615If a VALUE is numeric, then it is assumed that there is a single annotation
616and each occurrence of it increments the value of the property by that number.
617Thus, given the entry \(left-margin \(4 \"indent\")), if the left margin
618changes from 4 to 12, two <indent> annotations will be generated.
619
620If the VALUE is nil, then instead of annotations, a function should be
621specified. This function is used as a default: it is called for all
622transitions not explicitly listed in the table. The function is called with
623two arguments, the OLD and NEW values of the property. It should return
624lists of annotations like `format-annotate-location' does.
625
626 The same structure can be used in reverse for reading files."
627 (let ((all-ans nil) ; All annotations - becomes return value
628 (open-ans nil) ; Annotations not yet closed
629 (loc nil) ; Current location
630 (not-found nil)) ; Properties that couldn't be saved
631 (while (or (null loc)
632 (and (setq loc (next-property-change loc nil to))
633 (< loc to)))
634 (or loc (setq loc from))
635 (let* ((ans (format-annotate-location loc (= loc from) ignore trans))
636 (neg-ans (format-reorder (aref ans 0) open-ans))
637 (pos-ans (aref ans 1))
638 (ignored (aref ans 2)))
639 (setq not-found (append ignored not-found)
640 ignore (append ignored ignore))
641 ;; First do the negative (closing) annotations
642 (while neg-ans
643 ;; Check if it's missing. This can happen (eg, a numeric property
644 ;; going negative can generate closing annotations before there are
645 ;; any open). Warn user & ignore.
646 (if (not (member (car neg-ans) open-ans))
647 (message "Can't close %s: not open." (car neg-ans))
648 (while (not (equal (car neg-ans) (car open-ans)))
649 ;; To close anno. N, need to first close ans 1 to N-1,
650 ;; remembering to re-open them later.
651 (setq pos-ans (cons (car open-ans) pos-ans))
652 (setq all-ans
653 (cons (cons loc (funcall format-fn (car open-ans) nil))
654 all-ans))
655 (setq open-ans (cdr open-ans)))
656 ;; Now remove the one we're really interested in from open list.
657 (setq open-ans (cdr open-ans))
658 ;; And put the closing annotation here.
659 (setq all-ans
660 (cons (cons loc (funcall format-fn (car neg-ans) nil))
661 all-ans)))
662 (setq neg-ans (cdr neg-ans)))
663 ;; Now deal with positive (opening) annotations
664 (let ((p pos-ans))
665 (while pos-ans
666 (setq open-ans (cons (car pos-ans) open-ans))
667 (setq all-ans
668 (cons (cons loc (funcall format-fn (car pos-ans) t))
669 all-ans))
670 (setq pos-ans (cdr pos-ans))))))
671
672 ;; Close any annotations still open
673 (while open-ans
674 (setq all-ans
675 (cons (cons to (funcall format-fn (car open-ans) nil))
676 all-ans))
677 (setq open-ans (cdr open-ans)))
678 (if not-found
679 (message "These text properties could not be saved:\n %s"
680 not-found))
681 (nreverse all-ans)))
682
683;;; Internal functions for format-annotate-region.
684
685(defun format-annotate-location (loc all ignore trans)
686 "Return annotation(s) needed at LOCATION.
687This includes any properties that change between LOC-1 and LOC.
688If ALL is true, don't look at previous location, but generate annotations for
689all non-nil properties.
690Third argument IGNORE is a list of text-properties not to consider.
691
692Return value is a vector of 3 elements:
6931. List of names of the annotations to close
6942. List of the names of annotations to open.
6953. List of properties that were ignored or couldn't be annotated."
696 (let* ((prev-loc (1- loc))
697 (before-plist (if all nil (text-properties-at prev-loc)))
698 (after-plist (text-properties-at loc))
699 p negatives positives prop props not-found)
700 ;; make list of all property names involved
701 (setq p before-plist)
702 (while p
703 (if (not (memq (car p) props))
704 (setq props (cons (car p) props)))
705 (setq p (cdr (cdr p))))
706 (setq p after-plist)
707 (while p
708 (if (not (memq (car p) props))
709 (setq props (cons (car p) props)))
710 (setq p (cdr (cdr p))))
711
712 (while props
713 (setq prop (car props)
714 props (cdr props))
715 (if (memq prop ignore)
716 nil ; If it's been ignored before, ignore it now.
717 (let ((before (if all nil (car (cdr (memq prop before-plist)))))
718 (after (car (cdr (memq prop after-plist)))))
719 (if (equal before after)
720 nil ; no change; ignore
721 (let ((result (format-annotate-single-property-change
722 prop before after trans)))
723 (if (not result)
724 (setq not-found (cons prop not-found))
725 (setq negatives (nconc negatives (car result))
726 positives (nconc positives (cdr result)))))))))
727 (vector negatives positives not-found)))
728
729(defun format-annotate-single-property-change (prop old new trans)
730 "Return annotations for PROPERTY changing from OLD to NEW.
731These are searched for in the TRANSLATIONS alist.
732If NEW does not appear in the list, but there is a default function, then that
733function is called.
734Annotations to open and to close are returned as a dotted pair."
735 (let ((prop-alist (cdr (assoc prop trans)))
736 default)
737 (if (not prop-alist)
738 nil
739 ;; If property is numeric, nil means 0
740 (cond ((and (numberp old) (null new))
741 (setq new 0))
742 ((and (numberp new) (null old))
743 (setq old 0)))
744 ;; If either old or new is a list, have to treat both that way.
745 (if (or (consp old) (consp new))
746 (let* ((old (if (listp old) old (list old)))
747 (new (if (listp new) new (list new)))
748 (tail (format-common-tail old new))
749 close open)
750 (while old
751 (setq close
752 (append (car (format-annotate-atomic-property-change
753 prop-alist (car old) nil))
754 close)
755 old (cdr old)))
756 (while new
757 (setq open
758 (append (cdr (format-annotate-atomic-property-change
759 prop-alist nil (car new)))
760 open)
761 new (cdr new)))
762 (format-make-relatively-unique close open))
763 (format-annotate-atomic-property-change prop-alist old new)))))
764
765(defun format-annotate-atomic-property-change (prop-alist old new)
766 "Internal function annotate a single property change.
fa1f61e5 767PROP-ALIST is the relevant segment of a TRANSLATIONS list.
029894b9
BG
768OLD and NEW are the values."
769 (cond
770 ;; Numerical annotation - use difference
771 ((and (numberp old) (numberp new))
772 (let* ((entry (progn
773 (while (and (car (car prop-alist))
774 (not (numberp (car (car prop-alist)))))
775 (setq prop-alist (cdr prop-alist)))
776 (car prop-alist)))
777 (increment (car (car prop-alist)))
778 (n (ceiling (/ (float (- new old)) (float increment))))
779 (anno (car (cdr (car prop-alist)))))
780 (if (> n 0)
781 (cons nil (make-list n anno))
782 (cons (make-list (- n) anno) nil))))
783
784 ;; Standard annotation
785 (t (let ((close (and old (cdr (assoc old prop-alist))))
786 (open (and new (cdr (assoc new prop-alist)))))
787 (if (or close open)
788 (format-make-relatively-unique close open)
789 ;; Call "Default" function, if any
790 (let ((default (assq nil prop-alist)))
791 (if default
792 (funcall (car (cdr default)) old new))))))))
793
794;; format.el ends here