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