htmlize.el 76 KB

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