Klimi's new dotfiles with stow.
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.

1881 lines
74 KiB

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