format.el 42 KB

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