1 ;;; format.el --- read and save files in multiple formats
3 ;; Copyright (c) 1994, 1995, 1997 Free Software Foundation
5 ;; Author: Boris Goldowsky <boris@gnu.ai.mit.edu>
6 ;; Keywords: extensions, dumped
8 ;; This file is part of SXEmacs.
10 ;; SXEmacs 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 ;; SXEmacs 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 this program. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Synched up with: Emacs 20.2.
27 ;; This file is dumped with SXEmacs.
29 ;; This file defines a unified mechanism for saving & loading files stored
30 ;; in different formats. `format-alist' contains information that directs
31 ;; Emacs to call an encoding or decoding function when reading or writing
32 ;; files that match certain conditions.
34 ;; When a file is visited, its format is determined by matching the
35 ;; beginning of the file against regular expressions stored in
36 ;; `format-alist'. If this fails, you can manually translate the buffer
37 ;; using `format-decode-buffer'. In either case, the formats used are
38 ;; listed in the variable `buffer-file-format', and become the default
39 ;; format for saving the buffer. To save a buffer in a different format,
40 ;; change this variable, or use `format-write-file'.
42 ;; Auto-save files are normally created in the same format as the visited
43 ;; file, but the variable `auto-save-file-format' can be set to a
44 ;; particularly fast or otherwise preferred format to be used for
45 ;; auto-saving (or nil to do no encoding on auto-save files, but then you
46 ;; risk losing any text-properties in the buffer).
48 ;; You can manually translate a buffer into or out of a particular format
49 ;; with the functions `format-encode-buffer' and `format-decode-buffer'.
50 ;; To translate just the region use the functions `format-encode-region'
51 ;; and `format-decode-region'.
53 ;; You can define a new format by writing the encoding and decoding
54 ;; functions, and adding an entry to `format-alist'. See enriched.el for
55 ;; an example of how to implement a file format. There are various
56 ;; functions defined in this file that may be useful for writing the
57 ;; encoding and decoding functions:
58 ;; * `format-annotate-region' and `format-deannotate-region' allow a
59 ;; single alist of information to be used for encoding and decoding.
60 ;; The alist defines a correspondence between strings in the file
61 ;; ("annotations") and text-properties in the buffer.
62 ;; * `format-replace-strings' is similarly useful for doing simple
63 ;; string->string translations in a reversible manner.
67 (put 'buffer-file-format 'permanent-local t)
71 ; (image/jpeg "JPEG image" "\377\330\377\340\000\020JFIF"
72 ; image-decode-jpeg nil t image-mode)
73 ; (image/gif "GIF image" "GIF8[79]"
74 ; image-decode-gif nil t image-mode)
75 ; (image/png "Portable Network Graphics" "\211PNG"
76 ; image-decode-png nil t image-mode)
77 ; (image/x-xpm "XPM image" "/\\* XPM \\*/"
78 ; image-decode-xpm nil t image-mode)
80 ; ;; TIFF files have lousy magic
81 ; (image/tiff "TIFF image" "II\\*\000"
82 ; image-decode-tiff nil t image-mode) ;; TIFF 6.0 big-endian
83 ; (image/tiff "TIFF image" "MM\000\\*"
84 ; image-decode-tiff nil t image-mode) ;; TIFF 6.0 little-endian
86 (text/enriched "Extended MIME text/enriched format."
87 "Content-[Tt]ype:[ \t]*text/enriched"
88 enriched-decode enriched-encode t enriched-mode)
89 (text/richtext "Extended MIME obsolete text/richtext format."
90 "Content-[Tt]ype:[ \t]*text/richtext"
91 richtext-decode richtext-encode t enriched-mode)
92 (plain "ISO 8859-1 standard format, no text properties."
93 ;; Plain only exists so that there is an obvious neutral choice in
94 ;; the completion list.
96 ;; (ibm "IBM Code Page 850 (DOS)"
98 ;; "recode ibm-pc:latin1" "recode latin1:ibm-pc" t nil)
99 ;; (mac "Apple Macintosh"
101 ;; "recode mac:latin1" "recode latin1:mac" t nil)
104 ;; "recode roman8:latin1" "recode latin1:roman8" t nil)
105 ;; (TeX "TeX (encoding)"
107 ;; iso-tex2iso iso-iso2tex t nil)
108 ;; (gtex "German TeX (encoding)"
110 ;; iso-gtex2iso iso-iso2gtex t nil)
111 ;; (html "HTML (encoding)"
113 ;; "recode html:latin1" "recode latin1:html" t nil)
116 ;; "tr a-mn-z n-za-m" "tr a-mn-z n-za-m" t nil)
117 ;; (duden "Duden Ersatzdarstellung"
119 ;; "diac" iso-iso2duden t nil)
120 ;; (de646 "German ASCII (ISO 646)"
122 ;; "recode iso646-ge:latin1" "recode latin1:iso646-ge" t nil)
123 ;; (denet "net German"
125 ;; iso-german iso-cvt-read-only t nil)
126 ;; (esnet "net Spanish"
128 ;; iso-spanish iso-cvt-read-only t nil)
130 "List of information about understood file formats.
131 Elements are of the form \(NAME DOC-STR REGEXP FROM-FN TO-FN MODIFY MODE-FN).
133 NAME is a symbol, which is stored in `buffer-file-format'.
135 DOC-STR should be a single line providing more information about the
136 format. It is currently unused, but in the future will be shown to
137 the user if they ask for more information.
139 REGEXP is a regular expression to match against the beginning of the file;
140 it should match only files in that format.
142 FROM-FN is called to decode files in that format; it gets two args, BEGIN
143 and END, and can make any modifications it likes, returning the new
144 end. It must make sure that the beginning of the file no longer
145 matches REGEXP, or else it will get called again.
146 Alternatively, FROM-FN can be a string, which specifies a shell command
147 (including options) to be used as a filter to perform the conversion.
149 TO-FN is called to encode a region into that format; it is passed three
150 arguments: BEGIN, END, and BUFFER. BUFFER is the original buffer that
151 the data being written came from, which the function could use, for
152 example, to find the values of local variables. TO-FN should either
153 return a list of annotations like `write-region-annotate-functions',
154 or modify the region and return the new end.
155 Alternatively, TO-FN can be a string, which specifies a shell command
156 (including options) to be used as a filter to perform the conversion.
158 MODIFY, if non-nil, means the TO-FN wants to modify the region. If nil,
159 TO-FN will not make any changes but will instead return a list of
162 MODE-FN, if specified, is called when visiting a file with that format.")
164 ;;; Basic Functions (called from Lisp)
166 (defun format-encode-run-method (method from to &optional buffer)
167 "Translate using function or shell script METHOD the text from FROM to TO.
168 If METHOD is a string, it is a shell command;
169 otherwise, it should be a Lisp function.
170 BUFFER should be the buffer that the output originally came from."
174 (with-output-to-temp-buffer "*Format Errors*"
175 (shell-command-on-region from to method t nil))
177 (funcall method from to buffer)))
179 (defun format-decode-run-method (method from to &optional buffer)
180 "Decode using function or shell script METHOD the text from FROM to TO.
181 If METHOD is a string, it is a shell command;
182 otherwise, it should be a Lisp function."
185 (with-output-to-temp-buffer "*Format Errors*"
186 (shell-command-on-region from to method t nil))
188 (funcall method from to)))
190 (defun format-annotate-function (format from to orig-buf)
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 This function works like a function on `write-region-annotate-functions':
197 it either returns a list of annotations, or returns with a different buffer
198 current, which contains the modified text to write.
200 For most purposes, consider using `format-encode-region' instead."
201 ;; This function is called by write-region (actually build-annotations)
202 ;; for each element of buffer-file-format.
203 (let* ((info (assq format format-alist))
205 (modify (nth 5 info)))
208 ;; To-function wants to modify region. Copy to safe place.
209 (let ((copy-buf (get-buffer-create " *Format Temp*")))
210 (copy-to-buffer copy-buf from to)
211 (set-buffer copy-buf)
212 (format-insert-annotations write-region-annotations-so-far from)
213 (format-encode-run-method to-fn (point-min) (point-max) orig-buf)
215 ;; Otherwise just call function, it will return annotations.
216 (funcall to-fn from to orig-buf)))))
218 (defun format-decode (format length &optional visit-flag)
219 "Decode text from any known FORMAT.
220 FORMAT is a symbol appearing in `format-alist' or a list of such symbols,
221 or nil, in which case this function tries to guess the format of the data by
222 matching against the regular expressions in `format-alist'. After a match is
223 found and the region decoded, the alist is searched again from the beginning
226 Second arg LENGTH is the number of characters following point to operate on.
227 If optional third arg VISIT-FLAG is true, set `buffer-file-format'
228 to the list of formats used, and call any mode functions defined for those
231 Returns the new length of the decoded region.
233 For most purposes, consider using `format-decode-region' instead.
235 This function is called by insert-file-contents whenever a file is read."
236 (let ((mod (buffer-modified-p))
238 (end (+ (point) length)))
240 ;; Figure out which format it is in, remember list in `format'.
241 (let ((try format-alist))
246 (if (and regexp (looking-at regexp)
247 (< (match-end 0) (+ begin length)))
249 (setq format (cons (car f) format))
252 (setq end (format-decode-run-method (nth 3 f) begin end)))
253 ;; Call visit function if required
254 (if (and visit-flag (nth 6 f)) (funcall (nth 6 f) 1))
255 ;; Safeguard against either of the functions changing pt.
257 ;; Rewind list to look for another format
258 (setq try format-alist))
259 (setq try (cdr try))))))
260 ;; Deal with given format(s)
261 (or (listp format) (setq format (list format)))
264 (or (setq f (assq (car do) format-alist))
265 (error "Unknown format" (car do)))
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 (setq do (cdr do)))))
273 (setq buffer-file-format format))
274 (set-buffer-modified-p mod)
275 ;; Return new length of region
279 ;;; Interactive functions & entry points
282 (defun format-decode-buffer (&optional format)
283 "Translate the buffer from some FORMAT.
284 If the format is not specified, this function attempts to guess.
285 `buffer-file-format' is set to the format used, and any mode-functions
286 for the format are called."
288 (list (format-read "Translate buffer from format (default: guess): ")))
290 (goto-char (point-min))
291 (format-decode format (buffer-size) t)))
293 (defun format-decode-region (from to &optional format)
294 "Decode the region from some format.
295 Arg FORMAT is optional; if omitted the format will be determined by looking
296 for identifying regular expressions at the beginning of the region."
298 (list (region-beginning) (region-end)
299 (format-read "Translate region from format (default: guess): ")))
302 (format-decode format (- to from) nil)))
304 (defun format-encode-buffer (&optional format)
305 "Translate the buffer into FORMAT.
306 FORMAT defaults to `buffer-file-format'. It is a symbol naming one of the
307 formats defined in `format-alist', or a list of such symbols."
309 (list (format-read (format "Translate buffer to format (default %s): "
310 buffer-file-format))))
311 (format-encode-region (point-min) (point-max) format))
313 (defun format-encode-region (start end &optional format)
314 "Translate the region into some FORMAT.
315 FORMAT defaults to `buffer-file-format', it is a symbol naming
316 one of the formats defined in `format-alist', or a list of such symbols."
318 (list (region-beginning) (region-end)
319 (format-read (format "Translate region to format (default %s): "
320 buffer-file-format))))
321 (if (null format) (setq format buffer-file-format))
322 (if (symbolp format) (setq format (list format)))
325 (let ( ; (cur-buf (current-buffer))
326 (end (point-marker)))
328 (let* ((info (assq (car format) format-alist))
330 (modify (nth 5 info))
335 (setq end (format-encode-run-method to-fn start end
337 (format-insert-annotations
338 (funcall to-fn start end (current-buffer)))))
339 (setq format (cdr format)))))))
341 (defun format-write-file (filename format)
342 "Write current buffer into a FILE using some FORMAT.
343 Makes buffer visit that file and sets the format as the default for future
344 saves. If the buffer is already visiting a file, you can specify a directory
345 name as FILE, to write a file of the same old name in that directory."
347 ;; Same interactive spec as write-file, plus format question.
348 (let* ((file (if buffer-file-name
349 (read-file-name "Write file: "
351 (read-file-name "Write file: "
352 (cdr (assq 'default-directory
353 (buffer-local-variables)))
354 nil nil (buffer-name))))
355 (fmt (format-read (format "Write file `%s' in format: "
356 (file-name-nondirectory file)))))
358 (setq buffer-file-format format)
359 (write-file filename))
361 (defun format-find-file (filename format)
362 "Find the file FILE using data format FORMAT.
363 If FORMAT is nil then do not do any format conversion."
365 ;; Same interactive spec as write-file, plus format question.
366 (let* ((file (read-file-name "Find file: "))
367 (fmt (format-read (format "Read file `%s' in format: "
368 (file-name-nondirectory file)))))
370 (let ((format-alist nil))
371 (find-file filename))
373 (format-decode-buffer format)))
375 (defun format-insert-file (filename format &optional start end)
376 "Insert the contents of file FILE using data format FORMAT.
377 If FORMAT is nil then do not do any format conversion.
378 The optional third and fourth arguments START and END specify
379 the part of the file to read.
381 The return value is like the value of `insert-file-contents':
382 a list (ABSOLUTE-FILE-NAME . SIZE)."
384 ;; Same interactive spec as write-file, plus format question.
385 (let* ((file (read-file-name "Find file: "))
386 (fmt (format-read (format "Read file `%s' in format: "
387 (file-name-nondirectory file)))))
390 (let ((format-alist nil))
391 (setq value (insert-file-contents filename nil start end))
392 (setq size (nth 1 value)))
394 (setq size (format-decode format size)
395 value (cons (car value) size)))
398 (defun format-read (&optional prompt)
399 "Read and return the name of a format.
400 Return value is a list, like `buffer-file-format'; it may be nil.
401 Formats are defined in `format-alist'. Optional arg is the PROMPT to use."
402 (let* ((table (mapcar (lambda (x) (list (symbol-name (car x))))
404 (ans (completing-read (or prompt "Format: ") table nil t)))
405 (if (not (equal "" ans)) (list (intern ans)))))
409 ;;; Below are some functions that may be useful in writing encoding and
410 ;;; decoding functions for use in format-alist.
413 (defun format-replace-strings (alist &optional reverse start end)
414 "Do multiple replacements on the buffer.
415 ALIST is a list of (from . to) pairs, which should be proper arguments to
416 `search-forward' and `replace-match' respectively.
417 Optional 2nd arg REVERSE, if non-nil, means the pairs are (to . from), so that
418 you can use the same list in both directions if it contains only literal
420 Optional args BEGIN and END specify a region of the buffer to operate on."
423 (or start (setq start (point-min)))
424 (if end (narrow-to-region (point-min) end))
426 (let ((from (if reverse (cdr (car alist)) (car (car alist))))
427 (to (if reverse (car (cdr alist)) (cdr (car alist)))))
429 (while (search-forward from nil t)
430 (goto-char (match-beginning 0))
432 (set-text-properties (- (point) (length to)) (point)
433 (text-properties-at (point)))
434 (delete-region (point) (+ (point) (- (match-end 0)
435 (match-beginning 0)))))
436 (setq alist (cdr alist)))))))
438 ;;; Some list-manipulation functions that we need.
440 (defun format-delq-cons (cons list)
441 "Remove the given CONS from LIST by side effect,
442 and return the new LIST. Since CONS could be the first element
443 of LIST, write `\(setq foo \(format-delq-cons element foo))' to be sure of
444 changing the value of `foo'."
448 (while (not (eq (cdr p) cons))
449 (if (null p) (error "format-delq-cons: not an element."))
451 ;; Now (cdr p) is the cons to delete
452 (setcdr p (cdr cons))
455 (defun format-make-relatively-unique (a b)
456 "Delete common elements of lists A and B, return as pair.
457 Compares using `equal'."
458 (let* ((acopy (copy-sequence a))
459 (bcopy (copy-sequence b))
462 (let ((dup (member (car tail) bcopy))
464 (if dup (setq acopy (format-delq-cons tail acopy)
465 bcopy (format-delq-cons dup bcopy)))
469 (defun format-common-tail (a b)
470 "Given two lists that have a common tail, return it.
471 Compares with `equal', and returns the part of A that is equal to the
472 equivalent part of B. If even the last items of the two are not equal,
474 (let ((la (length a))
476 ;; Make sure they are the same length
478 (setq a (nthcdr (- la lb) a))
479 (setq b (nthcdr (- lb la) b))))
480 (while (not (equal a b))
485 (defun format-reorder (items order)
486 "Arrange ITEMS to following partial ORDER.
487 Elements of ITEMS equal to elements of ORDER will be rearranged to follow the
488 ORDER. Unmatched items will go last."
490 (let ((item (member (car order) items)))
493 (format-reorder (format-delq-cons item items)
495 (format-reorder items (cdr order))))
498 (put 'face 'format-list-valued t) ; These text-properties take values
499 (put 'unknown 'format-list-valued t) ; that are lists, the elements of which
500 ; should be considered separately.
501 ; See format-deannotate-region and
502 ; format-annotate-region.
508 (defun format-deannotate-region (from to translations next-fn)
509 "Translate annotations in the region into text properties.
510 This sets text properties between FROM to TO as directed by the
511 TRANSLATIONS and NEXT-FN arguments.
513 NEXT-FN is a function that searches forward from point for an annotation.
514 It should return a list of 4 elements: \(BEGIN END NAME POSITIVE). BEGIN and
515 END are buffer positions bounding the annotation, NAME is the name searched
516 for in TRANSLATIONS, and POSITIVE should be non-nil if this annotation marks
517 the beginning of a region with some property, or nil if it ends the region.
518 NEXT-FN should return nil if there are no annotations after point.
520 The basic format of the TRANSLATIONS argument is described in the
521 documentation for the `format-annotate-region' function. There are some
522 additional things to keep in mind for decoding, though:
524 When an annotation is found, the TRANSLATIONS list is searched for a
525 text-property name and value that corresponds to that annotation. If the
526 text-property has several annotations associated with it, it will be used only
527 if the other annotations are also in effect at that point. The first match
528 found whose annotations are all present is used.
530 The text property thus determined is set to the value over the region between
531 the opening and closing annotations. However, if the text-property name has a
532 non-nil `format-list-valued' property, then the value will be consed onto the
533 surrounding value of the property, rather than replacing that value.
535 There are some special symbols that can be used in the \"property\" slot of
536 the TRANSLATIONS list: PARAMETER and FUNCTION \(spelled in uppercase).
537 Annotations listed under the pseudo-property PARAMETER are considered to be
538 arguments of the immediately surrounding annotation; the text between the
539 opening and closing parameter annotations is deleted from the buffer but saved
540 as a string. The surrounding annotation should be listed under the
541 pseudo-property FUNCTION. Instead of inserting a text-property for this
542 annotation, the function listed in the VALUE slot is called to make whatever
543 changes are appropriate. The function's first two arguments are the START and
544 END locations, and the rest of the arguments are any PARAMETERs found in that
547 Any annotations that are found by NEXT-FN but not defined by TRANSLATIONS
548 are saved as values of the `unknown' text-property \(which is list-valued).
549 The TRANSLATIONS list should usually contain an entry of the form
550 \(unknown \(nil format-annotate-value))
551 to write these unknown annotations back into the file."
554 (narrow-to-region (point-min) to)
556 (let (next open-ans todo
559 (while (setq next (funcall next-fn))
560 (let* ((loc (nth 0 next))
563 (positive (nth 3 next))
566 ;; Delete the annotation
567 (delete-region loc end)
569 ;; Positive annotations are stacked, remembering location
570 (positive (setq open-ans (cons `(,name ((,loc . nil))) open-ans)))
571 ;; It is a negative annotation:
572 ;; Close the top annotation & add its text property.
573 ;; If the file's nesting is messed up, the close might not match
574 ;; the top thing on the open-annotations stack.
575 ;; If no matching annotation is open, just ignore the close.
576 ((not (assoc name open-ans))
577 (message "Extra closing annotation (%s) in file" name))
578 ;; If one is open, but not on the top of the stack, close
579 ;; the things in between as well. Set `found' when the real
583 (let* ((top (car open-ans)) ; first on stack: should match.
584 (top-name (car top)) ; text property name
585 (top-extents (nth 1 top)) ; property regions
586 (params (cdr (cdr top))) ; parameters
587 (aalist translations)
589 (if (equal name top-name)
591 (message "Improper nesting in file."))
592 ;; Look through property names in TRANSLATIONS
594 (let ((prop (car (car aalist)))
595 (alist (cdr (car aalist))))
596 ;; And look through values for each property
598 (let ((value (car (car alist)))
599 (ans (cdr (car alist))))
600 (if (member top-name ans)
601 ;; This annotation is listed, but still have to
602 ;; check if multiple annotations are satisfied
603 (if (member nil (mapcar (lambda (r)
606 nil ; multiple ans not satisfied
607 ;; If there are multiple annotations going
608 ;; into one text property, split up the other
609 ;; annotations so they apply individually to
610 ;; the other regions.
611 (setcdr (car top-extents) loc)
612 (let ((to-split ans) this-one extents)
615 (assoc (car to-split) open-ans)
616 extents (nth 1 this-one))
617 (if (not (eq this-one top))
618 (setcar (cdr this-one)
619 (format-subtract-regions
620 extents top-extents)))
621 (setq to-split (cdr to-split))))
622 ;; Set loop variables to nil so loop
624 (setq alist nil aalist nil matched t
625 ;; pop annotation off stack.
626 open-ans (cdr open-ans))
627 (let ((extents top-extents)
628 (start (car (car top-extents)))
629 (loc (cdr (car top-extents))))
632 ;; Check for pseudo-properties
633 ((eq prop 'PARAMETER)
634 ;; A parameter of the top open ann:
635 ;; delete text and use as arg.
637 ;; (If nothing open, discard).
640 (append (car open-ans)
645 (delete-region start loc))
647 ;; Not a property, but a function.
649 (apply value start loc params)))
650 (if rtn (setq todo (cons rtn todo)))))
652 ;; Normal property/value pair
654 (cons (list start loc prop value)
656 (setq extents (cdr extents)
657 start (car (car extents))
658 loc (cdr (car extents))))))))
659 (setq alist (cdr alist))))
660 (setq aalist (cdr aalist)))
662 ;; Didn't find any match for the annotation:
663 ;; Store as value of text-property `unknown'.
664 (setcdr (car top-extents) loc)
665 (let ((extents top-extents)
666 (start (car (car top-extents)))
667 (loc (cdr (car top-extents))))
669 (setq open-ans (cdr open-ans)
670 todo (cons (list start loc 'unknown top-name)
672 unknown-ans (cons name unknown-ans)
673 extents (cdr extents)
674 start (car (car extents))
675 loc (cdr (car extents))))))))))))
677 ;; Once entire file has been scanned, add the properties.
679 (let* ((item (car todo))
685 (if (numberp val) ; add to ambient value if numeric
686 (format-property-increment-region from to prop val 0)
689 (cond ((get prop 'format-list-valued) ; value gets consed onto
690 ; list-valued properties
691 (let ((prev (get-text-property from prop)))
692 (cons val (if (listp prev) prev (list prev)))))
693 (t val))))) ; normally, just set to val.
694 (setq todo (cdr todo)))
697 (message "Unknown annotations: %s" unknown-ans))))))
699 (defun format-subtract-regions (minu subtra)
700 "Remove the regions in SUBTRAHEND from the regions in MINUEND. A region
701 is a dotted pair (from . to). Both parameters are lists of regions. Each
702 list must contain nonoverlapping, noncontiguous regions, in descending
703 order. The result is also nonoverlapping, noncontiguous, and in descending
704 order. The first element of MINUEND can have a cdr of nil, indicating that
705 the end of that region is not yet known."
706 (let* ((minuend (copy-alist minu))
707 (subtrahend (copy-alist subtra))
711 (while (and minuend subtrahend)
713 ;; The minuend starts after the subtrahend ends; keep it.
715 (setq results (cons m results)
716 minuend (cdr minuend)
718 ;; The minuend extends beyond the end of the subtrahend. Chop it off.
719 ((or (null (cdr m)) (> (cdr m) (cdr s)))
720 (setq results (cons (cons (1+ (cdr s)) (cdr m)) results))
722 ;; The subtrahend starts after the minuend ends; throw it away.
724 (setq subtrahend (cdr subtrahend) s (car subtrahend)))
725 ;; The subtrahend extends beyond the end of the minuend. Chop it off.
726 (t ;(<= (cdr m) (cdr s)))
727 (if (>= (car m) (car s))
728 (setq minuend (cdr minuend) m (car minuend))
729 (setcdr m (1- (car s)))
730 (setq subtrahend (cdr subtrahend) s (car subtrahend))))))
731 (nconc (nreverse results) minuend)))
733 ;; This should probably go somewhere other than format.el. Then again,
734 ;; indent.el has alter-text-property. NOTE: We can also use
735 ;; next-single-property-change instead of text-property-not-all, but then
736 ;; we have to see if we passed TO.
737 (defun format-property-increment-region (from to prop delta default)
738 "Increment property PROP over the region between FROM and TO by the
739 amount DELTA (which may be negative). If property PROP is nil anywhere
740 in the region, it is treated as though it were DEFAULT."
741 (let ((cur from) val newval next)
743 (setq val (get-text-property cur prop)
744 newval (+ (or val default) delta)
745 next (text-property-not-all cur to prop val))
746 (put-text-property cur (or next to) prop newval)
753 (defun format-insert-annotations (list &optional offset)
754 "Apply list of annotations to buffer as `write-region' would.
755 Inserts each element of the given LIST of buffer annotations at its
756 appropriate place. Use second arg OFFSET if the annotations' locations are
757 not relative to the beginning of the buffer: annotations will be inserted
758 at their location-OFFSET+1 \(ie, the offset is treated as the character number
759 of the first character in the buffer)."
762 (setq offset (1- offset)))
763 (let ((l (reverse list)))
765 (goto-char (- (car (car l)) offset))
766 (insert (cdr (car l)))
769 (defun format-annotate-value (old new)
770 "Return OLD and NEW as a \(close . open) annotation pair.
771 Useful as a default function for TRANSLATIONS alist when the value of the text
772 property is the name of the annotation that you want to use, as it is for the
773 `unknown' text property."
774 (cons (if old (list old))
775 (if new (list new))))
777 (defun format-annotate-region (from to trans format-fn ignore)
778 "Generate annotations for text properties in the region.
779 Searches for changes between FROM and TO, and describes them with a list of
780 annotations as defined by alist TRANSLATIONS and FORMAT-FN. IGNORE lists text
781 properties not to consider; any text properties that are neither ignored nor
782 listed in TRANSLATIONS are warned about.
783 If you actually want to modify the region, give the return value of this
784 function to `format-insert-annotations'.
786 Format of the TRANSLATIONS argument:
788 Each element is a list whose car is a PROPERTY, and the following
789 elements are VALUES of that property followed by the names of zero or more
790 ANNOTATIONS. Whenever the property takes on that value, the annotations
791 \(as formatted by FORMAT-FN) are inserted into the file.
792 When the property stops having that value, the matching negated annotation
793 will be inserted \(it may actually be closed earlier and reopened, if
794 necessary, to keep proper nesting).
796 If the property's value is a list, then each element of the list is dealt with
799 If a VALUE is numeric, then it is assumed that there is a single annotation
800 and each occurrence of it increments the value of the property by that number.
801 Thus, given the entry \(left-margin \(4 \"indent\")), if the left margin
802 changes from 4 to 12, two <indent> annotations will be generated.
804 If the VALUE is nil, then instead of annotations, a function should be
805 specified. This function is used as a default: it is called for all
806 transitions not explicitly listed in the table. The function is called with
807 two arguments, the OLD and NEW values of the property. It should return
808 lists of annotations like `format-annotate-location' does.
810 The same structure can be used in reverse for reading files."
811 (let ((all-ans nil) ; All annotations - becomes return value
812 (open-ans nil) ; Annotations not yet closed
813 (loc nil) ; Current location
814 (not-found nil)) ; Properties that couldn't be saved
815 (while (or (null loc)
816 (and (setq loc (next-property-change loc nil to))
818 (or loc (setq loc from))
819 (let* ((ans (format-annotate-location loc (= loc from) ignore trans))
820 (neg-ans (format-reorder (aref ans 0) open-ans))
821 (pos-ans (aref ans 1))
822 (ignored (aref ans 2)))
823 (setq not-found (append ignored not-found)
824 ignore (append ignored ignore))
825 ;; First do the negative (closing) annotations
827 ;; Check if it's missing. This can happen (eg, a numeric property
828 ;; going negative can generate closing annotations before there are
829 ;; any open). Warn user & ignore.
830 (if (not (member (car neg-ans) open-ans))
831 (message "Can't close %s: not open." (car neg-ans))
832 (while (not (equal (car neg-ans) (car open-ans)))
833 ;; To close anno. N, need to first close ans 1 to N-1,
834 ;; remembering to re-open them later.
835 (setq pos-ans (cons (car open-ans) pos-ans))
837 (cons (cons loc (funcall format-fn (car open-ans) nil))
839 (setq open-ans (cdr open-ans)))
840 ;; Now remove the one we're really interested in from open list.
841 (setq open-ans (cdr open-ans))
842 ;; And put the closing annotation here.
844 (cons (cons loc (funcall format-fn (car neg-ans) nil))
846 (setq neg-ans (cdr neg-ans)))
847 ;; Now deal with positive (opening) annotations
851 (setq open-ans (cons (car pos-ans) open-ans))
853 (cons (cons loc (funcall format-fn (car pos-ans) t))
855 (setq pos-ans (cdr pos-ans))))))
857 ;; Close any annotations still open
860 (cons (cons to (funcall format-fn (car open-ans) nil))
862 (setq open-ans (cdr open-ans)))
864 (message "These text properties could not be saved:\n %s"
868 ;;; Internal functions for format-annotate-region.
870 (defun format-annotate-location (loc all ignore trans)
871 "Return annotation(s) needed at LOCATION.
872 This includes any properties that change between LOC-1 and LOC.
873 If ALL is true, don't look at previous location, but generate annotations for
874 all non-nil properties.
875 Third argument IGNORE is a list of text-properties not to consider.
877 Return value is a vector of 3 elements:
878 1. List of names of the annotations to close
879 2. List of the names of annotations to open.
880 3. List of properties that were ignored or couldn't be annotated."
881 (let* ((prev-loc (1- loc))
882 (before-plist (if all nil (text-properties-at prev-loc)))
883 (after-plist (text-properties-at loc))
884 p negatives positives prop props not-found)
885 ;; make list of all property names involved
886 (setq p before-plist)
888 (if (not (memq (car p) props))
889 (setq props (cons (car p) props)))
890 (setq p (cdr (cdr p))))
893 (if (not (memq (car p) props))
894 (setq props (cons (car p) props)))
895 (setq p (cdr (cdr p))))
898 (setq prop (car props)
900 (if (memq prop ignore)
901 nil ; If it's been ignored before, ignore it now.
902 (let ((before (if all nil (car (cdr (memq prop before-plist)))))
903 (after (car (cdr (memq prop after-plist)))))
904 (if (equal before after)
905 nil ; no change; ignore
906 (let ((result (format-annotate-single-property-change
907 prop before after trans)))
909 (setq not-found (cons prop not-found))
910 (setq negatives (nconc negatives (car result))
911 positives (nconc positives (cdr result)))))))))
912 (vector negatives positives not-found)))
914 (defun format-annotate-single-property-change (prop old new trans)
915 "Return annotations for PROPERTY changing from OLD to NEW.
916 These are searched for in the TRANSLATIONS alist.
917 If NEW does not appear in the list, but there is a default function, then that
919 Annotations to open and to close are returned as a dotted pair."
920 (let ((prop-alist (cdr (assoc prop trans)))
925 ;; If either old or new is a list, have to treat both that way.
926 (if (or (consp old) (consp new))
927 (let* ((old (if (listp old) old (list old)))
928 (new (if (listp new) new (list new)))
929 ;; (tail (format-common-tail old new))
933 (append (car (format-annotate-atomic-property-change
934 prop-alist (car old) nil))
939 (append (cdr (format-annotate-atomic-property-change
940 prop-alist nil (car new)))
943 (format-make-relatively-unique close open))
944 (format-annotate-atomic-property-change prop-alist old new)))))
946 (defun format-annotate-atomic-property-change (prop-alist old new)
947 "Internal function annotate a single property change.
948 PROP-ALIST is the relevant segment of a TRANSLATIONS list.
949 OLD and NEW are the values."
951 ;; If old and new values are numbers,
952 ;; look for a number in PROP-ALIST.
953 (if (and (or (null old) (numberp old))
954 (or (null new) (numberp new)))
956 (setq num-ann prop-alist)
957 (while (and num-ann (not (numberp (car (car num-ann)))))
958 (setq num-ann (cdr num-ann)))))
960 ;; Numerical annotation - use difference
962 ;; If property is numeric, nil means 0
963 (cond ((and (numberp old) (null new))
965 ((and (numberp new) (null old))
968 (let* ((entry (car num-ann))
969 (increment (car entry))
970 (n (ceiling (/ (float (- new old)) (float increment))))
971 (anno (car (cdr entry))))
973 (cons nil (make-list n anno))
974 (cons (make-list (- n) anno) nil))))
976 ;; Standard annotation
977 (let ((close (and old (cdr (assoc old prop-alist))))
978 (open (and new (cdr (assoc new prop-alist)))))
980 (format-make-relatively-unique close open)
981 ;; Call "Default" function, if any
982 (let ((default (assq nil prop-alist)))
984 (funcall (car (cdr default)) old new))))))))
986 ;;; format.el ends here