htmlize.el 69 KB

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