format.el 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070
  1. ;;; format.el --- read and save files in multiple formats
  2. ;; Copyright (C) 1994-1995, 1997, 1999, 2001-2012
  3. ;; Free Software 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. (copy-to-buffer copy-buf from to)
  203. (set-buffer copy-buf)
  204. (format-insert-annotations write-region-annotations-so-far from)
  205. (format-encode-run-method to-fn (point-min) (point-max) orig-buf)
  206. (when (buffer-live-p copy-buf)
  207. (with-current-buffer copy-buf
  208. ;; Set write-region-post-annotation-function to
  209. ;; delete the buffer once the write is done, but do
  210. ;; it after running to-fn so it doesn't affect
  211. ;; write-region calls in to-fn.
  212. (set (make-local-variable
  213. 'write-region-post-annotation-function)
  214. 'kill-buffer)))
  215. nil)
  216. ;; Otherwise just call function, it will return annotations.
  217. (funcall to-fn from to orig-buf)))))
  218. (defun format-decode (format length &optional visit-flag)
  219. ;; This function is called by insert-file-contents whenever a file is read.
  220. "Decode text from any known FORMAT.
  221. FORMAT is a symbol appearing in `format-alist' or a list of such symbols,
  222. or nil, in which case this function tries to guess the format of the data by
  223. matching against the regular expressions in `format-alist'. After a match is
  224. found and the region decoded, the alist is searched again from the beginning
  225. for another match.
  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 reverted list of formats used, and call any mode functions defined
  229. for those formats.
  230. Return the new length of the decoded region.
  231. For most purposes, consider using `format-decode-region' instead."
  232. (let ((mod (buffer-modified-p))
  233. (begin (point))
  234. (end (+ (point) length)))
  235. (unwind-protect
  236. (progn
  237. ;; Don't record undo information for the decoding.
  238. (if (null format)
  239. ;; Figure out which format it is in, remember list in `format'.
  240. (let ((try format-alist))
  241. (while try
  242. (let* ((f (car try))
  243. (regexp (nth 2 f))
  244. (p (point)))
  245. (if (and regexp (looking-at regexp)
  246. (< (match-end 0) (+ begin length)))
  247. (progn
  248. (push (car f) format)
  249. ;; Decode it
  250. (if (nth 3 f)
  251. (setq end (format-decode-run-method (nth 3 f) begin end)))
  252. ;; Call visit function if required
  253. (if (and visit-flag (nth 6 f)) (funcall (nth 6 f) 1))
  254. ;; Safeguard against either of the functions changing pt.
  255. (goto-char p)
  256. ;; Rewind list to look for another format
  257. (setq try format-alist))
  258. (setq try (cdr try))))))
  259. ;; Deal with given format(s)
  260. (or (listp format) (setq format (list format)))
  261. (let ((do format) f)
  262. (while do
  263. (or (setq f (assq (car do) format-alist))
  264. (error "Unknown format %s" (car do)))
  265. ;; Decode:
  266. (if (nth 3 f)
  267. (setq end (format-decode-run-method (nth 3 f) begin end)))
  268. ;; Call visit function if required
  269. (if (and visit-flag (nth 6 f)) (funcall (nth 6 f) 1))
  270. (setq do (cdr do))))
  271. ;; Encode in the opposite order.
  272. (setq format (reverse format)))
  273. (if visit-flag
  274. (setq buffer-file-format format)))
  275. (set-buffer-modified-p mod))
  276. ;; Return new length of region
  277. (- end begin)))
  278. ;;;
  279. ;;; Interactive functions & entry points
  280. ;;;
  281. (defun format-decode-buffer (&optional format)
  282. "Translate the buffer from some FORMAT.
  283. If the format is not specified, attempt a regexp-based guess.
  284. Set `buffer-file-format' to the format used, and call any
  285. format-specific mode functions."
  286. (interactive
  287. (list (format-read "Translate buffer from format (default guess): ")))
  288. (save-excursion
  289. (goto-char (point-min))
  290. (format-decode format (buffer-size) t)))
  291. (defun format-decode-region (from to &optional format)
  292. "Decode the region from some format.
  293. Arg FORMAT is optional; if omitted the format will be determined by looking
  294. for identifying regular expressions at the beginning of the region."
  295. (interactive
  296. (list (region-beginning) (region-end)
  297. (format-read "Translate region from format (default guess): ")))
  298. (save-excursion
  299. (goto-char from)
  300. (format-decode format (- to from) nil)))
  301. (defun format-encode-buffer (&optional format)
  302. "Translate the buffer into FORMAT.
  303. FORMAT defaults to `buffer-file-format'. It is a symbol naming one of the
  304. formats defined in `format-alist', or a list of such symbols."
  305. (interactive
  306. (list (format-read (format "Translate buffer to format (default %s): "
  307. buffer-file-format))))
  308. (format-encode-region (point-min) (point-max) format))
  309. (defun format-encode-region (beg end &optional format)
  310. "Translate the region into some FORMAT.
  311. FORMAT defaults to `buffer-file-format'. It is a symbol naming
  312. one of the formats defined in `format-alist', or a list of such symbols."
  313. (interactive
  314. (list (region-beginning) (region-end)
  315. (format-read (format "Translate region to format (default %s): "
  316. buffer-file-format))))
  317. (if (null format) (setq format buffer-file-format))
  318. (if (symbolp format) (setq format (list format)))
  319. (save-excursion
  320. (goto-char end)
  321. (let ((end (point-marker)))
  322. (while format
  323. (let* ((info (assq (car format) format-alist))
  324. (to-fn (nth 4 info))
  325. (modify (nth 5 info)))
  326. (if to-fn
  327. (if modify
  328. (setq end (format-encode-run-method to-fn beg end
  329. (current-buffer)))
  330. (format-insert-annotations
  331. (funcall to-fn beg end (current-buffer)))))
  332. (setq format (cdr format)))))))
  333. (defun format-write-file (filename format &optional confirm)
  334. "Write current buffer into FILENAME, using a format based on FORMAT.
  335. Constructs the actual format starting from FORMAT, then appending
  336. any elements from the value of `buffer-file-format' with a non-nil
  337. `preserve' flag (see the documentation of `format-alist'), if they
  338. are not already present in FORMAT. It then updates `buffer-file-format'
  339. with this format, making it the default for future saves.
  340. If the buffer is already visiting a file, you can specify a
  341. directory name as FILENAME, to write a file of the same old name
  342. in that directory.
  343. If optional third arg CONFIRM is non-nil, asks for confirmation before
  344. overwriting an existing file. Interactively, requires confirmation
  345. unless you supply a prefix argument."
  346. (interactive
  347. ;; Same interactive spec as write-file, plus format question.
  348. (let* ((file (if buffer-file-name
  349. (read-file-name "Write file: "
  350. nil nil nil nil)
  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)))))
  357. (list file fmt (not current-prefix-arg))))
  358. (let ((old-formats buffer-file-format)
  359. preserve-formats)
  360. (dolist (fmt old-formats)
  361. (let ((aelt (assq fmt format-alist)))
  362. (if (nth 7 aelt)
  363. (push fmt preserve-formats))))
  364. (setq buffer-file-format format)
  365. (dolist (fmt preserve-formats)
  366. (unless (memq fmt buffer-file-format)
  367. (setq buffer-file-format (append buffer-file-format (list fmt))))))
  368. (write-file filename confirm))
  369. (defun format-find-file (filename format)
  370. "Find the file FILENAME using data format FORMAT.
  371. If FORMAT is nil then do not do any format conversion."
  372. (interactive
  373. ;; Same interactive spec as write-file, plus format question.
  374. (let* ((file (read-file-name "Find file: "))
  375. (fmt (format-read (format "Read file `%s' in format: "
  376. (file-name-nondirectory file)))))
  377. (list file fmt)))
  378. (let ((format-alist nil))
  379. (find-file filename))
  380. (if format
  381. (format-decode-buffer format)))
  382. (defun format-insert-file (filename format &optional beg end)
  383. "Insert the contents of file FILENAME using data format FORMAT.
  384. If FORMAT is nil then do not do any format conversion.
  385. The optional third and fourth arguments BEG and END specify
  386. the part (in bytes) of the file to read.
  387. The return value is like the value of `insert-file-contents':
  388. a list (ABSOLUTE-FILE-NAME SIZE)."
  389. (interactive
  390. ;; Same interactive spec as write-file, plus format question.
  391. (let* ((file (read-file-name "Find file: "))
  392. (fmt (format-read (format "Read file `%s' in format: "
  393. (file-name-nondirectory file)))))
  394. (list file fmt)))
  395. (let (value size old-undo)
  396. ;; Record only one undo entry for the insertion. Inhibit point-motion and
  397. ;; modification hooks as with `insert-file-contents'.
  398. (let ((inhibit-point-motion-hooks t)
  399. (inhibit-modification-hooks t))
  400. ;; Don't bind `buffer-undo-list' to t here to assert that
  401. ;; `insert-file-contents' may record whether the buffer was unmodified
  402. ;; before.
  403. (let ((format-alist nil))
  404. (setq value (insert-file-contents filename nil beg end))
  405. (setq size (nth 1 value)))
  406. (when (consp buffer-undo-list)
  407. (let ((head (car buffer-undo-list)))
  408. (when (and (consp head)
  409. (equal (car head) (point))
  410. (equal (cdr head) (+ (point) size)))
  411. ;; Remove first entry from `buffer-undo-list', we shall insert
  412. ;; another one below.
  413. (setq old-undo (cdr buffer-undo-list)))))
  414. (when format
  415. (let ((buffer-undo-list t))
  416. (setq size (format-decode format size)
  417. value (list (car value) size)))
  418. (unless (eq buffer-undo-list t)
  419. (setq buffer-undo-list
  420. (cons (cons (point) (+ (point) size)) old-undo)))))
  421. (unless inhibit-modification-hooks
  422. (run-hook-with-args 'after-change-functions (point) (+ (point) size) 0))
  423. value))
  424. (defun format-read (&optional prompt)
  425. "Read and return the name of a format.
  426. Return value is a list, like `buffer-file-format'; it may be nil.
  427. Formats are defined in `format-alist'. Optional arg is the PROMPT to use."
  428. (let* ((table (mapcar (lambda (x) (list (symbol-name (car x))))
  429. format-alist))
  430. (ans (completing-read (or prompt "Format: ") table nil t)))
  431. (if (not (equal "" ans)) (list (intern ans)))))
  432. ;;;
  433. ;;; Below are some functions that may be useful in writing encoding and
  434. ;;; decoding functions for use in format-alist.
  435. ;;;
  436. (defun format-replace-strings (alist &optional reverse beg end)
  437. "Do multiple replacements on the buffer.
  438. ALIST is a list of (FROM . TO) pairs, which should be proper arguments to
  439. `search-forward' and `replace-match', respectively.
  440. Optional second arg REVERSE, if non-nil, means the pairs are (TO . FROM),
  441. so that you can use the same list in both directions if it contains only
  442. literal strings.
  443. Optional args BEG and END specify a region of the buffer on which to operate."
  444. (save-excursion
  445. (save-restriction
  446. (or beg (setq beg (point-min)))
  447. (if end (narrow-to-region (point-min) end))
  448. (while alist
  449. (let ((from (if reverse (cdr (car alist)) (car (car alist))))
  450. (to (if reverse (car (car alist)) (cdr (car alist)))))
  451. (goto-char beg)
  452. (while (search-forward from nil t)
  453. (goto-char (match-beginning 0))
  454. (insert to)
  455. (set-text-properties (- (point) (length to)) (point)
  456. (text-properties-at (point)))
  457. (delete-region (point) (+ (point) (- (match-end 0)
  458. (match-beginning 0)))))
  459. (setq alist (cdr alist)))))))
  460. ;;; Some list-manipulation functions that we need.
  461. (defun format-delq-cons (cons list)
  462. "Remove the given CONS from LIST by side effect and return the new LIST.
  463. Since CONS could be the first element of LIST, write
  464. `\(setq foo \(format-delq-cons element foo))' to be sure of changing
  465. the value of `foo'."
  466. (if (eq cons list)
  467. (cdr list)
  468. (let ((p list))
  469. (while (not (eq (cdr p) cons))
  470. (if (null p) (error "format-delq-cons: not an element"))
  471. (setq p (cdr p)))
  472. ;; Now (cdr p) is the cons to delete
  473. (setcdr p (cdr cons))
  474. list)))
  475. (defun format-make-relatively-unique (a b)
  476. "Delete common elements of lists A and B, return as pair.
  477. Compare using `equal'."
  478. (let* ((acopy (copy-sequence a))
  479. (bcopy (copy-sequence b))
  480. (tail acopy))
  481. (while tail
  482. (let ((dup (member (car tail) bcopy))
  483. (next (cdr tail)))
  484. (if dup (setq acopy (format-delq-cons tail acopy)
  485. bcopy (format-delq-cons dup bcopy)))
  486. (setq tail next)))
  487. (cons acopy bcopy)))
  488. (defun format-proper-list-p (list)
  489. "Return t if LIST is a proper list.
  490. A proper list is a list ending with a nil cdr, not with an atom "
  491. (when (listp list)
  492. (while (consp list)
  493. (setq list (cdr list)))
  494. (null list)))
  495. (defun format-reorder (items order)
  496. "Arrange ITEMS to follow partial ORDER.
  497. Elements of ITEMS equal to elements of ORDER will be rearranged
  498. to follow the ORDER. Unmatched items will go last."
  499. (if order
  500. (let ((item (member (car order) items)))
  501. (if item
  502. (cons (car item)
  503. (format-reorder (format-delq-cons item items)
  504. (cdr order)))
  505. (format-reorder items (cdr order))))
  506. items))
  507. (put 'face 'format-list-valued t) ; These text-properties take values
  508. (put 'unknown 'format-list-valued t) ; that are lists, the elements of which
  509. ; should be considered separately.
  510. ; See format-deannotate-region and
  511. ; format-annotate-region.
  512. ;; This text property has list values, but they are treated atomically.
  513. (put 'display 'format-list-atomic-p t)
  514. ;;;
  515. ;;; Decoding
  516. ;;;
  517. (defun format-deannotate-region (from to translations next-fn)
  518. "Translate annotations in the region into text properties.
  519. This sets text properties between FROM to TO as directed by the
  520. TRANSLATIONS and NEXT-FN arguments.
  521. NEXT-FN is a function that searches forward from point for an annotation.
  522. It should return a list of 4 elements: \(BEGIN END NAME POSITIVE). BEGIN and
  523. END are buffer positions bounding the annotation, NAME is the name searched
  524. for in TRANSLATIONS, and POSITIVE should be non-nil if this annotation marks
  525. the beginning of a region with some property, or nil if it ends the region.
  526. NEXT-FN should return nil if there are no annotations after point.
  527. The basic format of the TRANSLATIONS argument is described in the
  528. documentation for the `format-annotate-region' function. There are some
  529. additional things to keep in mind for decoding, though:
  530. When an annotation is found, the TRANSLATIONS list is searched for a
  531. text-property name and value that corresponds to that annotation. If the
  532. text-property has several annotations associated with it, it will be used only
  533. if the other annotations are also in effect at that point. The first match
  534. found whose annotations are all present is used.
  535. The text property thus determined is set to the value over the region between
  536. the opening and closing annotations. However, if the text-property name has a
  537. non-nil `format-list-valued' property, then the value will be consed onto the
  538. surrounding value of the property, rather than replacing that value.
  539. There are some special symbols that can be used in the \"property\" slot of
  540. the TRANSLATIONS list: PARAMETER and FUNCTION \(spelled in uppercase).
  541. Annotations listed under the pseudo-property PARAMETER are considered to be
  542. arguments of the immediately surrounding annotation; the text between the
  543. opening and closing parameter annotations is deleted from the buffer but saved
  544. as a string.
  545. The surrounding annotation should be listed under the pseudo-property
  546. FUNCTION. Instead of inserting a text-property for this annotation,
  547. the function listed in the VALUE slot is called to make whatever
  548. changes are appropriate. It can also return a list of the form
  549. \(START LOC PROP VALUE) which specifies a property to put on. The
  550. function's first two arguments are the START and END locations, and
  551. the rest of the arguments are any PARAMETERs found in that region.
  552. Any annotations that are found by NEXT-FN but not defined by TRANSLATIONS
  553. are saved as values of the `unknown' text-property \(which is list-valued).
  554. The TRANSLATIONS list should usually contain an entry of the form
  555. \(unknown \(nil format-annotate-value))
  556. to write these unknown annotations back into the file."
  557. (save-excursion
  558. (save-restriction
  559. (narrow-to-region (point-min) to)
  560. (goto-char from)
  561. (let (next open-ans todo unknown-ans)
  562. (while (setq next (funcall next-fn))
  563. (let* ((loc (nth 0 next))
  564. (end (nth 1 next))
  565. (name (nth 2 next))
  566. (positive (nth 3 next))
  567. (found nil))
  568. ;; Delete the annotation
  569. (delete-region loc end)
  570. (cond
  571. ;; Positive annotations are stacked, remembering location
  572. (positive (push `(,name ((,loc . nil))) open-ans))
  573. ;; It is a negative annotation:
  574. ;; Close the top annotation & add its text property.
  575. ;; If the file's nesting is messed up, the close might not match
  576. ;; the top thing on the open-annotations stack.
  577. ;; If no matching annotation is open, just ignore the close.
  578. ((not (assoc name open-ans))
  579. (message "Extra closing annotation (%s) in file" name))
  580. ;; If one is open, but not on the top of the stack, close
  581. ;; the things in between as well. Set `found' when the real
  582. ;; one is closed.
  583. (t
  584. (while (not found)
  585. (let* ((top (car open-ans)) ; first on stack: should match.
  586. (top-name (car top)) ; text property name
  587. (top-extents (nth 1 top)) ; property regions
  588. (params (cdr (cdr top))) ; parameters
  589. (aalist translations)
  590. (matched nil))
  591. (if (equal name top-name)
  592. (setq found t)
  593. (message "Improper nesting in file."))
  594. ;; Look through property names in TRANSLATIONS
  595. (while aalist
  596. (let ((prop (car (car aalist)))
  597. (alist (cdr (car aalist))))
  598. ;; And look through values for each property
  599. (while alist
  600. (let ((value (car (car alist)))
  601. (ans (cdr (car alist))))
  602. (if (member top-name ans)
  603. ;; This annotation is listed, but still have to
  604. ;; check if multiple annotations are satisfied
  605. (if (member nil (mapcar (lambda (r)
  606. (assoc r open-ans))
  607. ans))
  608. nil ; multiple ans not satisfied
  609. ;; If there are multiple annotations going
  610. ;; into one text property, split up the other
  611. ;; annotations so they apply individually to
  612. ;; the other regions.
  613. (setcdr (car top-extents) loc)
  614. (let ((to-split ans) this-one extents)
  615. (while to-split
  616. (setq this-one
  617. (assoc (car to-split) open-ans)
  618. extents (nth 1 this-one))
  619. (if (not (eq this-one top))
  620. (setcar (cdr this-one)
  621. (format-subtract-regions
  622. extents top-extents)))
  623. (setq to-split (cdr to-split))))
  624. ;; Set loop variables to nil so loop
  625. ;; will exit.
  626. (setq alist nil aalist nil matched t
  627. ;; pop annotation off stack.
  628. open-ans (cdr open-ans))
  629. (let ((extents top-extents)
  630. (start (car (car top-extents)))
  631. (loc (cdr (car top-extents))))
  632. (while extents
  633. (cond
  634. ;; Check for pseudo-properties
  635. ((eq prop 'PARAMETER)
  636. ;; A parameter of the top open ann:
  637. ;; delete text and use as arg.
  638. (if open-ans
  639. ;; (If nothing open, discard).
  640. (setq open-ans
  641. (cons
  642. (append (car open-ans)
  643. (list
  644. (buffer-substring
  645. start loc)))
  646. (cdr open-ans))))
  647. (delete-region start loc))
  648. ((eq prop 'FUNCTION)
  649. ;; Not a property, but a function.
  650. (let ((rtn
  651. (apply value start loc params)))
  652. (if rtn (push rtn todo))))
  653. (t
  654. ;; Normal property/value pair
  655. (setq todo
  656. (cons (list start loc prop value)
  657. todo))))
  658. (setq extents (cdr extents)
  659. start (car (car extents))
  660. loc (cdr (car extents))))))))
  661. (setq alist (cdr alist))))
  662. (setq aalist (cdr aalist)))
  663. (if (not matched)
  664. ;; Didn't find any match for the annotation:
  665. ;; Store as value of text-property `unknown'.
  666. (let ((extents top-extents)
  667. (start (car (car top-extents)))
  668. (loc (or (cdr (car top-extents)) loc)))
  669. (while extents
  670. (setq open-ans (cdr open-ans)
  671. todo (cons (list start loc 'unknown top-name)
  672. todo)
  673. unknown-ans (cons name unknown-ans)
  674. extents (cdr extents)
  675. start (car (car extents))
  676. loc (cdr (car extents))))))))))))
  677. ;; Once entire file has been scanned, add the properties.
  678. (while todo
  679. (let* ((item (car todo))
  680. (from (nth 0 item))
  681. (to (nth 1 item))
  682. (prop (nth 2 item))
  683. (val (nth 3 item)))
  684. (if (numberp val) ; add to ambient value if numeric
  685. (format-property-increment-region from to prop val 0)
  686. (put-text-property
  687. from to prop
  688. (cond ((get prop 'format-list-valued) ; value gets consed onto
  689. ; list-valued properties
  690. (let ((prev (get-text-property from prop)))
  691. (cons val (if (listp prev) prev (list prev)))))
  692. (t val))))) ; normally, just set to val.
  693. (setq todo (cdr todo)))
  694. (if unknown-ans
  695. (message "Unknown annotations: %s" unknown-ans))))))
  696. (defun format-subtract-regions (minu subtra)
  697. "Remove from the regions in MINUEND the regions in SUBTRAHEND.
  698. A region is a dotted pair (FROM . TO). Both parameters are lists of
  699. regions. Each list must contain nonoverlapping, noncontiguous
  700. regions, in descending order. The result is also nonoverlapping,
  701. noncontiguous, and in descending order. The first element of MINUEND
  702. can have a cdr of nil, indicating that the end of that region is not
  703. yet known.
  704. \(fn MINUEND SUBTRAHEND)"
  705. (let* ((minuend (copy-alist minu))
  706. (subtrahend (copy-alist subtra))
  707. (m (car minuend))
  708. (s (car subtrahend))
  709. results)
  710. (while (and minuend subtrahend)
  711. (cond
  712. ;; The minuend starts after the subtrahend ends; keep it.
  713. ((> (car m) (cdr s))
  714. (push m results)
  715. (setq minuend (cdr minuend)
  716. m (car minuend)))
  717. ;; The minuend extends beyond the end of the subtrahend. Chop it off.
  718. ((or (null (cdr m)) (> (cdr m) (cdr s)))
  719. (push (cons (1+ (cdr s)) (cdr m)) results)
  720. (setcdr m (cdr s)))
  721. ;; The subtrahend starts after the minuend ends; throw it away.
  722. ((< (cdr m) (car s))
  723. (setq subtrahend (cdr subtrahend) s (car subtrahend)))
  724. ;; The subtrahend extends beyond the end of the minuend. Chop it off.
  725. (t ;(<= (cdr m) (cdr s)))
  726. (if (>= (car m) (car s))
  727. (setq minuend (cdr minuend) m (car minuend))
  728. (setcdr m (1- (car s)))
  729. (setq subtrahend (cdr subtrahend) s (car subtrahend))))))
  730. (nconc (nreverse results) minuend)))
  731. ;; This should probably go somewhere other than format.el. Then again,
  732. ;; indent.el has alter-text-property. NOTE: We can also use
  733. ;; next-single-property-change instead of text-property-not-all, but then
  734. ;; we have to see if we passed TO.
  735. (defun format-property-increment-region (from to prop delta default)
  736. "In the region from FROM to TO increment property PROP by amount DELTA.
  737. DELTA may be negative. If property PROP is nil anywhere
  738. in the region, it is treated as though it were DEFAULT."
  739. (let ((cur from) val newval next)
  740. (while cur
  741. (setq val (get-text-property cur prop)
  742. newval (+ (or val default) delta)
  743. next (text-property-not-all cur to prop val))
  744. (put-text-property cur (or next to) prop newval)
  745. (setq cur next))))
  746. ;;;
  747. ;;; Encoding
  748. ;;;
  749. (defun format-insert-annotations (list &optional offset)
  750. "Apply list of annotations to buffer as `write-region' would.
  751. Insert each element of the given LIST of buffer annotations at its
  752. appropriate place. Use second arg OFFSET if the annotations' locations are
  753. not relative to the beginning of the buffer: annotations will be inserted
  754. at their location-OFFSET+1 \(ie, the offset is treated as the position of
  755. the first character in the buffer)."
  756. (if (not offset)
  757. (setq offset 0)
  758. (setq offset (1- offset)))
  759. (let ((l (reverse list)))
  760. (while l
  761. (goto-char (- (car (car l)) offset))
  762. (insert (cdr (car l)))
  763. (setq l (cdr l)))))
  764. (defun format-annotate-value (old new)
  765. "Return OLD and NEW as a \(CLOSE . OPEN) annotation pair.
  766. Useful as a default function for TRANSLATIONS alist when the value of the text
  767. property is the name of the annotation that you want to use, as it is for the
  768. `unknown' text property."
  769. (cons (if old (list old))
  770. (if new (list new))))
  771. (defun format-annotate-region (from to translations format-fn ignore)
  772. "Generate annotations for text properties in the region.
  773. Search for changes between FROM and TO, and describe them with a list of
  774. annotations as defined by alist TRANSLATIONS and FORMAT-FN. IGNORE lists text
  775. properties not to consider; any text properties that are neither ignored nor
  776. listed in TRANSLATIONS are warned about.
  777. If you actually want to modify the region, give the return value of this
  778. function to `format-insert-annotations'.
  779. Format of the TRANSLATIONS argument:
  780. Each element is a list whose car is a PROPERTY, and the following
  781. elements have the form (VALUE ANNOTATIONS...).
  782. Whenever the property takes on the value VALUE, the annotations
  783. \(as formatted by FORMAT-FN) are inserted into the file.
  784. When the property stops having that value, the matching negated annotation
  785. will be inserted \(it may actually be closed earlier and reopened, if
  786. necessary, to keep proper nesting).
  787. If VALUE is a list, then each element of the list is dealt with
  788. separately.
  789. If a VALUE is numeric, then it is assumed that there is a single annotation
  790. and each occurrence of it increments the value of the property by that number.
  791. Thus, given the entry \(left-margin \(4 \"indent\")), if the left margin
  792. changes from 4 to 12, two <indent> annotations will be generated.
  793. If the VALUE is nil, then instead of annotations, a function should be
  794. specified. This function is used as a default: it is called for all
  795. transitions not explicitly listed in the table. The function is called with
  796. two arguments, the OLD and NEW values of the property. It should return
  797. a cons cell (CLOSE . OPEN) as `format-annotate-single-property-change' does.
  798. The same TRANSLATIONS structure can be used in reverse for reading files."
  799. (let ((all-ans nil) ; All annotations - becomes return value
  800. (open-ans nil) ; Annotations not yet closed
  801. (loc nil) ; Current location
  802. (not-found nil)) ; Properties that couldn't be saved
  803. (while (or (null loc)
  804. (and (setq loc (next-property-change loc nil to))
  805. (< loc to)))
  806. (or loc (setq loc from))
  807. (let* ((ans (format-annotate-location loc (= loc from) ignore translations))
  808. (neg-ans (format-reorder (aref ans 0) open-ans))
  809. (pos-ans (aref ans 1))
  810. (ignored (aref ans 2)))
  811. (setq not-found (append ignored not-found)
  812. ignore (append ignored ignore))
  813. ;; First do the negative (closing) annotations
  814. (while neg-ans
  815. ;; Check if it's missing. This can happen (eg, a numeric property
  816. ;; going negative can generate closing annotations before there are
  817. ;; any open). Warn user & ignore.
  818. (if (not (member (car neg-ans) open-ans))
  819. (message "Can't close %s: not open." (car neg-ans))
  820. (while (not (equal (car neg-ans) (car open-ans)))
  821. ;; To close anno. N, need to first close ans 1 to N-1,
  822. ;; remembering to re-open them later.
  823. (push (car open-ans) pos-ans)
  824. (setq all-ans
  825. (cons (cons loc (funcall format-fn (car open-ans) nil))
  826. all-ans))
  827. (setq open-ans (cdr open-ans)))
  828. ;; Now remove the one we're really interested in from open list.
  829. (setq open-ans (cdr open-ans))
  830. ;; And put the closing annotation here.
  831. (push (cons loc (funcall format-fn (car neg-ans) nil))
  832. all-ans))
  833. (setq neg-ans (cdr neg-ans)))
  834. ;; Now deal with positive (opening) annotations
  835. (while pos-ans
  836. (push (car pos-ans) open-ans)
  837. (push (cons loc (funcall format-fn (car pos-ans) t))
  838. all-ans)
  839. (setq pos-ans (cdr pos-ans)))))
  840. ;; Close any annotations still open
  841. (while open-ans
  842. (setq all-ans
  843. (cons (cons to (funcall format-fn (car open-ans) nil))
  844. all-ans))
  845. (setq open-ans (cdr open-ans)))
  846. (if not-found
  847. (message "These text properties could not be saved:\n %s"
  848. not-found))
  849. (nreverse all-ans)))
  850. ;;; Internal functions for format-annotate-region.
  851. (defun format-annotate-location (loc all ignore translations)
  852. "Return annotation(s) needed at location LOC.
  853. This includes any properties that change between LOC - 1 and LOC.
  854. If ALL is true, don't look at previous location, but generate annotations for
  855. all non-nil properties.
  856. Third argument IGNORE is a list of text-properties not to consider.
  857. Use the TRANSLATIONS alist (see `format-annotate-region' for doc).
  858. Return value is a vector of 3 elements:
  859. 1. List of annotations to close
  860. 2. List of annotations to open.
  861. 3. List of properties that were ignored or couldn't be annotated.
  862. The annotations in lists 1 and 2 need not be strings.
  863. They can be whatever the FORMAT-FN in `format-annotate-region'
  864. can handle. If that is `enriched-make-annotation', they can be
  865. either strings, or lists of the form (PARAMETER VALUE)."
  866. (let* ((prev-loc (1- loc))
  867. (before-plist (if all nil (text-properties-at prev-loc)))
  868. (after-plist (text-properties-at loc))
  869. p negatives positives prop props not-found)
  870. ;; make list of all property names involved
  871. (setq p before-plist)
  872. (while p
  873. (if (not (memq (car p) props))
  874. (push (car p) props))
  875. (setq p (cdr (cdr p))))
  876. (setq p after-plist)
  877. (while p
  878. (if (not (memq (car p) props))
  879. (push (car p) props))
  880. (setq p (cdr (cdr p))))
  881. (while props
  882. (setq prop (pop props))
  883. (if (memq prop ignore)
  884. nil ; If it's been ignored before, ignore it now.
  885. (let ((before (if all nil (car (cdr (memq prop before-plist)))))
  886. (after (car (cdr (memq prop after-plist)))))
  887. (if (equal before after)
  888. nil ; no change; ignore
  889. (let ((result (format-annotate-single-property-change
  890. prop before after translations)))
  891. (if (not result)
  892. (push prop not-found)
  893. (setq negatives (nconc negatives (car result))
  894. positives (nconc positives (cdr result)))))))))
  895. (vector negatives positives not-found)))
  896. (defun format-annotate-single-property-change (prop old new translations)
  897. "Return annotations for property PROP changing from OLD to NEW.
  898. These are searched for in the translations alist TRANSLATIONS
  899. (see `format-annotate-region' for the format).
  900. If NEW does not appear in the list, but there is a default function,
  901. then call that function.
  902. Return a cons of the form (CLOSE . OPEN)
  903. where CLOSE is a list of annotations to close
  904. and OPEN is a list of annotations to open.
  905. The annotations in CLOSE and OPEN need not be strings.
  906. They can be whatever the FORMAT-FN in `format-annotate-region'
  907. can handle. If that is `enriched-make-annotation', they can be
  908. either strings, or lists of the form (PARAMETER VALUE)."
  909. (let ((prop-alist (cdr (assoc prop translations))))
  910. (if (not prop-alist)
  911. nil
  912. ;; If either old or new is a list, have to treat both that way.
  913. (if (and (or (listp old) (listp new))
  914. (not (get prop 'format-list-atomic-p)))
  915. (if (or (not (format-proper-list-p old))
  916. (not (format-proper-list-p new)))
  917. (format-annotate-atomic-property-change prop-alist old new)
  918. (let* ((old (if (listp old) old (list old)))
  919. (new (if (listp new) new (list new)))
  920. close open)
  921. (while old
  922. (setq close
  923. (append (car (format-annotate-atomic-property-change
  924. prop-alist (car old) nil))
  925. close)
  926. old (cdr old)))
  927. (while new
  928. (setq open
  929. (append (cdr (format-annotate-atomic-property-change
  930. prop-alist nil (car new)))
  931. open)
  932. new (cdr new)))
  933. (format-make-relatively-unique close open)))
  934. (format-annotate-atomic-property-change prop-alist old new)))))
  935. (defun format-annotate-atomic-property-change (prop-alist old new)
  936. "Internal function to annotate a single property change.
  937. PROP-ALIST is the relevant element of a TRANSLATIONS list.
  938. OLD and NEW are the values."
  939. (let (num-ann)
  940. ;; If old and new values are numbers,
  941. ;; look for a number in PROP-ALIST.
  942. (if (and (or (null old) (numberp old))
  943. (or (null new) (numberp new)))
  944. (progn
  945. (setq num-ann prop-alist)
  946. (while (and num-ann (not (numberp (car (car num-ann)))))
  947. (setq num-ann (cdr num-ann)))))
  948. (if num-ann
  949. ;; Numerical annotation - use difference
  950. (progn
  951. ;; If property is numeric, nil means 0
  952. (cond ((and (numberp old) (null new))
  953. (setq new 0))
  954. ((and (numberp new) (null old))
  955. (setq old 0)))
  956. (let* ((entry (car num-ann))
  957. (increment (car entry))
  958. (n (ceiling (/ (float (- new old)) (float increment))))
  959. (anno (car (cdr entry))))
  960. (if (> n 0)
  961. (cons nil (make-list n anno))
  962. (cons (make-list (- n) anno) nil))))
  963. ;; Standard annotation
  964. (let ((close (and old (cdr (assoc old prop-alist))))
  965. (open (and new (cdr (assoc new prop-alist)))))
  966. (if (or close open)
  967. (format-make-relatively-unique close open)
  968. ;; Call "Default" function, if any
  969. (let ((default (assq nil prop-alist)))
  970. (if default
  971. (funcall (car (cdr default)) old new))))))))
  972. (provide 'format)
  973. ;;; format.el ends here