enriched.el 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. ;;; enriched.el --- read and save files in text/enriched format
  2. ;; Copyright (C) 1994-1996, 2001-2012 Free Software Foundation, Inc.
  3. ;; Author: Boris Goldowsky <boris@gnu.org>
  4. ;; Keywords: wp, faces
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This file implements reading, editing, and saving files with
  18. ;; text-properties such as faces, levels of indentation, and true line
  19. ;; breaks distinguished from newlines just used to fit text into the window.
  20. ;; The file format used is the MIME text/enriched format, which is a
  21. ;; standard format defined in internet RFC 1563. All standard annotations
  22. ;; are supported except for <smaller> and <bigger>, which are currently not
  23. ;; possible to display.
  24. ;; A separate file, enriched.doc, contains further documentation and other
  25. ;; important information about this code. It also serves as an example
  26. ;; file in text/enriched format. It should be in the etc directory of your
  27. ;; emacs distribution.
  28. ;;; Code:
  29. (provide 'enriched)
  30. ;;;
  31. ;;; Variables controlling the display
  32. ;;;
  33. (defgroup enriched nil
  34. "Read and save files in text/enriched format."
  35. :group 'wp)
  36. (defcustom enriched-verbose t
  37. "If non-nil, give status messages when reading and writing files."
  38. :type 'boolean
  39. :group 'enriched)
  40. ;;;
  41. ;;; Set up faces & display table
  42. ;;;
  43. ;; Emacs doesn't have a "fixed" face by default, since all faces currently
  44. ;; have to be fixed-width. So we just pick one that looks different from the
  45. ;; default.
  46. (defface fixed
  47. '((t (:weight bold)))
  48. "Face used for text that must be shown in fixed width.
  49. Currently, Emacs can only display fixed-width fonts, but this may change.
  50. This face is used for text specifically marked as fixed-width, for example
  51. in text/enriched files."
  52. :group 'enriched)
  53. (defface excerpt
  54. '((t (:slant italic)))
  55. "Face used for text that is an excerpt from another document.
  56. This is used in Enriched mode for text explicitly marked as an excerpt."
  57. :group 'enriched)
  58. (defconst enriched-display-table (or (copy-sequence standard-display-table)
  59. (make-display-table)))
  60. (aset enriched-display-table ?\f (make-vector (1- (frame-width)) ?-))
  61. (defconst enriched-par-props '(left-margin right-margin justification)
  62. "Text-properties that usually apply to whole paragraphs.
  63. These are set front-sticky everywhere except at hard newlines.")
  64. ;;;
  65. ;;; Variables controlling the file format
  66. ;;; (bidirectional)
  67. (defconst enriched-initial-annotation
  68. (lambda ()
  69. (format "Content-Type: text/enriched\nText-Width: %d\n\n"
  70. fill-column))
  71. "What to insert at the start of a text/enriched file.
  72. If this is a string, it is inserted. If it is a list, it should be a lambda
  73. expression, which is evaluated to get the string to insert.")
  74. (defconst enriched-annotation-format "<%s%s>"
  75. "General format of enriched-text annotations.")
  76. (defconst enriched-annotation-regexp "<\\(/\\)?\\([-A-Za-z0-9]+\\)>"
  77. "Regular expression matching enriched-text annotations.")
  78. (defvar enriched-translations
  79. '((face (bold-italic "bold" "italic")
  80. (bold "bold")
  81. (italic "italic")
  82. (underline "underline")
  83. (fixed "fixed")
  84. (excerpt "excerpt")
  85. (default )
  86. (nil enriched-encode-other-face))
  87. (left-margin (4 "indent"))
  88. (right-margin (4 "indentright"))
  89. (justification (none "nofill")
  90. (right "flushright")
  91. (left "flushleft")
  92. (full "flushboth")
  93. (center "center"))
  94. (PARAMETER (t "param")) ; Argument of preceding annotation
  95. ;; The following are not part of the standard:
  96. (FUNCTION (enriched-decode-foreground "x-color")
  97. (enriched-decode-background "x-bg-color")
  98. (enriched-decode-display-prop "x-display"))
  99. (read-only (t "x-read-only"))
  100. (display (nil enriched-handle-display-prop))
  101. (unknown (nil format-annotate-value))
  102. ; (font-size (2 "bigger") ; unimplemented
  103. ; (-2 "smaller"))
  104. )
  105. "List of definitions of text/enriched annotations.
  106. See `format-annotate-region' and `format-deannotate-region' for the definition
  107. of this structure.")
  108. (defconst enriched-ignore
  109. '(front-sticky rear-nonsticky hard)
  110. "Properties that are OK to ignore when saving text/enriched files.
  111. Any property that is neither on this list nor dealt with by
  112. `enriched-translations' will generate a warning.")
  113. ;;; Internal variables
  114. (defcustom enriched-mode-hook nil
  115. "Hook run after entering/leaving Enriched mode.
  116. If you set variables in this hook, you should arrange for them to be restored
  117. to their old values if you leave Enriched mode. One way to do this is to add
  118. them and their old values to `enriched-old-bindings'."
  119. :type 'hook
  120. :group 'enriched)
  121. (defvar enriched-old-bindings nil
  122. "Store old variable values that we change when entering mode.
  123. The value is a list of \(VAR VALUE VAR VALUE...).")
  124. (make-variable-buffer-local 'enriched-old-bindings)
  125. ;; The next variable is buffer local if and only if Enriched mode is
  126. ;; enabled. The buffer local value records whether
  127. ;; `default-text-properties' should remain buffer local when disabling
  128. ;; Enriched mode. For technical reasons, the default value should be t.
  129. (defvar enriched-default-text-properties-local-flag t)
  130. ;; Technical internal variable. Bound to t if `enriched-mode' is
  131. ;; being rerun by a major mode to allow it to restore buffer-local
  132. ;; variables and to correctly update `enriched-old-bindings'.
  133. (defvar enriched-rerun-flag nil)
  134. ;;;
  135. ;;; Keybindings
  136. ;;;
  137. (defvar enriched-mode-map
  138. (let ((map (make-sparse-keymap)))
  139. (define-key map [remap move-beginning-of-line] 'beginning-of-line-text)
  140. (define-key map "\C-m" 'reindent-then-newline-and-indent)
  141. (define-key map
  142. [remap newline-and-indent] 'reindent-then-newline-and-indent)
  143. (define-key map "\M-j" 'facemenu-justification-menu)
  144. (define-key map "\M-S" 'set-justification-center)
  145. (define-key map "\C-x\t" 'increase-left-margin)
  146. (define-key map "\C-c[" 'set-left-margin)
  147. (define-key map "\C-c]" 'set-right-margin)
  148. map)
  149. "Keymap for Enriched mode.")
  150. ;;;
  151. ;;; Define the mode
  152. ;;;
  153. (put 'enriched-mode 'permanent-local t)
  154. ;;;###autoload
  155. (define-minor-mode enriched-mode
  156. "Minor mode for editing text/enriched files.
  157. These are files with embedded formatting information in the MIME standard
  158. text/enriched format.
  159. With a prefix argument ARG, enable the mode if ARG is positive,
  160. and disable it otherwise. If called from Lisp, enable the mode
  161. if ARG is omitted or nil.
  162. Turning the mode on or off runs `enriched-mode-hook'.
  163. More information about Enriched mode is available in the file
  164. etc/enriched.doc in the Emacs distribution directory.
  165. Commands:
  166. \\{enriched-mode-map}"
  167. :group 'enriched :lighter " Enriched"
  168. (cond ((null enriched-mode)
  169. ;; Turn mode off
  170. (remove-hook 'change-major-mode-hook
  171. 'enriched-before-change-major-mode 'local)
  172. (setq buffer-file-format (delq 'text/enriched buffer-file-format))
  173. ;; restore old variable values
  174. (while enriched-old-bindings
  175. (set (pop enriched-old-bindings) (pop enriched-old-bindings)))
  176. (unless enriched-default-text-properties-local-flag
  177. (kill-local-variable 'default-text-properties))
  178. (kill-local-variable 'enriched-default-text-properties-local-flag)
  179. (unless use-hard-newlines (use-hard-newlines 0)))
  180. ((and (memq 'text/enriched buffer-file-format)
  181. (not enriched-rerun-flag))
  182. ;; Mode already on; do nothing.
  183. nil)
  184. (t ; Turn mode on
  185. (add-hook 'change-major-mode-hook
  186. 'enriched-before-change-major-mode nil 'local)
  187. (add-to-list 'buffer-file-format 'text/enriched)
  188. ;; Save old variable values before we change them.
  189. ;; These will be restored if we exit Enriched mode.
  190. (setq enriched-old-bindings
  191. (list 'buffer-display-table buffer-display-table
  192. 'default-text-properties default-text-properties
  193. 'use-hard-newlines use-hard-newlines))
  194. (make-local-variable 'enriched-default-text-properties-local-flag)
  195. (setq enriched-default-text-properties-local-flag
  196. (local-variable-p 'default-text-properties))
  197. (make-local-variable 'default-text-properties)
  198. (setq buffer-display-table enriched-display-table)
  199. (use-hard-newlines 1 (if enriched-rerun-flag 'never nil))
  200. (let ((sticky (plist-get default-text-properties 'front-sticky))
  201. (p enriched-par-props))
  202. (dolist (x p)
  203. (add-to-list 'sticky x))
  204. (if sticky
  205. (setq default-text-properties
  206. (plist-put default-text-properties
  207. 'front-sticky sticky)))))))
  208. (defun enriched-before-change-major-mode ()
  209. (when enriched-mode
  210. (while enriched-old-bindings
  211. (set (pop enriched-old-bindings) (pop enriched-old-bindings)))))
  212. (defun enriched-after-change-major-mode ()
  213. (when enriched-mode
  214. (let ((enriched-rerun-flag t))
  215. (enriched-mode 1))))
  216. (add-hook 'after-change-major-mode-hook 'enriched-after-change-major-mode)
  217. (fset 'enriched-mode-map enriched-mode-map)
  218. ;;;
  219. ;;; Some functions dealing with text-properties, especially indentation
  220. ;;;
  221. (defun enriched-map-property-regions (prop func &optional from to)
  222. "Apply a function to regions of the buffer based on a text property.
  223. For each contiguous region of the buffer for which the value of PROPERTY is
  224. eq, the FUNCTION will be called. Optional arguments FROM and TO specify the
  225. region over which to scan.
  226. The specified function receives three arguments: the VALUE of the property in
  227. the region, and the START and END of each region."
  228. (save-excursion
  229. (save-restriction
  230. (if to (narrow-to-region (point-min) to))
  231. (goto-char (or from (point-min)))
  232. (let ((begin (point))
  233. end
  234. (marker (make-marker))
  235. (val (get-text-property (point) prop)))
  236. (while (setq end (text-property-not-all begin (point-max) prop val))
  237. (move-marker marker end)
  238. (funcall func val begin (marker-position marker))
  239. (setq begin (marker-position marker)
  240. val (get-text-property marker prop)))
  241. (if (< begin (point-max))
  242. (funcall func val begin (point-max)))))))
  243. (put 'enriched-map-property-regions 'lisp-indent-hook 1)
  244. (defun enriched-insert-indentation (&optional from to)
  245. "Indent and justify each line in the region."
  246. (save-excursion
  247. (save-restriction
  248. (if to (narrow-to-region (point-min) to))
  249. (goto-char (or from (point-min)))
  250. (if (not (bolp)) (forward-line 1))
  251. (while (not (eobp))
  252. (if (eolp)
  253. nil ; skip blank lines
  254. (indent-to (current-left-margin))
  255. (justify-current-line t nil t))
  256. (forward-line 1)))))
  257. ;;;
  258. ;;; Encoding Files
  259. ;;;
  260. ;;;###autoload
  261. (defun enriched-encode (from to orig-buf)
  262. (if enriched-verbose (message "Enriched: encoding document..."))
  263. (let ((inhibit-read-only t))
  264. (save-restriction
  265. (narrow-to-region from to)
  266. (delete-to-left-margin)
  267. (unjustify-region)
  268. (goto-char from)
  269. (format-replace-strings '(("<" . "<<")))
  270. (format-insert-annotations
  271. (format-annotate-region from (point-max) enriched-translations
  272. 'enriched-make-annotation enriched-ignore))
  273. (goto-char from)
  274. (insert (if (stringp enriched-initial-annotation)
  275. enriched-initial-annotation
  276. (save-excursion
  277. ;; Eval this in the buffer we are annotating. This
  278. ;; fixes a bug which was saving incorrect File-Width
  279. ;; information, since we were looking at local
  280. ;; variables in the wrong buffer.
  281. (if orig-buf (set-buffer orig-buf))
  282. (funcall enriched-initial-annotation))))
  283. (enriched-map-property-regions 'hard
  284. (lambda (v b e)
  285. (if (and v (= ?\n (char-after b)))
  286. (progn (goto-char b) (insert "\n"))))
  287. (point) nil)
  288. (if enriched-verbose (message nil))
  289. ;; Return new end.
  290. (point-max))))
  291. (defun enriched-make-annotation (internal-ann positive)
  292. "Format an annotation INTERNAL-ANN.
  293. INTERNAL-ANN may be a string, for a flag, or a list of the form (PARAM VALUE).
  294. If POSITIVE is non-nil, this is the opening annotation;
  295. if nil, the matching close."
  296. (cond ((stringp internal-ann)
  297. (format enriched-annotation-format (if positive "" "/") internal-ann))
  298. ;; Otherwise it is an annotation with parameters, represented as a list
  299. (positive
  300. (let ((item (car internal-ann))
  301. (params (cdr internal-ann)))
  302. (concat (format enriched-annotation-format "" item)
  303. (mapconcat (lambda (i) (concat "<param>" i "</param>"))
  304. params ""))))
  305. (t (format enriched-annotation-format "/" (car internal-ann)))))
  306. (defun enriched-encode-other-face (old new)
  307. "Generate annotations for random face change.
  308. One annotation each for foreground color, background color, italic, etc."
  309. (cons (and old (enriched-face-ans old))
  310. (and new (enriched-face-ans new))))
  311. (defun enriched-face-ans (face)
  312. "Return annotations specifying FACE.
  313. FACE may be a list of faces instead of a single face;
  314. it can also be anything allowed as an element of a list
  315. which can be the value of the `face' text property."
  316. (cond ((and (consp face) (eq (car face) 'foreground-color))
  317. (list (list "x-color" (cdr face))))
  318. ((and (consp face) (eq (car face) 'background-color))
  319. (list (list "x-bg-color" (cdr face))))
  320. ((and (listp face) (eq (car face) :foreground))
  321. (list (list "x-color" (cadr face))))
  322. ((and (listp face) (eq (car face) :background))
  323. (list (list "x-bg-color" (cadr face))))
  324. ((listp face)
  325. (apply 'append (mapcar 'enriched-face-ans face)))
  326. ((let* ((fg (face-attribute face :foreground))
  327. (bg (face-attribute face :background))
  328. (props (face-font face t))
  329. (ans (cdr (format-annotate-single-property-change
  330. 'face nil props enriched-translations))))
  331. (unless (eq fg 'unspecified)
  332. (setq ans (cons (list "x-color" fg) ans)))
  333. (unless (eq bg 'unspecified)
  334. (setq ans (cons (list "x-bg-color" bg) ans)))
  335. ans))))
  336. ;;;
  337. ;;; Decoding files
  338. ;;;
  339. ;;;###autoload
  340. (defun enriched-decode (from to)
  341. (if enriched-verbose (message "Enriched: decoding document..."))
  342. (use-hard-newlines 1 'never)
  343. (save-excursion
  344. (save-restriction
  345. (narrow-to-region from to)
  346. (goto-char from)
  347. ;; Deal with header
  348. (let ((file-width (enriched-get-file-width)))
  349. (enriched-remove-header)
  350. ;; Deal with newlines
  351. (while (search-forward-regexp "\n\n+" nil t)
  352. (if (current-justification)
  353. (delete-char -1))
  354. (set-hard-newline-properties (match-beginning 0) (point)))
  355. ;; Translate annotations
  356. (format-deannotate-region from (point-max) enriched-translations
  357. 'enriched-next-annotation)
  358. ;; Indent or fill the buffer
  359. (cond (file-width ; File was filled to this width
  360. (setq fill-column file-width)
  361. (if enriched-verbose (message "Indenting..."))
  362. (enriched-insert-indentation))
  363. (t ; File was not filled.
  364. (if enriched-verbose (message "Filling paragraphs..."))
  365. (fill-region (point-min) (point-max))))
  366. (if enriched-verbose (message nil)))
  367. (point-max))))
  368. (defun enriched-next-annotation ()
  369. "Find and return next text/enriched annotation.
  370. Any \"<<\" strings encountered are converted to \"<\".
  371. Return value is \(begin end name positive-p), or nil if none was found."
  372. (while (and (search-forward "<" nil 1)
  373. (progn (goto-char (match-beginning 0))
  374. (not (looking-at enriched-annotation-regexp))))
  375. (forward-char 1)
  376. (if (eq ?< (char-after (point)))
  377. (delete-char 1)
  378. ;; A single < that does not start an annotation is an error,
  379. ;; which we note and then ignore.
  380. (message "Warning: malformed annotation in file at %s"
  381. (1- (point)))))
  382. (if (not (eobp))
  383. (let* ((beg (match-beginning 0))
  384. (end (match-end 0))
  385. (name (downcase (buffer-substring
  386. (match-beginning 2) (match-end 2))))
  387. (pos (not (match-beginning 1))))
  388. (list beg end name pos))))
  389. (defun enriched-get-file-width ()
  390. "Look for file width information on this line."
  391. (save-excursion
  392. (if (search-forward "Text-Width: " (+ (point) 1000) t)
  393. (read (current-buffer)))))
  394. (defun enriched-remove-header ()
  395. "Remove file-format header at point."
  396. (while (looking-at "^[-A-Za-z]+: .*\n")
  397. (delete-region (point) (match-end 0)))
  398. (if (looking-at "^\n")
  399. (delete-char 1)))
  400. (defun enriched-decode-foreground (from to &optional color)
  401. (if color
  402. (list from to 'face (list ':foreground color))
  403. (message "Warning: no color specified for <x-color>")
  404. nil))
  405. (defun enriched-decode-background (from to &optional color)
  406. (if color
  407. (list from to 'face (list ':background color))
  408. (message "Warning: no color specified for <x-bg-color>")
  409. nil))
  410. ;;; Handling the `display' property.
  411. (defun enriched-handle-display-prop (old new)
  412. "Return a list of annotations for a change in the `display' property.
  413. OLD is the old value of the property, NEW is the new value. Value
  414. is a list `(CLOSE OPEN)', where CLOSE is a list of annotations to
  415. close and OPEN a list of annotations to open. Each of these lists
  416. has the form `(ANNOTATION PARAM ...)'."
  417. (let ((annotation "x-display")
  418. (param (prin1-to-string (or old new))))
  419. (if (null old)
  420. (cons nil (list (list annotation param)))
  421. (cons (list (list annotation param)) nil))))
  422. (defun enriched-decode-display-prop (start end &optional param)
  423. "Decode a `display' property for text between START and END.
  424. PARAM is a `<param>' found for the property.
  425. Value is a list `(START END SYMBOL VALUE)' with START and END denoting
  426. the range of text to assign text property SYMBOL with value VALUE."
  427. (let ((prop (when (stringp param)
  428. (condition-case ()
  429. (car (read-from-string param))
  430. (error nil)))))
  431. (unless prop
  432. (message "Warning: invalid <x-display> parameter %s" param))
  433. (list start end 'display prop)))
  434. ;;; enriched.el ends here