Sync to HEAD
[bpt/emacs.git] / lisp / format.el
CommitLineData
a8581027 1;;; format.el --- read and save files in multiple formats
b578f267 2
6b61353c 3;; Copyright (c) 1994, 1995, 1997, 1999, 2004 Free Software Foundation
029894b9 4
823139fb 5;; Author: Boris Goldowsky <boris@gnu.org>
029894b9
BG
6
7;; This file is part of GNU Emacs.
8
9;; GNU Emacs is free software; you can redistribute it and/or modify
10;; it under the terms of the GNU General Public License as published by
11;; the Free Software Foundation; either version 2, or (at your option)
12;; any later version.
b578f267 13
029894b9
BG
14;; GNU Emacs is distributed in the hope that it will be useful,
15;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17;; GNU General Public License for more details.
b578f267 18
029894b9 19;; You should have received a copy of the GNU General Public License
b578f267
EN
20;; along with GNU Emacs; see the file COPYING. If not, write to the
21;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22;; Boston, MA 02111-1307, USA.
029894b9
BG
23
24;;; Commentary:
b578f267
EN
25
26;; This file defines a unified mechanism for saving & loading files stored
27;; in different formats. `format-alist' contains information that directs
029894b9 28;; Emacs to call an encoding or decoding function when reading or writing
823139fb 29;; files that match certain conditions.
029894b9 30;;
b578f267
EN
31;; When a file is visited, its format is determined by matching the
32;; beginning of the file against regular expressions stored in
33;; `format-alist'. If this fails, you can manually translate the buffer
34;; using `format-decode-buffer'. In either case, the formats used are
35;; listed in the variable `buffer-file-format', and become the default
36;; format for saving the buffer. To save a buffer in a different format,
37;; change this variable, or use `format-write-file'.
029894b9
BG
38;;
39;; Auto-save files are normally created in the same format as the visited
b578f267
EN
40;; file, but the variable `auto-save-file-format' can be set to a
41;; particularly fast or otherwise preferred format to be used for
42;; auto-saving (or nil to do no encoding on auto-save files, but then you
43;; risk losing any text-properties in the buffer).
029894b9 44;;
b578f267
EN
45;; You can manually translate a buffer into or out of a particular format
46;; with the functions `format-encode-buffer' and `format-decode-buffer'.
47;; To translate just the region use the functions `format-encode-region'
823139fb 48;; and `format-decode-region'.
029894b9 49;;
b578f267
EN
50;; You can define a new format by writing the encoding and decoding
51;; functions, and adding an entry to `format-alist'. See enriched.el for
52;; an example of how to implement a file format. There are various
53;; functions defined in this file that may be useful for writing the
54;; encoding and decoding functions:
55;; * `format-annotate-region' and `format-deannotate-region' allow a
56;; single alist of information to be used for encoding and decoding.
57;; The alist defines a correspondence between strings in the file
58;; ("annotations") and text-properties in the buffer.
029894b9
BG
59;; * `format-replace-strings' is similarly useful for doing simple
60;; string->string translations in a reversible manner.
61
b578f267
EN
62;;; Code:
63
029894b9
BG
64(put 'buffer-file-format 'permanent-local t)
65
823139fb 66(defvar format-alist
8d0dd9d2 67 '((text/enriched "Extended MIME text/enriched format."
029894b9
BG
68 "Content-[Tt]ype:[ \t]*text/enriched"
69 enriched-decode enriched-encode t enriched-mode)
c84cf2bf 70 (plain "ISO 8859-1 standard format, no text properties."
029894b9
BG
71 ;; Plain only exists so that there is an obvious neutral choice in
72 ;; the completion list.
c84cf2bf 73 nil nil nil nil nil)
823139fb
DL
74 (TeX "TeX (encoding)"
75 nil
c84cf2bf 76 iso-tex2iso iso-iso2tex t nil)
823139fb
DL
77 (gtex "German TeX (encoding)"
78 nil
c84cf2bf 79 iso-gtex2iso iso-iso2gtex t nil)
f1d6fe69 80 (html "HTML/SGML \"ISO 8879:1986//ENTITIES Added Latin 1//EN\" (encoding)"
823139fb 81 nil
f1d6fe69 82 iso-sgml2iso iso-iso2sgml t nil)
823139fb
DL
83 (rot13 "rot13"
84 nil
c84cf2bf 85 "tr a-mn-z n-za-m" "tr a-mn-z n-za-m" t nil)
823139fb
DL
86 (duden "Duden Ersatzdarstellung"
87 nil
88 "diac" iso-iso2duden t nil)
89 (de646 "German ASCII (ISO 646)"
90 nil
271af233 91 "recode -f iso646-ge:latin1" "recode -f latin1:iso646-ge" t nil)
823139fb
DL
92 (denet "net German"
93 nil
c84cf2bf 94 iso-german iso-cvt-read-only t nil)
823139fb
DL
95 (esnet "net Spanish"
96 nil
8d0dd9d2 97 iso-spanish iso-cvt-read-only t nil))
029894b9
BG
98 "List of information about understood file formats.
99Elements are of the form \(NAME DOC-STR REGEXP FROM-FN TO-FN MODIFY MODE-FN).
d1ae737b 100
029894b9 101NAME is a symbol, which is stored in `buffer-file-format'.
d1ae737b 102
029894b9
BG
103DOC-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.
d1ae737b 106
029894b9 107REGEXP is a regular expression to match against the beginning of the file;
823139fb
DL
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.
d1ae737b 111
823139fb 112FROM-FN is called to decode files in that format; it gets two args, BEGIN
029894b9
BG
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.
d1ae737b
RS
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
d1abb42f
RS
119TO-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.
d1ae737b
RS
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
d1abb42f
RS
128MODIFY, 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
823139fb 130 annotations.
d1ae737b 131
3e224645
EZ
132MODE-FN, if specified, is called when visiting a file with that format.
133 It is called with a single positive argument, on the assumption
34f30f79
RS
134 that it turns on some Emacs mode.
135
136PRESERVE, if non-nil, means that `format-write-file' should not remove
137 this format from `buffer-file-formats'.")
029894b9
BG
138
139;;; Basic Functions (called from Lisp)
140
c84cf2bf
RS
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.
143If METHOD is a string, it is a shell command;
144otherwise, it should be a Lisp function.
145BUFFER should be the buffer that the output originally came from."
146 (if (stringp method)
823139fb 147 (let ((error-buff (get-buffer-create "*Format Errors*"))
7cc45a35 148 (coding-system-for-read 'no-conversion)
823139fb
DL
149 format-alist)
150 (with-current-buffer error-buff
151 (widen)
152 (erase-buffer))
10fa0073
GM
153 (if (and (zerop (save-window-excursion
154 (shell-command-on-region from to method t t
155 error-buff)))
823139fb
DL
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)
10fa0073 161 (error "Format encoding failed")))
c84cf2bf
RS
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.
823139fb
DL
166If METHOD is a string, it is a shell command; otherwise, it should be
167a Lisp function. Decoding is done for the given BUFFER."
c84cf2bf 168 (if (stringp method)
823139fb 169 (let ((error-buff (get-buffer-create "*Format Errors*"))
7cc45a35 170 (coding-system-for-write 'no-conversion)
823139fb
DL
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"))
c84cf2bf
RS
187 (point))
188 (funcall method from to)))
189
10fa0073 190(defun format-annotate-function (format from to orig-buf format-count)
823139fb 191 "Return annotations for writing region as FORMAT.
029894b9
BG
192FORMAT is a symbol naming one of the formats defined in `format-alist',
193it must be a single symbol, not a list like `buffer-file-format'.
d1abb42f
RS
194FROM and TO delimit the region to be operated on in the current buffer.
195ORIG-BUF is the original buffer that the data came from.
10fa0073
GM
196
197FORMAT-COUNT is an integer specifying how many times this function has
198been called in the process of decoding ORIG-BUF.
199
029894b9
BG
200This function works like a function on `write-region-annotate-functions':
201it either returns a list of annotations, or returns with a different buffer
10fa0073
GM
202current, which contains the modified text to write. In the latter case,
203this function's value is nil.
029894b9
BG
204
205For most purposes, consider using `format-encode-region' instead."
10fa0073
GM
206 ;; This function is called by write-region (actually
207 ;; build_annotations) for each element of buffer-file-format.
029894b9
BG
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.
10fa0073 214 (let ((copy-buf (get-buffer-create (format " *Format Temp %d*"
8a2f1176
RS
215 format-count)))
216 (sel-disp selective-display)
5258c763
JB
217 (multibyte enable-multibyte-characters)
218 (coding-system buffer-file-coding-system))
8a2f1176
RS
219 (with-current-buffer copy-buf
220 (setq selective-display sel-disp)
5258c763
JB
221 (set-buffer-multibyte multibyte)
222 (setq buffer-file-coding-system coding-system))
029894b9
BG
223 (copy-to-buffer copy-buf from to)
224 (set-buffer copy-buf)
225 (format-insert-annotations write-region-annotations-so-far from)
c84cf2bf 226 (format-encode-run-method to-fn (point-min) (point-max) orig-buf)
029894b9
BG
227 nil)
228 ;; Otherwise just call function, it will return annotations.
d1abb42f 229 (funcall to-fn from to orig-buf)))))
029894b9
BG
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.
823139fb 234FORMAT is a symbol appearing in `format-alist' or a list of such symbols,
029894b9
BG
235or nil, in which case this function tries to guess the format of the data by
236matching against the regular expressions in `format-alist'. After a match is
237found and the region decoded, the alist is searched again from the beginning
238for another match.
239
240Second arg LENGTH is the number of characters following point to operate on.
241If optional third arg VISIT-FLAG is true, set `buffer-file-format'
be227f22
SM
242to the reverted list of formats used, and call any mode functions defined
243for those formats.
029894b9
BG
244
245Returns the new length of the decoded region.
246
247For most purposes, consider using `format-decode-region' instead."
248 (let ((mod (buffer-modified-p))
10fa0073 249 (begin (point))
029894b9 250 (end (+ (point) length)))
10fa0073
GM
251 (unwind-protect
252 (progn
253 ;; Don't record undo information for the decoding.
71296446 254
10fa0073
GM
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
be227f22 265 (push (car f) format)
10fa0073
GM
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))
6b61353c 281 (error "Unknown format %s" (car do)))
10fa0073
GM
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))
be227f22
SM
287 (setq do (cdr do))))
288 ;; Encode in the opposite order.
289 (setq format (reverse format)))
10fa0073
GM
290 (if visit-flag
291 (setq buffer-file-format format)))
71296446 292
021cfbea
GM
293 (set-buffer-modified-p mod))
294
10fa0073 295 ;; Return new length of region
029894b9
BG
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.
304If the format is not specified, this function attempts to guess.
823139fb 305`buffer-file-format' is set to the format used, and any mode-functions
029894b9
BG
306for 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.
315Arg FORMAT is optional; if omitted the format will be determined by looking
316for identifying regular expressions at the beginning of the region."
317 (interactive
823139fb 318 (list (region-beginning) (region-end)
029894b9
BG
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.
326FORMAT defaults to `buffer-file-format'. It is a symbol naming one of the
327formats 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)
823139fb 334 "Translate the region into some FORMAT.
029894b9
BG
335FORMAT defaults to `buffer-file-format', it is a symbol naming
336one of the formats defined in `format-alist', or a list of such symbols."
823139fb
DL
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)))))))
029894b9 359
6b61353c 360(defun format-write-file (filename format &optional confirm)
823139fb 361 "Write current buffer into file FILENAME using some FORMAT.
6b61353c 362Make buffer visit that file and set the format as the default for future
029894b9 363saves. If the buffer is already visiting a file, you can specify a directory
6b61353c
KH
364name as FILENAME, to write a file of the same old name in that directory.
365
366If optional third arg CONFIRM is non-nil, this function asks for
367confirmation before overwriting an existing file. Interactively,
368confirmation is required unless you supply a prefix argument."
029894b9
BG
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))))
823139fb 378 (fmt (format-read (format "Write file `%s' in format: "
029894b9 379 (file-name-nondirectory file)))))
6b61353c 380 (list file fmt (not current-prefix-arg))))
34f30f79
RS
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))))))
6b61353c 391 (write-file filename confirm))
029894b9 392
ce6af52b 393(defun format-find-file (filename format)
823139fb 394 "Find the file FILENAME using data format FORMAT.
ce6af52b
KH
395If 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: "))
823139fb 399 (fmt (format-read (format "Read file `%s' in format: "
ce6af52b
KH
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)
823139fb 408 "Insert the contents of file FILENAME using data format FORMAT.
ce6af52b
KH
409If FORMAT is nil then do not do any format conversion.
410The optional third and fourth arguments BEG and END specify
411the part of the file to read.
412
413The return value is like the value of `insert-file-contents':
6b61353c 414a list (ABSOLUTE-FILE-NAME SIZE)."
ce6af52b
KH
415 (interactive
416 ;; Same interactive spec as write-file, plus format question.
417 (let* ((file (read-file-name "Find file: "))
823139fb 418 (fmt (format-read (format "Read file `%s' in format: "
ce6af52b
KH
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
c84cf2bf 426 (setq size (format-decode format size)
6b61353c 427 value (list (car value) size)))
ce6af52b
KH
428 value))
429
029894b9
BG
430(defun format-read (&optional prompt)
431 "Read and return the name of a format.
432Return value is a list, like `buffer-file-format'; it may be nil.
433Formats 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.
d0fc7e3b 447ALIST is a list of (FROM . TO) pairs, which should be proper arguments to
029894b9 448`search-forward' and `replace-match' respectively.
d0fc7e3b 449Optional 2nd arg REVERSE, if non-nil, means the pairs are (TO . FROM), so that
029894b9 450you can use the same list in both directions if it contains only literal
823139fb
DL
451strings.
452Optional args BEG and END specify a region of the buffer on which to operate."
029894b9
BG
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))))
2c3ac81d 459 (to (if reverse (car (car alist)) (cdr (car alist)))))
029894b9
BG
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)
823139fb
DL
473 "Remove the given CONS from LIST by side effect and return the new LIST.
474Since CONS could be the first element of LIST, write
475`\(setq foo \(format-delq-cons element foo))' to be sure of changing
476the value of `foo'."
029894b9
BG
477 (if (eq cons list)
478 (cdr list)
479 (let ((p list))
480 (while (not (eq (cdr p) cons))
e8af40ee 481 (if (null p) (error "format-delq-cons: not an element"))
029894b9
BG
482 (setq p (cdr p)))
483 ;; Now (cdr p) is the cons to delete
484 (setcdr p (cdr cons))
485 list)))
71296446 486
029894b9
BG
487(defun format-make-relatively-unique (a b)
488 "Delete common elements of lists A and B, return as pair.
489Compares 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.
503Compares with `equal', and returns the part of A that is equal to the
504equivalent part of B. If even the last items of the two are not equal,
505returns nil."
506 (let ((la (length a))
507 (lb (length b)))
508 ;; Make sure they are the same length
823139fb 509 (if (> la lb)
029894b9
BG
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
f0a6c717
GM
517(defun format-proper-list-p (list)
518 "Return t if LIST is a proper list.
519A 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
029894b9
BG
525(defun format-reorder (items order)
526 "Arrange ITEMS to following partial ORDER.
527Elements of ITEMS equal to elements of ORDER will be rearranged to follow the
528ORDER. Unmatched items will go last."
529 (if order
530 (let ((item (member (car order) items)))
531 (if item
823139fb 532 (cons (car item)
029894b9
BG
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
f3bbef87
GM
544;; This text property has list values, but they are treated atomically.
545
546(put 'display 'format-list-atomic-p t)
547
029894b9
BG
548;;;
549;;; Decoding
550;;;
551
552(defun format-deannotate-region (from to translations next-fn)
553 "Translate annotations in the region into text properties.
823139fb 554This sets text properties between FROM to TO as directed by the
029894b9
BG
555TRANSLATIONS and NEXT-FN arguments.
556
557NEXT-FN is a function that searches forward from point for an annotation.
558It should return a list of 4 elements: \(BEGIN END NAME POSITIVE). BEGIN and
559END are buffer positions bounding the annotation, NAME is the name searched
560for in TRANSLATIONS, and POSITIVE should be non-nil if this annotation marks
561the beginning of a region with some property, or nil if it ends the region.
562NEXT-FN should return nil if there are no annotations after point.
563
564The basic format of the TRANSLATIONS argument is described in the
565documentation for the `format-annotate-region' function. There are some
566additional things to keep in mind for decoding, though:
567
568When an annotation is found, the TRANSLATIONS list is searched for a
569text-property name and value that corresponds to that annotation. If the
570text-property has several annotations associated with it, it will be used only
571if the other annotations are also in effect at that point. The first match
572found whose annotations are all present is used.
573
574The text property thus determined is set to the value over the region between
575the opening and closing annotations. However, if the text-property name has a
576non-nil `format-list-valued' property, then the value will be consed onto the
577surrounding value of the property, rather than replacing that value.
578
579There are some special symbols that can be used in the \"property\" slot of
580the TRANSLATIONS list: PARAMETER and FUNCTION \(spelled in uppercase).
581Annotations listed under the pseudo-property PARAMETER are considered to be
582arguments of the immediately surrounding annotation; the text between the
583opening and closing parameter annotations is deleted from the buffer but saved
92308d3a
RS
584as a string.
585
586The surrounding annotation should be listed under the pseudo-property
587FUNCTION. Instead of inserting a text-property for this annotation,
588the function listed in the VALUE slot is called to make whatever
589changes are appropriate. It can also return a list of the form
590\(START LOC PROP VALUE) which specifies a property to put on. The
591function's first two arguments are the START and END locations, and
592the rest of the arguments are any PARAMETERs found in that region.
029894b9
BG
593
594Any annotations that are found by NEXT-FN but not defined by TRANSLATIONS
595are saved as values of the `unknown' text-property \(which is list-valued).
596The TRANSLATIONS list should usually contain an entry of the form
597 \(unknown \(nil format-annotate-value))
598to 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)
22828206
RS
613 (cond
614 ;; Positive annotations are stacked, remembering location
be227f22 615 (positive (push `(,name ((,loc . nil))) open-ans))
22828206
RS
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)))
be227f22 695 (if rtn (push rtn todo))))
22828206
RS
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)
029894b9
BG
707 ;; Didn't find any match for the annotation:
708 ;; Store as value of text-property `unknown'.
22828206
RS
709 (let ((extents top-extents)
710 (start (car (car top-extents)))
0b140219 711 (loc (or (cdr (car top-extents)) loc)))
22828206
RS
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))))))))))))
029894b9
BG
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)))
22828206
RS
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
029894b9 732 from to prop
22828206 733 (cond ((get prop 'format-list-valued) ; value gets consed onto
029894b9
BG
734 ; list-valued properties
735 (let ((prev (get-text-property from prop)))
736 (cons val (if (listp prev) prev (list prev)))))
22828206 737 (t val))))) ; normally, just set to val.
029894b9 738 (setq todo (cdr todo)))
22828206 739
029894b9
BG
740 (if unknown-ans
741 (message "Unknown annotations: %s" unknown-ans))))))
742
22828206 743(defun format-subtract-regions (minu subtra)
823139fb 744 "Remove from the regions in MINUend the regions in SUBTRAhend.
d0fc7e3b 745A region is a dotted pair (FROM . TO). Both parameters are lists of
823139fb
DL
746regions. Each list must contain nonoverlapping, noncontiguous
747regions, in descending order. The result is also nonoverlapping,
748noncontiguous, and in descending order. The first element of MINUEND
749can have a cdr of nil, indicating that the end of that region is not
750yet known."
22828206
RS
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)
823139fb 757 (cond
22828206
RS
758 ;; The minuend starts after the subtrahend ends; keep it.
759 ((> (car m) (cdr s))
be227f22
SM
760 (push m results)
761 (setq minuend (cdr minuend)
22828206
RS
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)))
be227f22 765 (push (cons (1+ (cdr s)) (cdr m)) results)
22828206
RS
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)
823139fb
DL
783 "Over the region between FROM and TO increment property PROP by amount DELTA.
784DELTA may be negative. If property PROP is nil anywhere
22828206
RS
785in 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
029894b9
BG
794;;;
795;;; Encoding
796;;;
797
798(defun format-insert-annotations (list &optional offset)
799 "Apply list of annotations to buffer as `write-region' would.
800Inserts each element of the given LIST of buffer annotations at its
801appropriate place. Use second arg OFFSET if the annotations' locations are
802not relative to the beginning of the buffer: annotations will be inserted
803at their location-OFFSET+1 \(ie, the offset is treated as the character number
804of the first character in the buffer)."
823139fb 805 (if (not offset)
029894b9
BG
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)
0b1ce6ba 815 "Return OLD and NEW as a \(CLOSE . OPEN) annotation pair.
029894b9
BG
816Useful as a default function for TRANSLATIONS alist when the value of the text
817property 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
823139fb 822(defun format-annotate-region (from to translations format-fn ignore)
029894b9
BG
823 "Generate annotations for text properties in the region.
824Searches for changes between FROM and TO, and describes them with a list of
825annotations as defined by alist TRANSLATIONS and FORMAT-FN. IGNORE lists text
826properties not to consider; any text properties that are neither ignored nor
827listed in TRANSLATIONS are warned about.
828If you actually want to modify the region, give the return value of this
829function to `format-insert-annotations'.
830
831Format of the TRANSLATIONS argument:
832
833Each element is a list whose car is a PROPERTY, and the following
d0fc7e3b
RS
834elements have the form (VALUE ANNOTATIONS...).
835Whenever the property takes on the value VALUE, the annotations
029894b9
BG
836\(as formatted by FORMAT-FN) are inserted into the file.
837When the property stops having that value, the matching negated annotation
838will be inserted \(it may actually be closed earlier and reopened, if
823139fb 839necessary, to keep proper nesting).
029894b9 840
d0fc7e3b 841If VALUE is a list, then each element of the list is dealt with
029894b9
BG
842separately.
843
844If a VALUE is numeric, then it is assumed that there is a single annotation
845and each occurrence of it increments the value of the property by that number.
846Thus, given the entry \(left-margin \(4 \"indent\")), if the left margin
847changes from 4 to 12, two <indent> annotations will be generated.
848
849If the VALUE is nil, then instead of annotations, a function should be
850specified. This function is used as a default: it is called for all
851transitions not explicitly listed in the table. The function is called with
852two arguments, the OLD and NEW values of the property. It should return
d0fc7e3b 853a cons cell (CLOSE . OPEN) as `format-annotate-single-property-change' does.
029894b9 854
d0fc7e3b 855The same TRANSLATIONS structure can be used in reverse for reading files."
029894b9
BG
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))
823139fb 864 (let* ((ans (format-annotate-location loc (= loc from) ignore translations))
029894b9
BG
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.
be227f22 880 (push (car open-ans) pos-ans)
823139fb 881 (setq all-ans
029894b9
BG
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.
be227f22
SM
888 (push (cons loc (funcall format-fn (car neg-ans) nil))
889 all-ans))
029894b9
BG
890 (setq neg-ans (cdr neg-ans)))
891 ;; Now deal with positive (opening) annotations
892 (let ((p pos-ans))
893 (while pos-ans
be227f22
SM
894 (push (car pos-ans) open-ans)
895 (push (cons loc (funcall format-fn (car pos-ans) t))
896 all-ans)
029894b9
BG
897 (setq pos-ans (cdr pos-ans))))))
898
899 ;; Close any annotations still open
900 (while open-ans
823139fb 901 (setq all-ans
029894b9
BG
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
823139fb
DL
912(defun format-annotate-location (loc all ignore translations)
913 "Return annotation(s) needed at location LOC.
029894b9
BG
914This includes any properties that change between LOC-1 and LOC.
915If ALL is true, don't look at previous location, but generate annotations for
916all non-nil properties.
917Third argument IGNORE is a list of text-properties not to consider.
d0fc7e3b 918Use the TRANSLATIONS alist (see `format-annotate-region' for doc).
029894b9
BG
919
920Return value is a vector of 3 elements:
d0fc7e3b
RS
9211. List of annotations to close
9222. List of annotations to open.
9233. List of properties that were ignored or couldn't be annotated.
924
925The annotations in lists 1 and 2 need not be strings.
926They can be whatever the FORMAT-FN in `format-annotate-region'
927can handle. If that is `enriched-make-annotation', they can be
928either strings, or lists of the form (PARAMETER VALUE)."
029894b9
BG
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))
be227f22 937 (push (car p) props))
029894b9
BG
938 (setq p (cdr (cdr p))))
939 (setq p after-plist)
940 (while p
941 (if (not (memq (car p) props))
be227f22 942 (push (car p) props))
029894b9
BG
943 (setq p (cdr (cdr p))))
944
945 (while props
be227f22 946 (setq prop (pop props))
029894b9
BG
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
823139fb 954 prop before after translations)))
029894b9 955 (if (not result)
be227f22 956 (push prop not-found)
029894b9
BG
957 (setq negatives (nconc negatives (car result))
958 positives (nconc positives (cdr result)))))))))
959 (vector negatives positives not-found)))
960
d0fc7e3b 961(defun format-annotate-single-property-change (prop old new translations)
823139fb 962 "Return annotations for property PROP changing from OLD to NEW.
d0fc7e3b
RS
963These are searched for in the translations alist TRANSLATIONS
964 (see `format-annotate-region' for the format).
029894b9
BG
965If NEW does not appear in the list, but there is a default function, then that
966function is called.
d0fc7e3b
RS
967Returns a cons of the form (CLOSE . OPEN)
968where CLOSE is a list of annotations to close
969and OPEN is a list of annotations to open.
970
971The annotations in CLOSE and OPEN need not be strings.
972They can be whatever the FORMAT-FN in `format-annotate-region'
973can handle. If that is `enriched-make-annotation', they can be
974either strings, or lists of the form (PARAMETER VALUE)."
975
976 (let ((prop-alist (cdr (assoc prop translations)))
029894b9
BG
977 default)
978 (if (not prop-alist)
979 nil
029894b9 980 ;; If either old or new is a list, have to treat both that way.
f0a6c717 981 (if (and (or (listp old) (listp new))
f3bbef87 982 (not (get prop 'format-list-atomic-p)))
f0a6c717
GM
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)))
029894b9
BG
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.
d0fc7e3b 1007PROP-ALIST is the relevant element of a TRANSLATIONS list.
029894b9 1008OLD and NEW are the values."
e5a60108
RS
1009 (let (num-ann)
1010 ;; If old and new values are numbers,
1011 ;; look for a number in PROP-ALIST.
5f525595
RS
1012 (if (and (or (null old) (numberp old))
1013 (or (null new) (numberp new)))
e5a60108
RS
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
5f525595 1019 ;; Numerical annotation - use difference
34fbecde
RS
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))))
e5a60108
RS
1034
1035 ;; Standard annotation
1036 (let ((close (and old (cdr (assoc old prop-alist))))
029894b9
BG
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
c84cf2bf 1045(provide 'format)
823139fb 1046
6b61353c 1047;;; arch-tag: c387e9c7-a93d-47bf-89bc-8ca67e96755a
823139fb 1048;;; format.el ends here