htmlfontify.el 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436
  1. ;;; htmlfontify.el --- htmlize a buffer/source tree with optional hyperlinks
  2. ;; Copyright (C) 2002-2003, 2009-2012 Free Software Foundation, Inc.
  3. ;; Emacs Lisp Archive Entry
  4. ;; Package: htmlfontify
  5. ;; Filename: htmlfontify.el
  6. ;; Version: 0.21
  7. ;; Keywords: html, hypermedia, markup, etags
  8. ;; Author: Vivek Dasmohapatra <vivek@etla.org>
  9. ;; Maintainer: Vivek Dasmohapatra <vivek@etla.org>
  10. ;; Created: 2002-01-05
  11. ;; Description: htmlize a buffer/source tree with optional hyperlinks
  12. ;; URL: http://rtfm.etla.org/emacs/htmlfontify/
  13. ;; Compatibility: Emacs23, Emacs22
  14. ;; Incompatibility: Emacs19, Emacs20, Emacs21
  15. ;; Last Updated: Thu 2009-11-19 01:31:21 +0000
  16. ;; Version: 0.21
  17. ;; This file is part of GNU Emacs.
  18. ;; GNU Emacs is free software: you can redistribute it and/or modify
  19. ;; it under the terms of the GNU General Public License as published by
  20. ;; the Free Software Foundation, either version 3 of the License, or
  21. ;; (at your option) any later version.
  22. ;; GNU Emacs is distributed in the hope that it will be useful,
  23. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. ;; GNU General Public License for more details.
  26. ;; You should have received a copy of the GNU General Public License
  27. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  28. ;;; Commentary:
  29. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  30. ;; I have made some changes to make it work for Emacs 22. A lot of
  31. ;; small bug fixes related to the format of text and overlay
  32. ;; properties (which might have changed since the beginning of 2003
  33. ;; when this file was originally written).
  34. ;;
  35. ;; The function `hfy-face-at' currently carries much of the burden of
  36. ;; my lacking understanding of the formats mentioned above and should
  37. ;; need some knowledgeable help.
  38. ;;
  39. ;; Another thing that maybe could be fixed is that overlay background
  40. ;; colors which are now only seen where there is text (in the XHTML
  41. ;; output). A bit of CSS tweaking is necessary there.
  42. ;;
  43. ;; The face 'default has a value :background "SystemWindow" for the
  44. ;; background color. There is no explicit notion that this should be
  45. ;; considered transparent, but I have assumed that it could be handled
  46. ;; like if it was here. (I am unsure that background and foreground
  47. ;; priorities are handled ok, but it looks ok in my tests now.)
  48. ;;
  49. ;; 2007-12-27 Lennart Borgman
  50. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  51. ;; Here's some elisp code to html-pretty-print an Emacs buffer, preserving
  52. ;; the Emacs syntax/whatever highlighting. It also knows how to drive etags
  53. ;; (exuberant-ctags or Emacs etags) and hyperlink the code according
  54. ;; to its (etags') output.
  55. ;; NOTE: Currently the hyperlinking code only knows how to drive GNU find
  56. ;; and the exuberant and GNU variants of etags : I do not know of any other
  57. ;; etags variants, but mechanisms have been provided to allow htmlfontify
  58. ;; to be taught how to drive them. As long as your version of find has
  59. ;; the -path test and is reasonably sane, you should be fine.
  60. ;; A sample of the htmlfontified / hyperlinked output of this module can be
  61. ;; found at http://rtfm.etla.org/sql/dbishell/src/ - it's not perfect, but
  62. ;; it's a hell of a lot faster and more thorough than I could hope to be
  63. ;; doing this by hand.
  64. ;; some user / horrified onlooker comments:
  65. ;; What? No! There's something deeply wrong here... (R. Shufflebotham)
  66. ;; You're a freak. (D. Silverstone)
  67. ;; Aren't we giving you enough to do? (J. Busuttil)
  68. ;; You're almost as messed up as Lexx is! (N. Graves-Morris)
  69. ;;; History:
  70. ;; Changes: moved to changelog (CHANGES) file.
  71. ;;; Code:
  72. (eval-when-compile (require 'cl))
  73. (require 'faces)
  74. ;; (`facep' `face-attr-construct' `x-color-values' `color-values' `face-name')
  75. (require 'custom)
  76. ;; (`defgroup' `defcustom')
  77. (require 'font-lock)
  78. ;; (`font-lock-fontify-region')
  79. (require 'cus-edit)
  80. (defconst htmlfontify-version 0.21)
  81. (defconst hfy-meta-tags
  82. (format "<meta name=\"generator\" content=\"emacs %s; htmlfontify %0.2f\" />"
  83. emacs-version htmlfontify-version)
  84. "The generator meta tag for this version of htmlfontify.")
  85. (defconst htmlfontify-manual "Htmlfontify Manual"
  86. "Copy and convert buffers and files to HTML, adding hyperlinks between files
  87. \(driven by etags) if requested.
  88. \nInteractive functions:
  89. `htmlfontify-buffer'
  90. `htmlfontify-run-etags'
  91. `htmlfontify-copy-and-link-dir'
  92. `htmlfontify-load-rgb-file'
  93. `htmlfontify-unload-rgb-file'\n
  94. In order to:\n
  95. fontify a file you have open: \\[htmlfontify-buffer]
  96. prepare the etags map for a directory: \\[htmlfontify-run-etags]
  97. copy a directory, fontifying as you go: \\[htmlfontify-copy-and-link-dir]\n
  98. The following might be useful when running non-windowed or in batch mode:
  99. \(note that they shouldn't be necessary - we have a built in map)\n
  100. load an X11 style rgb.txt file: \\[htmlfontify-load-rgb-file]
  101. unload the current rgb.txt file: \\[htmlfontify-unload-rgb-file]\n
  102. And here's a programmatic example:\n
  103. \(defun rtfm-build-page-header (file style)
  104. (format \"#define TEMPLATE red+black.html
  105. #define DEBUG 1
  106. #include <build/menu-dirlist|>\\n
  107. html-css-url := /css/red+black.css
  108. title := rtfm.etla.org ( %s / src/%s )
  109. bodytag :=
  110. head <=STYLESHEET;\\n
  111. %s
  112. STYLESHEET
  113. main-title := rtfm / %s / src/%s\\n
  114. main-content <=MAIN_CONTENT;\\n\" rtfm-section file style rtfm-section file))
  115. \(defun rtfm-build-page-footer (file) \"\\nMAIN_CONTENT\\n\")
  116. \(defun rtfm-build-source-docs (section srcdir destdir)
  117. (interactive
  118. \"s section[eg- emacs / p4-blame]:\\nD source-dir: \\nD output-dir: \")
  119. (require 'htmlfontify)
  120. (hfy-load-tags-cache srcdir)
  121. (let ((hfy-page-header 'rtfm-build-page-header)
  122. (hfy-page-footer 'rtfm-build-page-footer)
  123. (rtfm-section section)
  124. (hfy-index-file \"index\"))
  125. (htmlfontify-run-etags srcdir)
  126. (htmlfontify-copy-and-link-dir srcdir destdir \".src\" \".html\")))")
  127. (defgroup htmlfontify nil
  128. "Convert buffers and files to HTML."
  129. :group 'applications
  130. :link '(variable-link htmlfontify-manual)
  131. :prefix "hfy-")
  132. (defcustom hfy-page-header 'hfy-default-header
  133. "Function called to build the header of the HTML source.
  134. This is called with two arguments (the filename relative to the top
  135. level source directory being etag'd and fontified), and a string containing
  136. the <style>...</style> text to embed in the document.
  137. It should return a string that will be used as the header for the
  138. htmlfontified version of the source file.\n
  139. See also `hfy-page-footer'."
  140. :group 'htmlfontify
  141. ;; FIXME: Why place such a :tag everywhere? Isn't it imposing your
  142. ;; own Custom preference on your users? --Stef
  143. :tag "page-header"
  144. :type '(function))
  145. (defcustom hfy-split-index nil
  146. "Whether or not to split the index `hfy-index-file' alphabetically.
  147. If non-nil, the index is split on the first letter of each tag.
  148. Useful when the index would otherwise be large and take
  149. a long time to render or be difficult to navigate."
  150. :group 'htmlfontify
  151. :tag "split-index"
  152. :type '(boolean))
  153. (defcustom hfy-page-footer 'hfy-default-footer
  154. "As `hfy-page-header', but generates the output footer.
  155. It takes only one argument, the filename."
  156. :group 'htmlfontify
  157. :tag "page-footer"
  158. :type '(function))
  159. (defcustom hfy-extn ".html"
  160. "File extension used for output files."
  161. :group 'htmlfontify
  162. :tag "extension"
  163. :type '(string))
  164. (defcustom hfy-src-doc-link-style "text-decoration: underline;"
  165. "String to add to the '<style> a' variant of an htmlfontify CSS class."
  166. :group 'htmlfontify
  167. :tag "src-doc-link-style"
  168. :type '(string))
  169. (defcustom hfy-src-doc-link-unstyle " text-decoration: none;"
  170. "Regex to remove from the <style> a variant of an htmlfontify CSS class."
  171. :group 'htmlfontify
  172. :tag "src-doc-link-unstyle"
  173. :type '(string))
  174. (defcustom hfy-link-extn nil
  175. "File extension used for href links.
  176. Useful where the htmlfontify output files are going to be processed
  177. again, with a resulting change in file extension. If nil, then any
  178. code using this should fall back to `hfy-extn'."
  179. :group 'htmlfontify
  180. :tag "link-extension"
  181. :type '(choice string (const nil)))
  182. (defcustom hfy-link-style-fun 'hfy-link-style-string
  183. "Function to customize the appearance of hyperlinks.
  184. Set this to a function, which will be called with one argument
  185. \(a \"{ foo: bar; ...}\" CSS style-string) - it should return a copy of
  186. its argument, altered so as to make any changes you want made for text which
  187. is a hyperlink, in addition to being in the class to which that style would
  188. normally be applied."
  189. :group 'htmlfontify
  190. :tag "link-style-function"
  191. :type '(function))
  192. (defcustom hfy-index-file "hfy-index"
  193. "Name (sans extension) of the tag definition index file produced during
  194. fontification-and-hyperlinking."
  195. :group 'htmlfontify
  196. :tag "index-file"
  197. :type '(string))
  198. (defcustom hfy-instance-file "hfy-instance"
  199. "Name (sans extension) of the tag usage index file produced during
  200. fontification-and-hyperlinking."
  201. :group 'htmlfontify
  202. :tag "instance-file"
  203. :type '(string))
  204. (defcustom hfy-html-quote-regex "\\([<\"&>]\\)"
  205. "Regex to match (with a single back-reference per match) strings in HTML
  206. which should be quoted with `hfy-html-quote' (and `hfy-html-quote-map')
  207. to make them safe."
  208. :group 'htmlfontify
  209. :tag "html-quote-regex"
  210. :type '(regexp))
  211. (define-obsolete-variable-alias 'hfy-init-kludge-hooks 'hfy-init-kludge-hook
  212. "23.2")
  213. (defcustom hfy-init-kludge-hook '(hfy-kludge-cperl-mode)
  214. "List of functions to call when starting `htmlfontify-buffer' to do any
  215. kludging necessary to get highlighting modes to behave as you want, even
  216. when not running under a window system."
  217. :group 'htmlfontify
  218. :tag "init-kludge-hooks"
  219. :type '(hook))
  220. (defcustom hfy-post-html-hooks nil
  221. "List of functions to call after creating and filling the HTML buffer.
  222. These functions will be called with the HTML buffer as the current buffer."
  223. :group 'htmlfontify
  224. :tag "post-html-hooks"
  225. :options '(set-auto-mode)
  226. :type '(hook))
  227. (defcustom hfy-default-face-def nil
  228. "Fallback `defface' specification for the face 'default, used when
  229. `hfy-display-class' has been set (the normal htmlfontify way of extracting
  230. potentially non-current face information doesn't necessarily work for
  231. 'default).\n
  232. Example: I customize this to:\n
  233. \((t :background \"black\" :foreground \"white\" :family \"misc-fixed\"))"
  234. :group 'htmlfontify
  235. :tag "default-face-definition"
  236. :type '(alist))
  237. (defcustom hfy-etag-regex (concat ".*"
  238. "\x7f" "\\([^\x01\n]+\\)"
  239. "\x01" "\\([0-9]+\\)"
  240. "," "\\([0-9]+\\)$"
  241. "\\|" ".*\x7f[0-9]+,[0-9]+$")
  242. "Regex used to parse an etags entry: must have 3 subexps, corresponding,
  243. in order, to:\n
  244. 1 - The tag
  245. 2 - The line
  246. 3 - The char (point) at which the tag occurs."
  247. :group 'htmlfontify
  248. :tag "etag-regex"
  249. :type '(regexp))
  250. (defcustom hfy-html-quote-map '(("\"" "&quot;")
  251. ("<" "&lt;" )
  252. ("&" "&amp;" )
  253. (">" "&gt;" ))
  254. "Alist of char -> entity mappings used to make the text HTML-safe."
  255. :group 'htmlfontify
  256. :tag "html-quote-map"
  257. :type '(alist :key-type (string)))
  258. (defconst hfy-e2x-etags-cmd "for src in `find . -type f`;
  259. do
  260. ETAGS=%s;
  261. case ${src} in
  262. *.ad[absm]|*.[CFHMSacfhlmpsty]|*.def|*.in[cs]|*.s[as]|*.src|*.cc|\\
  263. *.hh|*.[chy]++|*.[ch]pp|*.[chy]xx|*.pdb|*.[ch]s|*.[Cc][Oo][Bb]|\\
  264. *.[eh]rl|*.f90|*.for|*.java|*.[cem]l|*.clisp|*.lisp|*.[Ll][Ss][Pp]|\\
  265. [Mm]akefile*|*.pas|*.[Pp][LlMm]|*.psw|*.lm|*.pc|*.prolog|*.oak|\\
  266. *.p[sy]|*.sch|*.scheme|*.[Ss][Cc][Mm]|*.[Ss][Mm]|*.bib|*.cl[os]|\\
  267. *.ltx|*.sty|*.TeX|*.tex|*.texi|*.texinfo|*.txi|*.x[bp]m|*.yy|\\
  268. *.[Ss][Qq][Ll])
  269. ${ETAGS} -o- ${src};
  270. ;;
  271. *)
  272. FTYPE=`file ${src}`;
  273. case ${FTYPE} in
  274. *script*text*)
  275. ${ETAGS} -o- ${src};
  276. ;;
  277. *text*)
  278. SHEBANG=`head -n1 ${src} | grep '#!' -c`;
  279. if [ ${SHEBANG} -eq 1 ];
  280. then
  281. ${ETAGS} -o- ${src};
  282. fi;
  283. ;;
  284. esac;
  285. ;;
  286. esac;
  287. done;")
  288. (defconst hfy-etags-cmd-alist-default
  289. `(("emacs etags" . ,hfy-e2x-etags-cmd)
  290. ("exuberant ctags" . "%s -R -f -" )))
  291. (defcustom hfy-etags-cmd-alist
  292. hfy-etags-cmd-alist-default
  293. "Alist of possible shell commands that will generate etags output that
  294. `htmlfontify' can use. '%s' will be replaced by `hfy-etags-bin'."
  295. :group 'htmlfontify
  296. :tag "etags-cmd-alist"
  297. :type '(alist :key-type (string) :value-type (string)))
  298. (defcustom hfy-etags-bin "etags"
  299. "Location of etags binary (we begin by assuming it's in your path).\n
  300. Note that if etags is not in your path, you will need to alter the shell
  301. commands in `hfy-etags-cmd-alist'."
  302. :group 'htmlfontify
  303. :tag "etags-bin"
  304. :type '(file))
  305. (defcustom hfy-shell-file-name "/bin/sh"
  306. "Shell (Bourne or compatible) to invoke for complex shell operations."
  307. :group 'htmlfontify
  308. :tag "shell-file-name"
  309. :type '(file))
  310. (defcustom hfy-ignored-properties '(read-only
  311. intangible
  312. modification-hooks
  313. insert-in-front-hooks
  314. insert-behind-hooks
  315. point-entered
  316. point-left)
  317. "Properties to omit when copying a fontified buffer for HTML transformation."
  318. :group 'htmlfontify
  319. :tag "ignored-properties"
  320. :type '(repeat symbol))
  321. (defun hfy-which-etags ()
  322. "Return a string indicating which flavor of etags we are using."
  323. (let ((v (shell-command-to-string (concat hfy-etags-bin " --version"))))
  324. (cond ((string-match "exube" v) "exuberant ctags")
  325. ((string-match "GNU E" v) "emacs etags" )) ))
  326. (defcustom hfy-etags-cmd
  327. ;; We used to wrap this in a `eval-and-compile', but:
  328. ;; - it had no effect because this expression was not seen by the
  329. ;; byte-compiler (defcustom used to quote this argument).
  330. ;; - it signals an error (`hfy-which-etags' is not defined at compile-time).
  331. ;; - we want this auto-detection to reflect the system on which Emacs is run
  332. ;; rather than the one on which it's compiled.
  333. (cdr (assoc (hfy-which-etags) hfy-etags-cmd-alist))
  334. "The etags equivalent command to run in a source directory to generate a tags
  335. file for the whole source tree from there on down. The command should emit
  336. the etags output on stdout.\n
  337. Two canned commands are provided - they drive Emacs's etags and
  338. exuberant-ctags' etags respectively."
  339. :group 'htmlfontify
  340. :tag "etags-command"
  341. :type (let ((clist (list '(string))))
  342. (dolist (C hfy-etags-cmd-alist)
  343. (push (list 'const :tag (car C) (cdr C)) clist))
  344. (cons 'choice clist)))
  345. (defcustom hfy-istext-command "file %s | sed -e 's@^[^:]*:[ \t]*@@'"
  346. "Command to run with the name of a file, to see whether it is a text file
  347. or not. The command should emit a string containing the word 'text' if
  348. the file is a text file, and a string not containing 'text' otherwise."
  349. :group 'htmlfontify
  350. :tag "istext-command"
  351. :type '(string))
  352. (defcustom hfy-find-cmd
  353. "find . -type f \\! -name \\*~ \\! -name \\*.flc \\! -path \\*/CVS/\\*"
  354. "Find command used to harvest a list of files to attempt to fontify."
  355. :group 'htmlfontify
  356. :tag "find-command"
  357. :type '(string))
  358. (defcustom hfy-display-class nil
  359. "Display class to use to determine which display class to use when
  360. calculating a face's attributes. This is useful when, for example, you
  361. are running Emacs on a tty or in batch mode, and want htmlfontify to have
  362. access to the face spec you would use if you were connected to an X display.\n
  363. Some valid class specification elements are:\n
  364. '(class color)
  365. '(class grayscale)
  366. '(background dark)
  367. '(background light)
  368. '(type x-toolkit)
  369. '(type tty)
  370. '(type motif)
  371. '(type lucid)
  372. Multiple values for a tag may be combined, to indicate that any one or more
  373. of these values in the specification key constitutes a match, eg:\n
  374. '((class color grayscale) (type tty)) would match any of:\n
  375. '((class color))
  376. '((class grayscale))
  377. '((class color grayscale))
  378. '((class color foo))
  379. '((type tty))
  380. '((type tty) (class color))\n
  381. and so on."
  382. :type '(alist :key-type (symbol) :value-type (symbol))
  383. :group 'htmlfontify
  384. :tag "display-class"
  385. :options '((type (choice (const :tag "X11" x-toolkit)
  386. (const :tag "Terminal" tty )
  387. (const :tag "Lucid Toolkit" lucid )
  388. (const :tag "Motif Toolkit" motif )))
  389. (class (choice (const :tag "Color" color )
  390. (const :tag "Grayscale" grayscale)))
  391. (background (choice (const :tag "Dark" dark )
  392. (const :tag "Bright" light ))) ))
  393. (defcustom hfy-optimisations (list 'keep-overlays)
  394. "Optimizations to turn on: So far, the following have been implemented:\n
  395. merge-adjacent-tags: If two (or more) span tags are adjacent, identical and
  396. separated by nothing more than whitespace, they will
  397. be merged into one span.
  398. zap-comment-links : Suppress hyperlinking of tags found in comments.
  399. zap-string-links : Suppress hyperlinking of tags found in strings.
  400. div-wrapper : Add <div class=\"default\"> </div> tags around the
  401. output.
  402. keep-overlays : More of a bell (or possibly whistle) than an
  403. optimization - If on, preserve overlay highlighting
  404. (cf ediff or goo-font-lock) as well as basic faces.\n
  405. body-text-only : Emit only body-text. In concrete terms,
  406. 1. Suppress calls to `hfy-page-header'and
  407. `hfy-page-footer'
  408. 2. Pretend that `div-wrapper' option above is
  409. turned off
  410. 3. Don't enclose output in <pre> </pre> tags
  411. And the following are planned but not yet available:\n
  412. kill-context-leak : Suppress hyperlinking between files highlighted by
  413. different modes.\n
  414. Note: like compiler optimizations, these optimize the _output_ of the code,
  415. not the processing of the source itself, and are therefore likely to slow
  416. htmlfontify down, at least a little. Except for skip-refontification,
  417. which can never slow you down, but may result in incomplete fontification."
  418. :type '(set (const :tag "merge-adjacent-tags" merge-adjacent-tags )
  419. (const :tag "zap-comment-links" zap-comment-links )
  420. (const :tag "zap-string-links" zap-string-links )
  421. (const :tag "skip-refontification" skip-refontification)
  422. (const :tag "kill-context-leak" kill-context-leak )
  423. (const :tag "div-wrapper" div-wrapper )
  424. (const :tag "keep-overlays" keep-overlays )
  425. (const :tag "body-text-only" body-text-only ))
  426. :group 'htmlfontify
  427. :tag "optimizations")
  428. (defvar hfy-tags-cache nil
  429. "Alist of the form:\n
  430. \((\"/src/dir/0\" . tag-hash0) (\"/src/dir/1\" tag-hash1) ...)\n
  431. Each tag hash entry then contains entries of the form:\n
  432. \"tag_string\" => ((\"file/name.ext\" line char) ... )\n
  433. ie an alist mapping (relative) file paths to line and character offsets.\n
  434. See also `hfy-load-tags-cache'.")
  435. (defvar hfy-tags-sortl nil
  436. "Alist of the form ((\"/src/dir\" . (tag0 tag1 tag2)) ... )\n
  437. where the tags are stored in descending order of length.\n
  438. See also `hfy-load-tags-cache'.")
  439. (defvar hfy-tags-rmap nil
  440. "Alist of the form ((\"/src/dir\" . tag-rmap-hash))\n
  441. where tag-rmap-hash has entries of the form:
  442. \"tag_string\" => ( \"file/name.ext\" line char )
  443. Unlike `hfy-tags-cache' these are the locations of occurrences of
  444. tagged items, not the locations of their definitions.")
  445. (defvar hfy-style-assoc 'please-ignore-this-line
  446. "An assoc representing/describing an Emacs face.
  447. Properties may be repeated, in which case later properties should be
  448. treated as if they were inherited from a 'parent' font.
  449. \(For some properties, only the first encountered value is of any importance,
  450. for others the values might be cumulative, and for others they might be
  451. cumulative in a complex way.)\n
  452. Some examples:\n
  453. \(hfy-face-to-style 'default) =>
  454. ((\"background\" . \"rgb(0, 0, 0)\")
  455. (\"color\" . \"rgb(255, 255, 255)\")
  456. (\"font-style\" . \"normal\")
  457. (\"font-weight\" . \"500\")
  458. (\"font-stretch\" . \"normal\")
  459. (\"font-family\" . \"misc-fixed\")
  460. (\"font-size\" . \"13pt\")
  461. (\"text-decoration\" . \"none\"))\n
  462. \(hfy-face-to-style 'Info-title-3-face) =>
  463. ((\"font-weight\" . \"700\")
  464. (\"font-family\" . \"helv\")
  465. (\"font-size\" . \"120%\")
  466. (\"text-decoration\" . \"none\"))\n")
  467. (defvar hfy-sheet-assoc 'please-ignore-this-line
  468. "An assoc with elements of the form (face-name style-name . style-string):\n
  469. '((default \"default\" . \"{background: black; color: white}\")
  470. (font-lock-string-face \"string\" . \"{color: rgb(64,224,208)}\"))" )
  471. (defvar hfy-facemap-assoc 'please-ignore-this-line
  472. "An assoc of (point . FACE-SYMBOL) or (point . DEFFACE-LIST)
  473. and (point . 'end) elements, in descending order of point value
  474. \(ie from the file's end to its beginning).\n
  475. The map is in reverse order because inserting a <style> tag (or any other
  476. string) at `point' invalidates the map for all entries with a greater value of
  477. point. By traversing the map from greatest to least point, we still invalidate
  478. the map as we go, but only those points we have already dealt with (and
  479. therefore no longer care about) will be invalid at any time.\n
  480. '((64820 . end)
  481. (64744 . font-lock-comment-face)
  482. (64736 . end)
  483. (64722 . font-lock-string-face)
  484. (64630 . end)
  485. (64623 . font-lock-string-face)
  486. (64449 . end)
  487. (64446 . font-lock-keyword-face)
  488. (64406 . end)
  489. (64395 . font-lock-constant-face)
  490. (64393 . end)
  491. (64386 . font-lock-keyword-face)
  492. (64379 . end)
  493. ;; big similar section elided. You get the idea.
  494. (4285 . font-lock-constant-face)
  495. (4285 . end)
  496. (4221 . font-lock-comment-face)
  497. (4221 . end)
  498. (4197 . font-lock-constant-face)
  499. (4197 . end)
  500. (1 . font-lock-comment-face))")
  501. (defvar hfy-tmpfont-stack nil
  502. "An alist of derived fonts resulting from overlays.")
  503. (defconst hfy-hex-regex "[0-9A-Fa-f]")
  504. (defconst hfy-triplet-regex
  505. (concat
  506. "\\(" hfy-hex-regex hfy-hex-regex "\\)"
  507. "\\(" hfy-hex-regex hfy-hex-regex "\\)"
  508. "\\(" hfy-hex-regex hfy-hex-regex "\\)"))
  509. (defun hfy-interq (set-a set-b)
  510. "Return the intersection (using `eq') of two lists SET-A and SET-B."
  511. (let ((sa set-a) (interq nil) (elt nil))
  512. (while sa
  513. (setq elt (car sa)
  514. sa (cdr sa))
  515. (if (memq elt set-b) (setq interq (cons elt interq))))
  516. interq))
  517. (defun hfy-colour-vals (colour)
  518. "Where COLOUR is a color name or #XXXXXX style triplet, return a
  519. list of three (16 bit) rgb values for said color.\n
  520. If a window system is unavailable, calls `hfy-fallback-colour-values'."
  521. (if (string-match hfy-triplet-regex colour)
  522. (mapcar
  523. (lambda (x) (* (string-to-number (match-string x colour) 16) 257))
  524. '(1 2 3))
  525. ;;(message ">> %s" colour)
  526. (if window-system
  527. (if (fboundp 'color-values)
  528. (color-values colour)
  529. ;;(message "[%S]" window-system)
  530. (x-color-values colour))
  531. ;; blarg - tty colors are no good - go fetch some X colors:
  532. (hfy-fallback-colour-values colour))))
  533. (defvar hfy-cperl-mode-kludged-p nil)
  534. (defun hfy-kludge-cperl-mode ()
  535. "CPerl mode does its damnedest not to do some of its fontification when not
  536. in a windowing system - try to trick it..."
  537. (if (not hfy-cperl-mode-kludged-p)
  538. (progn (if (not window-system)
  539. (let ((window-system 'htmlfontify))
  540. (eval-and-compile (require 'cperl-mode))
  541. (setq cperl-syntaxify-by-font-lock t)))
  542. (setq hfy-cperl-mode-kludged-p t))) )
  543. (defun hfy-opt (symbol)
  544. "Is option SYMBOL set."
  545. (memq symbol hfy-optimisations))
  546. (defun hfy-default-header (file style)
  547. "Default value for `hfy-page-header'.
  548. FILE is the name of the file.
  549. STYLE is the inline CSS stylesheet (or tag referring to an external sheet)."
  550. ;; (format "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
  551. ;; <html>\n <head>\n <title>%s</title>\n %s\n </head>\n <body>\n" file style))
  552. (format "<?xml version=\"1.0\" encoding=\"utf-8\"?>
  553. <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"
  554. \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">
  555. <html xmlns=\"http://www.w3.org/1999/xhtml\">
  556. <head>
  557. <title>%s</title>
  558. %s
  559. <script type=\"text/javascript\"><!--
  560. // this function is needed to work around
  561. // a bug in IE related to element attributes
  562. function hasClass(obj)
  563. {
  564. var result = false;
  565. if (obj.getAttributeNode(\"class\") != null)
  566. {
  567. result = obj.getAttributeNode(\"class\").value;
  568. }
  569. return result;
  570. }
  571. function stripe(id)
  572. {
  573. // the flag we'll use to keep track of
  574. // whether the current row is odd or even
  575. var even = false;
  576. // if arguments are provided to specify the colors
  577. // of the even & odd rows, then use the them;
  578. // otherwise use the following defaults:
  579. var evenColor = arguments[1] ? arguments[1] : \"#fff\";
  580. var oddColor = arguments[2] ? arguments[2] : \"#ddd\";
  581. // obtain a reference to the desired table
  582. // if no such table exists, abort
  583. var table = document.getElementById(id);
  584. if (! table) { return; }
  585. // by definition, tables can have more than one tbody
  586. // element, so we'll have to get the list of child
  587. // &lt;tbody&gt;s
  588. var tbodies = table.getElementsByTagName(\"tbody\");
  589. // and iterate through them...
  590. for (var h = 0; h < tbodies.length; h++)
  591. {
  592. // find all the &lt;tr&gt; elements...
  593. var trs = tbodies[h].getElementsByTagName(\"tr\");
  594. // ... and iterate through them
  595. for (var i = 0; i < trs.length; i++)
  596. {
  597. // avoid rows that have a class attribute
  598. // or backgroundColor style
  599. if (! hasClass(trs[i]) &&
  600. ! trs[i].style.backgroundColor)
  601. {
  602. // get all the cells in this row...
  603. var tds = trs[i].getElementsByTagName(\"td\");
  604. // and iterate through them...
  605. for (var j = 0; j < tds.length; j++)
  606. {
  607. var mytd = tds[j];
  608. // avoid cells that have a class attribute
  609. // or backgroundColor style
  610. if (! hasClass(mytd) &&
  611. ! mytd.style.backgroundColor)
  612. {
  613. mytd.style.backgroundColor =
  614. even ? evenColor : oddColor;
  615. }
  616. }
  617. }
  618. // flip from odd to even, or vice-versa
  619. even = ! even;
  620. }
  621. }
  622. }
  623. function toggle_invis( name )
  624. {
  625. var filter =
  626. { acceptNode:
  627. function( node )
  628. { var classname = node.id;
  629. if( classname )
  630. { var classbase = classname.substr( 0, name.length );
  631. if( classbase == name ) { return NodeFilter.FILTER_ACCEPT; } }
  632. return NodeFilter.FILTER_SKIP; } };
  633. var walker = document.createTreeWalker( document.body ,
  634. NodeFilter.SHOW_ELEMENT ,
  635. filter ,
  636. false );
  637. while( walker.nextNode() )
  638. {
  639. var e = walker.currentNode;
  640. if( e.style.display == \"none\" ) { e.style.display = \"inline\"; }
  641. else { e.style.display = \"none\"; }
  642. }
  643. }
  644. --> </script>
  645. </head>
  646. <body onload=\"stripe('index'); return true;\">\n"
  647. file style))
  648. (defun hfy-default-footer (_file)
  649. "Default value for `hfy-page-footer'.
  650. FILE is the name of the file being rendered, in case it is needed."
  651. "\n </body>\n</html>\n")
  652. (defun hfy-link-style-string (style-string)
  653. "Replace the end of a CSS style declaration STYLE-STRING with the contents
  654. of the variable `hfy-src-doc-link-style', removing text matching the regex
  655. `hfy-src-doc-link-unstyle' first, if necessary."
  656. ;;(message "hfy-colour-vals");;DBUG
  657. (if (string-match hfy-src-doc-link-unstyle style-string)
  658. (setq style-string (replace-match "" 'fixed-case 'literal style-string)))
  659. (if (and (not (string-match hfy-src-doc-link-style style-string))
  660. (string-match "} *$" style-string))
  661. (concat (replace-match hfy-src-doc-link-style
  662. 'fixed-case
  663. 'literal
  664. style-string) " }")
  665. style-string))
  666. ;; utility functions - cast emacs style specification values into their
  667. ;; css2 equivalents:
  668. (defun hfy-triplet (colour)
  669. "Takes a COLOUR name (string) and return a CSS rgb(R, G, B) triplet string.
  670. Uses the definition of \"white\" to map the numbers to the 0-255 range, so
  671. if you've redefined white, (esp. if you've redefined it to have a triplet
  672. member lower than that of the color you are processing) strange things
  673. may happen."
  674. ;;(message "hfy-colour-vals");;DBUG
  675. (let ((white (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals "white")))
  676. (rgb16 (mapcar (lambda (I) (float (1+ I))) (hfy-colour-vals colour))))
  677. (if rgb16
  678. ;;(apply 'format "rgb(%d, %d, %d)"
  679. ;; Use #rrggbb instead, it is smaller
  680. (apply 'format "#%02x%02x%02x"
  681. (mapcar (lambda (X)
  682. (* (/ (nth X rgb16)
  683. (nth X white)) 255))
  684. '(0 1 2))))))
  685. (defun hfy-family (family) (list (cons "font-family" family)))
  686. (defun hfy-bgcol (colour) (list (cons "background" (hfy-triplet colour))))
  687. (defun hfy-colour (colour) (list (cons "color" (hfy-triplet colour))))
  688. (defun hfy-width (width) (list (cons "font-stretch" (symbol-name width))))
  689. (defcustom hfy-font-zoom 1.05
  690. "Font scaling from Emacs to HTML."
  691. :type 'float
  692. :group 'htmlfontify)
  693. (defun hfy-size (height)
  694. "Derive a CSS font-size specifier from an Emacs font :height attribute HEIGHT.
  695. Does not cope with the case where height is a function to be applied to
  696. the height of the underlying font."
  697. (list
  698. (cond
  699. ;;(t (cons "font-size" ": 1em"))
  700. ((floatp height)
  701. (cons "font-size" (format "%d%%" (* (* hfy-font-zoom height) 100))))
  702. ((integerp height)
  703. (cons "font-size" (format "%dpt" (/ (* hfy-font-zoom height) 10 )))) )) )
  704. (defun hfy-slant (slant)
  705. "Derive a font-style CSS specifier from the Emacs :slant attribute SLANT:
  706. CSS does not define the reverse-* styles, so just maps those to the
  707. regular specifiers."
  708. (list (cons "font-style"
  709. (or (cdr (assq slant '((italic . "italic")
  710. (reverse-italic . "italic" )
  711. (oblique . "oblique")
  712. (reverse-oblique . "oblique"))))
  713. "normal"))))
  714. (defun hfy-weight (weight)
  715. "Derive a font-weight CSS specifier from an Emacs weight spec symbol WEIGHT."
  716. (list (cons "font-weight" (cdr (assq weight '((ultra-bold . "900")
  717. (extra-bold . "800")
  718. (bold . "700")
  719. (semi-bold . "600")
  720. (normal . "500")
  721. (semi-light . "400")
  722. (light . "300")
  723. (extra-light . "200")
  724. (ultra-light . "100")))))))
  725. (defun hfy-box-to-border-assoc (spec)
  726. (if spec
  727. (let ((tag (car spec))
  728. (val (cadr spec)))
  729. (cons (case tag
  730. (:color (cons "colour" val))
  731. (:width (cons "width" val))
  732. (:style (cons "style" val)))
  733. (hfy-box-to-border-assoc (cddr spec))))))
  734. (defun hfy-box-to-style (spec)
  735. (let* ((css (hfy-box-to-border-assoc spec))
  736. (col (cdr (assoc "colour" css)))
  737. (s (cdr (assoc "style" css))))
  738. (list
  739. (if col (cons "border-color" (cdr (assoc "colour" css))))
  740. (cons "border-width" (format "%dpx" (or (cdr (assoc "width" css)) 1)))
  741. (cons "border-style" (case s
  742. (released-button "outset")
  743. (pressed-button "inset" )
  744. (t "solid" ))))))
  745. (defun hfy-box (box)
  746. "Derive CSS border-* attributes from the Emacs :box attribute BOX."
  747. (if box
  748. (cond
  749. ((integerp box) (list (cons "border-width" (format "%dpx" box))))
  750. ((stringp box) (list (cons "border" (format "solid %s 1px" box))))
  751. ((listp box) (hfy-box-to-style box) ))) )
  752. (defun hfy-decor (tag _val)
  753. "Derive CSS text-decoration specifiers from various Emacs font attributes.
  754. TAG is an Emacs font attribute key (eg :underline).
  755. VAL is ignored."
  756. (list
  757. ;; FIXME: Why not '("text-decoration" . "underline")? --Stef
  758. (case tag
  759. (:underline (cons "text-decoration" "underline" ))
  760. (:overline (cons "text-decoration" "overline" ))
  761. (:strike-through (cons "text-decoration" "line-through")))))
  762. (defun hfy-invisible (&optional _val)
  763. "This text should be invisible.
  764. Do something in CSS to make that happen.
  765. VAL is ignored here."
  766. '(("display" . "none")))
  767. (defun hfy-combined-face-spec (face)
  768. "Return a `defface' style alist of possible specifications for FACE.
  769. Entries resulting from customization (`custom-set-faces') will take
  770. precedence."
  771. (append
  772. (if (and hfy-display-class hfy-default-face-def (eq face 'default))
  773. hfy-default-face-def)
  774. (get face 'saved-face)
  775. (get face 'face-defface-spec)))
  776. (defun hfy-face-attr-for-class (face &optional class)
  777. "Return the face attributes for FACE.
  778. If CLASS is set, it must be a `defface' alist key [see below],
  779. in which case the first face specification returned by `hfy-combined-face-spec'
  780. which *doesn't* clash with CLASS is returned.\n
  781. \(A specification with a class of t is considered to match any class you
  782. specify - this matches Emacs's behavior when deciding on which face attributes
  783. to use, to the best of my understanding).\n
  784. If CLASS is nil, then you just get whatever `face-attr-construct' returns,
  785. ie the current specification in effect for FACE.\n
  786. *NOTE*: This function forces any face that is not 'default and which has
  787. no :inherit property to inherit from 'default (this is because 'default
  788. is magical in that Emacs's fonts behave as if they inherit implicitly from
  789. 'default, but no such behavior exists in HTML/CSS).\n
  790. See also `hfy-display-class' for details of valid values for CLASS."
  791. (let ((face-spec
  792. (if class
  793. (let ((face-props (hfy-combined-face-spec face))
  794. (face-specn nil)
  795. (face-class nil)
  796. (face-attrs nil)
  797. (face-score -1)
  798. (face-match nil))
  799. (while face-props
  800. (setq face-specn (car face-props)
  801. face-class (car face-specn)
  802. face-attrs (cdr face-specn)
  803. face-props (cdr face-props))
  804. ;; if the current element CEL of CLASS is t we match
  805. ;; if the current face-class is t, we match
  806. ;; if the cdr of CEL has a non-nil
  807. ;; intersection with the cdr of the first member of
  808. ;; the current face-class with the same car as CEL, we match
  809. ;; if we actually clash, then we can't match
  810. (let ((cbuf class)
  811. (cel nil)
  812. (key nil)
  813. (val nil)
  814. (x nil)
  815. (next nil)
  816. (score 0))
  817. (while (and cbuf (not next))
  818. (setq cel (car cbuf)
  819. cbuf (cdr cbuf)
  820. key (car cel)
  821. val (cdr cel)
  822. val (if (listp val) val (list val)))
  823. (cond
  824. ((or (eq cel t)
  825. (memq face-class '(t default))) ;Default match.
  826. (setq score 0) (ignore "t match"))
  827. ((not (cdr (assq key face-class))) ;Neither good nor bad.
  828. nil (ignore "non match, non collision"))
  829. ((setq x (hfy-interq val (cdr (assq key face-class))))
  830. (setq score (+ score (length x)))
  831. (ignore "intersection"))
  832. (t ;; nope.
  833. (setq next t score -10) (ignore "collision")) ))
  834. (if (> score face-score)
  835. (progn
  836. (setq face-match face-attrs
  837. face-score score )
  838. (ignore "%d << %S/%S" score face-class class))
  839. (ignore "--- %d ---- (insufficient)" score)) ))
  840. ;; matched ? last attrs : nil
  841. (if face-match
  842. (if (listp (car face-match)) (car face-match) face-match)
  843. nil))
  844. ;; Unfortunately the default face returns a
  845. ;; :background. Fortunately we can remove it, but how do we do
  846. ;; that in a non-system specific way?
  847. (let ((spec (face-attr-construct face))
  848. (new-spec nil))
  849. (if (not (memq :background spec))
  850. spec
  851. (while spec
  852. (let ((a (nth 0 spec))
  853. (b (nth 1 spec)))
  854. (unless (and (eq a :background)
  855. (stringp b)
  856. (string= b "SystemWindow"))
  857. (setq new-spec (cons a (cons b new-spec)))))
  858. (setq spec (cddr spec)))
  859. new-spec)))))
  860. (if (or (memq :inherit face-spec) (eq 'default face))
  861. face-spec
  862. (append face-spec (list :inherit 'default)))))
  863. ;; construct an assoc of (css-tag-name . css-tag-value) pairs
  864. ;; from a face or assoc of face attributes:
  865. ;; Some tests etc:
  866. ;; (mumamo-message-with-face "testing face" 'highlight)
  867. ;; (mumamo-message-with-face "testing face" '(:foreground "red" :background "yellow"))
  868. ;; (hfy-face-to-style-i '(:inherit default foreground-color "red"))
  869. ;; default face=(:stipple nil :background "SystemWindow" :foreground
  870. ;; "SystemWindowText" :inverse-video nil :box nil :strike-through
  871. ;; nil :overline nil :underline nil :slant normal :weight normal
  872. ;; :height 98 :width normal :family "outline-courier new")
  873. (defun hfy-face-to-style-i (fn)
  874. "The guts of `hfy-face-to-style': FN should be a `defface' font spec,
  875. as returned by `face-attr-construct' or `hfy-face-attr-for-class'.
  876. Note that this function does not get font-sizes right if they are based
  877. on inherited modifiers (via the :inherit) attribute, and any other
  878. modifiers that are cumulative if they appear multiple times need to be
  879. merged by the user - `hfy-flatten-style' should do this."
  880. ;;(message "hfy-face-to-style-i");;DBUG
  881. ;; fn's value could be something like
  882. ;; (:inherit
  883. ;; ((foreground-color . "blue"))
  884. ;; (foreground-color . "blue")
  885. ;; nil)
  886. (when fn
  887. (let ((key (car fn))
  888. (val (cadr fn))
  889. (next (cddr fn))
  890. (that nil)
  891. (this nil)
  892. (parent nil))
  893. (if (eq key :inherit)
  894. (let ((vs (if (listp val) val (list val))))
  895. ;; (let ((x '(a b))) (setq x (append '(c d) x)))
  896. ;; (let ((x '(a b))) (setq x (append '(c d) x)))
  897. (dolist (v vs)
  898. (setq parent
  899. (append
  900. parent
  901. (hfy-face-to-style-i
  902. (hfy-face-attr-for-class v hfy-display-class)) ))))
  903. (setq this
  904. (if val (case key
  905. (:family (hfy-family val))
  906. (:width (hfy-width val))
  907. (:weight (hfy-weight val))
  908. (:slant (hfy-slant val))
  909. (:foreground (hfy-colour val))
  910. (:background (hfy-bgcol val))
  911. (:box (hfy-box val))
  912. (:height (hfy-size val))
  913. (:underline (hfy-decor key val))
  914. (:overline (hfy-decor key val))
  915. (:strike-through (hfy-decor key val))
  916. (:invisible (hfy-invisible val))
  917. (:bold (hfy-weight 'bold))
  918. (:italic (hfy-slant 'italic))))))
  919. (setq that (hfy-face-to-style-i next))
  920. ;;(lwarn t :warning "%S => %S" fn (nconc this that parent))
  921. (nconc this that parent))) )
  922. (defun hfy-size-to-int (spec)
  923. "Convert SPEC, a CSS font-size specifier, to an Emacs :height attribute value.
  924. Used while merging multiple font-size attributes."
  925. ;;(message "hfy-size-to-int");;DBUG
  926. (list
  927. (if (string-match "\\([0-9]+\\)\\(%\\|pt\\)" spec)
  928. (cond ((string= "%" (match-string 2 spec))
  929. (/ (string-to-number (match-string 1 spec)) 100.0))
  930. ((string= "pt" (match-string 2 spec))
  931. (* (string-to-number (match-string 1 spec)) 10)))
  932. (string-to-number spec))) )
  933. ;; size is different, in that in order to get it right at all,
  934. ;; we have to trawl the inheritance path, accumulating modifiers,
  935. ;; _until_ we get to an absolute (pt) specifier, then combine the lot
  936. (defun hfy-flatten-style (style)
  937. "Take STYLE (see `hfy-face-to-style-i', `hfy-face-to-style') and merge
  938. any multiple attributes appropriately. Currently only font-size is merged
  939. down to a single occurrence - others may need special handling, but I
  940. haven't encountered them yet. Returns a `hfy-style-assoc'."
  941. ;;(message "(hfy-flatten-style %S)" style) ;;DBUG
  942. (let ((n 0)
  943. (m (list 1))
  944. (x nil)
  945. (r nil))
  946. (dolist (css style)
  947. (if (string= (car css) "font-size")
  948. (progn
  949. (when (not x) (setq m (nconc m (hfy-size-to-int (cdr css)))))
  950. (when (string-match "pt" (cdr css)) (setq x t)))
  951. (setq r (nconc r (list css)))))
  952. ;;(message "r: %S" r)
  953. (setq n (apply '* m))
  954. (nconc r (hfy-size (if x (round n) (* n 1.0)))) ))
  955. (defun hfy-face-resolve-face (fn)
  956. (cond
  957. ((facep fn)
  958. (hfy-face-attr-for-class fn hfy-display-class))
  959. ((and (symbolp fn)
  960. (facep (symbol-value fn)))
  961. ;; Obsolete faces like `font-lock-reference-face' are defined as
  962. ;; aliases for another face.
  963. (hfy-face-attr-for-class (symbol-value fn) hfy-display-class))
  964. (t nil)))
  965. (defun hfy-face-to-style (fn)
  966. "Take FN, a font or `defface' style font specification,
  967. \(as returned by `face-attr-construct' or `hfy-face-attr-for-class')
  968. and return a `hfy-style-assoc'.\n
  969. See also `hfy-face-to-style-i', `hfy-flatten-style'."
  970. ;;(message "hfy-face-to-style");;DBUG
  971. (let* ((face-def (hfy-face-resolve-face fn))
  972. (final-style
  973. (hfy-flatten-style (hfy-face-to-style-i face-def))))
  974. ;;(message "%S" final-style)
  975. (if (not (assoc "text-decoration" final-style))
  976. (progn (setq final-style
  977. ;; Fix-me: there is no need for this since
  978. ;; text-decoration is not inherited.
  979. ;; but it's not wrong and if this ever changes it will
  980. ;; be needed, so I think it's better to leave it in? -- v
  981. (nconc final-style '(("text-decoration" . "none"))))))
  982. final-style))
  983. ;; strip redundant bits from a name. Technically, this could result in
  984. ;; a collision, but it is pretty unlikely - will fix later...
  985. ;; also handle ephemeral fonts created by overlays, which don't actually
  986. ;; have names:
  987. (defun hfy-face-or-def-to-name (fn)
  988. "Render a font symbol or `defface' font spec FN into a name (string)."
  989. ;;(message "generating name for %s" fn)
  990. (if (not (listp fn))
  991. (format "%s" fn)
  992. (let* ((key (format "%s" fn))
  993. (entry (assoc key hfy-tmpfont-stack))
  994. (base (cadr (memq :inherit fn)))
  995. (tag (cdr entry)))
  996. ;;(message "checking for key «%s» in font stack [%d]"
  997. ;; key (if entry 1 0))
  998. (if entry nil ;; noop
  999. (setq tag (format "%04d" (length hfy-tmpfont-stack))
  1000. entry (cons key tag)
  1001. hfy-tmpfont-stack (cons entry hfy-tmpfont-stack)))
  1002. ;;(message " -> name: %s-%s" (or base 'default) tag)
  1003. (format "%s-%s" (or base 'default) tag)) ))
  1004. (defun hfy-css-name (fn)
  1005. "Strip the boring bits from a font-name FN and return a CSS style name."
  1006. ;;(message "hfy-css-name");;DBUG
  1007. (let ((face-name (hfy-face-or-def-to-name fn)))
  1008. (if (or (string-match "font-lock-\\(.*\\)" face-name)
  1009. (string-match "cperl-\\(.*\\)" face-name)
  1010. (string-match "^[Ii]nfo-\\(.*\\)" face-name))
  1011. (progn
  1012. (setq face-name (match-string 1 face-name))
  1013. (if (string-match "\\(.*\\)-face\\'" face-name)
  1014. (setq face-name (match-string 1 face-name)))
  1015. face-name)
  1016. face-name)) )
  1017. ;; construct an assoc of (stripped-name . "{ css-stuff-here }") pairs
  1018. ;; from a face:
  1019. (defun hfy-face-to-css-default (fn)
  1020. "Default handler for mapping faces to styles.
  1021. See also `hfy-face-to-css'."
  1022. ;;(message "hfy-face-to-css");;DBUG
  1023. (let* ((css-list (hfy-face-to-style fn))
  1024. (seen nil)
  1025. (css-text
  1026. (mapcar
  1027. (lambda (E)
  1028. (if (car E)
  1029. (unless (member (car E) seen)
  1030. (push (car E) seen)
  1031. (format " %s: %s; " (car E) (cdr E)))))
  1032. css-list)))
  1033. (cons (hfy-css-name fn) (format "{%s}" (apply 'concat css-text)))) )
  1034. (defvar hfy-face-to-css 'hfy-face-to-css-default
  1035. "Handler for mapping faces to styles.
  1036. The signature of the handler is of the form \(lambda (FN) ...\).
  1037. FN is a font or `defface' specification (cf
  1038. `face-attr-construct'). The handler should return a cons cell of
  1039. the form (STYLE-NAME . STYLE-SPEC).
  1040. The default handler is `hfy-face-to-css-default'.
  1041. See also `hfy-face-to-style'.")
  1042. (defalias 'hfy-prop-invisible-p
  1043. (if (fboundp 'invisible-p) #'invisible-p
  1044. (lambda (prop)
  1045. "Is text property PROP an active invisibility property?"
  1046. (or (and (eq buffer-invisibility-spec t) prop)
  1047. (or (memq prop buffer-invisibility-spec)
  1048. (assq prop buffer-invisibility-spec))))))
  1049. (defun hfy-find-invisible-ranges ()
  1050. "Return a list of (start-point . end-point) cons cells of invisible regions."
  1051. (save-excursion
  1052. (let (invisible p i s) ;; return-value pos invisible end start
  1053. (setq p (goto-char (point-min)))
  1054. (when (invisible-p p) (setq s p i t))
  1055. (while (< p (point-max))
  1056. (if i ;; currently invisible
  1057. (when (not (invisible-p p)) ;; but became visible
  1058. (setq i nil
  1059. invisible (cons (cons s p) invisible)))
  1060. ;; currently visible:
  1061. (when (invisible-p p) ;; but have become invisible
  1062. (setq s p i t)))
  1063. (setq p (next-char-property-change p)))
  1064. ;; still invisible at buffer end?
  1065. (when i
  1066. (setq invisible (cons (cons s (point-max)) invisible)))
  1067. invisible)))
  1068. (defun hfy-invisible-name (point map)
  1069. "Generate a CSS style name for an invisible section of the buffer.
  1070. POINT is the point inside the invisible region.
  1071. MAP is the invisibility map as returned by `hfy-find-invisible-ranges'."
  1072. ;;(message "(hfy-invisible-name %S %S)" point map)
  1073. (let (name)
  1074. (dolist (range map)
  1075. (when (and (>= point (car range))
  1076. (< point (cdr range)))
  1077. (setq name (format "invisible-%S-%S" (car range) (cdr range)))))
  1078. name))
  1079. ;; Fix-me: This function needs some cleanup by someone who understand
  1080. ;; all the formats that face properties can have.
  1081. ;;
  1082. ;; overlay handling should be fine. haven't tested multiple stacked overlapping
  1083. ;; overlays recently, but the common case of a text property face + an overlay
  1084. ;; face produces the correct merged css style (or as close to it as css can get)
  1085. ;; -- v
  1086. (defun hfy-face-at (p)
  1087. "Find face in effect at point P.
  1088. If overlays are to be considered (see `hfy-optimisations') then this may
  1089. return a `defface' style list of face properties instead of a face symbol."
  1090. ;;(message "hfy-face-at");;DBUG
  1091. ;; Fix-me: clean up, remove face-name etc
  1092. ;; not sure why we'd want to remove face-name? -- v
  1093. (let ((overlay-data nil)
  1094. (base-face nil)
  1095. (face-name (get-text-property p 'face))
  1096. ;; (face-name (hfy-get-face-at p))
  1097. (prop-seen nil)
  1098. (extra-props nil)
  1099. (text-props (text-properties-at p)))
  1100. ;;(message "face-name: %S" face-name)
  1101. (when (and face-name (listp face-name) (facep (car face-name)))
  1102. ;;(message "face-name is a list %S" face-name)
  1103. ;;(setq text-props (cons 'face face-name))
  1104. (dolist (f face-name)
  1105. (setq extra-props (if (listp f)
  1106. ;; for things like (variable-pitch
  1107. ;; (:foreground "red"))
  1108. (cons f extra-props)
  1109. (cons :inherit (cons f extra-props)))))
  1110. (setq base-face (car face-name)
  1111. face-name nil))
  1112. ;; text-properties-at => (face (:foreground "red" ...))
  1113. ;; or => (face (compilation-info underline)) list of faces
  1114. ;; overlay-properties
  1115. ;; format= (evaporate t face ((foreground-color . "red")))
  1116. ;; SO: if we have turned overlays off,
  1117. ;; or if there's no overlay data
  1118. ;; just bail out and return whatever face data we've accumulated so far
  1119. (if (or (not (hfy-opt 'keep-overlays))
  1120. (not (setq overlay-data (hfy-overlay-props-at p))))
  1121. (progn
  1122. ;;(message "· %d: %s; %S; %s"
  1123. ;; p face-name extra-props text-props)
  1124. (or face-name base-face)) ;; no overlays or extra properties
  1125. ;; collect any face data and any overlay data for processing:
  1126. (when text-props
  1127. (push text-props overlay-data))
  1128. (setq overlay-data (nreverse overlay-data))
  1129. ;;(message "- %d: %s; %S; %s; %s"
  1130. ;; p face-name extra-props text-props overlay-data)
  1131. ;; remember the basic face name so we don't keep repeating its specs:
  1132. (when face-name (setq base-face face-name))
  1133. (dolist (P overlay-data)
  1134. (let ((iprops (cadr (memq 'invisible P)))) ;FIXME: plist-get?
  1135. ;;(message "(hfy-prop-invisible-p %S)" iprops)
  1136. (when (and iprops (hfy-prop-invisible-p iprops))
  1137. (setq extra-props
  1138. (cons :invisible (cons t extra-props))) ))
  1139. (let ((fprops (cadr (or (memq 'face P)
  1140. (memq 'font-lock-face P)))))
  1141. ;;(message "overlay face: %s" fprops)
  1142. (if (not (listp fprops))
  1143. (let ((this-face (if (stringp fprops) (intern fprops) fprops)))
  1144. (when (not (eq this-face base-face))
  1145. (setq extra-props
  1146. (cons :inherit
  1147. (cons this-face extra-props))) ))
  1148. (while fprops
  1149. (if (facep (car fprops))
  1150. (let ((face (car fprops)))
  1151. (when (stringp face) (setq face (intern fprops)))
  1152. (setq extra-props
  1153. (cons :inherit
  1154. (cons face
  1155. extra-props)))
  1156. (setq fprops (cdr fprops)))
  1157. (let (p v)
  1158. ;; Sigh.
  1159. (if (listp (car fprops))
  1160. (if (nlistp (cdr (car fprops)))
  1161. (progn
  1162. ;; ((prop . val))
  1163. (setq p (caar fprops))
  1164. (setq v (cdar fprops))
  1165. (setq fprops (cdr fprops)))
  1166. ;; ((prop val))
  1167. (setq p (caar fprops))
  1168. (setq v (cadar fprops))
  1169. (setq fprops (cdr fprops)))
  1170. (if (listp (cdr fprops))
  1171. (progn
  1172. ;; (:prop val :prop val ...)
  1173. (setq p (car fprops))
  1174. (setq v (cadr fprops))
  1175. (setq fprops (cddr fprops)))
  1176. (if (and (listp fprops)
  1177. (not (listp (cdr fprops))))
  1178. ;;(and (consp x) (cdr (last x)))
  1179. (progn
  1180. ;; (prop . val)
  1181. (setq p (car fprops))
  1182. (setq v (cdr fprops))
  1183. (setq fprops nil))
  1184. (error "Eh... another format! fprops=%s" fprops) )))
  1185. (setq p (case p
  1186. ;; These are all the properties handled
  1187. ;; in `hfy-face-to-style-i'.
  1188. ;;
  1189. ;; Are these translations right?
  1190. ;; yes, they are -- v
  1191. (family :family )
  1192. (width :width )
  1193. (height :height )
  1194. (weight :weight )
  1195. (slant :slant )
  1196. (underline :underline )
  1197. (overline :overline )
  1198. (strike-through :strike-through)
  1199. (box :box )
  1200. (foreground-color :foreground)
  1201. (background-color :background)
  1202. (bold :bold )
  1203. (italic :italic )
  1204. (t p)))
  1205. (if (memq p prop-seen) nil ;; noop
  1206. (setq prop-seen (cons p prop-seen)
  1207. extra-props (cons p (cons v extra-props))))))))))
  1208. ;;(message "+ %d: %s; %S" p face-name extra-props)
  1209. (if extra-props
  1210. (nconc extra-props (if (listp face-name)
  1211. face-name
  1212. (face-attr-construct face-name)))
  1213. face-name)) ))
  1214. (defun hfy-overlay-props-at (p)
  1215. "Grab overlay properties at point P.
  1216. The plists are returned in descending priority order."
  1217. (sort (mapcar #'overlay-properties (overlays-at p))
  1218. (lambda (A B) (> (or (cadr (memq 'priority A)) 0) ;FIXME: plist-get?
  1219. (or (cadr (memq 'priority B)) 0)))))
  1220. ;; construct an assoc of (face-name . (css-name . "{ css-style }")) elements:
  1221. (defun hfy-compile-stylesheet ()
  1222. "Trawl the current buffer, construct and return a `hfy-sheet-assoc'.
  1223. If `hfy-user-sheet-assoc' is currently bound then use it to
  1224. collect new styles discovered during this run. Otherwise create
  1225. a new assoc."
  1226. ;;(message "hfy-compile-stylesheet");;DBUG
  1227. (let ((pt (point-min))
  1228. ;; Make the font stack stay:
  1229. ;;(hfy-tmpfont-stack nil)
  1230. (fn nil)
  1231. (style (and (boundp 'hfy-user-sheet-assoc) hfy-user-sheet-assoc)))
  1232. (save-excursion
  1233. (goto-char pt)
  1234. (while (< pt (point-max))
  1235. (if (and (setq fn (hfy-face-at pt)) (not (assoc fn style)))
  1236. (push (cons fn (funcall hfy-face-to-css fn)) style))
  1237. (setq pt (next-char-property-change pt))))
  1238. (unless (assoc 'default style)
  1239. (push (cons 'default (funcall hfy-face-to-css 'default)) style))
  1240. (when (boundp 'hfy-user-sheet-assoc)
  1241. (setq hfy-user-sheet-assoc style))
  1242. style))
  1243. (defun hfy-fontified-p ()
  1244. "`font-lock' doesn't like to say it's been fontified when in batch
  1245. mode, but we want to know if we should fontify or raw copy, so in batch
  1246. mode we check for non-default face properties. Otherwise we test
  1247. variable `font-lock-mode' and variable `font-lock-fontified' for truth."
  1248. ;;(message "font-lock-fontified: %S" font-lock-fontified)
  1249. ;;(message "noninteractive : %S" noninteractive)
  1250. ;;(message "font-lock-mode : %S" font-lock-mode)
  1251. (and font-lock-fontified
  1252. (if noninteractive
  1253. (let ((pt (point-min))
  1254. (face-name nil))
  1255. (save-excursion
  1256. (goto-char pt)
  1257. (while (and (< pt (point-max)) (not face-name))
  1258. (setq face-name (hfy-face-at pt))
  1259. (setq pt (next-char-property-change pt))))
  1260. face-name)
  1261. font-lock-mode)))
  1262. ;; remember, the map is in reverse point order:
  1263. ;; I wrote this while suffering the effects of a cold, and maybe a
  1264. ;; mild fever - I think it's correct, but it might be a little warped
  1265. ;; as my minfd keeps ... where was I? Oh yes, the bunnies...
  1266. (defun hfy-merge-adjacent-spans (face-map)
  1267. "Where FACE-MAP is a `hfy-facemap-assoc' for the current buffer,
  1268. this function merges adjacent style blocks which are of the same value
  1269. and are separated by nothing more interesting than whitespace.\n
  1270. <span class=\"foo\">narf</span> <span class=\"foo\">brain</span>\n
  1271. \(as interpreted from FACE-MAP) would become:\n
  1272. <span class=\"foo\">narf brain</span>\n
  1273. Returns a modified copy of FACE-MAP."
  1274. (let ((tmp-map face-map)
  1275. (map-buf nil)
  1276. (first-start nil)
  1277. (first-stop nil)
  1278. (last-start nil)
  1279. (last-stop nil)
  1280. (span-stop nil)
  1281. (span-start nil)
  1282. (reduced-map nil))
  1283. ;;(push (car tmp-map) reduced-map)
  1284. ;;(push (cadr tmp-map) reduced-map)
  1285. (while tmp-map
  1286. (setq first-start (cadddr tmp-map)
  1287. first-stop (caddr tmp-map)
  1288. last-start (cadr tmp-map)
  1289. last-stop (car tmp-map)
  1290. map-buf tmp-map
  1291. span-start last-start
  1292. span-stop last-stop )
  1293. (while (and (equal (cdr first-start)
  1294. (cdr last-start))
  1295. (save-excursion
  1296. (goto-char (car first-stop))
  1297. (not (re-search-forward "[^ \t\n\r]" (car last-start) t))))
  1298. (setq map-buf (cddr map-buf)
  1299. span-start first-start
  1300. first-start (cadddr map-buf)
  1301. first-stop (caddr map-buf)
  1302. last-start (cadr map-buf)
  1303. last-stop (car map-buf)))
  1304. (push span-stop reduced-map)
  1305. (push span-start reduced-map)
  1306. (setq tmp-map (memq last-start tmp-map))
  1307. (setq tmp-map (cdr tmp-map)))
  1308. (setq reduced-map (nreverse reduced-map))))
  1309. ;; remember to generate 'synthetic' </span> entries -
  1310. ;; emacs copes by just having a stack of styles in effect
  1311. ;; and only using the top one: html has a more simplistic approach -
  1312. ;; we have to explicitly end a style, there's no way of temporarily
  1313. ;; overriding it w. another one... (afaik)
  1314. (defun hfy-compile-face-map ()
  1315. ;; no need for special <a> version.
  1316. ;; IME hyperlinks don't get underlined, esp when you htmlfontify a whole
  1317. ;; source tree, so the <a> version is needed -- v
  1318. ;; Fix-me: save table for multi-buffer
  1319. "Compile and return a `hfy-facemap-assoc' for the current buffer."
  1320. ;;(message "hfy-compile-face-map");;DBUG
  1321. (let* ((pt (point-min))
  1322. (pt-narrow (save-restriction (widen) (point-min)))
  1323. (offset (- pt pt-narrow))
  1324. (fn nil)
  1325. (map nil)
  1326. (prev-tag nil)) ;; t if the last tag-point was a span-start
  1327. ;; nil if it was a span-stop
  1328. (save-excursion
  1329. (goto-char pt)
  1330. (while (< pt (point-max))
  1331. (if (setq fn (hfy-face-at pt))
  1332. (progn (if prev-tag (push (cons pt-narrow 'end) map))
  1333. (push (cons pt-narrow fn) map)
  1334. (setq prev-tag t))
  1335. (if prev-tag (push (cons pt-narrow 'end) map))
  1336. (setq prev-tag nil))
  1337. (setq pt (next-char-property-change pt))
  1338. (setq pt-narrow (+ offset pt)))
  1339. (if (and map (not (eq 'end (cdar map))))
  1340. (push (cons (1+ (- (point-max) (point-min))) 'end) map)))
  1341. (if (hfy-opt 'merge-adjacent-tags) (hfy-merge-adjacent-spans map) map)))
  1342. (defun hfy-buffer ()
  1343. "Generate a buffer to hold the HTML output.
  1344. The filename of this buffer is derived from the source (current) buffer's
  1345. variable `buffer-file-name', if it is set, plus `hfy-extn'.
  1346. Otherwise a plausible filename is constructed from `default-directory',
  1347. `buffer-name' and `hfy-extn'."
  1348. (let* ((name (concat (buffer-name) hfy-extn))
  1349. (src (buffer-file-name))
  1350. (buf (get-buffer-create name)))
  1351. (with-current-buffer buf
  1352. (setq buffer-file-name
  1353. (if src (concat src hfy-extn)
  1354. (expand-file-name (if (string-match "^.*/\\([^/]*\\)\\'" name)
  1355. (match-string 1 name)
  1356. name))))
  1357. buf)))
  1358. (defun hfy-lookup (face style)
  1359. "Get a CSS style name for FACE from STYLE."
  1360. (cadr (assoc face style)))
  1361. (defun hfy-link-style (style-string)
  1362. "Copy, alter and return a STYLE-STRING to make it suitable for a hyperlink.
  1363. Uses `hfy-link-style-fun' to do this."
  1364. (if (functionp hfy-link-style-fun)
  1365. (funcall hfy-link-style-fun style-string)
  1366. style-string))
  1367. (defun hfy-sprintf-stylesheet (css file)
  1368. "Return the inline CSS style sheet for FILE as a string."
  1369. (let ((stylesheet
  1370. (concat
  1371. hfy-meta-tags
  1372. "\n<style type=\"text/css\"><!-- \n"
  1373. ;; Fix-me: Add handling of page breaks here + scan for ^L
  1374. ;; where appropriate.
  1375. (format "body %s\n" (cddr (assq 'default css)))
  1376. (apply 'concat
  1377. (mapcar
  1378. (lambda (style)
  1379. (format
  1380. "span.%s %s\nspan.%s a %s\n"
  1381. (cadr style) (cddr style)
  1382. (cadr style) (hfy-link-style (cddr style))))
  1383. css))
  1384. " --></style>\n")))
  1385. (funcall hfy-page-header file stylesheet)))
  1386. ;; tag all the dangerous characters we want to escape
  1387. ;; (ie any "<> chars we _didn't_ put there explicitly for css markup)
  1388. (defun hfy-html-enkludge-buffer ()
  1389. "Mark dangerous [\"<>] characters with the `hfy-quoteme' property.\n
  1390. See also `hfy-html-dekludge-buffer'."
  1391. ;;(message "hfy-html-enkludge-buffer");;DBUG
  1392. (save-excursion
  1393. (goto-char (point-min))
  1394. (while (re-search-forward hfy-html-quote-regex nil t)
  1395. (put-text-property (match-beginning 0) (point) 'hfy-quoteme t))) )
  1396. ;; dangerous char -> &entity;
  1397. (defun hfy-html-quote (char-string)
  1398. "Map CHAR-STRING to an HTML safe string (entity) if need be."
  1399. ;;(message "hfy-html-quote");;DBUG
  1400. (or (cadr (assoc char-string hfy-html-quote-map)) char-string) )
  1401. ;; actually entity-ise dangerous chars.
  1402. ;; note that we can't do this until _after_ we have inserted the css
  1403. ;; markup, since we use a position-based map to insert this, and if we
  1404. ;; enter any other text before we do this, we'd have to track another
  1405. ;; map of offsets, which would be tedious...
  1406. (defun hfy-html-dekludge-buffer ()
  1407. "Transform all dangerous characters marked with the `hfy-quoteme' property
  1408. using `hfy-html-quote'.\n
  1409. See also `hfy-html-enkludge-buffer'."
  1410. ;;(message "hfy-html-dekludge-buffer");;DBUG
  1411. (save-excursion
  1412. (goto-char (point-min))
  1413. (while (re-search-forward hfy-html-quote-regex nil t)
  1414. (if (get-text-property (match-beginning 0) 'hfy-quoteme)
  1415. (replace-match (hfy-html-quote (match-string 1))) )) ))
  1416. ;; Borrowed from font-lock.el
  1417. (defmacro hfy-save-buffer-state (varlist &rest body)
  1418. "Bind variables according to VARLIST and eval BODY restoring buffer state.
  1419. Do not record undo information during evaluation of BODY."
  1420. (declare (indent 1) (debug let))
  1421. (let ((modified (make-symbol "modified")))
  1422. `(let* ,(append varlist
  1423. `((,modified (buffer-modified-p))
  1424. (buffer-undo-list t)
  1425. (inhibit-read-only t)
  1426. (inhibit-point-motion-hooks t)
  1427. (inhibit-modification-hooks t)
  1428. deactivate-mark
  1429. buffer-file-name
  1430. buffer-file-truename))
  1431. (progn
  1432. ,@body)
  1433. (unless ,modified
  1434. (restore-buffer-modified-p nil)))))
  1435. (defun hfy-mark-trailing-whitespace ()
  1436. "Tag trailing whitespace with a hfy property if it is currently highlighted."
  1437. (when show-trailing-whitespace
  1438. (let ((inhibit-read-only t))
  1439. (save-excursion
  1440. (goto-char (point-min))
  1441. (hfy-save-buffer-state nil
  1442. (while (re-search-forward "[ \t]+$" nil t)
  1443. (put-text-property (match-beginning 0) (match-end 0)
  1444. 'hfy-show-trailing-whitespace t)))))))
  1445. (defun hfy-unmark-trailing-whitespace ()
  1446. "Undo the effect of `hfy-mark-trailing-whitespace'."
  1447. (when show-trailing-whitespace
  1448. (hfy-save-buffer-state nil
  1449. (remove-text-properties (point-min) (point-max)
  1450. '(hfy-show-trailing-whitespace)))))
  1451. (defun hfy-begin-span (style text-block text-id text-begins-block-p)
  1452. "Default handler to begin a span of text.
  1453. Insert \"<span class=\"STYLE\" ...>\". See
  1454. `hfy-begin-span-handler' for more information."
  1455. (when text-begins-block-p
  1456. (insert
  1457. (format "<span onclick=\"toggle_invis('%s');\">…</span>" text-block)))
  1458. (insert
  1459. (if text-block
  1460. (format "<span class=\"%s\" id=\"%s-%d\">" style text-block text-id)
  1461. (format "<span class=\"%s\">" style))))
  1462. (defun hfy-end-span ()
  1463. "Default handler to end a span of text.
  1464. Insert \"</span>\". See `hfy-end-span-handler' for more
  1465. information."
  1466. (insert "</span>"))
  1467. (defvar hfy-begin-span-handler 'hfy-begin-span
  1468. "Handler to begin a span of text.
  1469. The signature of the handler is \(lambda (STYLE TEXT-BLOCK
  1470. TEXT-ID TEXT-BEGINS-BLOCK-P) ...\). The handler must insert
  1471. appropriate tags to begin a span of text.
  1472. STYLE is the name of the style that begins at point. It is
  1473. derived from the face attributes as part of `hfy-face-to-css'
  1474. callback. The other arguments TEXT-BLOCK, TEXT-ID,
  1475. TEXT-BEGINS-BLOCK-P are non-nil only if the buffer contains
  1476. invisible text.
  1477. TEXT-BLOCK is a string that identifies a single chunk of visible
  1478. or invisible text of which the current position is a part. For
  1479. visible portions, it's value is \"nil\". For invisible portions,
  1480. it's value is computed as part of `hfy-invisible-name'.
  1481. TEXT-ID marks a unique position within a block. It is set to
  1482. value of `point' at the current buffer position.
  1483. TEXT-BEGINS-BLOCK-P is a boolean and is non-nil if the current
  1484. span also begins a invisible portion of text.
  1485. An implementation can use TEXT-BLOCK, TEXT-ID,
  1486. TEXT-BEGINS-BLOCK-P to implement fold/unfold-on-mouse-click like
  1487. behaviour.
  1488. The default handler is `hfy-begin-span'.")
  1489. (defvar hfy-end-span-handler 'hfy-end-span
  1490. "Handler to end a span of text.
  1491. The signature of the handler is \(lambda () ...\). The handler
  1492. must insert appropriate tags to end a span of text.
  1493. The default handler is `hfy-end-span'.")
  1494. (defun hfy-fontify-buffer (&optional srcdir file)
  1495. "Implement the guts of `htmlfontify-buffer'.
  1496. SRCDIR, if set, is the directory being htmlfontified.
  1497. FILE, if set, is the file name."
  1498. (if srcdir (setq srcdir (directory-file-name srcdir)))
  1499. (let* ( (html-buffer (hfy-buffer))
  1500. (css-sheet nil)
  1501. (css-map nil)
  1502. (invis-ranges nil)
  1503. (rovl nil)
  1504. (orig-ovls (overlays-in (point-min) (point-max)))
  1505. (rmin (when mark-active (region-beginning)))
  1506. (rmax (when mark-active (region-end ))) )
  1507. (when (and mark-active
  1508. transient-mark-mode)
  1509. (unless (and (= rmin (point-min))
  1510. (= rmax (point-max)))
  1511. (setq rovl (make-overlay rmin rmax))
  1512. (overlay-put rovl 'priority 1000)
  1513. (overlay-put rovl 'face 'region)))
  1514. ;; copy the buffer, including fontification, and switch to it:
  1515. (hfy-mark-trailing-whitespace)
  1516. (setq css-sheet (hfy-compile-stylesheet )
  1517. css-map (hfy-compile-face-map )
  1518. invis-ranges (hfy-find-invisible-ranges))
  1519. (hfy-unmark-trailing-whitespace)
  1520. (when rovl
  1521. (delete-overlay rovl))
  1522. (copy-to-buffer html-buffer (point-min) (point-max))
  1523. (set-buffer html-buffer)
  1524. ;; rip out props that could interfere with our htmlization of the buffer:
  1525. (remove-text-properties (point-min) (point-max) hfy-ignored-properties)
  1526. ;; Apply overlay invisible spec
  1527. (setq orig-ovls
  1528. (sort orig-ovls
  1529. (lambda (A B)
  1530. (> (or (cadr (memq 'priority (overlay-properties A))) 0)
  1531. (or (cadr (memq 'priority (overlay-properties B))) 0)))))
  1532. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1533. ;; at this point, html-buffer retains the fontification of the parent:
  1534. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1535. ;; we don't really need or want text in the html buffer to be invisible, as
  1536. ;; that can make it look like we've rendered invalid xhtml when all that's
  1537. ;; happened is some tags are in the invisible portions of the buffer:
  1538. (setq buffer-invisibility-spec nil)
  1539. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  1540. ;; #####################################################################
  1541. ;; if we are in etags mode, add properties to mark the anchors and links
  1542. (if (and srcdir file)
  1543. (progn
  1544. (hfy-mark-tag-names srcdir file) ;; mark anchors
  1545. (hfy-mark-tag-hrefs srcdir file))) ;; mark links
  1546. ;; #####################################################################
  1547. ;; mark the 'dangerous' characters
  1548. ;;(message "marking dangerous characters")
  1549. (hfy-html-enkludge-buffer)
  1550. ;; trawl the position-based face-map, inserting span tags as we go
  1551. ;; note that we cannot change any character positions before this point
  1552. ;; or we will invalidate the map:
  1553. ;; NB: This also means we have to trawl the map in descending file-offset
  1554. ;; order, obviously.
  1555. ;; ---------------------------------------------------------------------
  1556. ;; Remember, inserting pushes properties to the right, which we don't
  1557. ;; actually want to happen for link properties, so we have to flag
  1558. ;; them and move them by hand - if you don't, you end up with
  1559. ;;
  1560. ;; <span class="foo"><a href="bar">texta</span><span class="bletch"></a>...
  1561. ;;
  1562. ;; instead of:
  1563. ;;
  1564. ;; <span class="foo"><a href="bar">texta</a></span><span class="bletch">...
  1565. ;;
  1566. ;; If my analysis of the problem is correct, we can detect link-ness by
  1567. ;; either hfy-linkp or hfy-endl properties at the insertion point, but I
  1568. ;; think we only need to relocate the hfy-endl property, as the hfy-linkp
  1569. ;; property has already served its main purpose by this point.
  1570. ;;(message "mapcar over the CSS-MAP")
  1571. (message "invis-ranges:\n%S" invis-ranges)
  1572. (dolist (point-face css-map)
  1573. (let ((pt (car point-face))
  1574. (fn (cdr point-face))
  1575. (move-link nil))
  1576. (goto-char pt)
  1577. (setq move-link
  1578. (or (get-text-property pt 'hfy-linkp)
  1579. (get-text-property pt 'hfy-endl )))
  1580. (if (eq 'end fn)
  1581. (funcall hfy-end-span-handler)
  1582. (if (not (and srcdir file))
  1583. nil
  1584. (when move-link
  1585. (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
  1586. (put-text-property pt (1+ pt) 'hfy-endl t) ))
  1587. ;; if we have invisible blocks, we need to do some extra magic:
  1588. (funcall hfy-begin-span-handler
  1589. (hfy-lookup fn css-sheet)
  1590. (and invis-ranges
  1591. (format "%s" (hfy-invisible-name pt invis-ranges)))
  1592. (and invis-ranges pt)
  1593. (and invis-ranges (assq pt invis-ranges)))
  1594. (if (not move-link) nil
  1595. ;;(message "removing prop2 @ %d" (point))
  1596. (if (remove-text-properties (point) (1+ (point)) '(hfy-endl nil))
  1597. (put-text-property pt (1+ pt) 'hfy-endl t))))))
  1598. ;; #####################################################################
  1599. ;; Invisibility
  1600. ;; Maybe just make the text invisible in XHTML?
  1601. ;; DONE -- big block of obsolete invisibility code elided here -- v
  1602. ;; #####################################################################
  1603. ;; (message "checking to see whether we should link...")
  1604. (if (and srcdir file)
  1605. (let ((lp 'hfy-link)
  1606. (pt (point-min))
  1607. (pr nil)
  1608. (rr nil))
  1609. ;; (message " yes we should.")
  1610. ;; translate 'hfy-anchor properties to anchors
  1611. (while (setq pt (next-single-property-change pt 'hfy-anchor))
  1612. (if (setq pr (get-text-property pt 'hfy-anchor))
  1613. (progn (goto-char pt)
  1614. (remove-text-properties pt (1+ pt) '(hfy-anchor nil))
  1615. (insert (concat "<a name=\"" pr "\"></a>")))))
  1616. ;; translate alternate 'hfy-link and 'hfy-endl props to opening
  1617. ;; and closing links. (this should avoid those spurious closes
  1618. ;; we sometimes get by generating only paired tags)
  1619. (setq pt (point-min))
  1620. (while (setq pt (next-single-property-change pt lp))
  1621. (if (not (setq pr (get-text-property pt lp))) nil
  1622. (goto-char pt)
  1623. (remove-text-properties pt (1+ pt) (list lp nil))
  1624. (case lp
  1625. (hfy-link
  1626. (if (setq rr (get-text-property pt 'hfy-inst))
  1627. (insert (format "<a name=\"%s\"></a>" rr)))
  1628. (insert (format "<a href=\"%s\">" pr))
  1629. (setq lp 'hfy-endl))
  1630. (hfy-endl
  1631. (insert "</a>") (setq lp 'hfy-link)) ))) ))
  1632. ;; #####################################################################
  1633. ;; transform the dangerous chars. This changes character positions
  1634. ;; since entities have > char length.
  1635. ;; note that this deletes the dangerous characters, and therefore
  1636. ;; destroys any properties they may contain (such as 'hfy-endl),
  1637. ;; so we have to do this after we use said properties:
  1638. ;; (message "munging dangerous characters")
  1639. (hfy-html-dekludge-buffer)
  1640. (unless (hfy-opt 'body-text-only)
  1641. ;; insert the stylesheet at the top:
  1642. (goto-char (point-min))
  1643. ;;(message "inserting stylesheet")
  1644. (insert (hfy-sprintf-stylesheet css-sheet file))
  1645. (if (hfy-opt 'div-wrapper) (insert "<div class=\"default\">"))
  1646. (insert "\n<pre>")
  1647. (goto-char (point-max))
  1648. (insert "</pre>\n")
  1649. (if (hfy-opt 'div-wrapper) (insert "</div>"))
  1650. ;;(message "inserting footer")
  1651. (insert (funcall hfy-page-footer file)))
  1652. ;; call any post html-generation hooks:
  1653. (run-hooks 'hfy-post-html-hooks)
  1654. ;; return the html buffer
  1655. (set-buffer-modified-p nil)
  1656. html-buffer))
  1657. (defun htmlfontify-string (string)
  1658. "Take a STRING and return a fontified version of it.
  1659. It is assumed that STRING has text properties that allow it to be
  1660. fontified. This is a simple convenience wrapper around
  1661. `htmlfontify-buffer'."
  1662. (let* ((hfy-optimisations-1 (copy-sequence hfy-optimisations))
  1663. (hfy-optimisations (add-to-list 'hfy-optimisations-1
  1664. 'skip-refontification)))
  1665. (with-temp-buffer
  1666. (insert string)
  1667. (htmlfontify-buffer)
  1668. (buffer-string))))
  1669. (defun hfy-force-fontification ()
  1670. "Try to force font-locking even when it is optimized away."
  1671. (run-hooks 'hfy-init-kludge-hook)
  1672. (eval-and-compile (require 'font-lock))
  1673. (if (boundp 'font-lock-cache-position)
  1674. (or font-lock-cache-position
  1675. (set 'font-lock-cache-position (make-marker))))
  1676. (if (not noninteractive)
  1677. (progn
  1678. (message "hfy interactive mode (%S %S)" window-system major-mode)
  1679. (when (and font-lock-defaults
  1680. font-lock-mode)
  1681. (font-lock-fontify-region (point-min) (point-max) nil)))
  1682. (message "hfy batch mode (%s:%S)"
  1683. (or (buffer-file-name) (buffer-name)) major-mode)
  1684. (when font-lock-defaults
  1685. (font-lock-fontify-buffer)) ))
  1686. ;;;###autoload
  1687. (defun htmlfontify-buffer (&optional srcdir file)
  1688. "Create a new buffer, named for the current buffer + a .html extension,
  1689. containing an inline CSS-stylesheet and formatted CSS-markup HTML
  1690. that reproduces the look of the current Emacs buffer as closely
  1691. as possible.
  1692. Dangerous characters in the existing buffer are turned into HTML
  1693. entities, so you should even be able to do HTML-within-HTML
  1694. fontified display.
  1695. You should, however, note that random control or eight-bit
  1696. characters such as ^L (\x0c) or ¤ (\xa4) won't get mapped yet.
  1697. If the SRCDIR and FILE arguments are set, lookup etags derived
  1698. entries in the `hfy-tags-cache' and add HTML anchors and
  1699. hyperlinks as appropriate."
  1700. (interactive)
  1701. ;; pick up the file name in case we didn't receive it
  1702. (if (not file)
  1703. (progn (setq file (or (buffer-file-name) (buffer-name)))
  1704. (if (string-match "/\\([^/]*\\)\\'" file)
  1705. (setq file (match-string 1 file)))) )
  1706. (if (not (hfy-opt 'skip-refontification))
  1707. (save-excursion ;; Keep region
  1708. (hfy-force-fontification)))
  1709. (if (called-interactively-p 'any) ;; display the buffer in interactive mode:
  1710. (switch-to-buffer (hfy-fontify-buffer srcdir file))
  1711. (hfy-fontify-buffer srcdir file)))
  1712. ;; recursive file listing
  1713. (defun hfy-list-files (directory)
  1714. "Return a list of files under DIRECTORY.
  1715. Strips any leading \"./\" from each filename."
  1716. ;;(message "hfy-list-files");;DBUG
  1717. ;; FIXME: this changes the dir of the current buffer. Is that right??
  1718. (cd directory)
  1719. (mapcar (lambda (F) (if (string-match "^./\\(.*\\)" F) (match-string 1 F) F))
  1720. (split-string (shell-command-to-string hfy-find-cmd))) )
  1721. ;; strip the filename off, return a directory name
  1722. ;; not a particularly thorough implementation, but it will be
  1723. ;; fed pretty carefully, so it should be Ok:
  1724. (defun hfy-dirname (file)
  1725. "Return everything preceding the last \"/\" from a relative filename FILE,
  1726. on the assumption that this will produce a relative directory name.
  1727. Hardly bombproof, but good enough in the context in which it is being used."
  1728. ;;(message "hfy-dirname");;DBUG
  1729. (let ((f (directory-file-name file)))
  1730. (and (string-match "^\\(.*\\)/" f) (match-string 1 f))))
  1731. ;; create a directory, cf mkdir -p
  1732. (defun hfy-make-directory (dir)
  1733. "Approx. equivalent of mkdir -p DIR."
  1734. ;;(message "hfy-make-directory");;DBUG
  1735. (if (file-exists-p dir)
  1736. (if (file-directory-p dir) t)
  1737. (make-directory dir t)))
  1738. (defun hfy-text-p (srcdir file)
  1739. "Is SRCDIR/FILE text? Uses `hfy-istext-command' to determine this."
  1740. (let* ((cmd (format hfy-istext-command (expand-file-name file srcdir)))
  1741. (rsp (shell-command-to-string cmd)))
  1742. (string-match "text" rsp)))
  1743. ;; open a file, check fontification, if fontified, write a fontified copy
  1744. ;; to the destination directory, otherwise just copy the file:
  1745. (defun hfy-copy-and-fontify-file (srcdir dstdir file)
  1746. "Open FILE in SRCDIR - if fontified, write a fontified copy to DSTDIR
  1747. adding an extension of `hfy-extn'. Fontification is actually done by
  1748. `htmlfontify-buffer'. If the buffer is not fontified, just copy it."
  1749. ;;(message "hfy-copy-and-fontify-file");;DBUG
  1750. (let (;;(fast-lock-minimum-size hfy-fast-lock-save)
  1751. ;;(font-lock-support-mode 'fast-lock-mode)
  1752. ;;(window-system (or window-system 'htmlfontify))
  1753. (target nil)
  1754. (source nil)
  1755. (html nil))
  1756. (cd srcdir)
  1757. (with-current-buffer (setq source (find-file-noselect file))
  1758. ;; FIXME: Shouldn't this use expand-file-name? --Stef
  1759. (setq target (concat dstdir "/" file))
  1760. (hfy-make-directory (hfy-dirname target))
  1761. (if (not (hfy-opt 'skip-refontification)) (hfy-force-fontification))
  1762. (if (or (hfy-fontified-p) (hfy-text-p srcdir file))
  1763. (progn (setq html (hfy-fontify-buffer srcdir file))
  1764. (set-buffer html)
  1765. (write-file (concat target hfy-extn))
  1766. (kill-buffer html))
  1767. ;; #o0200 == 128, but emacs20 doesn't know that
  1768. (if (and (file-exists-p target) (not (file-writable-p target)))
  1769. (set-file-modes target (logior (file-modes target) 128)))
  1770. (copy-file (buffer-file-name source) target 'overwrite))
  1771. (kill-buffer source)) ))
  1772. ;; list of tags in file in srcdir
  1773. (defun hfy-tags-for-file (cache-hash file)
  1774. "List of etags tags that have definitions in this FILE.
  1775. CACHE-HASH is the tags cache."
  1776. ;;(message "hfy-tags-for-file");;DBUG
  1777. (let* ((tag-list nil))
  1778. (if cache-hash
  1779. (maphash
  1780. (lambda (K V)
  1781. (if (assoc file V)
  1782. (setq tag-list (cons K tag-list))))
  1783. cache-hash))
  1784. tag-list))
  1785. ;; mark the tags native to this file for anchors
  1786. (defun hfy-mark-tag-names (srcdir file)
  1787. "Mark tags in FILE (lookup SRCDIR in `hfy-tags-cache') with the `hfy-anchor'
  1788. property, with a value of \"tag.line-number\"."
  1789. ;;(message "(hfy-mark-tag-names %s %s)" srcdir file);;DBUG
  1790. (let* ((cache-entry (assoc srcdir hfy-tags-cache))
  1791. (cache-hash (cadr cache-entry)))
  1792. (if cache-hash
  1793. (mapcar
  1794. (lambda (TAG)
  1795. (mapcar
  1796. (lambda (TLIST)
  1797. (if (string= file (car TLIST))
  1798. (let* ((line (cadr TLIST) )
  1799. (chr (caddr TLIST) )
  1800. (link (format "%s.%d" TAG line) ))
  1801. (put-text-property (+ 1 chr)
  1802. (+ 2 chr)
  1803. 'hfy-anchor link))))
  1804. (gethash TAG cache-hash)))
  1805. (hfy-tags-for-file cache-hash file)))))
  1806. (defun hfy-relstub (file &optional start)
  1807. "Return a \"../\" stub of the appropriate length for the current source
  1808. tree depth, as determined from FILE (a filename).
  1809. START is the offset at which to start looking for the / character in FILE."
  1810. ;;(message "hfy-relstub");;DBUG
  1811. (let ((c ""))
  1812. (while (setq start (string-match "/" file start))
  1813. (setq start (1+ start)) (setq c (concat c "../")))
  1814. c))
  1815. (defun hfy-href-stub (this-file def-files tag)
  1816. "Return an href stub for a tag href in THIS-FILE.
  1817. If DEF-FILES (list of files containing definitions for the tag in question)
  1818. contains only one entry, the href should link straight to that file.
  1819. Otherwise, the link should be to the index file.\n
  1820. We are not yet concerned with the file extensions/tag line number and so on at
  1821. this point.\n
  1822. If `hfy-split-index' is set, and the href wil be to an index file rather than
  1823. a source file, append a .X to `hfy-index-file', where X is the uppercased
  1824. first character of TAG.\n
  1825. See also `hfy-relstub', `hfy-index-file'."
  1826. ;;(message "hfy-href-stub");;DBUG
  1827. ;; FIXME: Why not use something like
  1828. ;; (file-relative-name (if ...) (file-name-directory this-file)) ? --Stef
  1829. (concat
  1830. (hfy-relstub this-file)
  1831. (if (= 1 (length def-files)) (car def-files)
  1832. (if (not hfy-split-index) hfy-index-file
  1833. (concat hfy-index-file "." (upcase (substring tag 0 1)))))) )
  1834. (defun hfy-href (this-file def-files tag tag-map)
  1835. "Return a relative href to the tag in question, based on\n
  1836. THIS-FILE `hfy-link-extn' `hfy-extn' DEF-FILES TAG and TAG-MAP\n
  1837. THIS-FILE is the current source file
  1838. DEF-FILES is a list of file containing possible link endpoints for TAG
  1839. TAG is the tag in question
  1840. TAG-MAP is the entry in `hfy-tags-cache'."
  1841. ;;(message "hfy-href");;DBUG
  1842. (concat
  1843. (hfy-href-stub this-file def-files tag)
  1844. (or hfy-link-extn hfy-extn) "#" tag ;;(.src -> .html)
  1845. (if (= 1 (length def-files))
  1846. (concat "." (format "%d" (cadr (assoc (car def-files) tag-map)))))) )
  1847. (defun hfy-word-regex (string)
  1848. "Return a regex that matches STRING as the first `match-string', with non
  1849. word characters on either side."
  1850. ;; FIXME: Should this use [^$[:alnum:]_] instead? --Stef
  1851. (concat "[^$A-Za-z_0-9]\\(" (regexp-quote string) "\\)[^A-Za-z_0-9]"))
  1852. ;; mark all tags for hyperlinking, except the tags at
  1853. ;; their own points of definition, iyswim:
  1854. (defun hfy-mark-tag-hrefs (srcdir file)
  1855. "Mark href start points with the `hfy-link' prop (value: href string).\n
  1856. Mark href end points with the `hfy-endl' prop (value t).\n
  1857. Avoid overlapping links, and mark links in descending length of
  1858. tag name in order to prevent subtags from usurping supertags,
  1859. \(eg \"term\" for \"terminal\").
  1860. SRCDIR is the directory being \"published\".
  1861. FILE is the specific file we are rendering."
  1862. ;;(message "hfy-mark-tag-hrefs");;DBUG
  1863. (let ((cache-entry (assoc srcdir hfy-tags-cache))
  1864. (list-cache (assoc srcdir hfy-tags-sortl))
  1865. (rmap-cache (assoc srcdir hfy-tags-rmap ))
  1866. (no-comment (hfy-opt 'zap-comment-links))
  1867. (no-strings (hfy-opt 'zap-string-links ))
  1868. (cache-hash nil)
  1869. (tags-list nil)
  1870. (tags-rmap nil)
  1871. (case-fold-search nil))
  1872. ;; extract the tag mapping hashes (fwd and rev) and the tag list:
  1873. (if (and (setq cache-hash (cadr cache-entry))
  1874. (setq tags-rmap (cadr rmap-cache ))
  1875. (setq tags-list (cadr list-cache )))
  1876. (mapcar
  1877. (lambda (TAG)
  1878. (let* ((start nil)
  1879. (stop nil)
  1880. (href nil)
  1881. (name nil)
  1882. (case-fold-search nil)
  1883. (tmp-point nil)
  1884. (maybe-start nil)
  1885. (face-at nil)
  1886. (rmap-entry nil)
  1887. (rnew-elt nil)
  1888. (rmap-line nil)
  1889. (tag-regex (hfy-word-regex TAG))
  1890. (tag-map (gethash TAG cache-hash))
  1891. (tag-files (mapcar #'car tag-map)))
  1892. ;; find instances of TAG and do what needs to be done:
  1893. (goto-char (point-min))
  1894. (while (search-forward TAG nil 'NOERROR)
  1895. (setq tmp-point (point)
  1896. maybe-start (- (match-beginning 0) 1))
  1897. (goto-char maybe-start)
  1898. (if (not (looking-at tag-regex))
  1899. nil
  1900. (setq start (match-beginning 1))
  1901. (setq stop (match-end 1))
  1902. (setq face-at
  1903. (and (or no-comment no-strings) (hfy-face-at start)))
  1904. (if (listp face-at)
  1905. (setq face-at (cadr (memq :inherit face-at))))
  1906. (if (or (text-property-any start (1+ stop) 'hfy-linkp t)
  1907. (and no-comment (eq 'font-lock-comment-face face-at))
  1908. (and no-strings (eq 'font-lock-string-face face-at)))
  1909. nil ;; already a link, NOOP
  1910. ;; set a reverse map entry:
  1911. (setq rmap-line (line-number-at-pos)
  1912. rmap-entry (gethash TAG tags-rmap)
  1913. rnew-elt (list file rmap-line start)
  1914. rmap-entry (cons rnew-elt rmap-entry)
  1915. name (format "%s.%d" TAG rmap-line))
  1916. (put-text-property start (1+ start) 'hfy-inst name)
  1917. (puthash TAG rmap-entry tags-rmap)
  1918. ;; mark the link. link to index if the tag has > 1 def
  1919. ;; add the line number to the #name if it does not:
  1920. (setq href (hfy-href file tag-files TAG tag-map))
  1921. (put-text-property start (1+ start) 'hfy-link href)
  1922. (put-text-property stop (1+ stop ) 'hfy-endl t )
  1923. (put-text-property start (1+ stop ) 'hfy-linkp t )))
  1924. (goto-char tmp-point)) ))
  1925. tags-list) )))
  1926. (defun hfy-shell ()
  1927. "Return `shell-file-name', or \"/bin/sh\" if it is a non-Bourne shell."
  1928. (if (string-match "\\<bash\\>\\|\\<sh\\>\\|\\<dash\\>" shell-file-name)
  1929. shell-file-name
  1930. (or hfy-shell-file-name "/bin/sh")))
  1931. ;; cache the #(tag => file line point) entries for files under srcdir
  1932. ;; and cache the descending sorted list of tags in the relevant alist,
  1933. ;; also keyed by srcdir:
  1934. (defun hfy-load-tags-cache (srcdir)
  1935. "Run `hfy-etags-cmd' on SRCDIR, then call `hfy-parse-tags-buffer'."
  1936. ;;(message "hfy-load-tags-cache");;DBUG
  1937. (let ((etags-buffer (get-buffer-create "*hfy-tags*"))
  1938. (etags-command (format hfy-etags-cmd hfy-etags-bin))
  1939. (shell-file-name (hfy-shell)))
  1940. (cd srcdir)
  1941. (shell-command etags-command etags-buffer)
  1942. (hfy-parse-tags-buffer srcdir etags-buffer)) )
  1943. ;; break this out from `hfy-load-tags-cache' to make the tar file
  1944. ;; functionality easier to implement.
  1945. ;; ( tar file functionality not merged here because it requires a
  1946. ;; hacked copy of etags capable of tagging stdin: if Francesco
  1947. ;; Potorti accepts a patch, or otherwise implements stdin tagging,
  1948. ;; then I will provide a `htmlfontify-tar-file' defun )
  1949. (defun hfy-parse-tags-buffer (srcdir buffer)
  1950. "Parse a BUFFER containing etags formatted output, loading the
  1951. `hfy-tags-cache' and `hfy-tags-sortl' entries for SRCDIR."
  1952. (let ((cache-entry (assoc srcdir hfy-tags-cache))
  1953. (tlist-cache (assoc srcdir hfy-tags-sortl))
  1954. (trmap-cache (assoc srcdir hfy-tags-rmap ))
  1955. (cache-hash nil) (trmap-hash nil) (tags-list nil)
  1956. (hash-entry nil) (tag-string nil) (tag-line nil)
  1957. (tag-point nil) (new-entry nil) (etags-file nil))
  1958. ;; (re)initialize the tag reverse map:
  1959. (if trmap-cache (setq trmap-hash (cadr trmap-cache))
  1960. (setq trmap-hash (make-hash-table :test 'equal))
  1961. (setq hfy-tags-rmap (list (list srcdir trmap-hash) hfy-tags-rmap)))
  1962. (clrhash trmap-hash)
  1963. ;; (re)initialize the tag cache:
  1964. (if cache-entry (setq cache-hash (cadr cache-entry))
  1965. (setq cache-hash (make-hash-table :test 'equal))
  1966. (setq hfy-tags-cache (list (list srcdir cache-hash) hfy-tags-cache)))
  1967. (clrhash cache-hash)
  1968. ;; cache the TAG => ((file line point) (file line point) ... ) entries:
  1969. (with-current-buffer buffer
  1970. (goto-char (point-min))
  1971. (while (and (looking-at "^\x0c") (= 0 (forward-line 1)))
  1972. ;;(message "^L boundary")
  1973. (if (and (looking-at "^\\(.+\\),\\([0-9]+\\)$")
  1974. (= 0 (forward-line 1)))
  1975. (progn
  1976. (setq etags-file (match-string 1))
  1977. ;;(message "TAGS for file: %s" etags-file)
  1978. (while (and (looking-at hfy-etag-regex) (= 0 (forward-line 1)))
  1979. (setq tag-string (match-string 1))
  1980. (if (= 0 (length tag-string)) nil ;; noop
  1981. (setq tag-line (round (string-to-number (match-string 2))))
  1982. (setq tag-point (round (string-to-number (match-string 3))))
  1983. (setq hash-entry (gethash tag-string cache-hash))
  1984. (setq new-entry (list etags-file tag-line tag-point))
  1985. (push new-entry hash-entry)
  1986. ;;(message "HASH-ENTRY %s %S" tag-string new-entry)
  1987. (puthash tag-string hash-entry cache-hash)))) )))
  1988. ;; cache a list of tags in descending length order:
  1989. (maphash (lambda (K _V) (push K tags-list)) cache-hash)
  1990. (setq tags-list (sort tags-list (lambda (A B) (< (length B) (length A)))))
  1991. ;; put the tag list into the cache:
  1992. (if tlist-cache (setcar (cdr tlist-cache) tags-list)
  1993. (push (list srcdir tags-list) hfy-tags-sortl))
  1994. ;; return the number of tags found:
  1995. (length tags-list) ))
  1996. (defun hfy-prepare-index-i (srcdir dstdir filename &optional stub map)
  1997. "Prepare a tags index buffer for SRCDIR.
  1998. `hfy-tags-cache' must already have an entry for SRCDIR for this to work.
  1999. `hfy-page-header', `hfy-page-footer', `hfy-link-extn' and `hfy-extn'
  2000. all play a part here.\n
  2001. If STUB is set, prepare an (appropriately named) index buffer
  2002. specifically for entries beginning with STUB.\n
  2003. If MAP is set, use that instead of `hfy-tags-cache'.
  2004. FILENAME is the name of the file being indexed.
  2005. DSTDIR is the output directory, where files will be written."
  2006. ;;(message "hfy-write-index");;DBUG
  2007. (let ((cache-entry (assoc srcdir (or map hfy-tags-cache)))
  2008. (cache-hash nil)
  2009. (tag-list nil)
  2010. (index-file
  2011. (concat filename (if stub (concat "." stub) "") hfy-extn))
  2012. (index-buf nil))
  2013. (if (not (and cache-entry
  2014. (setq cache-hash (cadr cache-entry))
  2015. (setq index-buf (get-buffer-create index-file))))
  2016. nil ;; noop
  2017. (maphash (lambda (K _V) (push K tag-list)) cache-hash)
  2018. (setq tag-list (sort tag-list 'string<))
  2019. (set-buffer index-buf)
  2020. (erase-buffer)
  2021. (insert (funcall hfy-page-header filename "<!-- CSS -->"))
  2022. (insert "<table class=\"index\">\n")
  2023. (dolist (TAG tag-list)
  2024. (let ((tag-started nil))
  2025. (dolist (DEF (gethash TAG cache-hash))
  2026. (if (and stub (not (string-match (concat "^" stub) TAG)))
  2027. nil ;; we have a stub and it didn't match: NOOP
  2028. (let ((file (car DEF))
  2029. (line (cadr DEF)))
  2030. (insert
  2031. (format
  2032. (concat
  2033. " <tr> \n"
  2034. " <td>%s</td> \n"
  2035. " <td><a href=\"%s%s\">%s</a></td> \n"
  2036. " <td><a href=\"%s%s#%s.%d\">%d</a></td>\n"
  2037. " </tr> \n")
  2038. (if (string= TAG tag-started) "&nbsp;"
  2039. (format "<a name=\"%s\">%s</a>" TAG TAG))
  2040. file (or hfy-link-extn hfy-extn) file
  2041. file (or hfy-link-extn hfy-extn) TAG line line))
  2042. (setq tag-started TAG))))))
  2043. (insert "</table>\n")
  2044. (insert (funcall hfy-page-footer filename))
  2045. (and dstdir (cd dstdir))
  2046. (set-visited-file-name index-file)
  2047. index-buf) ))
  2048. (defun hfy-prepare-index (srcdir dstdir)
  2049. "Return a list of index buffer(s), as determined by `hfy-split-index'.
  2050. SRCDIR and DSTDIR are the source and output directories respectively."
  2051. (if (not hfy-split-index)
  2052. (list (hfy-prepare-index-i srcdir dstdir hfy-index-file nil))
  2053. (let ((stub-list nil)
  2054. (cache-hash nil)
  2055. (index-list nil)
  2056. (cache-entry (assoc srcdir hfy-tags-cache)))
  2057. (if (and cache-entry (setq cache-hash (cadr cache-entry)))
  2058. (maphash
  2059. (lambda (K _V)
  2060. (let ((stub (upcase (substring K 0 1))))
  2061. (if (member stub stub-list)
  2062. nil ;; seen this already: NOOP
  2063. (setq
  2064. stub-list (cons stub stub-list)
  2065. index-list (cons (hfy-prepare-index-i srcdir
  2066. dstdir
  2067. hfy-index-file
  2068. stub)
  2069. index-list)) )))
  2070. cache-hash) )
  2071. index-list)))
  2072. (defun hfy-prepare-tag-map (srcdir dstdir)
  2073. "Prepare the counterpart(s) to the index buffer(s) - a list of buffers
  2074. with the same structure, but listing (and linking to) instances of tags
  2075. \(as opposed to their definitions).\n
  2076. SRCDIR and DSTDIR are the source and output directories respectively.
  2077. See also `hfy-prepare-index', `hfy-split-index'."
  2078. (if (not hfy-split-index)
  2079. (list (hfy-prepare-index-i srcdir
  2080. dstdir
  2081. hfy-instance-file
  2082. nil
  2083. hfy-tags-rmap))
  2084. (let ((stub-list nil)
  2085. (cache-hash nil)
  2086. (index-list nil)
  2087. (cache-entry (assoc srcdir hfy-tags-rmap)))
  2088. (if (and cache-entry (setq cache-hash (cadr cache-entry)))
  2089. (maphash
  2090. (lambda (K _V)
  2091. (let ((stub (upcase (substring K 0 1))))
  2092. (if (member stub stub-list)
  2093. nil ;; seen this already: NOOP
  2094. (setq
  2095. stub-list (cons stub stub-list)
  2096. index-list (cons (hfy-prepare-index-i srcdir
  2097. dstdir
  2098. hfy-instance-file
  2099. stub
  2100. hfy-tags-rmap)
  2101. index-list)) )))
  2102. cache-hash) )
  2103. index-list)))
  2104. (defun hfy-subtract-maps (srcdir)
  2105. "Internal function - strips definitions of tags from the instance map.
  2106. SRCDIR is the directory being \"published\".
  2107. See also `hfy-tags-cache', `hfy-tags-rmap'."
  2108. (let ((new-list nil)
  2109. (old-list nil)
  2110. (def-list nil)
  2111. (exc-list nil)
  2112. (fwd-map (cadr (assoc srcdir hfy-tags-cache)))
  2113. (rev-map (cadr (assoc srcdir hfy-tags-rmap )))
  2114. (taglist (cadr (assoc srcdir hfy-tags-sortl))))
  2115. (dolist (TAG taglist)
  2116. (setq def-list (gethash TAG fwd-map)
  2117. old-list (gethash TAG rev-map)
  2118. exc-list (mapcar (lambda (P) (list (car P) (cadr P))) def-list)
  2119. new-list nil)
  2120. (dolist (P old-list)
  2121. (or (member (list (car P) (cadr P)) exc-list)
  2122. (push P new-list)))
  2123. (puthash TAG new-list rev-map))))
  2124. (defun htmlfontify-run-etags (srcdir)
  2125. "Load the etags cache for SRCDIR.
  2126. See also `hfy-load-tags-cache'."
  2127. (interactive "D source directory: ")
  2128. (hfy-load-tags-cache (directory-file-name srcdir)))
  2129. ;;(defun hfy-test-read-args (foo bar)
  2130. ;; (interactive "D source directory: \nD target directory: ")
  2131. ;; (message "foo: %S\nbar: %S" foo bar))
  2132. (defun hfy-save-kill-buffers (buffer-list &optional dstdir)
  2133. (dolist (B buffer-list)
  2134. (set-buffer B)
  2135. (and dstdir (file-directory-p dstdir) (cd dstdir))
  2136. (save-buffer)
  2137. (kill-buffer B)))
  2138. ;;;###autoload
  2139. (defun htmlfontify-copy-and-link-dir (srcdir dstdir &optional f-ext l-ext)
  2140. "Trawl SRCDIR and write fontified-and-hyperlinked output in DSTDIR.
  2141. F-EXT and L-EXT specify values for `hfy-extn' and `hfy-link-extn'.\n
  2142. You may also want to set `hfy-page-header' and `hfy-page-footer'."
  2143. (interactive "D source directory: \nD output directory: ")
  2144. ;;(message "htmlfontify-copy-and-link-dir")
  2145. (setq srcdir (directory-file-name srcdir))
  2146. (setq dstdir (directory-file-name dstdir))
  2147. (let ((source-files "SETME: list of source files, relative to srcdir")
  2148. (tr-cache (assoc srcdir hfy-tags-rmap))
  2149. (hfy-extn (or f-ext ".html"))
  2150. (hfy-link-extn (or l-ext ".html")))
  2151. ;; oops, forgot to load etags for srcdir:
  2152. (if tr-cache nil
  2153. (message "autoload of tags cache")
  2154. (hfy-load-tags-cache srcdir)
  2155. (setq tr-cache (assoc srcdir hfy-tags-rmap)))
  2156. ;; clear out the old cache:
  2157. (clrhash (cadr tr-cache))
  2158. (hfy-make-directory dstdir)
  2159. (setq source-files (hfy-list-files srcdir))
  2160. (dolist (file source-files)
  2161. (hfy-copy-and-fontify-file srcdir dstdir file))
  2162. (hfy-subtract-maps srcdir)
  2163. (hfy-save-kill-buffers (hfy-prepare-index srcdir dstdir) dstdir)
  2164. (hfy-save-kill-buffers (hfy-prepare-tag-map srcdir dstdir) dstdir) ))
  2165. ;; name of the init file we want:
  2166. (defun hfy-initfile ()
  2167. "Return the expected location of the htmlfontify specific init/custom file."
  2168. (let* ((file (or (getenv "HFY_INITFILE") ".hfy.el")))
  2169. (expand-file-name file "~") ))
  2170. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2171. ;; incomplete as yet : transfer hook settings to hfy init file:
  2172. ;; (defalias 'hfy-set-hooks 'custom-set-variables)
  2173. ;; (defun hfy-pp-hook (H)
  2174. ;; (and (string-match "-hook\\'" (symbol-name H))
  2175. ;; (boundp H)
  2176. ;; (symbol-value H)
  2177. ;; (insert (format "\n '(%S %S)" H (symbol-value H)))
  2178. ;; )
  2179. ;; )
  2180. ;; (defun hfy-save-hooks ()
  2181. ;; (let ((custom-file (hfy-initfile)))
  2182. ;; (custom-save-delete 'hfy-set-hooks)
  2183. ;; (let ((standard-output (current-buffer)))
  2184. ;; (princ "(hfy-set-hooks\n;;auto-generated, only one copy allowed\n")
  2185. ;; (mapatoms 'hfy-pp-hook)
  2186. ;; (insert "\n)")
  2187. ;; )
  2188. ;; )
  2189. ;; )
  2190. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  2191. (defalias 'hfy-init-progn 'progn)
  2192. (defun hfy-save-initvar (sym)
  2193. (princ (format "(setq %s\n '" sym))
  2194. (pp (symbol-value sym))
  2195. (princ ")\n"))
  2196. (defun htmlfontify-save-initfile ()
  2197. "Save the htmlfontify settings to the htmlfontify init file."
  2198. (interactive)
  2199. (let* ((start-pos nil)
  2200. (custom-file (hfy-initfile))
  2201. (standard-output (find-file-noselect custom-file 'nowarn)))
  2202. (save-excursion
  2203. (custom-save-delete 'hfy-init-progn)
  2204. (setq start-pos (point))
  2205. (princ "(hfy-init-progn\n;;auto-generated, only one copy allowed\n")
  2206. ;; FIXME: This saving&restoring of global customization
  2207. ;; variables can interfere with other customization settings for
  2208. ;; those vars (in .emacs or in Customize).
  2209. (mapc 'hfy-save-initvar
  2210. '(auto-mode-alist interpreter-mode-alist))
  2211. (princ ")\n")
  2212. (indent-region start-pos (point) nil))
  2213. (custom-save-all) ))
  2214. (defun htmlfontify-load-initfile ()
  2215. "Load the htmlfontify specific init/custom file."
  2216. (interactive)
  2217. (let ((file (hfy-initfile)))
  2218. (load file 'NOERROR nil nil) ))
  2219. ;;;### (autoloads (hfy-fallback-colour-values htmlfontify-load-rgb-file)
  2220. ;;;;;; "hfy-cmap" "hfy-cmap.el" "ef24066922f1e27b7580d572f12fabbe")
  2221. ;;; Generated autoloads from hfy-cmap.el
  2222. (autoload 'htmlfontify-load-rgb-file "hfy-cmap" "\
  2223. Load an X11 style rgb.txt FILE.
  2224. Search `hfy-rgb-load-path' if FILE is not specified.
  2225. Loads the variable `hfy-rgb-txt-colour-map', which is used by
  2226. `hfy-fallback-colour-values'.
  2227. \(fn &optional FILE)" t nil)
  2228. (autoload 'hfy-fallback-colour-values "hfy-cmap" "\
  2229. Use a fallback method for obtaining the rgb values for a color.
  2230. \(fn COLOUR-STRING)" nil nil)
  2231. ;;;***
  2232. (provide 'htmlfontify)
  2233. ;; Local Variables:
  2234. ;; coding: utf-8
  2235. ;; End:
  2236. ;;; htmlfontify.el ends here