htmlize.el 77 KB

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