htmlize.el 74 KB

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