htmlize.el 77 KB

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