(read-shell-command, shell-command):
[emacs.git] / lisp / format.el
blobb58a265dcc293264f67bb39690ff2ee045c2a846
1 ;;; format.el --- read and save files in multiple formats
3 ;; Copyright (C) 1994, 1995, 1997, 1999, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Author: Boris Goldowsky <boris@gnu.org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This file defines a unified mechanism for saving & loading files stored
26 ;; in 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.
30 ;; When a file is visited, its format is determined by matching the
31 ;; beginning of the file against regular expressions stored in
32 ;; `format-alist'. If this fails, you can manually translate the buffer
33 ;; using `format-decode-buffer'. In either case, the formats used are
34 ;; listed in the variable `buffer-file-format', and become the default
35 ;; format for saving the buffer. To save a buffer in a different format,
36 ;; change this variable, or use `format-write-file'.
38 ;; Auto-save files are normally created in the same format as the visited
39 ;; file, but the variable `buffer-auto-save-file-format' can be set to a
40 ;; particularly fast or otherwise preferred format to be used for
41 ;; auto-saving (or nil to do no encoding on auto-save files, but then you
42 ;; risk losing any text-properties in the buffer).
44 ;; You can manually translate a buffer into or out of a particular format
45 ;; with the functions `format-encode-buffer' and `format-decode-buffer'.
46 ;; To translate just the region use the functions `format-encode-region'
47 ;; and `format-decode-region'.
49 ;; You can define a new format by writing the encoding and decoding
50 ;; functions, and adding an entry to `format-alist'. See enriched.el for
51 ;; an example of how to implement a file format. There are various
52 ;; functions defined in this file that may be useful for writing the
53 ;; encoding and decoding functions:
54 ;; * `format-annotate-region' and `format-deannotate-region' allow a
55 ;; single alist of information to be used for encoding and decoding.
56 ;; The alist defines a correspondence between strings in the file
57 ;; ("annotations") and text-properties in the buffer.
58 ;; * `format-replace-strings' is similarly useful for doing simple
59 ;; string->string translations in a reversible manner.
61 ;;; Code:
63 (put 'buffer-file-format 'permanent-local t)
64 (put 'buffer-auto-save-file-format 'permanent-local t)
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).
101 NAME is a symbol, which is stored in `buffer-file-format'.
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.
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 it isn't appropriate to
110 require explicit encoding/decoding.
112 FROM-FN is called to decode files in that format; it takes 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.
119 TO-FN is called to encode a region into that format; it takes 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.
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.
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 this would turn on some minor mode.
136 PRESERVE, if non-nil, means that `format-write-file' should not remove
137 this format from `buffer-file-format'.")
139 ;;; Basic Functions (called from Lisp)
141 (defun format-encode-run-method (method from to &optional buffer)
142 "Translate using METHOD the text from FROM to TO.
143 If METHOD is a string, it is a shell command (including options);
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)))
164 (defun format-decode-run-method (method from to &optional buffer)
165 "Decode using METHOD the text from FROM to TO.
166 If METHOD is a string, it is a shell command (including options); otherwise,
167 it should be 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)))
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.
197 FORMAT-COUNT is an integer specifying how many times this function has
198 been called in the process of decoding ORIG-BUF.
200 This function works like a function in `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.
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)))))
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.
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.
245 Return the new length of the decoded region.
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.
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)))
293 (set-buffer-modified-p mod))
295 ;; Return new length of region
296 (- end begin)))
299 ;;; Interactive functions & entry points
302 (defun format-decode-buffer (&optional format)
303 "Translate the buffer from some FORMAT.
304 If the format is not specified, attempt a regexp-based guess.
305 Set `buffer-file-format' to the format used, and call any
306 format-specific mode functions."
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)))
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)))
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))
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)))))))
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.
366 If optional third arg CONFIRM is non-nil, ask for confirmation before
367 overwriting an existing file. Interactively, confirmation is required
368 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))
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)))
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 (in bytes) of the file to read.
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 old-undo)
422 ;; Record only one undo entry for the insertion. Inhibit point-motion and
423 ;; modification hooks as with `insert-file-contents'.
424 (let ((inhibit-point-motion-hooks t)
425 (inhibit-modification-hooks t))
426 ;; Don't bind `buffer-undo-list' to t here to assert that
427 ;; `insert-file-contents' may record whether the buffer was unmodified
428 ;; before.
429 (let ((format-alist nil))
430 (setq value (insert-file-contents filename nil beg end))
431 (setq size (nth 1 value)))
432 (when (consp buffer-undo-list)
433 (let ((head (car buffer-undo-list)))
434 (when (and (consp head)
435 (equal (car head) (point))
436 (equal (cdr head) (+ (point) size)))
437 ;; Remove first entry from `buffer-undo-list', we shall insert
438 ;; another one below.
439 (setq old-undo (cdr buffer-undo-list)))))
440 (when format
441 (let ((buffer-undo-list t))
442 (setq size (format-decode format size)
443 value (list (car value) size)))
444 (unless (eq buffer-undo-list t)
445 (setq buffer-undo-list
446 (cons (cons (point) (+ (point) size)) old-undo)))))
447 (unless inhibit-modification-hooks
448 (run-hook-with-args 'after-change-functions (point) (+ (point) size) 0))
449 value))
451 (defun format-read (&optional prompt)
452 "Read and return the name of a format.
453 Return value is a list, like `buffer-file-format'; it may be nil.
454 Formats are defined in `format-alist'. Optional arg is the PROMPT to use."
455 (let* ((table (mapcar (lambda (x) (list (symbol-name (car x))))
456 format-alist))
457 (ans (completing-read (or prompt "Format: ") table nil t)))
458 (if (not (equal "" ans)) (list (intern ans)))))
462 ;;; Below are some functions that may be useful in writing encoding and
463 ;;; decoding functions for use in format-alist.
466 (defun format-replace-strings (alist &optional reverse beg end)
467 "Do multiple replacements on the buffer.
468 ALIST is a list of (FROM . TO) pairs, which should be proper arguments to
469 `search-forward' and `replace-match', respectively.
470 Optional second arg REVERSE, if non-nil, means the pairs are (TO . FROM),
471 so that you can use the same list in both directions if it contains only
472 literal strings.
473 Optional args BEG and END specify a region of the buffer on which to operate."
474 (save-excursion
475 (save-restriction
476 (or beg (setq beg (point-min)))
477 (if end (narrow-to-region (point-min) end))
478 (while alist
479 (let ((from (if reverse (cdr (car alist)) (car (car alist))))
480 (to (if reverse (car (car alist)) (cdr (car alist)))))
481 (goto-char beg)
482 (while (search-forward from nil t)
483 (goto-char (match-beginning 0))
484 (insert to)
485 (set-text-properties (- (point) (length to)) (point)
486 (text-properties-at (point)))
487 (delete-region (point) (+ (point) (- (match-end 0)
488 (match-beginning 0)))))
489 (setq alist (cdr alist)))))))
491 ;;; Some list-manipulation functions that we need.
493 (defun format-delq-cons (cons list)
494 "Remove the given CONS from LIST by side effect and return the new LIST.
495 Since CONS could be the first element of LIST, write
496 `\(setq foo \(format-delq-cons element foo))' to be sure of changing
497 the value of `foo'."
498 (if (eq cons list)
499 (cdr list)
500 (let ((p list))
501 (while (not (eq (cdr p) cons))
502 (if (null p) (error "format-delq-cons: not an element"))
503 (setq p (cdr p)))
504 ;; Now (cdr p) is the cons to delete
505 (setcdr p (cdr cons))
506 list)))
508 (defun format-make-relatively-unique (a b)
509 "Delete common elements of lists A and B, return as pair.
510 Compare using `equal'."
511 (let* ((acopy (copy-sequence a))
512 (bcopy (copy-sequence b))
513 (tail acopy))
514 (while tail
515 (let ((dup (member (car tail) bcopy))
516 (next (cdr tail)))
517 (if dup (setq acopy (format-delq-cons tail acopy)
518 bcopy (format-delq-cons dup bcopy)))
519 (setq tail next)))
520 (cons acopy bcopy)))
522 (defun format-common-tail (a b)
523 "Given two lists that have a common tail, return it.
524 Compare with `equal', and return the part of A that is equal to the
525 equivalent part of B. If even the last items of the two are not equal,
526 return nil."
527 (let ((la (length a))
528 (lb (length b)))
529 ;; Make sure they are the same length
530 (if (> la lb)
531 (setq a (nthcdr (- la lb) a))
532 (setq b (nthcdr (- lb la) b))))
533 (while (not (equal a b))
534 (setq a (cdr a)
535 b (cdr b)))
538 (defun format-proper-list-p (list)
539 "Return t if LIST is a proper list.
540 A proper list is a list ending with a nil cdr, not with an atom "
541 (when (listp list)
542 (while (consp list)
543 (setq list (cdr list)))
544 (null list)))
546 (defun format-reorder (items order)
547 "Arrange ITEMS to follow partial ORDER.
548 Elements of ITEMS equal to elements of ORDER will be rearranged
549 to follow the ORDER. Unmatched items will go last."
550 (if order
551 (let ((item (member (car order) items)))
552 (if item
553 (cons (car item)
554 (format-reorder (format-delq-cons item items)
555 (cdr order)))
556 (format-reorder items (cdr order))))
557 items))
559 (put 'face 'format-list-valued t) ; These text-properties take values
560 (put 'unknown 'format-list-valued t) ; that are lists, the elements of which
561 ; should be considered separately.
562 ; See format-deannotate-region and
563 ; format-annotate-region.
565 ;; This text property has list values, but they are treated atomically.
567 (put 'display 'format-list-atomic-p t)
570 ;;; Decoding
573 (defun format-deannotate-region (from to translations next-fn)
574 "Translate annotations in the region into text properties.
575 This sets text properties between FROM to TO as directed by the
576 TRANSLATIONS and NEXT-FN arguments.
578 NEXT-FN is a function that searches forward from point for an annotation.
579 It should return a list of 4 elements: \(BEGIN END NAME POSITIVE). BEGIN and
580 END are buffer positions bounding the annotation, NAME is the name searched
581 for in TRANSLATIONS, and POSITIVE should be non-nil if this annotation marks
582 the beginning of a region with some property, or nil if it ends the region.
583 NEXT-FN should return nil if there are no annotations after point.
585 The basic format of the TRANSLATIONS argument is described in the
586 documentation for the `format-annotate-region' function. There are some
587 additional things to keep in mind for decoding, though:
589 When an annotation is found, the TRANSLATIONS list is searched for a
590 text-property name and value that corresponds to that annotation. If the
591 text-property has several annotations associated with it, it will be used only
592 if the other annotations are also in effect at that point. The first match
593 found whose annotations are all present is used.
595 The text property thus determined is set to the value over the region between
596 the opening and closing annotations. However, if the text-property name has a
597 non-nil `format-list-valued' property, then the value will be consed onto the
598 surrounding value of the property, rather than replacing that value.
600 There are some special symbols that can be used in the \"property\" slot of
601 the TRANSLATIONS list: PARAMETER and FUNCTION \(spelled in uppercase).
602 Annotations listed under the pseudo-property PARAMETER are considered to be
603 arguments of the immediately surrounding annotation; the text between the
604 opening and closing parameter annotations is deleted from the buffer but saved
605 as a string.
607 The surrounding annotation should be listed under the pseudo-property
608 FUNCTION. Instead of inserting a text-property for this annotation,
609 the function listed in the VALUE slot is called to make whatever
610 changes are appropriate. It can also return a list of the form
611 \(START LOC PROP VALUE) which specifies a property to put on. The
612 function's first two arguments are the START and END locations, and
613 the rest of the arguments are any PARAMETERs found in that region.
615 Any annotations that are found by NEXT-FN but not defined by TRANSLATIONS
616 are saved as values of the `unknown' text-property \(which is list-valued).
617 The TRANSLATIONS list should usually contain an entry of the form
618 \(unknown \(nil format-annotate-value))
619 to write these unknown annotations back into the file."
620 (save-excursion
621 (save-restriction
622 (narrow-to-region (point-min) to)
623 (goto-char from)
624 (let (next open-ans todo loc unknown-ans)
625 (while (setq next (funcall next-fn))
626 (let* ((loc (nth 0 next))
627 (end (nth 1 next))
628 (name (nth 2 next))
629 (positive (nth 3 next))
630 (found nil))
632 ;; Delete the annotation
633 (delete-region loc end)
634 (cond
635 ;; Positive annotations are stacked, remembering location
636 (positive (push `(,name ((,loc . nil))) open-ans))
637 ;; It is a negative annotation:
638 ;; Close the top annotation & add its text property.
639 ;; If the file's nesting is messed up, the close might not match
640 ;; the top thing on the open-annotations stack.
641 ;; If no matching annotation is open, just ignore the close.
642 ((not (assoc name open-ans))
643 (message "Extra closing annotation (%s) in file" name))
644 ;; If one is open, but not on the top of the stack, close
645 ;; the things in between as well. Set `found' when the real
646 ;; one is closed.
648 (while (not found)
649 (let* ((top (car open-ans)) ; first on stack: should match.
650 (top-name (car top)) ; text property name
651 (top-extents (nth 1 top)) ; property regions
652 (params (cdr (cdr top))) ; parameters
653 (aalist translations)
654 (matched nil))
655 (if (equal name top-name)
656 (setq found t)
657 (message "Improper nesting in file."))
658 ;; Look through property names in TRANSLATIONS
659 (while aalist
660 (let ((prop (car (car aalist)))
661 (alist (cdr (car aalist))))
662 ;; And look through values for each property
663 (while alist
664 (let ((value (car (car alist)))
665 (ans (cdr (car alist))))
666 (if (member top-name ans)
667 ;; This annotation is listed, but still have to
668 ;; check if multiple annotations are satisfied
669 (if (member nil (mapcar (lambda (r)
670 (assoc r open-ans))
671 ans))
672 nil ; multiple ans not satisfied
673 ;; If there are multiple annotations going
674 ;; into one text property, split up the other
675 ;; annotations so they apply individually to
676 ;; the other regions.
677 (setcdr (car top-extents) loc)
678 (let ((to-split ans) this-one extents)
679 (while to-split
680 (setq this-one
681 (assoc (car to-split) open-ans)
682 extents (nth 1 this-one))
683 (if (not (eq this-one top))
684 (setcar (cdr this-one)
685 (format-subtract-regions
686 extents top-extents)))
687 (setq to-split (cdr to-split))))
688 ;; Set loop variables to nil so loop
689 ;; will exit.
690 (setq alist nil aalist nil matched t
691 ;; pop annotation off stack.
692 open-ans (cdr open-ans))
693 (let ((extents top-extents)
694 (start (car (car top-extents)))
695 (loc (cdr (car top-extents))))
696 (while extents
697 (cond
698 ;; Check for pseudo-properties
699 ((eq prop 'PARAMETER)
700 ;; A parameter of the top open ann:
701 ;; delete text and use as arg.
702 (if open-ans
703 ;; (If nothing open, discard).
704 (setq open-ans
705 (cons
706 (append (car open-ans)
707 (list
708 (buffer-substring
709 start loc)))
710 (cdr open-ans))))
711 (delete-region start loc))
712 ((eq prop 'FUNCTION)
713 ;; Not a property, but a function.
714 (let ((rtn
715 (apply value start loc params)))
716 (if rtn (push rtn todo))))
718 ;; Normal property/value pair
719 (setq todo
720 (cons (list start loc prop value)
721 todo))))
722 (setq extents (cdr extents)
723 start (car (car extents))
724 loc (cdr (car extents))))))))
725 (setq alist (cdr alist))))
726 (setq aalist (cdr aalist)))
727 (if (not matched)
728 ;; Didn't find any match for the annotation:
729 ;; Store as value of text-property `unknown'.
730 (let ((extents top-extents)
731 (start (car (car top-extents)))
732 (loc (or (cdr (car top-extents)) loc)))
733 (while extents
734 (setq open-ans (cdr open-ans)
735 todo (cons (list start loc 'unknown top-name)
736 todo)
737 unknown-ans (cons name unknown-ans)
738 extents (cdr extents)
739 start (car (car extents))
740 loc (cdr (car extents))))))))))))
742 ;; Once entire file has been scanned, add the properties.
743 (while todo
744 (let* ((item (car todo))
745 (from (nth 0 item))
746 (to (nth 1 item))
747 (prop (nth 2 item))
748 (val (nth 3 item)))
750 (if (numberp val) ; add to ambient value if numeric
751 (format-property-increment-region from to prop val 0)
752 (put-text-property
753 from to prop
754 (cond ((get prop 'format-list-valued) ; value gets consed onto
755 ; list-valued properties
756 (let ((prev (get-text-property from prop)))
757 (cons val (if (listp prev) prev (list prev)))))
758 (t val))))) ; normally, just set to val.
759 (setq todo (cdr todo)))
761 (if unknown-ans
762 (message "Unknown annotations: %s" unknown-ans))))))
764 (defun format-subtract-regions (minu subtra)
765 "Remove from the regions in MINUEND the regions in SUBTRAHEND.
766 A region is a dotted pair (FROM . TO). Both parameters are lists of
767 regions. Each list must contain nonoverlapping, noncontiguous
768 regions, in descending order. The result is also nonoverlapping,
769 noncontiguous, and in descending order. The first element of MINUEND
770 can have a cdr of nil, indicating that the end of that region is not
771 yet known.
773 \(fn MINUEND SUBTRAHEND)"
774 (let* ((minuend (copy-alist minu))
775 (subtrahend (copy-alist subtra))
776 (m (car minuend))
777 (s (car subtrahend))
778 results)
779 (while (and minuend subtrahend)
780 (cond
781 ;; The minuend starts after the subtrahend ends; keep it.
782 ((> (car m) (cdr s))
783 (push m results)
784 (setq minuend (cdr minuend)
785 m (car minuend)))
786 ;; The minuend extends beyond the end of the subtrahend. Chop it off.
787 ((or (null (cdr m)) (> (cdr m) (cdr s)))
788 (push (cons (1+ (cdr s)) (cdr m)) results)
789 (setcdr m (cdr s)))
790 ;; The subtrahend starts after the minuend ends; throw it away.
791 ((< (cdr m) (car s))
792 (setq subtrahend (cdr subtrahend) s (car subtrahend)))
793 ;; The subtrahend extends beyond the end of the minuend. Chop it off.
794 (t ;(<= (cdr m) (cdr s)))
795 (if (>= (car m) (car s))
796 (setq minuend (cdr minuend) m (car minuend))
797 (setcdr m (1- (car s)))
798 (setq subtrahend (cdr subtrahend) s (car subtrahend))))))
799 (nconc (nreverse results) minuend)))
801 ;; This should probably go somewhere other than format.el. Then again,
802 ;; indent.el has alter-text-property. NOTE: We can also use
803 ;; next-single-property-change instead of text-property-not-all, but then
804 ;; we have to see if we passed TO.
805 (defun format-property-increment-region (from to prop delta default)
806 "In the region from FROM to TO increment property PROP by amount DELTA.
807 DELTA may be negative. If property PROP is nil anywhere
808 in the region, it is treated as though it were DEFAULT."
809 (let ((cur from) val newval next)
810 (while cur
811 (setq val (get-text-property cur prop)
812 newval (+ (or val default) delta)
813 next (text-property-not-all cur to prop val))
814 (put-text-property cur (or next to) prop newval)
815 (setq cur next))))
818 ;;; Encoding
821 (defun format-insert-annotations (list &optional offset)
822 "Apply list of annotations to buffer as `write-region' would.
823 Insert each element of the given LIST of buffer annotations at its
824 appropriate place. Use second arg OFFSET if the annotations' locations are
825 not relative to the beginning of the buffer: annotations will be inserted
826 at their location-OFFSET+1 \(ie, the offset is treated as the position of
827 the first character in the buffer)."
828 (if (not offset)
829 (setq offset 0)
830 (setq offset (1- offset)))
831 (let ((l (reverse list)))
832 (while l
833 (goto-char (- (car (car l)) offset))
834 (insert (cdr (car l)))
835 (setq l (cdr l)))))
837 (defun format-annotate-value (old new)
838 "Return OLD and NEW as a \(CLOSE . OPEN) annotation pair.
839 Useful as a default function for TRANSLATIONS alist when the value of the text
840 property is the name of the annotation that you want to use, as it is for the
841 `unknown' text property."
842 (cons (if old (list old))
843 (if new (list new))))
845 (defun format-annotate-region (from to translations format-fn ignore)
846 "Generate annotations for text properties in the region.
847 Search for changes between FROM and TO, and describe them with a list of
848 annotations as defined by alist TRANSLATIONS and FORMAT-FN. IGNORE lists text
849 properties not to consider; any text properties that are neither ignored nor
850 listed in TRANSLATIONS are warned about.
851 If you actually want to modify the region, give the return value of this
852 function to `format-insert-annotations'.
854 Format of the TRANSLATIONS argument:
856 Each element is a list whose car is a PROPERTY, and the following
857 elements have the form (VALUE ANNOTATIONS...).
858 Whenever the property takes on the value VALUE, the annotations
859 \(as formatted by FORMAT-FN) are inserted into the file.
860 When the property stops having that value, the matching negated annotation
861 will be inserted \(it may actually be closed earlier and reopened, if
862 necessary, to keep proper nesting).
864 If VALUE is a list, then each element of the list is dealt with
865 separately.
867 If a VALUE is numeric, then it is assumed that there is a single annotation
868 and each occurrence of it increments the value of the property by that number.
869 Thus, given the entry \(left-margin \(4 \"indent\")), if the left margin
870 changes from 4 to 12, two <indent> annotations will be generated.
872 If the VALUE is nil, then instead of annotations, a function should be
873 specified. This function is used as a default: it is called for all
874 transitions not explicitly listed in the table. The function is called with
875 two arguments, the OLD and NEW values of the property. It should return
876 a cons cell (CLOSE . OPEN) as `format-annotate-single-property-change' does.
878 The same TRANSLATIONS structure can be used in reverse for reading files."
879 (let ((all-ans nil) ; All annotations - becomes return value
880 (open-ans nil) ; Annotations not yet closed
881 (loc nil) ; Current location
882 (not-found nil)) ; Properties that couldn't be saved
883 (while (or (null loc)
884 (and (setq loc (next-property-change loc nil to))
885 (< loc to)))
886 (or loc (setq loc from))
887 (let* ((ans (format-annotate-location loc (= loc from) ignore translations))
888 (neg-ans (format-reorder (aref ans 0) open-ans))
889 (pos-ans (aref ans 1))
890 (ignored (aref ans 2)))
891 (setq not-found (append ignored not-found)
892 ignore (append ignored ignore))
893 ;; First do the negative (closing) annotations
894 (while neg-ans
895 ;; Check if it's missing. This can happen (eg, a numeric property
896 ;; going negative can generate closing annotations before there are
897 ;; any open). Warn user & ignore.
898 (if (not (member (car neg-ans) open-ans))
899 (message "Can't close %s: not open." (car neg-ans))
900 (while (not (equal (car neg-ans) (car open-ans)))
901 ;; To close anno. N, need to first close ans 1 to N-1,
902 ;; remembering to re-open them later.
903 (push (car open-ans) pos-ans)
904 (setq all-ans
905 (cons (cons loc (funcall format-fn (car open-ans) nil))
906 all-ans))
907 (setq open-ans (cdr open-ans)))
908 ;; Now remove the one we're really interested in from open list.
909 (setq open-ans (cdr open-ans))
910 ;; And put the closing annotation here.
911 (push (cons loc (funcall format-fn (car neg-ans) nil))
912 all-ans))
913 (setq neg-ans (cdr neg-ans)))
914 ;; Now deal with positive (opening) annotations
915 (let ((p pos-ans))
916 (while pos-ans
917 (push (car pos-ans) open-ans)
918 (push (cons loc (funcall format-fn (car pos-ans) t))
919 all-ans)
920 (setq pos-ans (cdr pos-ans))))))
922 ;; Close any annotations still open
923 (while open-ans
924 (setq all-ans
925 (cons (cons to (funcall format-fn (car open-ans) nil))
926 all-ans))
927 (setq open-ans (cdr open-ans)))
928 (if not-found
929 (message "These text properties could not be saved:\n %s"
930 not-found))
931 (nreverse all-ans)))
933 ;;; Internal functions for format-annotate-region.
935 (defun format-annotate-location (loc all ignore translations)
936 "Return annotation(s) needed at location LOC.
937 This includes any properties that change between LOC - 1 and LOC.
938 If ALL is true, don't look at previous location, but generate annotations for
939 all non-nil properties.
940 Third argument IGNORE is a list of text-properties not to consider.
941 Use the TRANSLATIONS alist (see `format-annotate-region' for doc).
943 Return value is a vector of 3 elements:
944 1. List of annotations to close
945 2. List of annotations to open.
946 3. List of properties that were ignored or couldn't be annotated.
948 The annotations in lists 1 and 2 need not be strings.
949 They can be whatever the FORMAT-FN in `format-annotate-region'
950 can handle. If that is `enriched-make-annotation', they can be
951 either strings, or lists of the form (PARAMETER VALUE)."
952 (let* ((prev-loc (1- loc))
953 (before-plist (if all nil (text-properties-at prev-loc)))
954 (after-plist (text-properties-at loc))
955 p negatives positives prop props not-found)
956 ;; make list of all property names involved
957 (setq p before-plist)
958 (while p
959 (if (not (memq (car p) props))
960 (push (car p) props))
961 (setq p (cdr (cdr p))))
962 (setq p after-plist)
963 (while p
964 (if (not (memq (car p) props))
965 (push (car p) props))
966 (setq p (cdr (cdr p))))
968 (while props
969 (setq prop (pop props))
970 (if (memq prop ignore)
971 nil ; If it's been ignored before, ignore it now.
972 (let ((before (if all nil (car (cdr (memq prop before-plist)))))
973 (after (car (cdr (memq prop after-plist)))))
974 (if (equal before after)
975 nil ; no change; ignore
976 (let ((result (format-annotate-single-property-change
977 prop before after translations)))
978 (if (not result)
979 (push prop not-found)
980 (setq negatives (nconc negatives (car result))
981 positives (nconc positives (cdr result)))))))))
982 (vector negatives positives not-found)))
984 (defun format-annotate-single-property-change (prop old new translations)
985 "Return annotations for property PROP changing from OLD to NEW.
986 These are searched for in the translations alist TRANSLATIONS
987 (see `format-annotate-region' for the format).
988 If NEW does not appear in the list, but there is a default function,
989 then call that function.
990 Return a cons of the form (CLOSE . OPEN)
991 where CLOSE is a list of annotations to close
992 and OPEN is a list of annotations to open.
994 The annotations in CLOSE and OPEN need not be strings.
995 They can be whatever the FORMAT-FN in `format-annotate-region'
996 can handle. If that is `enriched-make-annotation', they can be
997 either strings, or lists of the form (PARAMETER VALUE)."
999 (let ((prop-alist (cdr (assoc prop translations)))
1000 default)
1001 (if (not prop-alist)
1003 ;; If either old or new is a list, have to treat both that way.
1004 (if (and (or (listp old) (listp new))
1005 (not (get prop 'format-list-atomic-p)))
1006 (if (or (not (format-proper-list-p old))
1007 (not (format-proper-list-p new)))
1008 (format-annotate-atomic-property-change prop-alist old new)
1009 (let* ((old (if (listp old) old (list old)))
1010 (new (if (listp new) new (list new)))
1011 (tail (format-common-tail old new))
1012 close open)
1013 (while old
1014 (setq close
1015 (append (car (format-annotate-atomic-property-change
1016 prop-alist (car old) nil))
1017 close)
1018 old (cdr old)))
1019 (while new
1020 (setq open
1021 (append (cdr (format-annotate-atomic-property-change
1022 prop-alist nil (car new)))
1023 open)
1024 new (cdr new)))
1025 (format-make-relatively-unique close open)))
1026 (format-annotate-atomic-property-change prop-alist old new)))))
1028 (defun format-annotate-atomic-property-change (prop-alist old new)
1029 "Internal function to annotate a single property change.
1030 PROP-ALIST is the relevant element of a TRANSLATIONS list.
1031 OLD and NEW are the values."
1032 (let (num-ann)
1033 ;; If old and new values are numbers,
1034 ;; look for a number in PROP-ALIST.
1035 (if (and (or (null old) (numberp old))
1036 (or (null new) (numberp new)))
1037 (progn
1038 (setq num-ann prop-alist)
1039 (while (and num-ann (not (numberp (car (car num-ann)))))
1040 (setq num-ann (cdr num-ann)))))
1041 (if num-ann
1042 ;; Numerical annotation - use difference
1043 (progn
1044 ;; If property is numeric, nil means 0
1045 (cond ((and (numberp old) (null new))
1046 (setq new 0))
1047 ((and (numberp new) (null old))
1048 (setq old 0)))
1050 (let* ((entry (car num-ann))
1051 (increment (car entry))
1052 (n (ceiling (/ (float (- new old)) (float increment))))
1053 (anno (car (cdr entry))))
1054 (if (> n 0)
1055 (cons nil (make-list n anno))
1056 (cons (make-list (- n) anno) nil))))
1058 ;; Standard annotation
1059 (let ((close (and old (cdr (assoc old prop-alist))))
1060 (open (and new (cdr (assoc new prop-alist)))))
1061 (if (or close open)
1062 (format-make-relatively-unique close open)
1063 ;; Call "Default" function, if any
1064 (let ((default (assq nil prop-alist)))
1065 (if default
1066 (funcall (car (cdr default)) old new))))))))
1068 (provide 'format)
1070 ;; arch-tag: c387e9c7-a93d-47bf-89bc-8ca67e96755a
1071 ;;; format.el ends here