Personal emacs config
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1883 lines
74 KiB

  1. ;;; htmlize.el --- Convert buffer text and decorations to HTML. -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1997-2003,2005,2006,2009,2011,2012,2014,2017,2018 Hrvoje Niksic
  3. ;; Author: Hrvoje Niksic <hniksic@gmail.com>
  4. ;; Keywords: hypermedia, extensions
  5. ;; Package-Version: 1.55
  6. ;; Package-Commit: 682edbf751f5c255bfd4af0eb714a8bce0737cec
  7. ;; Version: 1.55
  8. ;; This program is free software; you can redistribute it and/or modify
  9. ;; it under the terms of the GNU General Public License as published by
  10. ;; the Free Software Foundation; either version 2, or (at your option)
  11. ;; any later version.
  12. ;; This program is distributed in the hope that it will be useful,
  13. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;; GNU General Public License for more details.
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with this program; see the file COPYING. If not, write to the
  18. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. ;; Boston, MA 02111-1307, USA.
  20. ;;; Commentary:
  21. ;; This package converts the buffer text and the associated
  22. ;; decorations to HTML. Mail to <hniksic@gmail.com> to discuss
  23. ;; features and additions. All suggestions are more than welcome.
  24. ;; To use it, just switch to the buffer you want HTML-ized and type
  25. ;; `M-x htmlize-buffer'. You will be switched to a new buffer that
  26. ;; contains the resulting HTML code. You can edit and inspect this
  27. ;; buffer, or you can just save it with C-x C-w. `M-x htmlize-file'
  28. ;; will find a file, fontify it, and save the HTML version in
  29. ;; FILE.html, without any additional intervention. `M-x
  30. ;; htmlize-many-files' allows you to htmlize any number of files in
  31. ;; the same manner. `M-x htmlize-many-files-dired' does the same for
  32. ;; files marked in a dired buffer.
  33. ;; htmlize supports three types of HTML output, selected by setting
  34. ;; `htmlize-output-type': `css', `inline-css', and `font'. In `css'
  35. ;; mode, htmlize uses cascading style sheets to specify colors; it
  36. ;; generates classes that correspond to Emacs faces and uses <span
  37. ;; class=FACE>...</span> to color parts of text. In this mode, the
  38. ;; produced HTML is valid under the 4.01 strict DTD, as confirmed by
  39. ;; the W3C validator. `inline-css' is like `css', except the CSS is
  40. ;; put directly in the STYLE attribute of the SPAN element, making it
  41. ;; possible to paste the generated HTML into existing HTML documents.
  42. ;; In `font' mode, htmlize uses <font color="...">...</font> to
  43. ;; colorize HTML, which is not standard-compliant, but works better in
  44. ;; older browsers. `css' mode is the default.
  45. ;; You can also use htmlize from your Emacs Lisp code. When called
  46. ;; non-interactively, `htmlize-buffer' and `htmlize-region' will
  47. ;; return the resulting HTML buffer, but will not change current
  48. ;; buffer or move the point. htmlize will do its best to work on
  49. ;; non-windowing Emacs sessions but the result will be limited to
  50. ;; colors supported by the terminal.
  51. ;; htmlize aims for compatibility with older Emacs versions. Please
  52. ;; let me know if it doesn't work on the version of GNU Emacs that you
  53. ;; are using. The package relies on the presence of CL extensions;
  54. ;; please don't try to remove that dependency. I see no practical
  55. ;; problems with using the full power of the CL extensions, except
  56. ;; that one might learn to like them too much.
  57. ;; The latest version is available at:
  58. ;;
  59. ;; <https://github.com/hniksic/emacs-htmlize>
  60. ;; <https://code.orgmode.org/mirrors/emacs-htmlize>
  61. ;;
  62. ;; Thanks go to the many people who have sent reports and contributed
  63. ;; comments, suggestions, and fixes. They include Ron Gut, Bob
  64. ;; Weiner, Toni Drabik, Peter Breton, Ville Skytta, Thomas Vogels,
  65. ;; Juri Linkov, Maciek Pasternacki, and many others.
  66. ;; User quotes: "You sir, are a sick, sick, _sick_ person. :)"
  67. ;; -- Bill Perry, author of Emacs/W3
  68. ;;; Code:
  69. (require 'cl)
  70. (eval-when-compile
  71. (defvar font-lock-auto-fontify)
  72. (defvar font-lock-support-mode)
  73. (defvar global-font-lock-mode))
  74. (defconst htmlize-version "1.55")
  75. (defgroup htmlize nil
  76. "Convert buffer text and faces to HTML."
  77. :group 'hypermedia)
  78. (defcustom htmlize-head-tags ""
  79. "Additional tags to insert within HEAD of the generated document."
  80. :type 'string
  81. :group 'htmlize)
  82. (defcustom htmlize-output-type 'css
  83. "Output type of generated HTML, one of `css', `inline-css', or `font'.
  84. When set to `css' (the default), htmlize will generate a style sheet
  85. with description of faces, and use it in the HTML document, specifying
  86. the faces in the actual text with <span class=\"FACE\">.
  87. When set to `inline-css', the style will be generated as above, but
  88. placed directly in the STYLE attribute of the span ELEMENT: <span
  89. style=\"STYLE\">. This makes it easier to paste the resulting HTML to
  90. other documents.
  91. When set to `font', the properties will be set using layout tags
  92. <font>, <b>, <i>, <u>, and <strike>.
  93. `css' output is normally preferred, but `font' is still useful for
  94. supporting old, pre-CSS browsers, and both `inline-css' and `font' for
  95. easier embedding of colorized text in foreign HTML documents (no style
  96. sheet to carry around)."
  97. :type '(choice (const css) (const inline-css) (const font))
  98. :group 'htmlize)
  99. (defcustom htmlize-use-images t
  100. "Whether htmlize generates `img' for images attached to buffer contents."
  101. :type 'boolean
  102. :group 'htmlize)
  103. (defcustom htmlize-force-inline-images nil
  104. "Non-nil means generate all images inline using data URLs.
  105. Normally htmlize converts image descriptors with :file properties to
  106. relative URIs, and those with :data properties to data URIs. With this
  107. flag set, the images specified as a file name are loaded into memory and
  108. embedded in the HTML as data URIs."
  109. :type 'boolean
  110. :group 'htmlize)
  111. (defcustom htmlize-max-alt-text 100
  112. "Maximum size of text to use as ALT text in images.
  113. Normally when htmlize encounters text covered by the `display' property
  114. that specifies an image, it generates an `alt' attribute containing the
  115. original text. If the text is larger than `htmlize-max-alt-text' characters,
  116. this will not be done."
  117. :type 'integer
  118. :group 'htmlize)
  119. (defcustom htmlize-transform-image 'htmlize-default-transform-image
  120. "Function called to modify the image descriptor.
  121. The function is called with the image descriptor found in the buffer and
  122. the text the image is supposed to replace. It should return a (possibly
  123. different) image descriptor property list or a replacement string to use
  124. instead of of the original buffer text.
  125. Returning nil is the same as returning the original text."
  126. :type 'boolean
  127. :group 'htmlize)
  128. (defcustom htmlize-generate-hyperlinks t
  129. "Non-nil means auto-generate the links from URLs and mail addresses in buffer.
  130. This is on by default; set it to nil if you don't want htmlize to
  131. autogenerate such links. Note that this option only turns off automatic
  132. search for contents that looks like URLs and converting them to links.
  133. It has no effect on whether htmlize respects the `htmlize-link' property."
  134. :type 'boolean
  135. :group 'htmlize)
  136. (defcustom htmlize-hyperlink-style "
  137. a {
  138. color: inherit;
  139. background-color: inherit;
  140. font: inherit;
  141. text-decoration: inherit;
  142. }
  143. a:hover {
  144. text-decoration: underline;
  145. }
  146. "
  147. "The CSS style used for hyperlinks when in CSS mode."
  148. :type 'string
  149. :group 'htmlize)
  150. (defcustom htmlize-replace-form-feeds t
  151. "Non-nil means replace form feeds in source code with HTML separators.
  152. Form feeds are the ^L characters at line beginnings that are sometimes
  153. used to separate sections of source code. If this variable is set to
  154. `t', form feed characters are replaced with the <hr> separator. If this
  155. is a string, it specifies the replacement to use. Note that <pre> is
  156. temporarily closed before the separator is inserted, so the default
  157. replacement is effectively \"</pre><hr /><pre>\". If you specify
  158. another replacement, don't forget to close and reopen the <pre> if you
  159. want the output to remain valid HTML.
  160. If you need more elaborate processing, set this to nil and use
  161. htmlize-after-hook."
  162. :type 'boolean
  163. :group 'htmlize)
  164. (defcustom htmlize-html-charset nil
  165. "The charset declared by the resulting HTML documents.
  166. When non-nil, causes htmlize to insert the following in the HEAD section
  167. of the generated HTML:
  168. <meta http-equiv=\"Content-Type\" content=\"text/html; charset=CHARSET\">
  169. where CHARSET is the value you've set for htmlize-html-charset. Valid
  170. charsets are defined by MIME and include strings like \"iso-8859-1\",
  171. \"iso-8859-15\", \"utf-8\", etc.
  172. If you are using non-Latin-1 charsets, you might need to set this for
  173. your documents to render correctly. Also, the W3C validator requires
  174. submitted HTML documents to declare a charset. So if you care about
  175. validation, you can use this to prevent the validator from bitching.
  176. Needless to say, if you set this, you should actually make sure that
  177. the buffer is in the encoding you're claiming it is in. (This is
  178. normally achieved by using the correct file coding system for the
  179. buffer.) If you don't understand what that means, you should probably
  180. leave this option in its default setting."
  181. :type '(choice (const :tag "Unset" nil)
  182. string)
  183. :group 'htmlize)
  184. (defcustom htmlize-convert-nonascii-to-entities t
  185. "Whether non-ASCII characters should be converted to HTML entities.
  186. When this is non-nil, characters with codes in the 128-255 range will be
  187. considered Latin 1 and rewritten as \"&#CODE;\". Characters with codes
  188. above 255 will be converted to \"&#UCS;\", where UCS denotes the Unicode
  189. code point of the character. If the code point cannot be determined,
  190. the character will be copied unchanged, as would be the case if the
  191. option were nil.
  192. When the option is nil, the non-ASCII characters are copied to HTML
  193. without modification. In that case, the web server and/or the browser
  194. must be set to understand the encoding that was used when saving the
  195. buffer. (You might also want to specify it by setting
  196. `htmlize-html-charset'.)
  197. Note that in an HTML entity \"&#CODE;\", CODE is always a UCS code point,
  198. which has nothing to do with the charset the page is in. For example,
  199. \"&#169;\" *always* refers to the copyright symbol, regardless of charset
  200. specified by the META tag or the charset sent by the HTTP server. In
  201. other words, \"&#169;\" is exactly equivalent to \"&copy;\".
  202. For most people htmlize will work fine with this option left at the
  203. default setting; don't change it unless you know what you're doing."
  204. :type 'sexp
  205. :group 'htmlize)
  206. (defcustom htmlize-ignore-face-size 'absolute
  207. "Whether face size should be ignored when generating HTML.
  208. If this is nil, face sizes are used. If set to t, sizes are ignored
  209. If set to `absolute', only absolute size specifications are ignored.
  210. Please note that font sizes only work with CSS-based output types."
  211. :type '(choice (const :tag "Don't ignore" nil)
  212. (const :tag "Ignore all" t)
  213. (const :tag "Ignore absolute" absolute))
  214. :group 'htmlize)
  215. (defcustom htmlize-css-name-prefix ""
  216. "The prefix used for CSS names.
  217. The CSS names that htmlize generates from face names are often too
  218. generic for CSS files; for example, `font-lock-type-face' is transformed
  219. to `type'. Use this variable to add a prefix to the generated names.
  220. The string \"htmlize-\" is an example of a reasonable prefix."
  221. :type 'string
  222. :group 'htmlize)
  223. (defcustom htmlize-use-rgb-txt t
  224. "Whether `rgb.txt' should be used to convert color names to RGB.
  225. This conversion means determining, for instance, that the color
  226. \"IndianRed\" corresponds to the (205, 92, 92) RGB triple. `rgb.txt'
  227. is the X color database that maps hundreds of color names to such RGB
  228. triples. When this variable is non-nil, `htmlize' uses `rgb.txt' to
  229. look up color names.
  230. If this variable is nil, htmlize queries Emacs for RGB components of
  231. colors using `color-instance-rgb-components' and `color-values'.
  232. This can yield incorrect results on non-true-color displays.
  233. If the `rgb.txt' file is not found (which will be the case if you're
  234. running Emacs on non-X11 systems), this option is ignored."
  235. :type 'boolean
  236. :group 'htmlize)
  237. (defvar htmlize-face-overrides nil
  238. "Overrides for face definitions.
  239. Normally face definitions are taken from Emacs settings for fonts
  240. in the current frame. For faces present in this plist, the
  241. definitions will be used instead. Keys in the plist are symbols
  242. naming the face and values are the overriding definitions. For
  243. example:
  244. (setq htmlize-face-overrides
  245. '(font-lock-warning-face \"black\"
  246. font-lock-function-name-face \"red\"
  247. font-lock-comment-face \"blue\"
  248. default (:foreground \"dark-green\" :background \"yellow\")))
  249. This variable can be also be `let' bound when running `htmlize-buffer'.")
  250. (defcustom htmlize-untabify t
  251. "Non-nil means untabify buffer contents during htmlization."
  252. :type 'boolean
  253. :group 'htmlize)
  254. (defcustom htmlize-html-major-mode nil
  255. "The mode the newly created HTML buffer will be put in.
  256. Set this to nil if you prefer the default (fundamental) mode."
  257. :type '(radio (const :tag "No mode (fundamental)" nil)
  258. (function-item html-mode)
  259. (function :tag "User-defined major mode"))
  260. :group 'htmlize)
  261. (defcustom htmlize-pre-style nil
  262. "When non-nil, `<pre>' tags will be decorated with style
  263. information in `font' and `inline-css' modes. This allows a
  264. consistent background for captures of regions."
  265. :type 'boolean
  266. :group 'htmlize)
  267. (defvar htmlize-before-hook nil
  268. "Hook run before htmlizing a buffer.
  269. The hook functions are run in the source buffer (not the resulting HTML
  270. buffer).")
  271. (defvar htmlize-after-hook nil
  272. "Hook run after htmlizing a buffer.
  273. Unlike `htmlize-before-hook', these functions are run in the generated
  274. HTML buffer. You may use them to modify the outlook of the final HTML
  275. output.")
  276. (defvar htmlize-file-hook nil
  277. "Hook run by `htmlize-file' after htmlizing a file, but before saving it.")
  278. (defvar htmlize-buffer-places)
  279. ;;; Some cross-Emacs compatibility.
  280. ;; We need a function that efficiently finds the next change of a
  281. ;; property regardless of whether the change occurred because of a
  282. ;; text property or an extent/overlay.
  283. (defun htmlize-next-change (pos prop &optional limit)
  284. (if prop
  285. (next-single-char-property-change pos prop nil limit)
  286. (next-char-property-change pos limit)))
  287. (defun htmlize-overlay-faces-at (pos)
  288. (delq nil (mapcar (lambda (o) (overlay-get o 'face)) (overlays-at pos))))
  289. (defun htmlize-next-face-change (pos &optional limit)
  290. ;; (htmlize-next-change pos 'face limit) would skip over entire
  291. ;; overlays that specify the `face' property, even when they
  292. ;; contain smaller text properties that also specify `face'.
  293. ;; Emacs display engine merges those faces, and so must we.
  294. (or limit
  295. (setq limit (point-max)))
  296. (let ((next-prop (next-single-property-change pos 'face nil limit))
  297. (overlay-faces (htmlize-overlay-faces-at pos)))
  298. (while (progn
  299. (setq pos (next-overlay-change pos))
  300. (and (< pos next-prop)
  301. (equal overlay-faces (htmlize-overlay-faces-at pos)))))
  302. (setq pos (min pos next-prop))
  303. ;; Additionally, we include the entire region that specifies the
  304. ;; `display' property.
  305. (when (get-char-property pos 'display)
  306. (setq pos (next-single-char-property-change pos 'display nil limit)))
  307. pos))
  308. (defmacro htmlize-lexlet (&rest letforms)
  309. (declare (indent 1) (debug let))
  310. (if (and (boundp 'lexical-binding)
  311. lexical-binding)
  312. `(let ,@letforms)
  313. ;; cl extensions have a macro implementing lexical let
  314. `(lexical-let ,@letforms)))
  315. ;;; Transformation of buffer text: HTML escapes, untabification, etc.
  316. (defvar htmlize-basic-character-table
  317. ;; Map characters in the 0-127 range to either one-character strings
  318. ;; or to numeric entities.
  319. (let ((table (make-vector 128 ?\0)))
  320. ;; Map characters in the 32-126 range to themselves, others to
  321. ;; &#CODE entities;
  322. (dotimes (i 128)
  323. (setf (aref table i) (if (and (>= i 32) (<= i 126))
  324. (char-to-string i)
  325. (format "&#%d;" i))))
  326. ;; Set exceptions manually.
  327. (setf
  328. ;; Don't escape newline, carriage return, and TAB.
  329. (aref table ?\n) "\n"
  330. (aref table ?\r) "\r"
  331. (aref table ?\t) "\t"
  332. ;; Escape &, <, and >.
  333. (aref table ?&) "&amp;"
  334. (aref table ?<) "&lt;"
  335. (aref table ?>) "&gt;"
  336. ;; Not escaping '"' buys us a measurable speedup. It's only
  337. ;; necessary to quote it for strings used in attribute values,
  338. ;; which htmlize doesn't typically do.
  339. ;(aref table ?\") "&quot;"
  340. )
  341. table))
  342. ;; A cache of HTML representation of non-ASCII characters. Depending
  343. ;; on the setting of `htmlize-convert-nonascii-to-entities', this maps
  344. ;; non-ASCII characters to either "&#<code>;" or "<char>" (mapconcat's
  345. ;; mapper must always return strings). It's only filled as characters
  346. ;; are encountered, so that in a buffer with e.g. French text, it will
  347. ;; only ever contain French accented characters as keys. It's cleared
  348. ;; on each entry to htmlize-buffer-1 to allow modifications of
  349. ;; `htmlize-convert-nonascii-to-entities' to take effect.
  350. (defvar htmlize-extended-character-cache (make-hash-table :test 'eq))
  351. (defun htmlize-protect-string (string)
  352. "HTML-protect string, escaping HTML metacharacters and I18N chars."
  353. ;; Only protecting strings that actually contain unsafe or non-ASCII
  354. ;; chars removes a lot of unnecessary funcalls and consing.
  355. (if (not (string-match "[^\r\n\t -%'-;=?-~]" string))
  356. string
  357. (mapconcat (lambda (char)
  358. (cond
  359. ((< char 128)
  360. ;; ASCII: use htmlize-basic-character-table.
  361. (aref htmlize-basic-character-table char))
  362. ((gethash char htmlize-extended-character-cache)
  363. ;; We've already seen this char; return the cached
  364. ;; string.
  365. )
  366. ((not htmlize-convert-nonascii-to-entities)
  367. ;; If conversion to entities is not desired, always
  368. ;; copy the char literally.
  369. (setf (gethash char htmlize-extended-character-cache)
  370. (char-to-string char)))
  371. ((< char 256)
  372. ;; Latin 1: no need to call encode-char.
  373. (setf (gethash char htmlize-extended-character-cache)
  374. (format "&#%d;" char)))
  375. ((encode-char char 'ucs)
  376. ;; Must check if encode-char works for CHAR;
  377. ;; it fails for Arabic and possibly elsewhere.
  378. (setf (gethash char htmlize-extended-character-cache)
  379. (format "&#%d;" (encode-char char 'ucs))))
  380. (t
  381. ;; encode-char doesn't work for this char. Copy it
  382. ;; unchanged and hope for the best.
  383. (setf (gethash char htmlize-extended-character-cache)
  384. (char-to-string char)))))
  385. string "")))
  386. (defun htmlize-attr-escape (string)
  387. ;; Like htmlize-protect-string, but also escapes double-quoted
  388. ;; strings to make it usable in attribute values.
  389. (setq string (htmlize-protect-string string))
  390. (if (not (string-match "\"" string))
  391. string
  392. (mapconcat (lambda (char)
  393. (if (eql char ?\")
  394. "&quot;"
  395. (char-to-string char)))
  396. string "")))
  397. (defsubst htmlize-concat (list)
  398. (if (and (consp list) (null (cdr list)))
  399. ;; Don't create a new string in the common case where the list only
  400. ;; consists of one element.
  401. (car list)
  402. (apply #'concat list)))
  403. (defun htmlize-format-link (linkprops text)
  404. (let ((uri (if (stringp linkprops)
  405. linkprops
  406. (plist-get linkprops :uri)))
  407. (escaped-text (htmlize-protect-string text)))
  408. (if uri
  409. (format "<a href=\"%s\">%s</a>" (htmlize-attr-escape uri) escaped-text)
  410. escaped-text)))
  411. (defun htmlize-escape-or-link (string)
  412. ;; Escape STRING and/or add hyperlinks. STRING comes from a
  413. ;; `display' property.
  414. (let ((pos 0) (end (length string)) outlist)
  415. (while (< pos end)
  416. (let* ((link (get-char-property pos 'htmlize-link string))
  417. (next-link-change (next-single-property-change
  418. pos 'htmlize-link string end))
  419. (chunk (substring string pos next-link-change)))
  420. (push
  421. (cond (link
  422. (htmlize-format-link link chunk))
  423. ((get-char-property 0 'htmlize-literal chunk)
  424. chunk)
  425. (t
  426. (htmlize-protect-string chunk)))
  427. outlist)
  428. (setq pos next-link-change)))
  429. (htmlize-concat (nreverse outlist))))
  430. (defun htmlize-display-prop-to-html (display text)
  431. (let (desc)
  432. (cond ((stringp display)
  433. ;; Emacs ignores recursive display properties.
  434. (htmlize-escape-or-link display))
  435. ((not (eq (car-safe display) 'image))
  436. (htmlize-protect-string text))
  437. ((null (setq desc (funcall htmlize-transform-image
  438. (cdr display) text)))
  439. (htmlize-escape-or-link text))
  440. ((stringp desc)
  441. (htmlize-escape-or-link desc))
  442. (t
  443. (htmlize-generate-image desc text)))))
  444. (defun htmlize-string-to-html (string)
  445. ;; Convert the string to HTML, including images attached as
  446. ;; `display' property and links as `htmlize-link' property. In a
  447. ;; string without images or links, this is equivalent to
  448. ;; `htmlize-protect-string'.
  449. (let ((pos 0) (end (length string)) outlist)
  450. (while (< pos end)
  451. (let* ((display (get-char-property pos 'display string))
  452. (next-display-change (next-single-property-change
  453. pos 'display string end))
  454. (chunk (substring string pos next-display-change)))
  455. (push
  456. (if display
  457. (htmlize-display-prop-to-html display chunk)
  458. (htmlize-escape-or-link chunk))
  459. outlist)
  460. (setq pos next-display-change)))
  461. (htmlize-concat (nreverse outlist))))
  462. (defun htmlize-default-transform-image (imgprops _text)
  463. "Default transformation of image descriptor to something usable in HTML.
  464. If `htmlize-use-images' is nil, the function always returns nil, meaning
  465. use original text. Otherwise, it tries to find the image for images that
  466. specify a file name. If `htmlize-force-inline-images' is non-nil, it also
  467. converts the :file attribute to :data and returns the modified property
  468. list."
  469. (when htmlize-use-images
  470. (when (plist-get imgprops :file)
  471. (let ((location (plist-get (cdr (find-image (list imgprops))) :file)))
  472. (when location
  473. (setq imgprops (plist-put (copy-list imgprops) :file location)))))
  474. (if htmlize-force-inline-images
  475. (let ((location (plist-get imgprops :file))
  476. data)
  477. (when location
  478. (with-temp-buffer
  479. (condition-case nil
  480. (progn
  481. (insert-file-contents-literally location)
  482. (setq data (buffer-string)))
  483. (error nil))))
  484. ;; if successful, return the new plist, otherwise return
  485. ;; nil, which will use the original text
  486. (and data
  487. (plist-put (plist-put imgprops :file nil)
  488. :data data)))
  489. imgprops)))
  490. (defun htmlize-alt-text (_imgprops origtext)
  491. (and (/= (length origtext) 0)
  492. (<= (length origtext) htmlize-max-alt-text)
  493. (not (string-match "[\0-\x1f]" origtext))
  494. origtext))
  495. (defun htmlize-generate-image (imgprops origtext)
  496. (let* ((alt-text (htmlize-alt-text imgprops origtext))
  497. (alt-attr (if alt-text
  498. (format " alt=\"%s\"" (htmlize-attr-escape alt-text))
  499. "")))
  500. (cond ((plist-get imgprops :file)
  501. ;; Try to find the image in image-load-path
  502. (let* ((found-props (cdr (find-image (list imgprops))))
  503. (file (or (plist-get found-props :file)
  504. (plist-get imgprops :file))))
  505. (format "<img src=\"%s\"%s />"
  506. (htmlize-attr-escape (file-relative-name file))
  507. alt-attr)))
  508. ((plist-get imgprops :data)
  509. (format "<img src=\"data:image/%s;base64,%s\"%s />"
  510. (or (plist-get imgprops :type) "")
  511. (base64-encode-string (plist-get imgprops :data))
  512. alt-attr)))))
  513. (defconst htmlize-ellipsis "...")
  514. (put-text-property 0 (length htmlize-ellipsis) 'htmlize-ellipsis t htmlize-ellipsis)
  515. (defun htmlize-match-inv-spec (inv)
  516. (member* inv buffer-invisibility-spec
  517. :key (lambda (i)
  518. (if (symbolp i) i (car i)))))
  519. (defun htmlize-decode-invisibility-spec (invisible)
  520. ;; Return t, nil, or `ellipsis', depending on how invisible text should be inserted.
  521. (if (not (listp buffer-invisibility-spec))
  522. ;; If buffer-invisibility-spec is not a list, then all
  523. ;; characters with non-nil `invisible' property are visible.
  524. (not invisible)
  525. ;; Otherwise, the value of a non-nil `invisible' property can be:
  526. ;; 1. a symbol -- make the text invisible if it matches
  527. ;; buffer-invisibility-spec.
  528. ;; 2. a list of symbols -- make the text invisible if
  529. ;; any symbol in the list matches
  530. ;; buffer-invisibility-spec.
  531. ;; If the match of buffer-invisibility-spec has a non-nil
  532. ;; CDR, replace the invisible text with an ellipsis.
  533. (let ((match (if (symbolp invisible)
  534. (htmlize-match-inv-spec invisible)
  535. (some #'htmlize-match-inv-spec invisible))))
  536. (cond ((null match) t)
  537. ((cdr-safe (car match)) 'ellipsis)
  538. (t nil)))))
  539. (defun htmlize-add-before-after-strings (beg end text)
  540. ;; Find overlays specifying before-string and after-string in [beg,
  541. ;; pos). If any are found, splice them into TEXT and return the new
  542. ;; text.
  543. (let (additions)
  544. (dolist (overlay (overlays-in beg end))
  545. (let ((before (overlay-get overlay 'before-string))
  546. (after (overlay-get overlay 'after-string)))
  547. (when after
  548. (push (cons (- (overlay-end overlay) beg)
  549. after)
  550. additions))
  551. (when before
  552. (push (cons (- (overlay-start overlay) beg)
  553. before)
  554. additions))))
  555. (if additions
  556. (let ((textlist nil)
  557. (strpos 0))
  558. (dolist (add (stable-sort additions #'< :key #'car))
  559. (let ((addpos (car add))
  560. (addtext (cdr add)))
  561. (push (substring text strpos addpos) textlist)
  562. (push addtext textlist)
  563. (setq strpos addpos)))
  564. (push (substring text strpos) textlist)
  565. (apply #'concat (nreverse textlist)))
  566. text)))
  567. (defun htmlize-copy-prop (prop beg end string)
  568. ;; Copy the specified property from the specified region of the
  569. ;; buffer to the target string. We cannot rely on Emacs to copy the
  570. ;; property because we want to handle properties coming from both
  571. ;; text properties and overlays.
  572. (let ((pos beg))
  573. (while (< pos end)
  574. (let ((value (get-char-property pos prop))
  575. (next-change (htmlize-next-change pos prop end)))
  576. (when value
  577. (put-text-property (- pos beg) (- next-change beg)
  578. prop value string))
  579. (setq pos next-change)))))
  580. (defun htmlize-get-text-with-display (beg end)
  581. ;; Like buffer-substring-no-properties, except it copies the
  582. ;; `display' property from the buffer, if found.
  583. (let ((text (buffer-substring-no-properties beg end)))
  584. (htmlize-copy-prop 'display beg end text)
  585. (htmlize-copy-prop 'htmlize-link beg end text)
  586. (setq text (htmlize-add-before-after-strings beg end text))
  587. text))
  588. (defun htmlize-buffer-substring-no-invisible (beg end)
  589. ;; Like buffer-substring-no-properties, but don't copy invisible
  590. ;; parts of the region. Where buffer-substring-no-properties
  591. ;; mandates an ellipsis to be shown, htmlize-ellipsis is inserted.
  592. (let ((pos beg)
  593. visible-list invisible show last-show next-change)
  594. ;; Iterate over the changes in the `invisible' property and filter
  595. ;; out the portions where it's non-nil, i.e. where the text is
  596. ;; invisible.
  597. (while (< pos end)
  598. (setq invisible (get-char-property pos 'invisible)
  599. next-change (htmlize-next-change pos 'invisible end)
  600. show (htmlize-decode-invisibility-spec invisible))
  601. (cond ((eq show t)
  602. (push (htmlize-get-text-with-display pos next-change)
  603. visible-list))
  604. ((and (eq show 'ellipsis)
  605. (not (eq last-show 'ellipsis))
  606. ;; Conflate successive ellipses.
  607. (push htmlize-ellipsis visible-list))))
  608. (setq pos next-change last-show show))
  609. (htmlize-concat (nreverse visible-list))))
  610. (defun htmlize-trim-ellipsis (text)
  611. ;; Remove htmlize-ellipses ("...") from the beginning of TEXT if it
  612. ;; starts with it. It checks for the special property of the
  613. ;; ellipsis so it doesn't work on ordinary text that begins with
  614. ;; "...".
  615. (if (get-text-property 0 'htmlize-ellipsis text)
  616. (substring text (length htmlize-ellipsis))
  617. text))
  618. (defconst htmlize-tab-spaces
  619. ;; A table of strings with spaces. (aref htmlize-tab-spaces 5) is
  620. ;; like (make-string 5 ?\ ), except it doesn't cons.
  621. (let ((v (make-vector 32 nil)))
  622. (dotimes (i (length v))
  623. (setf (aref v i) (make-string i ?\ )))
  624. v))
  625. (defun htmlize-untabify-string (text start-column)
  626. "Untabify TEXT, assuming it starts at START-COLUMN."
  627. (let ((column start-column)
  628. (last-match 0)
  629. (chunk-start 0)
  630. chunks match-pos tab-size)
  631. (while (string-match "[\t\n]" text last-match)
  632. (setq match-pos (match-beginning 0))
  633. (cond ((eq (aref text match-pos) ?\t)
  634. ;; Encountered a tab: create a chunk of text followed by
  635. ;; the expanded tab.
  636. (push (substring text chunk-start match-pos) chunks)
  637. ;; Increase COLUMN by the length of the text we've
  638. ;; skipped since last tab or newline. (Encountering
  639. ;; newline resets it.)
  640. (incf column (- match-pos last-match))
  641. ;; Calculate tab size based on tab-width and COLUMN.
  642. (setq tab-size (- tab-width (% column tab-width)))
  643. ;; Expand the tab, carefully recreating the `display'
  644. ;; property if one was on the TAB.
  645. (let ((display (get-text-property match-pos 'display text))
  646. (expanded-tab (aref htmlize-tab-spaces tab-size)))
  647. (when display
  648. (put-text-property 0 tab-size 'display display expanded-tab))
  649. (push expanded-tab chunks))
  650. (incf column tab-size)
  651. (setq chunk-start (1+ match-pos)))
  652. (t
  653. ;; Reset COLUMN at beginning of line.
  654. (setq column 0)))
  655. (setq last-match (1+ match-pos)))
  656. ;; If no chunks have been allocated, it means there have been no
  657. ;; tabs to expand. Return TEXT unmodified.
  658. (if (null chunks)
  659. text
  660. (when (< chunk-start (length text))
  661. ;; Push the remaining chunk.
  662. (push (substring text chunk-start) chunks))
  663. ;; Generate the output from the available chunks.
  664. (htmlize-concat (nreverse chunks)))))
  665. (defun htmlize-extract-text (beg end trailing-ellipsis)
  666. ;; Extract buffer text, sans the invisible parts. Then
  667. ;; untabify it and escape the HTML metacharacters.
  668. (let ((text (htmlize-buffer-substring-no-invisible beg end)))
  669. (when trailing-ellipsis
  670. (setq text (htmlize-trim-ellipsis text)))
  671. ;; If TEXT ends up empty, don't change trailing-ellipsis.
  672. (when (> (length text) 0)
  673. (setq trailing-ellipsis
  674. (get-text-property (1- (length text))
  675. 'htmlize-ellipsis text)))
  676. (when htmlize-untabify
  677. (setq text (htmlize-untabify-string text (current-column))))
  678. (setq text (htmlize-string-to-html text))
  679. (values text trailing-ellipsis)))
  680. (defun htmlize-despam-address (string)
  681. "Replace every occurrence of '@' in STRING with %40.
  682. This is used to protect mailto links without modifying their meaning."
  683. ;; Suggested by Ville Skytta.
  684. (while (string-match "@" string)
  685. (setq string (replace-match "%40" nil t string)))
  686. string)
  687. (defun htmlize-make-tmp-overlay (beg end props)
  688. (let ((overlay (make-overlay beg end)))
  689. (overlay-put overlay 'htmlize-tmp-overlay t)
  690. (while props
  691. (overlay-put overlay (pop props) (pop props)))
  692. overlay))
  693. (defun htmlize-delete-tmp-overlays ()
  694. (dolist (overlay (overlays-in (point-min) (point-max)))
  695. (when (overlay-get overlay 'htmlize-tmp-overlay)
  696. (delete-overlay overlay))))
  697. (defun htmlize-make-link-overlay (beg end uri)
  698. (htmlize-make-tmp-overlay beg end `(htmlize-link (:uri ,uri))))
  699. (defun htmlize-create-auto-links ()
  700. "Add `htmlize-link' property to all mailto links in the buffer."
  701. (save-excursion
  702. (goto-char (point-min))
  703. (while (re-search-forward
  704. "<\\(\\(mailto:\\)?\\([-=+_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\\)\\)>"
  705. nil t)
  706. (let* ((address (match-string 3))
  707. (beg (match-beginning 0)) (end (match-end 0))
  708. (uri (concat "mailto:" (htmlize-despam-address address))))
  709. (htmlize-make-link-overlay beg end uri)))
  710. (goto-char (point-min))
  711. (while (re-search-forward "<\\(\\(URL:\\)?\\([a-zA-Z]+://[^;]+\\)\\)>"
  712. nil t)
  713. (htmlize-make-link-overlay
  714. (match-beginning 0) (match-end 0) (match-string 3)))))
  715. ;; Tests for htmlize-create-auto-links:
  716. ;; <mailto:hniksic@xemacs.org>
  717. ;; <http://fly.srk.fer.hr>
  718. ;; <URL:http://www.xemacs.org>
  719. ;; <http://www.mail-archive.com/bbdb-info@xemacs.org/>
  720. ;; <hniksic@xemacs.org>
  721. ;; <xalan-dev-sc.10148567319.hacuhiucknfgmpfnjcpg-john=doe.com@xml.apache.org>
  722. (defun htmlize-shadow-form-feeds ()
  723. (let ((s "\n<hr />"))
  724. (put-text-property 0 (length s) 'htmlize-literal t s)
  725. (let ((disp `(display ,s)))
  726. (while (re-search-forward "\n\^L" nil t)
  727. (let* ((beg (match-beginning 0))
  728. (end (match-end 0))
  729. (form-feed-pos (1+ beg))
  730. ;; don't process ^L if invisible or covered by `display'
  731. (show (and (htmlize-decode-invisibility-spec
  732. (get-char-property form-feed-pos 'invisible))
  733. (not (get-char-property form-feed-pos 'display)))))
  734. (when show
  735. (htmlize-make-tmp-overlay beg end disp)))))))
  736. (defun htmlize-defang-local-variables ()
  737. ;; Juri Linkov reports that an HTML-ized "Local variables" can lead
  738. ;; visiting the HTML to fail with "Local variables list is not
  739. ;; properly terminated". He suggested changing the phrase to
  740. ;; syntactically equivalent HTML that Emacs doesn't recognize.
  741. (goto-char (point-min))
  742. (while (search-forward "Local Variables:" nil t)
  743. (replace-match "Local Variables&#58;" nil t)))
  744. ;;; Color handling.
  745. (defvar htmlize-x-library-search-path
  746. `(,data-directory
  747. "/etc/X11/rgb.txt"
  748. "/usr/share/X11/rgb.txt"
  749. ;; the remainder of this list really belongs in a museum
  750. "/usr/X11R6/lib/X11/"
  751. "/usr/X11R5/lib/X11/"
  752. "/usr/lib/X11R6/X11/"
  753. "/usr/lib/X11R5/X11/"
  754. "/usr/local/X11R6/lib/X11/"
  755. "/usr/local/X11R5/lib/X11/"
  756. "/usr/local/lib/X11R6/X11/"
  757. "/usr/local/lib/X11R5/X11/"
  758. "/usr/X11/lib/X11/"
  759. "/usr/lib/X11/"
  760. "/usr/local/lib/X11/"
  761. "/usr/X386/lib/X11/"
  762. "/usr/x386/lib/X11/"
  763. "/usr/XFree86/lib/X11/"
  764. "/usr/unsupported/lib/X11/"
  765. "/usr/athena/lib/X11/"
  766. "/usr/local/x11r5/lib/X11/"
  767. "/usr/lpp/Xamples/lib/X11/"
  768. "/usr/openwin/lib/X11/"
  769. "/usr/openwin/share/lib/X11/"))
  770. (defun htmlize-get-color-rgb-hash (&optional rgb-file)
  771. "Return a hash table mapping X color names to RGB values.
  772. The keys in the hash table are X11 color names, and the values are the
  773. #rrggbb RGB specifications, extracted from `rgb.txt'.
  774. If RGB-FILE is nil, the function will try hard to find a suitable file
  775. in the system directories.
  776. If no rgb.txt file is found, return nil."
  777. (let ((rgb-file (or rgb-file (locate-file
  778. "rgb.txt"
  779. htmlize-x-library-search-path)))
  780. (hash nil))
  781. (when rgb-file
  782. (with-temp-buffer
  783. (insert-file-contents rgb-file)
  784. (setq hash (make-hash-table :test 'equal))
  785. (while (not (eobp))
  786. (cond ((looking-at "^\\s-*\\([!#]\\|$\\)")
  787. ;; Skip comments and empty lines.
  788. )
  789. ((looking-at
  790. "[ \t]*\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\([0-9]+\\)[ \t]+\\(.*\\)")
  791. (setf (gethash (downcase (match-string 4)) hash)
  792. (format "#%02x%02x%02x"
  793. (string-to-number (match-string 1))
  794. (string-to-number (match-string 2))
  795. (string-to-number (match-string 3)))))
  796. (t
  797. (error
  798. "Unrecognized line in %s: %s"
  799. rgb-file
  800. (buffer-substring (point) (progn (end-of-line) (point))))))
  801. (forward-line 1))))
  802. hash))
  803. ;; Compile the RGB map when loaded. On systems where rgb.txt is
  804. ;; missing, the value of the variable will be nil, and rgb.txt will
  805. ;; not be used.
  806. (defvar htmlize-color-rgb-hash (htmlize-get-color-rgb-hash))
  807. ;;; Face handling.
  808. (defun htmlize-face-color-internal (face fg)
  809. ;; Used only under GNU Emacs. Return the color of FACE, but don't
  810. ;; return "unspecified-fg" or "unspecified-bg". If the face is
  811. ;; `default' and the color is unspecified, look up the color in
  812. ;; frame parameters.
  813. (let* ((function (if fg #'face-foreground #'face-background))
  814. (color (funcall function face nil t)))
  815. (when (and (eq face 'default) (null color))
  816. (setq color (cdr (assq (if fg 'foreground-color 'background-color)
  817. (frame-parameters)))))
  818. (when (or (eq color 'unspecified)
  819. (equal color "unspecified-fg")
  820. (equal color "unspecified-bg"))
  821. (setq color nil))
  822. (when (and (eq face 'default)
  823. (null color))
  824. ;; Assuming black on white doesn't seem right, but I can't think
  825. ;; of anything better to do.
  826. (setq color (if fg "black" "white")))
  827. color))
  828. (defun htmlize-face-foreground (face)
  829. ;; Return the name of the foreground color of FACE. If FACE does
  830. ;; not specify a foreground color, return nil.
  831. (htmlize-face-color-internal face t))
  832. (defun htmlize-face-background (face)
  833. ;; Return the name of the background color of FACE. If FACE does
  834. ;; not specify a background color, return nil.
  835. ;; GNU Emacs.
  836. (htmlize-face-color-internal face nil))
  837. ;; Convert COLOR to the #RRGGBB string. If COLOR is already in that
  838. ;; format, it's left unchanged.
  839. (defun htmlize-color-to-rgb (color)
  840. (let ((rgb-string nil))
  841. (cond ((null color)
  842. ;; Ignore nil COLOR because it means that the face is not
  843. ;; specifying any color. Hence (htmlize-color-to-rgb nil)
  844. ;; returns nil.
  845. )
  846. ((string-match "\\`#" color)
  847. ;; The color is already in #rrggbb format.
  848. (setq rgb-string color))
  849. ((and htmlize-use-rgb-txt
  850. htmlize-color-rgb-hash)
  851. ;; Use of rgb.txt is requested, and it's available on the
  852. ;; system. Use it.
  853. (setq rgb-string (gethash (downcase color) htmlize-color-rgb-hash)))
  854. (t
  855. ;; We're getting the RGB components from Emacs.
  856. (let ((rgb (mapcar (lambda (arg)
  857. (/ arg 256))
  858. (color-values color))))
  859. (when rgb
  860. (setq rgb-string (apply #'format "#%02x%02x%02x" rgb))))))
  861. ;; If RGB-STRING is still nil, it means the color cannot be found,
  862. ;; for whatever reason. In that case just punt and return COLOR.
  863. ;; Most browsers support a decent set of color names anyway.
  864. (or rgb-string color)))
  865. ;; We store the face properties we care about into an
  866. ;; `htmlize-fstruct' type. That way we only have to analyze face
  867. ;; properties, which can be time consuming, once per each face. The
  868. ;; mapping between Emacs faces and htmlize-fstructs is established by
  869. ;; htmlize-make-face-map. The name "fstruct" refers to variables of
  870. ;; type `htmlize-fstruct', while the term "face" is reserved for Emacs
  871. ;; faces.
  872. (defstruct htmlize-fstruct
  873. foreground ; foreground color, #rrggbb
  874. background ; background color, #rrggbb
  875. size ; size
  876. boldp ; whether face is bold
  877. italicp ; whether face is italic
  878. underlinep ; whether face is underlined
  879. overlinep ; whether face is overlined
  880. strikep ; whether face is struck through
  881. css-name ; CSS name of face
  882. )
  883. (defun htmlize-face-set-from-keyword-attr (fstruct attr value)
  884. ;; For ATTR and VALUE, set the equivalent value in FSTRUCT.
  885. (case attr
  886. (:foreground
  887. (setf (htmlize-fstruct-foreground fstruct) (htmlize-color-to-rgb value)))
  888. (:background
  889. (setf (htmlize-fstruct-background fstruct) (htmlize-color-to-rgb value)))
  890. (:height
  891. (setf (htmlize-fstruct-size fstruct) value))
  892. (:weight
  893. (when (string-match (symbol-name value) "bold")
  894. (setf (htmlize-fstruct-boldp fstruct) t)))
  895. (:slant
  896. (setf (htmlize-fstruct-italicp fstruct) (or (eq value 'italic)
  897. (eq value 'oblique))))
  898. (:bold
  899. (setf (htmlize-fstruct-boldp fstruct) value))
  900. (:italic
  901. (setf (htmlize-fstruct-italicp fstruct) value))
  902. (:underline
  903. (setf (htmlize-fstruct-underlinep fstruct) value))
  904. (:overline
  905. (setf (htmlize-fstruct-overlinep fstruct) value))
  906. (:strike-through
  907. (setf (htmlize-fstruct-strikep fstruct) value))))
  908. (defun htmlize-face-size (face)
  909. ;; The size (height) of FACE, taking inheritance into account.
  910. ;; Only works in Emacs 21 and later.
  911. (let* ((face-list (list face))
  912. (head face-list)
  913. (tail face-list))
  914. (while head
  915. (let ((inherit (face-attribute (car head) :inherit)))
  916. (cond ((listp inherit)
  917. (setcdr tail (copy-list inherit))
  918. (setq tail (last tail)))
  919. ((eq inherit 'unspecified))
  920. (t
  921. (setcdr tail (list inherit))
  922. (setq tail (cdr tail)))))
  923. (pop head))
  924. (let ((size-list
  925. (loop
  926. for f in face-list
  927. for h = (face-attribute f :height)
  928. collect (if (eq h 'unspecified) nil h))))
  929. (reduce 'htmlize-merge-size (cons nil size-list)))))
  930. (defun htmlize-face-css-name (face)
  931. ;; Generate the css-name property for the given face. Emacs places
  932. ;; no restrictions on the names of symbols that represent faces --
  933. ;; any characters may be in the name, even control chars. We try
  934. ;; hard to beat the face name into shape, both esthetically and
  935. ;; according to CSS1 specs.
  936. (let ((name (downcase (symbol-name face))))
  937. (when (string-match "\\`font-lock-" name)
  938. ;; font-lock-FOO-face -> FOO.
  939. (setq name (replace-match "" t t name)))
  940. (when (string-match "-face\\'" name)
  941. ;; Drop the redundant "-face" suffix.
  942. (setq name (replace-match "" t t name)))
  943. (while (string-match "[^-a-zA-Z0-9]" name)
  944. ;; Drop the non-alphanumerics.
  945. (setq name (replace-match "X" t t name)))
  946. (when (string-match "\\`[-0-9]" name)
  947. ;; CSS identifiers may not start with a digit.
  948. (setq name (concat "X" name)))
  949. ;; After these transformations, the face could come out empty.
  950. (when (equal name "")
  951. (setq name "face"))
  952. ;; Apply the prefix.
  953. (concat htmlize-css-name-prefix name)))
  954. (defun htmlize-face-to-fstruct-1 (face)
  955. "Convert Emacs face FACE to fstruct, internal."
  956. (let ((fstruct (make-htmlize-fstruct
  957. :foreground (htmlize-color-to-rgb
  958. (htmlize-face-foreground face))
  959. :background (htmlize-color-to-rgb
  960. (htmlize-face-background face)))))
  961. ;; GNU Emacs
  962. (dolist (attr '(:weight :slant :underline :overline :strike-through))
  963. (let ((value (face-attribute face attr nil t)))
  964. (when (and value (not (eq value 'unspecified)))
  965. (htmlize-face-set-from-keyword-attr fstruct attr value))))
  966. (let ((size (htmlize-face-size face)))
  967. (unless (eql size 1.0) ; ignore non-spec
  968. (setf (htmlize-fstruct-size fstruct) size)))
  969. (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face))
  970. fstruct))
  971. (defun htmlize-face-to-fstruct (face)
  972. (let* ((face-list (or (and (symbolp face)
  973. (cdr (assq face face-remapping-alist)))
  974. (list face)))
  975. (fstruct (htmlize-merge-faces
  976. (mapcar (lambda (face)
  977. (if (symbolp face)
  978. (or (htmlize-get-override-fstruct face)
  979. (htmlize-face-to-fstruct-1 face))
  980. (htmlize-attrlist-to-fstruct face)))
  981. (nreverse face-list)))))
  982. (when (symbolp face)
  983. (setf (htmlize-fstruct-css-name fstruct) (htmlize-face-css-name face)))
  984. fstruct))
  985. (defmacro htmlize-copy-attr-if-set (attr-list dest source)
  986. ;; Generate code with the following pattern:
  987. ;; (progn
  988. ;; (when (htmlize-fstruct-ATTR source)
  989. ;; (setf (htmlize-fstruct-ATTR dest) (htmlize-fstruct-ATTR source)))
  990. ;; ...)
  991. ;; for the given list of boolean attributes.
  992. (cons 'progn
  993. (loop for attr in attr-list
  994. for attr-sym = (intern (format "htmlize-fstruct-%s" attr))
  995. collect `(when (,attr-sym ,source)
  996. (setf (,attr-sym ,dest) (,attr-sym ,source))))))
  997. (defun htmlize-merge-size (merged next)
  998. ;; Calculate the size of the merge of MERGED and NEXT.
  999. (cond ((null merged) next)
  1000. ((integerp next) next)
  1001. ((null next) merged)
  1002. ((floatp merged) (* merged next))
  1003. ((integerp merged) (round (* merged next)))))
  1004. (defun htmlize-merge-two-faces (merged next)
  1005. (htmlize-copy-attr-if-set
  1006. (foreground background boldp italicp underlinep overlinep strikep)
  1007. merged next)
  1008. (setf (htmlize-fstruct-size merged)
  1009. (htmlize-merge-size (htmlize-fstruct-size merged)
  1010. (htmlize-fstruct-size next)))
  1011. merged)
  1012. (defun htmlize-merge-faces (fstruct-list)
  1013. (cond ((null fstruct-list)
  1014. ;; Nothing to do, return a dummy face.
  1015. (make-htmlize-fstruct))
  1016. ((null (cdr fstruct-list))
  1017. ;; Optimize for the common case of a single face, simply
  1018. ;; return it.
  1019. (car fstruct-list))
  1020. (t
  1021. (reduce #'htmlize-merge-two-faces
  1022. (cons (make-htmlize-fstruct) fstruct-list)))))
  1023. ;; GNU Emacs 20+ supports attribute lists in `face' properties. For
  1024. ;; example, you can use `(:foreground "red" :weight bold)' as an
  1025. ;; overlay's "face", or you can even use a list of such lists, etc.
  1026. ;; We call those "attrlists".
  1027. ;;
  1028. ;; htmlize supports attrlist by converting them to fstructs, the same
  1029. ;; as with regular faces.
  1030. (defun htmlize-attrlist-to-fstruct (attrlist &optional name)
  1031. ;; Like htmlize-face-to-fstruct, but accepts an ATTRLIST as input.
  1032. (let ((fstruct (make-htmlize-fstruct)))
  1033. (cond ((eq (car attrlist) 'foreground-color)
  1034. ;; ATTRLIST is (foreground-color . COLOR)
  1035. (setf (htmlize-fstruct-foreground fstruct)
  1036. (htmlize-color-to-rgb (cdr attrlist))))
  1037. ((eq (car attrlist) 'background-color)
  1038. ;; ATTRLIST is (background-color . COLOR)
  1039. (setf (htmlize-fstruct-background fstruct)
  1040. (htmlize-color-to-rgb (cdr attrlist))))
  1041. (t
  1042. ;; ATTRLIST is a plist.
  1043. (while attrlist
  1044. (let ((attr (pop attrlist))
  1045. (value (pop attrlist)))
  1046. (when (and value (not (eq value 'unspecified)))
  1047. (htmlize-face-set-from-keyword-attr fstruct attr value))))))
  1048. (setf (htmlize-fstruct-css-name fstruct) (or name "custom"))
  1049. fstruct))
  1050. (defun htmlize-decode-face-prop (prop)
  1051. "Turn face property PROP into a list of face-like objects."
  1052. ;; PROP can be a symbol naming a face, a string naming such a
  1053. ;; symbol, a cons (foreground-color . COLOR) or (background-color
  1054. ;; COLOR), a property list (:attr1 val1 :attr2 val2 ...), or a list
  1055. ;; of any of those.
  1056. ;;
  1057. ;; (htmlize-decode-face-prop 'face) -> (face)
  1058. ;; (htmlize-decode-face-prop '(face1 face2)) -> (face1 face2)
  1059. ;; (htmlize-decode-face-prop '(:attr "val")) -> ((:attr "val"))
  1060. ;; (htmlize-decode-face-prop '((:attr "val") face (foreground-color "red")))
  1061. ;; -> ((:attr "val") face (foreground-color "red"))
  1062. ;;
  1063. ;; Unrecognized atoms or non-face symbols/strings are silently
  1064. ;; stripped away.
  1065. (cond ((null prop)
  1066. nil)
  1067. ((symbolp prop)
  1068. (and (facep prop)
  1069. (list prop)))
  1070. ((stringp prop)
  1071. (and (facep (intern-soft prop))
  1072. (list prop)))
  1073. ((atom prop)
  1074. nil)
  1075. ((and (symbolp (car prop))
  1076. (eq ?: (aref (symbol-name (car prop)) 0)))
  1077. (list prop))
  1078. ((or (eq (car prop) 'foreground-color)
  1079. (eq (car prop) 'background-color))
  1080. (list prop))
  1081. (t
  1082. (apply #'nconc (mapcar #'htmlize-decode-face-prop prop)))))
  1083. (defun htmlize-get-override-fstruct (face)
  1084. (let* ((raw-def (plist-get htmlize-face-overrides face))
  1085. (def (cond ((stringp raw-def) (list :foreground raw-def))
  1086. ((listp raw-def) raw-def)
  1087. (t
  1088. (error (format (concat "face override must be an "
  1089. "attribute list or string, got %s")
  1090. raw-def))))))
  1091. (and def
  1092. (htmlize-attrlist-to-fstruct def (symbol-name face)))))
  1093. (defun htmlize-make-face-map (faces)
  1094. ;; Return a hash table mapping Emacs faces to htmlize's fstructs.
  1095. ;; The keys are either face symbols or attrlists, so the test
  1096. ;; function must be `equal'.
  1097. (let ((face-map (make-hash-table :test 'equal))
  1098. css-names)
  1099. (dolist (face faces)
  1100. (unless (gethash face face-map)
  1101. ;; Haven't seen FACE yet; convert it to an fstruct and cache
  1102. ;; it.
  1103. (let ((fstruct (htmlize-face-to-fstruct face)))
  1104. (setf (gethash face face-map) fstruct)
  1105. (let* ((css-name (htmlize-fstruct-css-name fstruct))
  1106. (new-name css-name)
  1107. (i 0))
  1108. ;; Uniquify the face's css-name by using NAME-1, NAME-2,
  1109. ;; etc.
  1110. (while (member new-name css-names)
  1111. (setq new-name (format "%s-%s" css-name (incf i))))
  1112. (unless (equal new-name css-name)
  1113. (setf (htmlize-fstruct-css-name fstruct) new-name))
  1114. (push new-name css-names)))))
  1115. face-map))
  1116. (defun htmlize-unstringify-face (face)
  1117. "If FACE is a string, return it interned, otherwise return it unchanged."
  1118. (if (stringp face)
  1119. (intern face)
  1120. face))
  1121. (defun htmlize-faces-in-buffer ()
  1122. "Return a list of faces used in the current buffer.
  1123. This is the set of faces specified by the `face' text property and by buffer
  1124. overlays that specify `face'."
  1125. (let (faces)
  1126. ;; Faces used by text properties.
  1127. (let ((pos (point-min)) face-prop next)
  1128. (while (< pos (point-max))
  1129. (setq face-prop (get-text-property pos 'face)
  1130. next (or (next-single-property-change pos 'face) (point-max)))
  1131. (setq faces (nunion (htmlize-decode-face-prop face-prop)
  1132. faces :test 'equal))
  1133. (setq pos next)))
  1134. ;; Faces used by overlays.
  1135. (dolist (overlay (overlays-in (point-min) (point-max)))
  1136. (let ((face-prop (overlay-get overlay 'face)))
  1137. (setq faces (nunion (htmlize-decode-face-prop face-prop)
  1138. faces :test 'equal))))
  1139. faces))
  1140. (if (>= emacs-major-version 25)
  1141. (defun htmlize-sorted-overlays-at (pos)
  1142. (overlays-at pos t))
  1143. (defun htmlize-sorted-overlays-at (pos)
  1144. ;; Like OVERLAYS-AT with the SORTED argument, for older Emacsen.
  1145. (let ((overlays (overlays-at pos)))
  1146. (setq overlays (sort* overlays #'<
  1147. :key (lambda (o)
  1148. (- (overlay-end o) (overlay-start o)))))
  1149. (setq overlays
  1150. (stable-sort overlays #'<
  1151. :key (lambda (o)
  1152. (let ((prio (overlay-get o 'priority)))
  1153. (if (numberp prio) prio 0)))))
  1154. (nreverse overlays))))
  1155. ;; htmlize-faces-at-point returns the faces in use at point. The
  1156. ;; faces are sorted by increasing priority, i.e. the last face takes
  1157. ;; precedence.
  1158. ;;
  1159. ;; This returns all the faces in the `face' property and all the faces
  1160. ;; in the overlays at point.
  1161. (defun htmlize-faces-at-point ()
  1162. (let (all-faces)
  1163. ;; Faces from text properties.
  1164. (let ((face-prop (get-text-property (point) 'face)))
  1165. ;; we need to reverse the `face' prop because we want
  1166. ;; more specific faces to come later
  1167. (setq all-faces (nreverse (htmlize-decode-face-prop face-prop))))
  1168. ;; Faces from overlays.
  1169. (let ((overlays
  1170. ;; Collect overlays at point that specify `face'.
  1171. (delete-if-not (lambda (o)
  1172. (overlay-get o 'face))
  1173. (nreverse (htmlize-sorted-overlays-at (point)))))
  1174. list face-prop)
  1175. (dolist (overlay overlays)
  1176. (setq face-prop (overlay-get overlay 'face)
  1177. list (nconc (htmlize-decode-face-prop face-prop) list)))
  1178. ;; Under "Merging Faces" the manual explicitly states
  1179. ;; that faces specified by overlays take precedence over
  1180. ;; faces specified by text properties.
  1181. (setq all-faces (nconc all-faces list)))
  1182. all-faces))
  1183. ;; htmlize supports generating HTML in several flavors, some of which
  1184. ;; use CSS, and others the <font> element. We take an OO approach and
  1185. ;; define "methods" that indirect to the functions that depend on
  1186. ;; `htmlize-output-type'. The currently used methods are `doctype',
  1187. ;; `insert-head', `body-tag', `pre-tag', and `text-markup'. Not all
  1188. ;; output types define all methods.
  1189. ;;
  1190. ;; Methods are called either with (htmlize-method METHOD ARGS...)
  1191. ;; special form, or by accessing the function with
  1192. ;; (htmlize-method-function 'METHOD) and calling (funcall FUNCTION).
  1193. ;; The latter form is useful in tight loops because `htmlize-method'
  1194. ;; conses.
  1195. (defmacro htmlize-method (method &rest args)
  1196. ;; Expand to (htmlize-TYPE-METHOD ...ARGS...). TYPE is the value of
  1197. ;; `htmlize-output-type' at run time.
  1198. `(funcall (htmlize-method-function ',method) ,@args))
  1199. (defun htmlize-method-function (method)
  1200. ;; Return METHOD's function definition for the current output type.
  1201. ;; The returned object can be safely funcalled.
  1202. (let ((sym (intern (format "htmlize-%s-%s" htmlize-output-type method))))
  1203. (indirect-function (if (fboundp sym)
  1204. sym
  1205. (let ((default (intern (concat "htmlize-default-"
  1206. (symbol-name method)))))
  1207. (if (fboundp default)
  1208. default
  1209. 'ignore))))))
  1210. (defvar htmlize-memoization-table (make-hash-table :test 'equal))
  1211. (defmacro htmlize-memoize (key generator)
  1212. "Return the value of GENERATOR, memoized as KEY.
  1213. That means that GENERATOR will be evaluated and returned the first time
  1214. it's called with the same value of KEY. All other times, the cached
  1215. \(memoized) value will be returned."
  1216. (let ((value (gensym)))
  1217. `(let ((,value (gethash ,key htmlize-memoization-table)))
  1218. (unless ,value
  1219. (setq ,value ,generator)
  1220. (setf (gethash ,key htmlize-memoization-table) ,value))
  1221. ,value)))
  1222. ;;; Default methods.
  1223. (defun htmlize-default-doctype ()
  1224. nil ; no doc-string
  1225. ;; Note that the `font' output is technically invalid under this DTD
  1226. ;; because the DTD doesn't allow embedding <font> in <pre>.
  1227. "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\">"
  1228. )
  1229. (defun htmlize-default-body-tag (face-map)
  1230. nil ; no doc-string
  1231. face-map ; shut up the byte-compiler
  1232. "<body>")
  1233. (defun htmlize-default-pre-tag (face-map)
  1234. nil ; no doc-string
  1235. face-map ; shut up the byte-compiler
  1236. "<pre>")
  1237. ;;; CSS based output support.
  1238. ;; Internal function; not a method.
  1239. (defun htmlize-css-specs (fstruct)
  1240. (let (result)
  1241. (when (htmlize-fstruct-foreground fstruct)
  1242. (push (format "color: %s;" (htmlize-fstruct-foreground fstruct))
  1243. result))
  1244. (when (htmlize-fstruct-background fstruct)
  1245. (push (format "background-color: %s;"
  1246. (htmlize-fstruct-background fstruct))
  1247. result))
  1248. (let ((size (htmlize-fstruct-size fstruct)))
  1249. (when (and size (not (eq htmlize-ignore-face-size t)))
  1250. (cond ((floatp size)
  1251. (push (format "font-size: %d%%;" (* 100 size)) result))
  1252. ((not (eq htmlize-ignore-face-size 'absolute))
  1253. (push (format "font-size: %spt;" (/ size 10.0)) result)))))
  1254. (when (htmlize-fstruct-boldp fstruct)
  1255. (push "font-weight: bold;" result))
  1256. (when (htmlize-fstruct-italicp fstruct)
  1257. (push "font-style: italic;" result))
  1258. (when (htmlize-fstruct-underlinep fstruct)
  1259. (push "text-decoration: underline;" result))
  1260. (when (htmlize-fstruct-overlinep fstruct)
  1261. (push "text-decoration: overline;" result))
  1262. (when (htmlize-fstruct-strikep fstruct)
  1263. (push "text-decoration: line-through;" result))
  1264. (nreverse result)))
  1265. (defun htmlize-css-insert-head (buffer-faces face-map)
  1266. (insert " <style type=\"text/css\">\n <!--\n")
  1267. (insert " body {\n "
  1268. (mapconcat #'identity
  1269. (htmlize-css-specs (gethash 'default face-map))
  1270. "\n ")
  1271. "\n }\n")
  1272. (dolist (face (sort* (copy-list buffer-faces) #'string-lessp
  1273. :key (lambda (f)
  1274. (htmlize-fstruct-css-name (gethash f face-map)))))
  1275. (let* ((fstruct (gethash face face-map))
  1276. (cleaned-up-face-name
  1277. (let ((s
  1278. ;; Use `prin1-to-string' rather than `symbol-name'
  1279. ;; to get the face name because the "face" can also
  1280. ;; be an attrlist, which is not a symbol.
  1281. (prin1-to-string face)))
  1282. ;; If the name contains `--' or `*/', remove them.
  1283. (while (string-match "--" s)
  1284. (setq s (replace-match "-" t t s)))
  1285. (while (string-match "\\*/" s)
  1286. (setq s (replace-match "XX" t t s)))
  1287. s))
  1288. (specs (htmlize-css-specs fstruct)))
  1289. (insert " ." (htmlize-fstruct-css-name fstruct))
  1290. (if (null specs)
  1291. (insert " {")
  1292. (insert " {\n /* " cleaned-up-face-name " */\n "
  1293. (mapconcat #'identity specs "\n ")))
  1294. (insert "\n }\n")))
  1295. (insert htmlize-hyperlink-style
  1296. " -->\n </style>\n"))
  1297. (defun htmlize-css-text-markup (fstruct-list buffer)
  1298. ;; Open the markup needed to insert text colored with FACES into
  1299. ;; BUFFER. Return the function that closes the markup.
  1300. ;; In CSS mode, this is easy: just nest the text in one <span
  1301. ;; class=...> tag for each face in FSTRUCT-LIST.
  1302. (dolist (fstruct fstruct-list)
  1303. (princ "<span class=\"" buffer)
  1304. (princ (htmlize-fstruct-css-name fstruct) buffer)
  1305. (princ "\">" buffer))
  1306. (htmlize-lexlet ((fstruct-list fstruct-list) (buffer buffer))
  1307. (lambda ()
  1308. (dolist (fstruct fstruct-list)
  1309. (ignore fstruct) ; shut up the byte-compiler
  1310. (princ "</span>" buffer)))))
  1311. ;; `inline-css' output support.
  1312. (defun htmlize-inline-css-body-tag (face-map)
  1313. (format "<body style=\"%s\">"
  1314. (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
  1315. " ")))
  1316. (defun htmlize-inline-css-pre-tag (face-map)
  1317. (if htmlize-pre-style
  1318. (format "<pre style=\"%s\">"
  1319. (mapconcat #'identity (htmlize-css-specs (gethash 'default face-map))
  1320. " "))
  1321. (format "<pre>")))
  1322. (defun htmlize-inline-css-text-markup (fstruct-list buffer)
  1323. (let* ((merged (htmlize-merge-faces fstruct-list))
  1324. (style (htmlize-memoize
  1325. merged
  1326. (let ((specs (htmlize-css-specs merged)))
  1327. (and specs
  1328. (mapconcat #'identity (htmlize-css-specs merged) " "))))))
  1329. (when style
  1330. (princ "<span style=\"" buffer)
  1331. (princ style buffer)
  1332. (princ "\">" buffer))
  1333. (htmlize-lexlet ((style style) (buffer buffer))
  1334. (lambda ()
  1335. (when style
  1336. (princ "</span>" buffer))))))
  1337. ;;; `font' tag based output support.
  1338. (defun htmlize-font-body-tag (face-map)
  1339. (let ((fstruct (gethash 'default face-map)))
  1340. (format "<body text=\"%s\" bgcolor=\"%s\">"
  1341. (htmlize-fstruct-foreground fstruct)
  1342. (htmlize-fstruct-background fstruct))))
  1343. (defun htmlize-font-pre-tag (face-map)
  1344. (if htmlize-pre-style
  1345. (let ((fstruct (gethash 'default face-map)))
  1346. (format "<pre text=\"%s\" bgcolor=\"%s\">"
  1347. (htmlize-fstruct-foreground fstruct)
  1348. (htmlize-fstruct-background fstruct)))
  1349. (format "<pre>")))
  1350. (defun htmlize-font-text-markup (fstruct-list buffer)
  1351. ;; In `font' mode, we use the traditional HTML means of altering
  1352. ;; presentation: <font> tag for colors, <b> for bold, <u> for
  1353. ;; underline, and <strike> for strike-through.
  1354. (let* ((merged (htmlize-merge-faces fstruct-list))
  1355. (markup (htmlize-memoize
  1356. merged
  1357. (cons (concat
  1358. (and (htmlize-fstruct-foreground merged)
  1359. (format "<font color=\"%s\">" (htmlize-fstruct-foreground merged)))
  1360. (and (htmlize-fstruct-boldp merged) "<b>")
  1361. (and (htmlize-fstruct-italicp merged) "<i>")
  1362. (and (htmlize-fstruct-underlinep merged) "<u>")
  1363. (and (htmlize-fstruct-strikep merged) "<strike>"))
  1364. (concat
  1365. (and (htmlize-fstruct-strikep merged) "</strike>")
  1366. (and (htmlize-fstruct-underlinep merged) "</u>")
  1367. (and (htmlize-fstruct-italicp merged) "</i>")
  1368. (and (htmlize-fstruct-boldp merged) "</b>")
  1369. (and (htmlize-fstruct-foreground merged) "</font>"))))))
  1370. (princ (car markup) buffer)
  1371. (htmlize-lexlet ((markup markup) (buffer buffer))
  1372. (lambda ()
  1373. (princ (cdr markup) buffer)))))
  1374. (defun htmlize-buffer-1 ()
  1375. ;; Internal function; don't call it from outside this file. Htmlize
  1376. ;; current buffer, writing the resulting HTML to a new buffer, and
  1377. ;; return it. Unlike htmlize-buffer, this doesn't change current
  1378. ;; buffer or use switch-to-buffer.
  1379. (save-excursion
  1380. ;; Protect against the hook changing the current buffer.
  1381. (save-excursion
  1382. (run-hooks 'htmlize-before-hook))
  1383. ;; Convince font-lock support modes to fontify the entire buffer
  1384. ;; in advance.
  1385. (htmlize-ensure-fontified)
  1386. (clrhash htmlize-extended-character-cache)
  1387. (clrhash htmlize-memoization-table)
  1388. ;; It's important that the new buffer inherits default-directory
  1389. ;; from the current buffer.
  1390. (let ((htmlbuf (generate-new-buffer (if (buffer-file-name)
  1391. (htmlize-make-file-name
  1392. (file-name-nondirectory
  1393. (buffer-file-name)))
  1394. "*html*")))
  1395. (completed nil))
  1396. (unwind-protect
  1397. (let* ((buffer-faces (htmlize-faces-in-buffer))
  1398. (face-map (htmlize-make-face-map (adjoin 'default buffer-faces)))
  1399. (places (gensym))
  1400. (title (if (buffer-file-name)
  1401. (file-name-nondirectory (buffer-file-name))
  1402. (buffer-name))))
  1403. (when htmlize-generate-hyperlinks
  1404. (htmlize-create-auto-links))
  1405. (when htmlize-replace-form-feeds
  1406. (htmlize-shadow-form-feeds))
  1407. ;; Initialize HTMLBUF and insert the HTML prolog.
  1408. (with-current-buffer htmlbuf
  1409. (buffer-disable-undo)
  1410. (insert (htmlize-method doctype) ?\n
  1411. (format "<!-- Created by htmlize-%s in %s mode. -->\n"
  1412. htmlize-version htmlize-output-type)
  1413. "<html>\n ")
  1414. (put places 'head-start (point-marker))
  1415. (insert "<head>\n"
  1416. " <title>" (htmlize-protect-string title) "</title>\n"
  1417. (if htmlize-html-charset
  1418. (format (concat " <meta http-equiv=\"Content-Type\" "
  1419. "content=\"text/html; charset=%s\">\n")
  1420. htmlize-html-charset)
  1421. "")
  1422. htmlize-head-tags)
  1423. (htmlize-method insert-head buffer-faces face-map)
  1424. (insert " </head>")
  1425. (put places 'head-end (point-marker))
  1426. (insert "\n ")
  1427. (put places 'body-start (point-marker))
  1428. (insert (htmlize-method body-tag face-map)
  1429. "\n ")
  1430. (put places 'content-start (point-marker))
  1431. (insert (htmlize-method pre-tag face-map) "\n"))
  1432. (let ((text-markup
  1433. ;; Get the inserter method, so we can funcall it inside
  1434. ;; the loop. Not calling `htmlize-method' in the loop
  1435. ;; body yields a measurable speed increase.
  1436. (htmlize-method-function 'text-markup))
  1437. ;; Declare variables used in loop body outside the loop
  1438. ;; because it's faster to establish `let' bindings only
  1439. ;; once.
  1440. next-change text face-list trailing-ellipsis
  1441. fstruct-list last-fstruct-list
  1442. (close-markup (lambda ())))
  1443. ;; This loop traverses and reads the source buffer, appending
  1444. ;; the resulting HTML to HTMLBUF. This method is fast
  1445. ;; because: 1) it doesn't require examining the text
  1446. ;; properties char by char (htmlize-next-face-change is used
  1447. ;; to move between runs with the same face), and 2) it doesn't
  1448. ;; require frequent buffer switches, which are slow because
  1449. ;; they rebind all buffer-local vars.
  1450. (goto-char (point-min))
  1451. (while (not (eobp))
  1452. (setq next-change (htmlize-next-face-change (point)))
  1453. ;; Get faces in use between (point) and NEXT-CHANGE, and
  1454. ;; convert them to fstructs.
  1455. (setq face-list (htmlize-faces-at-point)
  1456. fstruct-list (delq nil (mapcar (lambda (f)
  1457. (gethash f face-map))
  1458. face-list)))
  1459. (multiple-value-setq (text trailing-ellipsis)
  1460. (htmlize-extract-text (point) next-change trailing-ellipsis))
  1461. ;; Don't bother writing anything if there's no text (this
  1462. ;; happens in invisible regions).
  1463. (when (> (length text) 0)
  1464. ;; Open the new markup if necessary and insert the text.
  1465. (when (not (equalp fstruct-list last-fstruct-list))
  1466. (funcall close-markup)
  1467. (setq last-fstruct-list fstruct-list
  1468. close-markup (funcall text-markup fstruct-list htmlbuf)))
  1469. (princ text htmlbuf))
  1470. (goto-char next-change))
  1471. ;; We've gone through the buffer; close the markup from
  1472. ;; the last run, if any.
  1473. (funcall close-markup))
  1474. ;; Insert the epilog and post-process the buffer.
  1475. (with-current-buffer htmlbuf
  1476. (insert "</pre>")
  1477. (put places 'content-end (point-marker))
  1478. (insert "\n </body>")
  1479. (put places 'body-end (point-marker))
  1480. (insert "\n</html>\n")
  1481. (htmlize-defang-local-variables)
  1482. (goto-char (point-min))
  1483. (when htmlize-html-major-mode
  1484. ;; What sucks about this is that the minor modes, most notably
  1485. ;; font-lock-mode, won't be initialized. Oh well.
  1486. (funcall htmlize-html-major-mode))
  1487. (set (make-local-variable 'htmlize-buffer-places)
  1488. (symbol-plist places))
  1489. (run-hooks 'htmlize-after-hook)
  1490. (buffer-enable-undo))
  1491. (setq completed t)
  1492. htmlbuf)
  1493. (when (not completed)
  1494. (kill-buffer htmlbuf))
  1495. (htmlize-delete-tmp-overlays)))))
  1496. ;; Utility functions.
  1497. (defmacro htmlize-with-fontify-message (&rest body)
  1498. ;; When forcing fontification of large buffers in
  1499. ;; htmlize-ensure-fontified, inform the user that he is waiting for
  1500. ;; font-lock, not for htmlize to finish.
  1501. `(progn
  1502. (if (> (buffer-size) 65536)
  1503. (message "Forcing fontification of %s..."
  1504. (buffer-name (current-buffer))))
  1505. ,@body
  1506. (if (> (buffer-size) 65536)
  1507. (message "Forcing fontification of %s...done"
  1508. (buffer-name (current-buffer))))))
  1509. (defun htmlize-ensure-fontified ()
  1510. ;; If font-lock is being used, ensure that the "support" modes
  1511. ;; actually fontify the buffer. If font-lock is not in use, we
  1512. ;; don't care because, except in htmlize-file, we don't force
  1513. ;; font-lock on the user.
  1514. (when font-lock-mode
  1515. ;; In part taken from ps-print-ensure-fontified in GNU Emacs 21.
  1516. (when (and (boundp 'jit-lock-mode)
  1517. (symbol-value 'jit-lock-mode))
  1518. (htmlize-with-fontify-message
  1519. (jit-lock-fontify-now (point-min) (point-max))))
  1520. (if (fboundp 'font-lock-ensure)
  1521. (font-lock-ensure)
  1522. ;; Emacs prior to 25.1
  1523. (with-no-warnings
  1524. (font-lock-mode 1)
  1525. (font-lock-fontify-buffer)))))
  1526. ;;;###autoload
  1527. (defun htmlize-buffer (&optional buffer)
  1528. "Convert BUFFER to HTML, preserving colors and decorations.
  1529. The generated HTML is available in a new buffer, which is returned.
  1530. When invoked interactively, the new buffer is selected in the current
  1531. window. The title of the generated document will be set to the buffer's
  1532. file name or, if that's not available, to the buffer's name.
  1533. Note that htmlize doesn't fontify your buffers, it only uses the
  1534. decorations that are already present. If you don't set up font-lock or
  1535. something else to fontify your buffers, the resulting HTML will be
  1536. plain. Likewise, if you don't like the choice of colors, fix the mode
  1537. that created them, or simply alter the faces it uses."
  1538. (interactive)
  1539. (let ((htmlbuf (with-current-buffer (or buffer (current-buffer))
  1540. (htmlize-buffer-1))))
  1541. (when (interactive-p)
  1542. (switch-to-buffer htmlbuf))
  1543. htmlbuf))
  1544. ;;;###autoload
  1545. (defun htmlize-region (beg end)
  1546. "Convert the region to HTML, preserving colors and decorations.
  1547. See `htmlize-buffer' for details."
  1548. (interactive "r")
  1549. ;; Don't let zmacs region highlighting end up in HTML.
  1550. (when (fboundp 'zmacs-deactivate-region)
  1551. (zmacs-deactivate-region))
  1552. (let ((htmlbuf (save-restriction
  1553. (narrow-to-region beg end)
  1554. (htmlize-buffer-1))))
  1555. (when (interactive-p)
  1556. (switch-to-buffer htmlbuf))
  1557. htmlbuf))
  1558. (defun htmlize-region-for-paste (beg end)
  1559. "Htmlize the region and return just the HTML as a string.
  1560. This forces the `inline-css' style and only returns the HTML body,
  1561. but without the BODY tag. This should make it useful for inserting
  1562. the text to another HTML buffer."
  1563. (let* ((htmlize-output-type 'inline-css)
  1564. (htmlbuf (htmlize-region beg end)))
  1565. (unwind-protect
  1566. (with-current-buffer htmlbuf
  1567. (buffer-substring (plist-get htmlize-buffer-places 'content-start)
  1568. (plist-get htmlize-buffer-places 'content-end)))
  1569. (kill-buffer htmlbuf))))
  1570. (defun htmlize-region-save-screenshot (beg end)
  1571. "Save the htmlized (see `htmlize-region-for-paste') region in
  1572. the kill ring. Uses `inline-css', with style information in
  1573. `<pre>' tags, so that the rendering of the marked up text
  1574. approximates the buffer as closely as possible."
  1575. (interactive "r")
  1576. (let ((htmlize-pre-style t))
  1577. (kill-new (htmlize-region-for-paste beg end)))
  1578. (deactivate-mark))
  1579. (defun htmlize-make-file-name (file)
  1580. "Make an HTML file name from FILE.
  1581. In its default implementation, this simply appends `.html' to FILE.
  1582. This function is called by htmlize to create the buffer file name, and
  1583. by `htmlize-file' to create the target file name.
  1584. More elaborate transformations are conceivable, such as changing FILE's
  1585. extension to `.html' (\"file.c\" -> \"file.html\"). If you want them,
  1586. overload this function to do it and htmlize will comply."
  1587. (concat file ".html"))
  1588. ;; Older implementation of htmlize-make-file-name that changes FILE's
  1589. ;; extension to ".html".
  1590. ;(defun htmlize-make-file-name (file)
  1591. ; (let ((extension (file-name-extension file))
  1592. ; (sans-extension (file-name-sans-extension file)))
  1593. ; (if (or (equal extension "html")
  1594. ; (equal extension "htm")
  1595. ; (equal sans-extension ""))
  1596. ; (concat file ".html")
  1597. ; (concat sans-extension ".html"))))
  1598. ;;;###autoload
  1599. (defun htmlize-file (file &optional target)
  1600. "Load FILE, fontify it, convert it to HTML, and save the result.
  1601. Contents of FILE are inserted into a temporary buffer, whose major mode
  1602. is set with `normal-mode' as appropriate for the file type. The buffer
  1603. is subsequently fontified with `font-lock' and converted to HTML. Note
  1604. that, unlike `htmlize-buffer', this function explicitly turns on
  1605. font-lock. If a form of highlighting other than font-lock is desired,
  1606. please use `htmlize-buffer' directly on buffers so highlighted.
  1607. Buffers currently visiting FILE are unaffected by this function. The
  1608. function does not change current buffer or move the point.
  1609. If TARGET is specified and names a directory, the resulting file will be
  1610. saved there instead of to FILE's directory. If TARGET is specified and
  1611. does not name a directory, it will be used as output file name."
  1612. (interactive (list (read-file-name
  1613. "HTML-ize file: "
  1614. nil nil nil (and (buffer-file-name)
  1615. (file-name-nondirectory
  1616. (buffer-file-name))))))
  1617. (let ((output-file (if (and target (not (file-directory-p target)))
  1618. target
  1619. (expand-file-name
  1620. (htmlize-make-file-name (file-name-nondirectory file))
  1621. (or target (file-name-directory file)))))
  1622. ;; Try to prevent `find-file-noselect' from triggering
  1623. ;; font-lock because we'll fontify explicitly below.
  1624. (font-lock-mode nil)
  1625. (font-lock-auto-fontify nil)
  1626. (global-font-lock-mode nil)
  1627. ;; Ignore the size limit for the purposes of htmlization.
  1628. (font-lock-maximum-size nil))
  1629. (with-temp-buffer
  1630. ;; Insert FILE into the temporary buffer.
  1631. (insert-file-contents file)
  1632. ;; Set the file name so normal-mode and htmlize-buffer-1 pick it
  1633. ;; up. Restore it afterwards so with-temp-buffer's kill-buffer
  1634. ;; doesn't complain about killing a modified buffer.
  1635. (let ((buffer-file-name file))
  1636. ;; Set the major mode for the sake of font-lock.
  1637. (normal-mode)
  1638. ;; htmlize the buffer and save the HTML.
  1639. (with-current-buffer (htmlize-buffer-1)
  1640. (unwind-protect
  1641. (progn
  1642. (run-hooks 'htmlize-file-hook)
  1643. (write-region (point-min) (point-max) output-file))
  1644. (kill-buffer (current-buffer)))))))
  1645. ;; I haven't decided on a useful return value yet, so just return
  1646. ;; nil.
  1647. nil)
  1648. ;;;###autoload
  1649. (defun htmlize-many-files (files &optional target-directory)
  1650. "Convert FILES to HTML and save the corresponding HTML versions.
  1651. FILES should be a list of file names to convert. This function calls
  1652. `htmlize-file' on each file; see that function for details. When
  1653. invoked interactively, you are prompted for a list of files to convert,
  1654. terminated with RET.
  1655. If TARGET-DIRECTORY is specified, the HTML files will be saved to that
  1656. directory. Normally, each HTML file is saved to the directory of the
  1657. corresponding source file."
  1658. (interactive
  1659. (list
  1660. (let (list file)
  1661. ;; Use empty string as DEFAULT because setting DEFAULT to nil
  1662. ;; defaults to the directory name, which is not what we want.
  1663. (while (not (equal (setq file (read-file-name
  1664. "HTML-ize file (RET to finish): "
  1665. (and list (file-name-directory
  1666. (car list)))
  1667. "" t))
  1668. ""))
  1669. (push file list))
  1670. (nreverse list))))
  1671. ;; Verify that TARGET-DIRECTORY is indeed a directory. If it's a
  1672. ;; file, htmlize-file will use it as target, and that doesn't make
  1673. ;; sense.
  1674. (and target-directory
  1675. (not (file-directory-p target-directory))
  1676. (error "target-directory must name a directory: %s" target-directory))
  1677. (dolist (file files)
  1678. (htmlize-file file target-directory)))
  1679. ;;;###autoload
  1680. (defun htmlize-many-files-dired (arg &optional target-directory)
  1681. "HTMLize dired-marked files."
  1682. (interactive "P")
  1683. (htmlize-many-files (dired-get-marked-files nil arg) target-directory))
  1684. (provide 'htmlize)
  1685. ;; Local Variables:
  1686. ;; byte-compile-warnings: (not cl-functions unresolved obsolete)
  1687. ;; End:
  1688. ;;; htmlize.el ends here