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