comparison lisp/prim/format.el @ 0:376386a54a3c r19-14

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